diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/com/othersonline/kv/distributed/impl/PropertiesConfigurator.java b/src/com/othersonline/kv/distributed/impl/PropertiesConfigurator.java
index 57aed8d..51618b5 100644
--- a/src/com/othersonline/kv/distributed/impl/PropertiesConfigurator.java
+++ b/src/com/othersonline/kv/distributed/impl/PropertiesConfigurator.java
@@ -1,159 +1,159 @@
package com.othersonline.kv.distributed.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import com.othersonline.kv.backends.ConnectionFactory;
import com.othersonline.kv.backends.UriConnectionFactory;
import com.othersonline.kv.distributed.Configuration;
import com.othersonline.kv.distributed.Configurator;
import com.othersonline.kv.distributed.NodeStore;
public class PropertiesConfigurator implements Configurator {
public static final String SYNC_OP_THREAD_POOL = "syncpool.threads";
public static final String SYNC_OP_MAX_QUEUE_SIZE = "syncpool.maxQueueSize";
public static final String ASYNC_OP_THREAD_POOL = "asyncpool.threads";
public static final String ASYNC_OP_MAX_QUEUE_SIZE = "asyncpool.maxQueueSize";
public static final String MAX_NODE_ERROR_COUNT = "node.maxErrorCount";
public static final String NODE_STORE = "nodestore.implementation";
public static final String NODE_STORE_URL = "nodestore.url";
public static final String READ_OPERATION_TIMEOUT = "read.timeout";
public static final String READ_REPLICAS = "read.replicas";
public static final String REQUIRED_READS = "read.required";
public static final String REQUIRED_WRITES = "write.required";
public static final String WRITE_OPERATION_TIMEOUT = "write.timeout";
public static final String WRITE_REPLICAS = "write.replicas";
public static final String BACKFILL_NULL_GET_REQUESTS = "backfill.nullGets";
public static final String BACKFILL_FAILED_GET_REQUESTS = "backfill.failedGets";
private volatile Configuration config;
public PropertiesConfigurator() {
}
public PropertiesConfigurator(File file) throws IOException {
load(file);
}
public PropertiesConfigurator(InputStream is) throws IOException {
load(is);
}
public PropertiesConfigurator(Properties p) throws IOException {
load(p);
}
public void load(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
try {
load(fis);
} finally {
fis.close();
}
}
public void load(InputStream in) throws IOException {
Properties p = new Properties();
p.load(in);
load(p);
}
public void load(Properties props) throws IOException {
this.config = getConfig(props);
}
public Configuration getConfiguration() throws IOException {
return config;
}
private Configuration getConfig(Properties p)
throws IllegalArgumentException {
ConnectionFactory cf = new UriConnectionFactory();
int syncOperationThreadPoolCount = getIntProperty(p,
SYNC_OP_THREAD_POOL, 100);
int syncOperationMaxQueueSize = getIntProperty(p,
SYNC_OP_MAX_QUEUE_SIZE, 100);
int asyncOperationThreadPoolCount = getIntProperty(p,
ASYNC_OP_THREAD_POOL, 10);
int asyncOperationMaxQueueSize = getIntProperty(p,
ASYNC_OP_MAX_QUEUE_SIZE, 100);
Configuration config = new Configuration();
config
.setAsyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, asyncOperationThreadPoolCount,
- syncOperationMaxQueueSize));
+ asyncOperationMaxQueueSize));
config.setConnectionFactory(cf);
config
.setMaxNodeErrorCount(getIntProperty(p, MAX_NODE_ERROR_COUNT,
100));
config.setNodeErrorCountPeriod(TimeUnit.MINUTES);
config.setNodeStore(getNodeStore(NODE_STORE, p));
config.setReadOperationTimeout(getIntProperty(p,
READ_OPERATION_TIMEOUT, 500));
config.setReadReplicas(getIntProperty(p, READ_REPLICAS, 3));
config.setRequiredReads(getIntProperty(p, REQUIRED_READS, 2));
config.setRequiredWrites(getIntProperty(p, REQUIRED_WRITES, 2));
config
.setSyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, syncOperationThreadPoolCount,
- asyncOperationMaxQueueSize));
+ syncOperationMaxQueueSize));
config.setWriteOperationTimeout(getIntProperty(p,
WRITE_OPERATION_TIMEOUT, 500));
config.setWriteReplicas(getIntProperty(p, WRITE_REPLICAS, 3));
config.setFillNullGetResults(getBooleanProperty(p,
BACKFILL_NULL_GET_REQUESTS, true));
config.setFillErrorGetResults(getBooleanProperty(p,
BACKFILL_FAILED_GET_REQUESTS, false));
return config;
}
private NodeStore getNodeStore(String name, Properties props)
throws IllegalArgumentException {
try {
Class<NodeStore> cls = (Class<NodeStore>) Class.forName(props
.getProperty(NODE_STORE));
Object obj = cls.newInstance();
NodeStore ns = (NodeStore) obj;
ns.setProperties(props);
return ns;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private int getIntProperty(Properties p, String name, int defaultValue) {
String value = p.getProperty(name);
if (value == null) {
value = Integer.toString(defaultValue);
}
return Integer.parseInt(value);
}
public boolean getBooleanProperty(Properties p, String name,
boolean defaultValue) {
String value = p.getProperty(name);
if (value == null) {
value = Boolean.toString(defaultValue);
}
return Boolean.parseBoolean(value);
}
}
| false | true | private Configuration getConfig(Properties p)
throws IllegalArgumentException {
ConnectionFactory cf = new UriConnectionFactory();
int syncOperationThreadPoolCount = getIntProperty(p,
SYNC_OP_THREAD_POOL, 100);
int syncOperationMaxQueueSize = getIntProperty(p,
SYNC_OP_MAX_QUEUE_SIZE, 100);
int asyncOperationThreadPoolCount = getIntProperty(p,
ASYNC_OP_THREAD_POOL, 10);
int asyncOperationMaxQueueSize = getIntProperty(p,
ASYNC_OP_MAX_QUEUE_SIZE, 100);
Configuration config = new Configuration();
config
.setAsyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, asyncOperationThreadPoolCount,
syncOperationMaxQueueSize));
config.setConnectionFactory(cf);
config
.setMaxNodeErrorCount(getIntProperty(p, MAX_NODE_ERROR_COUNT,
100));
config.setNodeErrorCountPeriod(TimeUnit.MINUTES);
config.setNodeStore(getNodeStore(NODE_STORE, p));
config.setReadOperationTimeout(getIntProperty(p,
READ_OPERATION_TIMEOUT, 500));
config.setReadReplicas(getIntProperty(p, READ_REPLICAS, 3));
config.setRequiredReads(getIntProperty(p, REQUIRED_READS, 2));
config.setRequiredWrites(getIntProperty(p, REQUIRED_WRITES, 2));
config
.setSyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, syncOperationThreadPoolCount,
asyncOperationMaxQueueSize));
config.setWriteOperationTimeout(getIntProperty(p,
WRITE_OPERATION_TIMEOUT, 500));
config.setWriteReplicas(getIntProperty(p, WRITE_REPLICAS, 3));
config.setFillNullGetResults(getBooleanProperty(p,
BACKFILL_NULL_GET_REQUESTS, true));
config.setFillErrorGetResults(getBooleanProperty(p,
BACKFILL_FAILED_GET_REQUESTS, false));
return config;
}
| private Configuration getConfig(Properties p)
throws IllegalArgumentException {
ConnectionFactory cf = new UriConnectionFactory();
int syncOperationThreadPoolCount = getIntProperty(p,
SYNC_OP_THREAD_POOL, 100);
int syncOperationMaxQueueSize = getIntProperty(p,
SYNC_OP_MAX_QUEUE_SIZE, 100);
int asyncOperationThreadPoolCount = getIntProperty(p,
ASYNC_OP_THREAD_POOL, 10);
int asyncOperationMaxQueueSize = getIntProperty(p,
ASYNC_OP_MAX_QUEUE_SIZE, 100);
Configuration config = new Configuration();
config
.setAsyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, asyncOperationThreadPoolCount,
asyncOperationMaxQueueSize));
config.setConnectionFactory(cf);
config
.setMaxNodeErrorCount(getIntProperty(p, MAX_NODE_ERROR_COUNT,
100));
config.setNodeErrorCountPeriod(TimeUnit.MINUTES);
config.setNodeStore(getNodeStore(NODE_STORE, p));
config.setReadOperationTimeout(getIntProperty(p,
READ_OPERATION_TIMEOUT, 500));
config.setReadReplicas(getIntProperty(p, READ_REPLICAS, 3));
config.setRequiredReads(getIntProperty(p, REQUIRED_READS, 2));
config.setRequiredWrites(getIntProperty(p, REQUIRED_WRITES, 2));
config
.setSyncOperationQueue(new NonPersistentThreadPoolOperationQueue(
p, cf, syncOperationThreadPoolCount,
syncOperationMaxQueueSize));
config.setWriteOperationTimeout(getIntProperty(p,
WRITE_OPERATION_TIMEOUT, 500));
config.setWriteReplicas(getIntProperty(p, WRITE_REPLICAS, 3));
config.setFillNullGetResults(getBooleanProperty(p,
BACKFILL_NULL_GET_REQUESTS, true));
config.setFillErrorGetResults(getBooleanProperty(p,
BACKFILL_FAILED_GET_REQUESTS, false));
return config;
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/WebSocketProcessor.java b/modules/cpr/src/main/java/org/atmosphere/cpr/WebSocketProcessor.java
index f9070e522..515341989 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/WebSocketProcessor.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/WebSocketProcessor.java
@@ -1,173 +1,173 @@
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.cpr;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketEventListener;
import org.atmosphere.websocket.WebSocketHttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Like the {@link AsynchronousProcessor} class, this class is responsible for dispatching WebSocket request to the
* proper {@link org.atmosphere.websocket.WebSocket} implementation.
*
* @author Jeanfrancois Arcand
*/
public abstract class WebSocketProcessor implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(WebSocketProcessor.class);
private final AtmosphereServlet atmosphereServlet;
private final WebSocket webSocket;
private final AtomicBoolean loggedMsg = new AtomicBoolean(false);
private AtmosphereResource<HttpServletRequest, HttpServletResponse> resource;
private AtmosphereHandler handler;
public WebSocketProcessor(AtmosphereServlet atmosphereServlet, WebSocket webSocket) {
this.webSocket = webSocket;
this.atmosphereServlet = atmosphereServlet;
}
public final void connect(final HttpServletRequest request) throws IOException {
if (!loggedMsg.getAndSet(true)) {
logger.info("Atmosphere detected WebSocket: {}", webSocket.getClass().getName());
}
WebSocketHttpServletResponse wsr = new WebSocketHttpServletResponse<WebSocket>(webSocket);
request.setAttribute(WebSocket.WEBSOCKET_SUSPEND, true);
try {
atmosphereServlet.doCometSupport(request, wsr);
} catch (IOException e) {
logger.info("failed invoking atmosphere servlet doCometSupport()", e);
} catch (ServletException e) {
logger.info("failed invoking atmosphere servlet doCometSupport()", e);
}
resource = (AtmosphereResource) request.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE);
handler = (AtmosphereHandler) request.getAttribute(AtmosphereServlet.ATMOSPHERE_HANDLER);
if (resource == null || !resource.getAtmosphereResourceEvent().isSuspended()) {
logger.error("No AtmosphereResource has been suspended. The WebSocket will be closed.");
webSocket.close();
}
}
public AtmosphereResource resource() {
return resource;
}
public AtmosphereServlet atmosphereServlet() {
return atmosphereServlet;
}
public HttpServletRequest request() {
return resource.getRequest();
}
public WebSocket webSocketSupport() {
return webSocket;
}
abstract public void broadcast(String data);
abstract public void broadcast(byte[] data, int offset, int length);
public void close() {
try {
if (handler != null && resource != null) {
handler.onStateChange(new AtmosphereResourceEventImpl((AtmosphereResourceImpl) resource, false, true));
}
} catch (IOException e) {
if (AtmosphereResourceImpl.class.isAssignableFrom(resource.getClass())) {
AtmosphereResourceImpl.class.cast(resource).onThrowable(e);
}
logger.info("Failed invoking atmosphere handler onStateChange()", e);
}
if (resource != null) {
resource.getBroadcaster().removeAtmosphereResource(resource);
}
}
@Override
public String toString() {
return "WebSocketProcessor{ handler=" + handler + ", resource=" + resource + ", webSocket=" +
webSocket + " }";
}
public void notifyListener(WebSocketEventListener.WebSocketEvent event) {
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
- WebSocketEventListener.class.cast(l).onMessage(event);
+ WebSocketEventListener.class.cast(l).onHandshake(event);
break;
case CLOSE:
- WebSocketEventListener.class.cast(l).onMessage(event);
+ WebSocketEventListener.class.cast(l).onClose(event);
break;
}
}
}
}
}
| false | true | public void notifyListener(WebSocketEventListener.WebSocketEvent event) {
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case CLOSE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
}
}
}
}
| public void notifyListener(WebSocketEventListener.WebSocketEvent event) {
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
WebSocketEventListener.class.cast(l).onHandshake(event);
break;
case CLOSE:
WebSocketEventListener.class.cast(l).onClose(event);
break;
}
}
}
}
|
diff --git a/src/org/opensolaris/opengrok/configuration/Configuration.java b/src/org/opensolaris/opengrok/configuration/Configuration.java
index 8763fd3..1e3cd79 100644
--- a/src/org/opensolaris/opengrok/configuration/Configuration.java
+++ b/src/org/opensolaris/opengrok/configuration/Configuration.java
@@ -1,474 +1,475 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.configuration;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.opensolaris.opengrok.history.RepositoryInfo;
import org.opensolaris.opengrok.index.IgnoredNames;
/**
* Placeholder class for all configuration variables. Due to the multithreaded
* nature of the web application, each thread will use the same instance of the
* configuration object for each page request. Class and methods should have
* package scope, but that didn't work with the XMLDecoder/XMLEncoder.
*/
public final class Configuration {
private String ctags;
/** Should the history log be cached? */
private boolean historyCache;
/**
* The maximum time in milliseconds {@code HistoryCache.get()} can take
* before its result is cached.
*/
private int historyCacheTime;
/** Should the history cache be stored in a database? */
private boolean historyCacheInDB;
private List<Project> projects;
private String sourceRoot;
private String dataRoot;
private List<RepositoryInfo> repositories;
private String urlPrefix;
private boolean generateHtml;
private Project defaultProject;
private int indexWordLimit;
private boolean verbose;
private boolean allowLeadingWildcard;
private IgnoredNames ignoredNames;
private String userPage;
private String bugPage;
private String bugPattern;
private String reviewPage;
private String reviewPattern;
private String webappLAF;
private boolean remoteScmSupported;
private boolean optimizeDatabase;
private boolean useLuceneLocking;
private boolean compressXref;
private boolean indexVersionedFilesOnly;
private int hitsPerPage;
private int cachePages;
private String databaseDriver;
private String databaseUrl;
/** Creates a new instance of Configuration */
public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
- setIndexWordLimit(60000);
+ //below can cause an outofmemory error, since it is defaulting to NO LIMIT
+ setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
public String getCtags() {
return ctags;
}
public void setCtags(String ctags) {
this.ctags = ctags;
}
public int getCachePages() {
return cachePages;
}
public void setCachePages(int cachePages) {
this.cachePages = cachePages;
}
public int getHitsPerPage() {
return hitsPerPage;
}
public void setHitsPerPage(int hitsPerPage) {
this.hitsPerPage = hitsPerPage;
}
/**
* Should the history log be cached?
* @return {@code true} if a {@code HistoryCache} implementation should
* be used, {@code false} otherwise
*/
public boolean isHistoryCache() {
return historyCache;
}
/**
* Set whether history should be cached.
* @param historyCache if {@code true} enable history cache
*/
public void setHistoryCache(boolean historyCache) {
this.historyCache = historyCache;
}
/**
* How long can a history request take before it's cached? If the time
* is exceeded, the result is cached. This setting only affects
* {@code FileHistoryCache}.
*
* @return the maximum time in milliseconds a history request can take
* before it's cached
*/
public int getHistoryCacheTime() {
return historyCacheTime;
}
/**
* Set the maximum time a history request can take before it's cached.
* This setting is only respected if {@code FileHistoryCache} is used.
*
* @param historyCacheTime maximum time in milliseconds
*/
public void setHistoryCacheTime(int historyCacheTime) {
this.historyCacheTime = historyCacheTime;
}
/**
* Should the history cache be stored in a database? If yes,
* {@code JDBCHistoryCache} will be used to cache the history; otherwise,
* {@code FileHistoryCache} is used.
*
* @return whether the history cache should be stored in a database
*/
public boolean isHistoryCacheInDB() {
return historyCacheInDB;
}
/**
* Set whether the history cache should be stored in a database, and
* {@code JDBCHistoryCache} should be used instead of {@code
* FileHistoryCache}.
*
* @param historyCacheInDB whether the history cached should be stored in
* a database
*/
public void setHistoryCacheInDB(boolean historyCacheInDB) {
this.historyCacheInDB = historyCacheInDB;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public String getSourceRoot() {
return sourceRoot;
}
public void setSourceRoot(String sourceRoot) {
this.sourceRoot = sourceRoot;
}
public String getDataRoot() {
return dataRoot;
}
public void setDataRoot(String dataRoot) {
this.dataRoot = dataRoot;
}
public List<RepositoryInfo> getRepositories() {
return repositories;
}
public void setRepositories(List<RepositoryInfo> repositories) {
this.repositories = repositories;
}
public String getUrlPrefix() {
return urlPrefix;
}
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public void setGenerateHtml(boolean generateHtml) {
this.generateHtml = generateHtml;
}
public boolean isGenerateHtml() {
return generateHtml;
}
public void setDefaultProject(Project defaultProject) {
this.defaultProject = defaultProject;
}
public Project getDefaultProject() {
return defaultProject;
}
public int getIndexWordLimit() {
return indexWordLimit;
}
public void setIndexWordLimit(int indexWordLimit) {
this.indexWordLimit = indexWordLimit;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
this.allowLeadingWildcard = allowLeadingWildcard;
}
public boolean isAllowLeadingWildcard() {
return allowLeadingWildcard;
}
private boolean quickContextScan;
public boolean isQuickContextScan() {
return quickContextScan;
}
public void setQuickContextScan(boolean quickContextScan) {
this.quickContextScan = quickContextScan;
}
public void setIgnoredNames(IgnoredNames ignoredNames) {
this.ignoredNames = ignoredNames;
}
public IgnoredNames getIgnoredNames() {
return ignoredNames;
}
public void setUserPage(String userPage) {
this.userPage = userPage;
}
public String getUserPage() {
return userPage;
}
public void setBugPage(String bugPage) {
this.bugPage = bugPage;
}
public String getBugPage() {
return bugPage;
}
public void setBugPattern(String bugPattern) {
this.bugPattern = bugPattern;
}
public String getBugPattern() {
return bugPattern;
}
public String getReviewPage() {
return reviewPage;
}
public void setReviewPage(String reviewPage) {
this.reviewPage = reviewPage;
}
public String getReviewPattern() {
return reviewPattern;
}
public void setReviewPattern(String reviewPattern) {
this.reviewPattern = reviewPattern;
}
public String getWebappLAF() {
return webappLAF;
}
public void setWebappLAF(String webappLAF) {
this.webappLAF = webappLAF;
}
public boolean isRemoteScmSupported() {
return remoteScmSupported;
}
public void setRemoteScmSupported(boolean remoteScmSupported) {
this.remoteScmSupported = remoteScmSupported;
}
public boolean isOptimizeDatabase() {
return optimizeDatabase;
}
public void setOptimizeDatabase(boolean optimizeDatabase) {
this.optimizeDatabase = optimizeDatabase;
}
public boolean isUsingLuceneLocking() {
return useLuceneLocking;
}
public void setUsingLuceneLocking(boolean useLuceneLocking) {
this.useLuceneLocking = useLuceneLocking;
}
public void setCompressXref(boolean compressXref) {
this.compressXref = compressXref;
}
public boolean isCompressXref() {
return compressXref;
}
public boolean isIndexVersionedFilesOnly() {
return indexVersionedFilesOnly;
}
public void setIndexVersionedFilesOnly(boolean indexVersionedFilesOnly) {
this.indexVersionedFilesOnly = indexVersionedFilesOnly;
}
public Date getDateForLastIndexRun() {
File timestamp = new File(getDataRoot(), "timestamp");
return new Date(timestamp.lastModified());
}
public String getDatabaseDriver() {
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabaseUrl() {
if (databaseUrl == null) {
return "jdbc:derby://localhost/cachedb;create=true";
}
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
/**
* Write the current configuration to a file
* @param file the file to write the configuration into
* @throws IOException if an error occurs
*/
public void write(File file) throws IOException {
final FileOutputStream out = new FileOutputStream(file);
try {
this.encodeObject(out);
} finally {
out.close();
}
}
public String getXMLRepresentationAsString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
this.encodeObject(bos);
return bos.toString();
}
private void encodeObject(OutputStream out) {
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
e.writeObject(this);
e.close();
}
public static Configuration read(File file) throws IOException {
final FileInputStream in = new FileInputStream(file);
try {
return decodeObject(in);
} finally {
in.close();
}
}
public static Configuration makeXMLStringAsConfiguration(String xmlconfig) throws IOException {
final Configuration ret;
final ByteArrayInputStream in = new ByteArrayInputStream(xmlconfig.getBytes());
ret = decodeObject(in);
return ret;
}
private static Configuration decodeObject(InputStream in) throws IOException {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(in));
final Object ret = d.readObject();
d.close();
if (!(ret instanceof Configuration)) {
throw new IOException("Not a valid config file");
}
return (Configuration)ret;
}
}
| true | true | public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
setIndexWordLimit(60000);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
| public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
|
diff --git a/src/main/java/com/jayway/maven/plugins/android/common/NativeHelper.java b/src/main/java/com/jayway/maven/plugins/android/common/NativeHelper.java
index b513a14f..03a3ac97 100644
--- a/src/main/java/com/jayway/maven/plugins/android/common/NativeHelper.java
+++ b/src/main/java/com/jayway/maven/plugins/android/common/NativeHelper.java
@@ -1,218 +1,218 @@
package com.jayway.maven.plugins.android.common;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.AndroidNdk;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyFilter;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.graph.Exclusion;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.util.filter.AndDependencyFilter;
import org.sonatype.aether.util.filter.ExclusionsDependencyFilter;
import org.sonatype.aether.util.filter.ScopeDependencyFilter;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB;
import static org.apache.maven.RepositoryUtils.toDependency;
/**
* @author Johan Lindquist
*/
public class NativeHelper {
public static final int NDK_REQUIRED_VERSION = 7;
private MavenProject project;
private RepositorySystemSession repoSession;
private RepositorySystem repoSystem;
private ArtifactFactory artifactFactory;
private Log log;
private List<RemoteRepository> projectRepos;
public NativeHelper( MavenProject project, List<RemoteRepository> projectRepos, RepositorySystemSession repoSession, RepositorySystem repoSystem, ArtifactFactory artifactFactory, Log log ) {
this.project = project;
this.projectRepos = projectRepos;
this.repoSession = repoSession;
this.repoSystem = repoSystem;
this.artifactFactory = artifactFactory;
this.log = log;
}
public static boolean hasStaticNativeLibraryArtifact(Set<Artifact> resolveNativeLibraryArtifacts) {
for (Artifact resolveNativeLibraryArtifact : resolveNativeLibraryArtifacts) {
if ( "a".equals(resolveNativeLibraryArtifact.getType()) ) {
return true;
}
}
return false;
}
public static boolean hasSharedNativeLibraryArtifact(Set<Artifact> resolveNativeLibraryArtifacts) {
for (Artifact resolveNativeLibraryArtifact : resolveNativeLibraryArtifacts) {
if ( "so".equals(resolveNativeLibraryArtifact.getType()) ) {
return true;
}
}
return false;
}
public Set<Artifact> getNativeDependenciesArtifacts(File unpackDirectory, boolean sharedLibraries) throws MojoExecutionException {
final Set<Artifact> filteredArtifacts = new LinkedHashSet<Artifact>();
// Add all dependent artifacts declared in the pom file
@SuppressWarnings( "unchecked" )
final Set<Artifact> allArtifacts = project.getDependencyArtifacts();
// Add all attached artifacts as well - this could come from the NDK mojo for example
boolean result = allArtifacts.addAll( project.getAttachedArtifacts() );
for ( Artifact artifact : allArtifacts ) {
// A null value in the scope indicates that the artifact has been attached
// as part of a previous build step (NDK mojo)
if ( isNativeLibrary( sharedLibraries, artifact.getType() ) && artifact.getScope() == null ) {
// Including attached artifact
log.debug( "Including attached artifact: "+artifact.getArtifactId()+"("+artifact.getGroupId()+")" );
filteredArtifacts.add( artifact );
} else if ( isNativeLibrary( sharedLibraries, artifact.getType() ) && ( Artifact.SCOPE_COMPILE.equals( artifact.getScope() ) || Artifact.SCOPE_RUNTIME.equals( artifact.getScope() ) ) ) {
filteredArtifacts.add( artifact );
} else if ( APKLIB.equals( artifact.getType() ) ) {
// Check if the artifact contains a libs folder - if so, include it in the list
File libsFolder = new File( AbstractAndroidMojo.getLibraryUnpackDirectory( unpackDirectory, artifact )+"/libs" );
if ( libsFolder.exists() ) {
filteredArtifacts.add( artifact );
}
}
}
Set<Artifact> transientArtifacts = processTransientDependencies( project.getDependencies(), sharedLibraries );
filteredArtifacts.addAll( transientArtifacts );
return filteredArtifacts;
}
private boolean isNativeLibrary( boolean sharedLibraries, String artifactType ) {
return (sharedLibraries ? "so".equals( artifactType ) : "a".equals( artifactType ));
}
private Set<Artifact> processTransientDependencies( List<org.apache.maven.model.Dependency> dependencies, boolean sharedLibraries ) throws MojoExecutionException {
Set<Artifact> transientArtifacts = new LinkedHashSet<Artifact>();
for ( org.apache.maven.model.Dependency dependency : dependencies ) {
if ( !"provided".equals( dependency.getScope() ) && !dependency.isOptional()) {
transientArtifacts.addAll( processTransientDependencies( toDependency(dependency, repoSession.getArtifactTypeRegistry()), sharedLibraries) );
}
}
return transientArtifacts;
}
private Set<Artifact> processTransientDependencies( Dependency dependency, boolean sharedLibraries ) throws MojoExecutionException {
try {
final Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
final CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot( dependency );
collectRequest.setRepositories( projectRepos );
final DependencyNode node = repoSystem.collectDependencies( repoSession, collectRequest ).getRoot();
Collection<String> exclusionPatterns = new ArrayList<String>();
- if (!dependency.getExclusions().isEmpty())
+ if (dependency.getExclusions() != null && !dependency.getExclusions().isEmpty())
{
for (Exclusion exclusion : dependency.getExclusions()) {
exclusionPatterns.add(exclusion.getGroupId()+ ":" + exclusion.getArtifactId());
}
}
final DependencyRequest dependencyRequest = new DependencyRequest( node, new AndDependencyFilter(
new ExclusionsDependencyFilter(exclusionPatterns)
,new AndDependencyFilter(
new ScopeDependencyFilter( Arrays.asList( "compile", "runtime" ), Arrays.asList( "test" ) ),
// Also exclude any optional dependencies
new DependencyFilter() {
@Override
public boolean accept( DependencyNode dependencyNode, List<DependencyNode> dependencyNodes ) {
return !dependencyNode.getDependency().isOptional();
}
}
)));
repoSystem.resolveDependencies( repoSession, dependencyRequest );
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept( nlg );
final List<Dependency> dependencies = nlg.getDependencies( false );
for ( Dependency dep : dependencies ) {
final org.sonatype.aether.artifact.Artifact depAetherArtifact = dep.getArtifact();
if ( isNativeLibrary( sharedLibraries, depAetherArtifact.getExtension() ) ) {
final Artifact mavenArtifact = artifactFactory.createDependencyArtifact( depAetherArtifact.getGroupId(), depAetherArtifact.getArtifactId(), VersionRange.createFromVersion( depAetherArtifact.getVersion() ), depAetherArtifact.getExtension(), depAetherArtifact.getClassifier(), dep.getScope() );
mavenArtifact.setFile(depAetherArtifact.getFile());
artifacts.add( mavenArtifact );
}
}
return artifacts;
} catch ( Exception e ) {
throw new MojoExecutionException( "Error while processing transient dependencies", e );
}
}
public static void validateNDKVersion(File ndkHomeDir) throws MojoExecutionException {
final File ndkVersionFile = new File(ndkHomeDir, "RELEASE.TXT");
if (!ndkVersionFile.exists()) {
throw new MojoExecutionException("Could not locate RELEASE.TXT in the Android NDK base directory '" + ndkHomeDir.getAbsolutePath() + "'. Please verify your setup! " + AndroidNdk.PROPER_NDK_HOME_DIRECTORY_MESSAGE);
}
try {
String versionStr = FileUtils.readFileToString(ndkVersionFile);
validateNDKVersion(NDK_REQUIRED_VERSION, versionStr);
} catch (Exception e) {
throw new MojoExecutionException("Error while extracting NDK version from '" + ndkVersionFile.getAbsolutePath() + "'. Please verify your setup! " + AndroidNdk.PROPER_NDK_HOME_DIRECTORY_MESSAGE);
}
}
public static void validateNDKVersion(int desiredVersion, String versionStr) throws MojoExecutionException {
int version = 0;
if (versionStr != null) {
versionStr = versionStr.trim();
Pattern pattern = Pattern.compile("[r]([0-9]{1,3})([a-z]{0,1}).*");
Matcher m = pattern.matcher(versionStr);
if (m.matches()) {
final String group = m.group(1);
version = Integer.parseInt(group);
}
}
if (version < desiredVersion) {
throw new MojoExecutionException("You are running an old NDK (version " + versionStr + "), please update to at least r'" + desiredVersion + "' or later");
}
}
}
| true | true | private Set<Artifact> processTransientDependencies( Dependency dependency, boolean sharedLibraries ) throws MojoExecutionException {
try {
final Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
final CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot( dependency );
collectRequest.setRepositories( projectRepos );
final DependencyNode node = repoSystem.collectDependencies( repoSession, collectRequest ).getRoot();
Collection<String> exclusionPatterns = new ArrayList<String>();
if (!dependency.getExclusions().isEmpty())
{
for (Exclusion exclusion : dependency.getExclusions()) {
exclusionPatterns.add(exclusion.getGroupId()+ ":" + exclusion.getArtifactId());
}
}
final DependencyRequest dependencyRequest = new DependencyRequest( node, new AndDependencyFilter(
new ExclusionsDependencyFilter(exclusionPatterns)
,new AndDependencyFilter(
new ScopeDependencyFilter( Arrays.asList( "compile", "runtime" ), Arrays.asList( "test" ) ),
// Also exclude any optional dependencies
new DependencyFilter() {
@Override
public boolean accept( DependencyNode dependencyNode, List<DependencyNode> dependencyNodes ) {
return !dependencyNode.getDependency().isOptional();
}
}
)));
repoSystem.resolveDependencies( repoSession, dependencyRequest );
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept( nlg );
final List<Dependency> dependencies = nlg.getDependencies( false );
for ( Dependency dep : dependencies ) {
final org.sonatype.aether.artifact.Artifact depAetherArtifact = dep.getArtifact();
if ( isNativeLibrary( sharedLibraries, depAetherArtifact.getExtension() ) ) {
final Artifact mavenArtifact = artifactFactory.createDependencyArtifact( depAetherArtifact.getGroupId(), depAetherArtifact.getArtifactId(), VersionRange.createFromVersion( depAetherArtifact.getVersion() ), depAetherArtifact.getExtension(), depAetherArtifact.getClassifier(), dep.getScope() );
mavenArtifact.setFile(depAetherArtifact.getFile());
artifacts.add( mavenArtifact );
}
}
return artifacts;
} catch ( Exception e ) {
throw new MojoExecutionException( "Error while processing transient dependencies", e );
}
}
| private Set<Artifact> processTransientDependencies( Dependency dependency, boolean sharedLibraries ) throws MojoExecutionException {
try {
final Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
final CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot( dependency );
collectRequest.setRepositories( projectRepos );
final DependencyNode node = repoSystem.collectDependencies( repoSession, collectRequest ).getRoot();
Collection<String> exclusionPatterns = new ArrayList<String>();
if (dependency.getExclusions() != null && !dependency.getExclusions().isEmpty())
{
for (Exclusion exclusion : dependency.getExclusions()) {
exclusionPatterns.add(exclusion.getGroupId()+ ":" + exclusion.getArtifactId());
}
}
final DependencyRequest dependencyRequest = new DependencyRequest( node, new AndDependencyFilter(
new ExclusionsDependencyFilter(exclusionPatterns)
,new AndDependencyFilter(
new ScopeDependencyFilter( Arrays.asList( "compile", "runtime" ), Arrays.asList( "test" ) ),
// Also exclude any optional dependencies
new DependencyFilter() {
@Override
public boolean accept( DependencyNode dependencyNode, List<DependencyNode> dependencyNodes ) {
return !dependencyNode.getDependency().isOptional();
}
}
)));
repoSystem.resolveDependencies( repoSession, dependencyRequest );
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept( nlg );
final List<Dependency> dependencies = nlg.getDependencies( false );
for ( Dependency dep : dependencies ) {
final org.sonatype.aether.artifact.Artifact depAetherArtifact = dep.getArtifact();
if ( isNativeLibrary( sharedLibraries, depAetherArtifact.getExtension() ) ) {
final Artifact mavenArtifact = artifactFactory.createDependencyArtifact( depAetherArtifact.getGroupId(), depAetherArtifact.getArtifactId(), VersionRange.createFromVersion( depAetherArtifact.getVersion() ), depAetherArtifact.getExtension(), depAetherArtifact.getClassifier(), dep.getScope() );
mavenArtifact.setFile(depAetherArtifact.getFile());
artifacts.add( mavenArtifact );
}
}
return artifacts;
} catch ( Exception e ) {
throw new MojoExecutionException( "Error while processing transient dependencies", e );
}
}
|
diff --git a/src/main/java/org/apache/ibatis/builder/annotation/MapperAnnotationBuilder.java b/src/main/java/org/apache/ibatis/builder/annotation/MapperAnnotationBuilder.java
index 4c5796e8dd..de50a63115 100644
--- a/src/main/java/org/apache/ibatis/builder/annotation/MapperAnnotationBuilder.java
+++ b/src/main/java/org/apache/ibatis/builder/annotation/MapperAnnotationBuilder.java
@@ -1,538 +1,539 @@
/*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.builder.annotation;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.annotations.Arg;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.CacheNamespaceRef;
import org.apache.ibatis.annotations.Case;
import org.apache.ibatis.annotations.ConstructorArgs;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.TypeDiscriminator;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.builder.xml.dynamic.DynamicSqlSource;
import org.apache.ibatis.builder.xml.dynamic.MixedSqlNode;
import org.apache.ibatis.builder.xml.dynamic.SqlNode;
import org.apache.ibatis.builder.xml.dynamic.TextSqlNode;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Discriminator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultFlag;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.ResultSetType;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.UnknownTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class MapperAnnotationBuilder {
private final Set<Class<? extends Annotation>> sqlAnnotationTypes = new HashSet<Class<? extends Annotation>>();
private final Set<Class<? extends Annotation>> sqlProviderAnnotationTypes = new HashSet<Class<? extends Annotation>>();
private Configuration configuration;
private MapperBuilderAssistant assistant;
private Class<?> type;
public MapperAnnotationBuilder(Configuration configuration, Class<?> type) {
String resource = type.getName().replace('.', '/') + ".java (best guess)";
this.assistant = new MapperBuilderAssistant(configuration, resource);
this.configuration = configuration;
this.type = type;
sqlAnnotationTypes.add(Select.class);
sqlAnnotationTypes.add(Insert.class);
sqlAnnotationTypes.add(Update.class);
sqlAnnotationTypes.add(Delete.class);
sqlProviderAnnotationTypes.add(SelectProvider.class);
sqlProviderAnnotationTypes.add(InsertProvider.class);
sqlProviderAnnotationTypes.add(UpdateProvider.class);
sqlProviderAnnotationTypes.add(DeleteProvider.class);
}
public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
Method[] methods = type.getMethods();
for (Method method : methods) {
parseResultsAndConstructorArgs(method);
parseStatement(method);
}
}
}
private void loadXmlResource() {
// Spring may not know the real resource name so we check a flag
// to prevent loading again a resource twice
// this flag is set at XMLMapperBuilder#bindMapperForNamespace
if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
String xmlResource = type.getName().replace('.', '/') + ".xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
} catch (IOException e) {
// ignore, resource is not required
}
if (inputStream != null) {
XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
xmlParser.parse();
}
}
}
private void parseCache() {
CacheNamespace cacheDomain = type.getAnnotation(CacheNamespace.class);
if (cacheDomain != null) {
assistant.useNewCache(cacheDomain.implementation(), cacheDomain.eviction(), cacheDomain.flushInterval(), cacheDomain.size(), cacheDomain.readWrite(), null);
}
}
private void parseCacheRef() {
CacheNamespaceRef cacheDomainRef = type.getAnnotation(CacheNamespaceRef.class);
if (cacheDomainRef != null) {
assistant.useCacheRef(cacheDomainRef.value().getName());
}
}
private void parseResultsAndConstructorArgs(Method method) {
Class<?> returnType = getReturnType(method);
if (returnType != null) {
ConstructorArgs args = method.getAnnotation(ConstructorArgs.class);
Results results = method.getAnnotation(Results.class);
TypeDiscriminator typeDiscriminator = method.getAnnotation(TypeDiscriminator.class);
String resultMapId = generateResultMapName(method);
applyResultMap(resultMapId, returnType, argsIf(args), resultsIf(results), typeDiscriminator);
}
}
private String generateResultMapName(Method method) {
StringBuilder suffix = new StringBuilder();
for (Class<?> c : method.getParameterTypes()) {
suffix.append("-");
suffix.append(c.getSimpleName());
}
if (suffix.length() < 1) {
suffix.append("-void");
}
return type.getName() + "." + method.getName() + suffix;
}
private void applyResultMap(String resultMapId, Class<?> returnType, Arg[] args, Result[] results, TypeDiscriminator discriminator) {
List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
applyConstructorArgs(args, returnType, resultMappings);
applyResults(results, returnType, resultMappings);
Discriminator disc = applyDiscriminator(resultMapId, returnType, discriminator);
assistant.addResultMap(resultMapId, returnType, null, disc, resultMappings);
createDiscriminatorResultMaps(resultMapId, returnType, discriminator);
}
private void createDiscriminatorResultMaps(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) {
if (discriminator != null) {
for (Case c : discriminator.cases()) {
String value = c.value();
Class<?> type = c.type();
String caseResultMapId = resultMapId + "-" + value;
List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
for (Result result : c.results()) {
List<ResultFlag> flags = new ArrayList<ResultFlag>();
if (result.id()) {
flags.add(ResultFlag.ID);
}
ResultMapping resultMapping = assistant.buildResultMapping(
resultType,
nullOrEmpty(result.property()),
nullOrEmpty(result.column()),
result.javaType() == void.class ? null : result.javaType(),
result.jdbcType() == JdbcType.UNDEFINED ? null : result.jdbcType(),
hasNestedSelect(result) ? nestedSelectId(result) : null,
null,
null,
null,
result.typeHandler() == UnknownTypeHandler.class ? null : result.typeHandler(),
flags);
resultMappings.add(resultMapping);
}
assistant.addResultMap(caseResultMapId, type, resultMapId, null, resultMappings);
}
}
}
private Discriminator applyDiscriminator(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) {
if (discriminator != null) {
String column = discriminator.column();
Class<?> javaType = discriminator.javaType() == void.class ? String.class : discriminator.javaType();
JdbcType jdbcType = discriminator.jdbcType() == JdbcType.UNDEFINED ? null : discriminator.jdbcType();
Class<? extends TypeHandler<?>> typeHandler = discriminator.typeHandler() == UnknownTypeHandler.class ? null : discriminator.typeHandler();
Case[] cases = discriminator.cases();
Map<String, String> discriminatorMap = new HashMap<String, String>();
for (Case c : cases) {
String value = c.value();
String caseResultMapId = resultMapId + "-" + value;
discriminatorMap.put(value, caseResultMapId);
}
return assistant.buildDiscriminator(resultType, column, javaType, jdbcType, typeHandler, discriminatorMap);
}
return null;
}
private void parseStatement(Method method) {
SqlSource sqlSource = getSqlSourceFromAnnotations(method);
if (sqlSource != null) {
Options options = method.getAnnotation(Options.class);
final String mappedStatementId = type.getName() + "." + method.getName();
- boolean flushCache = false;
- boolean useCache = true;
Integer fetchSize = null;
Integer timeout = null;
StatementType statementType = StatementType.PREPARED;
ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
SqlCommandType sqlCommandType = getSqlCommandType(method);
+ boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
+ boolean flushCache = !isSelect;
+ boolean useCache = isSelect;
KeyGenerator keyGenerator;
String keyProperty = "id";
String keyColumn = null;
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
// first check for SelectKey annotation - that overrides everything else
SelectKey selectKey = method.getAnnotation(SelectKey.class);
if (selectKey != null) {
keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method));
keyProperty = selectKey.keyProperty();
} else {
if (options == null) {
keyGenerator = configuration.isUseGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
} else {
keyGenerator = options.useGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
keyProperty = options.keyProperty();
keyColumn = options.keyColumn();
}
}
} else {
keyGenerator = new NoKeyGenerator();
}
if (options != null) {
flushCache = options.flushCache();
useCache = options.useCache();
fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
timeout = options.timeout() > -1 ? options.timeout() : null;
statementType = options.statementType();
resultSetType = options.resultSetType();
}
ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
String resultMapId;
if (resultMapAnnotation == null) {
resultMapId = generateResultMapName(method);
} else {
resultMapId = resultMapAnnotation.value();
}
assistant.addMappedStatement(
mappedStatementId,
sqlSource,
statementType,
sqlCommandType,
fetchSize,
timeout,
null, // ParameterMapID
getParameterType(method),
resultMapId, // ResultMapID
getReturnType(method),
resultSetType,
flushCache,
useCache,
keyGenerator,
keyProperty,
keyColumn,
null);
}
}
private Class<?> getParameterType(Method method) {
Class<?> parameterType = null;
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (!RowBounds.class.isAssignableFrom(parameterTypes[i])) {
if (parameterType == null) {
parameterType = parameterTypes[i];
} else {
parameterType = Map.class;
}
}
}
return parameterType;
}
private Class<?> getReturnType(Method method) {
Class<?> returnType = method.getReturnType();
if (Collection.class.isAssignableFrom(returnType)) {
Type returnTypeParameter = method.getGenericReturnType();
if (returnTypeParameter instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) returnTypeParameter).getActualTypeArguments();
if (actualTypeArguments != null && actualTypeArguments.length == 1) {
returnTypeParameter = actualTypeArguments[0];
if (returnTypeParameter instanceof Class) {
returnType = (Class<?>) returnTypeParameter;
} else if (returnTypeParameter instanceof ParameterizedType) { // (issue 443) actual type can be a also a parametrized type
returnType = (Class<?>) ((ParameterizedType) returnTypeParameter).getRawType();
}
}
}
} else if (method.isAnnotationPresent(MapKey.class) && Map.class.isAssignableFrom(returnType)) {
// (issue 504) Do not look into Maps if there is not MapKey annotation
Type returnTypeParameter = method.getGenericReturnType();
if (returnTypeParameter instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) returnTypeParameter).getActualTypeArguments();
if (actualTypeArguments != null && actualTypeArguments.length == 2) {
returnTypeParameter = actualTypeArguments[1];
if (returnTypeParameter instanceof Class) {
returnType = (Class<?>) returnTypeParameter;
} else if (returnTypeParameter instanceof ParameterizedType) { // (issue 443) actual type can be a also a parametrized type
returnType = (Class<?>) ((ParameterizedType) returnTypeParameter).getRawType();
}
}
}
}
return returnType;
}
private SqlSource getSqlSourceFromAnnotations(Method method) {
try {
Class<? extends Annotation> sqlAnnotationType = getSqlAnnotationType(method);
Class<? extends Annotation> sqlProviderAnnotationType = getSqlProviderAnnotationType(method);
if (sqlAnnotationType != null) {
if (sqlProviderAnnotationType != null) {
throw new BindingException("You cannot supply both a static SQL and SqlProvider to method named " + method.getName());
}
Annotation sqlAnnotation = method.getAnnotation(sqlAnnotationType);
final String[] strings = (String[]) sqlAnnotation.getClass().getMethod("value").invoke(sqlAnnotation);
return buildSqlSourceFromStrings(strings);
} else if (sqlProviderAnnotationType != null) {
Annotation sqlProviderAnnotation = method.getAnnotation(sqlProviderAnnotationType);
return new ProviderSqlSource(assistant.getConfiguration(), sqlProviderAnnotation);
}
return null;
} catch (Exception e) {
throw new BuilderException("Could not find value method on SQL annotation. Cause: " + e, e);
}
}
private SqlSource buildSqlSourceFromStrings(String[] strings) {
final StringBuilder sql = new StringBuilder();
for (String fragment : strings) {
sql.append(fragment);
sql.append(" ");
}
ArrayList<SqlNode> contents = new ArrayList<SqlNode>();
contents.add(new TextSqlNode(sql.toString()));
MixedSqlNode rootSqlNode = new MixedSqlNode(contents);
return new DynamicSqlSource(configuration, rootSqlNode);
}
private SqlCommandType getSqlCommandType(Method method) {
Class<? extends Annotation> type = getSqlAnnotationType(method);
if (type == null) {
type = getSqlProviderAnnotationType(method);
if (type == null) {
return SqlCommandType.UNKNOWN;
}
if (type == SelectProvider.class) {
type = Select.class;
} else if (type == InsertProvider.class) {
type = Insert.class;
} else if (type == UpdateProvider.class) {
type = Update.class;
} else if (type == DeleteProvider.class) {
type = Delete.class;
}
}
return SqlCommandType.valueOf(type.getSimpleName().toUpperCase(Locale.ENGLISH));
}
private Class<? extends Annotation> getSqlAnnotationType(Method method) {
return chooseAnnotationType(method, sqlAnnotationTypes);
}
private Class<? extends Annotation> getSqlProviderAnnotationType(Method method) {
return chooseAnnotationType(method, sqlProviderAnnotationTypes);
}
private Class<? extends Annotation> chooseAnnotationType(Method method, Set<Class<? extends Annotation>> types) {
for (Class<? extends Annotation> type : types) {
Annotation annotation = method.getAnnotation(type);
if (annotation != null) {
return type;
}
}
return null;
}
private void applyResults(Result[] results, Class<?> resultType, List<ResultMapping> resultMappings) {
if (results.length > 0) {
for (Result result : results) {
ArrayList<ResultFlag> flags = new ArrayList<ResultFlag>();
if (result.id())
flags.add(ResultFlag.ID);
ResultMapping resultMapping = assistant.buildResultMapping(
resultType,
nullOrEmpty(result.property()),
nullOrEmpty(result.column()),
result.javaType() == void.class ? null : result.javaType(),
result.jdbcType() == JdbcType.UNDEFINED ? null : result.jdbcType(),
hasNestedSelect(result) ? nestedSelectId(result) : null,
null,
null,
null,
result.typeHandler() == UnknownTypeHandler.class ? null : result.typeHandler(),
flags);
resultMappings.add(resultMapping);
}
}
}
private String nestedSelectId(Result result) {
String nestedSelect = result.one().select();
if (nestedSelect.length() < 1) {
nestedSelect = result.many().select();
}
if (!nestedSelect.contains(".")) {
nestedSelect = type.getName() + "." + nestedSelect;
}
return nestedSelect;
}
private boolean hasNestedSelect(Result result) {
return result.one().select().length() > 0 || result.many().select().length() > 0;
}
private void applyConstructorArgs(Arg[] args, Class<?> resultType, List<ResultMapping> resultMappings) {
if (args.length > 0) {
for (Arg arg : args) {
ArrayList<ResultFlag> flags = new ArrayList<ResultFlag>();
flags.add(ResultFlag.CONSTRUCTOR);
if (arg.id()) flags.add(ResultFlag.ID);
ResultMapping resultMapping = assistant.buildResultMapping(
resultType,
null,
nullOrEmpty(arg.column()),
arg.javaType() == void.class ? null : arg.javaType(),
arg.jdbcType() == JdbcType.UNDEFINED ? null : arg.jdbcType(),
nullOrEmpty(arg.select()),
nullOrEmpty(arg.resultMap()),
null,
null,
arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler(),
flags);
resultMappings.add(resultMapping);
}
}
}
private String nullOrEmpty(String value) {
return value == null || value.trim().length() == 0 ? null : value;
}
private Result[] resultsIf(Results results) {
return results == null ? new Result[0] : results.value();
}
private Arg[] argsIf(ConstructorArgs args) {
return args == null ? new Arg[0] : args.value();
}
private KeyGenerator handleSelectKeyAnnotation(SelectKey selectKeyAnnotation, String baseStatementId, Class<?> parameterTypeClass) {
String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
Class<?> resultTypeClass = selectKeyAnnotation.resultType();
StatementType statementType = selectKeyAnnotation.statementType();
String keyProperty = selectKeyAnnotation.keyProperty();
boolean executeBefore = selectKeyAnnotation.before();
// defaults
boolean useCache = false;
KeyGenerator keyGenerator = new NoKeyGenerator();
Integer fetchSize = null;
Integer timeout = null;
boolean flushCache = false;
String parameterMap = null;
String resultMap = null;
ResultSetType resultSetTypeEnum = null;
SqlSource sqlSource = buildSqlSourceFromStrings(selectKeyAnnotation.statement());
SqlCommandType sqlCommandType = SqlCommandType.SELECT;
assistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum,
flushCache, useCache, keyGenerator, keyProperty, null, null);
id = assistant.applyCurrentNamespace(id, false);
MappedStatement keyStatement = configuration.getMappedStatement(id, false);
SelectKeyGenerator answer = new SelectKeyGenerator(keyStatement, executeBefore);
configuration.addKeyGenerator(id, answer);
return answer;
}
}
| false | true | private void parseStatement(Method method) {
SqlSource sqlSource = getSqlSourceFromAnnotations(method);
if (sqlSource != null) {
Options options = method.getAnnotation(Options.class);
final String mappedStatementId = type.getName() + "." + method.getName();
boolean flushCache = false;
boolean useCache = true;
Integer fetchSize = null;
Integer timeout = null;
StatementType statementType = StatementType.PREPARED;
ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
SqlCommandType sqlCommandType = getSqlCommandType(method);
KeyGenerator keyGenerator;
String keyProperty = "id";
String keyColumn = null;
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
// first check for SelectKey annotation - that overrides everything else
SelectKey selectKey = method.getAnnotation(SelectKey.class);
if (selectKey != null) {
keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method));
keyProperty = selectKey.keyProperty();
} else {
if (options == null) {
keyGenerator = configuration.isUseGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
} else {
keyGenerator = options.useGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
keyProperty = options.keyProperty();
keyColumn = options.keyColumn();
}
}
} else {
keyGenerator = new NoKeyGenerator();
}
if (options != null) {
flushCache = options.flushCache();
useCache = options.useCache();
fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
timeout = options.timeout() > -1 ? options.timeout() : null;
statementType = options.statementType();
resultSetType = options.resultSetType();
}
ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
String resultMapId;
if (resultMapAnnotation == null) {
resultMapId = generateResultMapName(method);
} else {
resultMapId = resultMapAnnotation.value();
}
assistant.addMappedStatement(
mappedStatementId,
sqlSource,
statementType,
sqlCommandType,
fetchSize,
timeout,
null, // ParameterMapID
getParameterType(method),
resultMapId, // ResultMapID
getReturnType(method),
resultSetType,
flushCache,
useCache,
keyGenerator,
keyProperty,
keyColumn,
null);
}
}
| private void parseStatement(Method method) {
SqlSource sqlSource = getSqlSourceFromAnnotations(method);
if (sqlSource != null) {
Options options = method.getAnnotation(Options.class);
final String mappedStatementId = type.getName() + "." + method.getName();
Integer fetchSize = null;
Integer timeout = null;
StatementType statementType = StatementType.PREPARED;
ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
SqlCommandType sqlCommandType = getSqlCommandType(method);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = !isSelect;
boolean useCache = isSelect;
KeyGenerator keyGenerator;
String keyProperty = "id";
String keyColumn = null;
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
// first check for SelectKey annotation - that overrides everything else
SelectKey selectKey = method.getAnnotation(SelectKey.class);
if (selectKey != null) {
keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method));
keyProperty = selectKey.keyProperty();
} else {
if (options == null) {
keyGenerator = configuration.isUseGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
} else {
keyGenerator = options.useGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
keyProperty = options.keyProperty();
keyColumn = options.keyColumn();
}
}
} else {
keyGenerator = new NoKeyGenerator();
}
if (options != null) {
flushCache = options.flushCache();
useCache = options.useCache();
fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
timeout = options.timeout() > -1 ? options.timeout() : null;
statementType = options.statementType();
resultSetType = options.resultSetType();
}
ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
String resultMapId;
if (resultMapAnnotation == null) {
resultMapId = generateResultMapName(method);
} else {
resultMapId = resultMapAnnotation.value();
}
assistant.addMappedStatement(
mappedStatementId,
sqlSource,
statementType,
sqlCommandType,
fetchSize,
timeout,
null, // ParameterMapID
getParameterType(method),
resultMapId, // ResultMapID
getReturnType(method),
resultSetType,
flushCache,
useCache,
keyGenerator,
keyProperty,
keyColumn,
null);
}
}
|
diff --git a/src/net/sf/egonet/persistence/DB.java b/src/net/sf/egonet/persistence/DB.java
index bbb4820..bdce015 100644
--- a/src/net/sf/egonet/persistence/DB.java
+++ b/src/net/sf/egonet/persistence/DB.java
@@ -1,84 +1,88 @@
package net.sf.egonet.persistence;
import net.sf.egonet.model.Entity;
import net.sf.egonet.web.Main;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.google.common.base.Function;
public class DB {
static void save(Session session, Entity e) {
session.saveOrUpdate(e);
}
public static void save(final Entity e) {
withTx(new Function<Session,Object>(){
public Object apply(Session s) {
save(s,e);
return null;
}
});
}
static void delete(Session s, Entity e) {
e.setActive(false);
s.saveOrUpdate(e);
}
static void delete(final Entity e) {
withTx(new Function<Session,Object>(){
public Object apply(Session s) {
delete(s,e);
return null;
}
});
}
static <E> E withTx(Function<Session,E> f) {
Session session = Main.getDBSessionFactory().openSession();
Transaction tx = session.beginTransaction();
E result = f.apply(session);
tx.commit();
session.close();
return result;
}
static abstract class Action<R> implements Function<Session,R> {
protected Session session;
public R apply(Session session) {
this.session = session;
return get();
}
public abstract R get();
public R execute() {
return withTx(this);
}
}
public static void migrate() {
new Action<Object>() {
public Object get() {
// TODO: Need to store schema version so each migration can be applied exactly once.
+ session.createSQLQuery(
+ "create index idx_questionoption_qid_ord on " +
+ "question_option(question_id,ordering)")
+ .executeUpdate();
/*
for(String entity : new String[]{
"Alter","Answer","Expression","Interview","Question","QuestionOption","Study"})
{
this.session.createQuery(
"update "+entity+" set active = 1 where active is null")
.executeUpdate();
}
*/
return null;
}
}.execute();
}
}
| true | true | public static void migrate() {
new Action<Object>() {
public Object get() {
// TODO: Need to store schema version so each migration can be applied exactly once.
/*
for(String entity : new String[]{
"Alter","Answer","Expression","Interview","Question","QuestionOption","Study"})
{
this.session.createQuery(
"update "+entity+" set active = 1 where active is null")
.executeUpdate();
}
*/
return null;
}
}.execute();
}
| public static void migrate() {
new Action<Object>() {
public Object get() {
// TODO: Need to store schema version so each migration can be applied exactly once.
session.createSQLQuery(
"create index idx_questionoption_qid_ord on " +
"question_option(question_id,ordering)")
.executeUpdate();
/*
for(String entity : new String[]{
"Alter","Answer","Expression","Interview","Question","QuestionOption","Study"})
{
this.session.createQuery(
"update "+entity+" set active = 1 where active is null")
.executeUpdate();
}
*/
return null;
}
}.execute();
}
|
diff --git a/src/main/java/org/uncertweb/aquacrop/AquaCropInterface.java b/src/main/java/org/uncertweb/aquacrop/AquaCropInterface.java
index e3f5003..b70c2fb 100644
--- a/src/main/java/org/uncertweb/aquacrop/AquaCropInterface.java
+++ b/src/main/java/org/uncertweb/aquacrop/AquaCropInterface.java
@@ -1,226 +1,230 @@
package org.uncertweb.aquacrop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uncertweb.aquacrop.data.Output;
import org.uncertweb.aquacrop.data.Project;
/**
* Okay...
*
* The AquaCrop plug-in program has no UI, but creates an application window when it runs
* (containing nothing, disappears upon program termination).
*
* Therefore running the plug-in program with Wine results in the following:
* - Application tried to create a window, but no driver could be loaded.
* - Make sure that your X server is running and that $DISPLAY is set correctly.
*
* As we want to run the program behind a web service interface, on a server somewhere, which
* may or may not have X server running or a display, this poses an issue!
*
* The solution is Xvfb.
*
* The xvfb-run script creates...
*
*
*
* @author Richard Jones
*
*/
public class AquaCropInterface {
private final Logger logger = LoggerFactory.getLogger(AquaCropInterface.class);
private String basePath;
private String prefixCommand;
private String basePathOverride;
public AquaCropInterface(String basePath) {
this.basePath = basePath;
}
/**
*
*
*
* @param basePath
* @param prefixCommand
*/
public AquaCropInterface(String basePath, String prefixCommand, String basePathOverride) {
this(basePath);
this.prefixCommand = prefixCommand;
this.basePathOverride = basePathOverride;
}
public Output run(Project project) throws AquaCropException {
// check given params are sensible
preRunChecks();
// generate an id
final String runId = String.valueOf(System.currentTimeMillis());
// generate run folder
File runDir = new File(basePath, "aquacrop_" + runId);
String runPath = runDir.getAbsolutePath();
try {
FileUtils.copyDirectoryToDirectory(new File(basePath, "ACsaV31plus"), runDir);
FileUtils.copyDirectoryToDirectory(new File(basePath, "AquaCrop"), runDir);
}
catch (IOException e) {
throw new AquaCropException("Couldn't create run directory.", e);
}
// serialize project and run
+ Output output = null;
try {
// this will create all data files
if (basePathOverride != null) {
basePathOverride = basePathOverride + "\\" + runDir.getName() + "\\AquaCrop\\DATA";
}
logger.debug("Serializing project...");
AquaCropSerializer serializer = new AquaCropSerializer("project", runPath, basePathOverride);
serializer.serialize(project);
// move files
// PRO to ACsaV31plus/LIST/
// everything else to AquaCrop/DATA/
moveFile(runPath, "project.PRO", "ACsaV31plus/LIST/");
moveFile(runPath, "project.CLI", "AquaCrop/DATA/");
moveFile(runPath, "project.CRO", "AquaCrop/DATA/");
moveFile(runPath, "project.PLU", "AquaCrop/DATA/");
moveFile(runPath, "project.TMP", "AquaCrop/DATA/");
moveFile(runPath, "project.SOL", "AquaCrop/DATA/");
moveFile(runPath, "project.CO2", "AquaCrop/DATA/");
moveFile(runPath, "project.ETO", "AquaCrop/DATA/");
// get runtime
logger.debug("Getting runtime...");
Runtime runtime = Runtime.getRuntime();
// for monitoring and reading
File outputFile = new File(runPath, "ACsaV31plus/OUTP/projectPRO.OUT");
// run program
try {
// start aquacrop process
logger.debug("Starting process...");
Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + runPath + "/ACsaV31plus/ACsaV31plus.exe");
// wait for process
// we could be waiting forever if no output is produced
logger.debug("Waiting for process to end...");
boolean done = false;
while (!done) {
if (outputFile.exists()) {
done = true;
Thread.sleep(2000); // wait for write
process.destroy(); // force required if error
}
else {
Thread.sleep(500);
}
}
process.waitFor();
}
catch (IOException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
catch (InterruptedException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
// parse output
logger.debug("Process finished, parsing output...");
FileReader reader = new FileReader(outputFile);
- Output output = AquaCropInterface.deserializeOutput(reader);
+ output = AquaCropInterface.deserializeOutput(reader);
reader.close();
if (output == null) {
// must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs!
String message = "Couldn't parse empty AquaCrop output, parameters may be invalid.";
throw new AquaCropException(message);
}
else {
logger.debug("Parsed output successfully.");
return output;
- }
+ }
}
catch (IOException e) {
// will be from creating the project file, or reading the output file
String message = "Error reading input/output files: " + e.getMessage();
throw new AquaCropException(message, e);
}
finally {
// clean up input files
try {
- FileUtils.deleteDirectory(runDir);
+ // helps debugging
+ if (output != null) {
+ FileUtils.deleteDirectory(runDir);
+ }
}
catch (IOException e) {
logger.warn("Couldn't remove output directory.", e);
}
}
}
private void preRunChecks() throws AquaCropException {
// check given params are sensible
boolean basePathExists = new File(basePath).exists();
if (!basePathExists) {
throw new AquaCropException("Can't find AquaCrop executables at " + basePath + ".");
}
}
private void moveFile(String path, String filename, String dest) {
File file = new File(new File(path), filename);
file.renameTo(new File(new File(path, dest), filename));
}
private static Output deserializeOutput(Reader reader) throws FileNotFoundException, IOException {
BufferedReader bufReader = new BufferedReader(reader);
bufReader.readLine(); // skip first line containing aquacrop version, creation date
bufReader.readLine(); // skip following empty line
bufReader.readLine(); // skip column headings
bufReader.readLine(); // skip column headings units
String line;
while ((line = bufReader.readLine()) != null && line.length() > 0) { // could be blank line at bottom
// split on whitespace
String[] tokens = line.trim().split("\\s+");
// totals is all we want
if (tokens[0].startsWith("Tot")) {
// parse results
double rain = Double.parseDouble(tokens[4]);
double eto = Double.parseDouble(tokens[5]);
double gdd = Double.parseDouble(tokens[6]);
double co2 = Double.parseDouble(tokens[7]);
double irri = Double.parseDouble(tokens[8]);
double infilt = Double.parseDouble(tokens[9]);
double e = Double.parseDouble(tokens[10]);
double eEx = Double.parseDouble(tokens[11]);
double tr = Double.parseDouble(tokens[12]);
double trTrx = Double.parseDouble(tokens[13]);
double drain = Double.parseDouble(tokens[14]);
double bioMass = Double.parseDouble(tokens[15]);
double brW = Double.parseDouble(tokens[16]);
double brWsf = Double.parseDouble(tokens[17]);
double wPetB = Double.parseDouble(tokens[18]);
double hi = Double.parseDouble(tokens[19]);
double yield = Double.parseDouble(tokens[20]);
double wPetY = Double.parseDouble(tokens[21]);
// and return
return new Output(rain, eto, gdd, co2, irri, infilt, e, eEx, tr, trTrx, drain, bioMass, brW, brWsf, wPetB, hi, yield, wPetY);
}
}
return null;
}
}
| false | true | public Output run(Project project) throws AquaCropException {
// check given params are sensible
preRunChecks();
// generate an id
final String runId = String.valueOf(System.currentTimeMillis());
// generate run folder
File runDir = new File(basePath, "aquacrop_" + runId);
String runPath = runDir.getAbsolutePath();
try {
FileUtils.copyDirectoryToDirectory(new File(basePath, "ACsaV31plus"), runDir);
FileUtils.copyDirectoryToDirectory(new File(basePath, "AquaCrop"), runDir);
}
catch (IOException e) {
throw new AquaCropException("Couldn't create run directory.", e);
}
// serialize project and run
try {
// this will create all data files
if (basePathOverride != null) {
basePathOverride = basePathOverride + "\\" + runDir.getName() + "\\AquaCrop\\DATA";
}
logger.debug("Serializing project...");
AquaCropSerializer serializer = new AquaCropSerializer("project", runPath, basePathOverride);
serializer.serialize(project);
// move files
// PRO to ACsaV31plus/LIST/
// everything else to AquaCrop/DATA/
moveFile(runPath, "project.PRO", "ACsaV31plus/LIST/");
moveFile(runPath, "project.CLI", "AquaCrop/DATA/");
moveFile(runPath, "project.CRO", "AquaCrop/DATA/");
moveFile(runPath, "project.PLU", "AquaCrop/DATA/");
moveFile(runPath, "project.TMP", "AquaCrop/DATA/");
moveFile(runPath, "project.SOL", "AquaCrop/DATA/");
moveFile(runPath, "project.CO2", "AquaCrop/DATA/");
moveFile(runPath, "project.ETO", "AquaCrop/DATA/");
// get runtime
logger.debug("Getting runtime...");
Runtime runtime = Runtime.getRuntime();
// for monitoring and reading
File outputFile = new File(runPath, "ACsaV31plus/OUTP/projectPRO.OUT");
// run program
try {
// start aquacrop process
logger.debug("Starting process...");
Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + runPath + "/ACsaV31plus/ACsaV31plus.exe");
// wait for process
// we could be waiting forever if no output is produced
logger.debug("Waiting for process to end...");
boolean done = false;
while (!done) {
if (outputFile.exists()) {
done = true;
Thread.sleep(2000); // wait for write
process.destroy(); // force required if error
}
else {
Thread.sleep(500);
}
}
process.waitFor();
}
catch (IOException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
catch (InterruptedException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
// parse output
logger.debug("Process finished, parsing output...");
FileReader reader = new FileReader(outputFile);
Output output = AquaCropInterface.deserializeOutput(reader);
reader.close();
if (output == null) {
// must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs!
String message = "Couldn't parse empty AquaCrop output, parameters may be invalid.";
throw new AquaCropException(message);
}
else {
logger.debug("Parsed output successfully.");
return output;
}
}
catch (IOException e) {
// will be from creating the project file, or reading the output file
String message = "Error reading input/output files: " + e.getMessage();
throw new AquaCropException(message, e);
}
finally {
// clean up input files
try {
FileUtils.deleteDirectory(runDir);
}
catch (IOException e) {
logger.warn("Couldn't remove output directory.", e);
}
}
}
| public Output run(Project project) throws AquaCropException {
// check given params are sensible
preRunChecks();
// generate an id
final String runId = String.valueOf(System.currentTimeMillis());
// generate run folder
File runDir = new File(basePath, "aquacrop_" + runId);
String runPath = runDir.getAbsolutePath();
try {
FileUtils.copyDirectoryToDirectory(new File(basePath, "ACsaV31plus"), runDir);
FileUtils.copyDirectoryToDirectory(new File(basePath, "AquaCrop"), runDir);
}
catch (IOException e) {
throw new AquaCropException("Couldn't create run directory.", e);
}
// serialize project and run
Output output = null;
try {
// this will create all data files
if (basePathOverride != null) {
basePathOverride = basePathOverride + "\\" + runDir.getName() + "\\AquaCrop\\DATA";
}
logger.debug("Serializing project...");
AquaCropSerializer serializer = new AquaCropSerializer("project", runPath, basePathOverride);
serializer.serialize(project);
// move files
// PRO to ACsaV31plus/LIST/
// everything else to AquaCrop/DATA/
moveFile(runPath, "project.PRO", "ACsaV31plus/LIST/");
moveFile(runPath, "project.CLI", "AquaCrop/DATA/");
moveFile(runPath, "project.CRO", "AquaCrop/DATA/");
moveFile(runPath, "project.PLU", "AquaCrop/DATA/");
moveFile(runPath, "project.TMP", "AquaCrop/DATA/");
moveFile(runPath, "project.SOL", "AquaCrop/DATA/");
moveFile(runPath, "project.CO2", "AquaCrop/DATA/");
moveFile(runPath, "project.ETO", "AquaCrop/DATA/");
// get runtime
logger.debug("Getting runtime...");
Runtime runtime = Runtime.getRuntime();
// for monitoring and reading
File outputFile = new File(runPath, "ACsaV31plus/OUTP/projectPRO.OUT");
// run program
try {
// start aquacrop process
logger.debug("Starting process...");
Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + runPath + "/ACsaV31plus/ACsaV31plus.exe");
// wait for process
// we could be waiting forever if no output is produced
logger.debug("Waiting for process to end...");
boolean done = false;
while (!done) {
if (outputFile.exists()) {
done = true;
Thread.sleep(2000); // wait for write
process.destroy(); // force required if error
}
else {
Thread.sleep(500);
}
}
process.waitFor();
}
catch (IOException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
catch (InterruptedException e) {
throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage(), e);
}
// parse output
logger.debug("Process finished, parsing output...");
FileReader reader = new FileReader(outputFile);
output = AquaCropInterface.deserializeOutput(reader);
reader.close();
if (output == null) {
// must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs!
String message = "Couldn't parse empty AquaCrop output, parameters may be invalid.";
throw new AquaCropException(message);
}
else {
logger.debug("Parsed output successfully.");
return output;
}
}
catch (IOException e) {
// will be from creating the project file, or reading the output file
String message = "Error reading input/output files: " + e.getMessage();
throw new AquaCropException(message, e);
}
finally {
// clean up input files
try {
// helps debugging
if (output != null) {
FileUtils.deleteDirectory(runDir);
}
}
catch (IOException e) {
logger.warn("Couldn't remove output directory.", e);
}
}
}
|
diff --git a/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java b/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
index 0acd55cb..958c0394 100644
--- a/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
+++ b/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
@@ -1,1619 +1,1632 @@
/*
* @(#)BasicStyledLabelUI.java 9/6/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.plaf.basic;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.StyleRange;
import com.jidesoft.swing.StyledLabel;
import com.jidesoft.swing.FontUtils;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicLabelUI;
import javax.swing.text.View;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class BasicStyledLabelUI extends BasicLabelUI implements SwingConstants {
public static Comparator<StyleRange> _comparator;
protected static BasicStyledLabelUI styledLabelUI = new BasicStyledLabelUI();
@SuppressWarnings({"UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return styledLabelUI;
}
class StyledText {
StyleRange styleRange;
String text;
public StyledText(String text) {
this.text = text;
}
public StyledText(String text, StyleRange styleRange) {
this.text = text;
this.styleRange = styleRange;
}
}
private final List<StyledText> _styledTexts = new ArrayList<StyledText>();
private int _preferredRowCount = 1;
@Override
public void propertyChange(PropertyChangeEvent e) {
super.propertyChange(e);
if (StyledLabel.PROPERTY_STYLE_RANGE.equals(e.getPropertyName())) {
synchronized (_styledTexts) {
_styledTexts.clear();
}
if (e.getSource() instanceof StyledLabel) {
((StyledLabel) e.getSource()).revalidate();
((StyledLabel) e.getSource()).repaint();
}
}
else if (StyledLabel.PROPERTY_IGNORE_COLOR_SETTINGS.equals(e.getPropertyName())) {
if (e.getSource() instanceof StyledLabel) {
((StyledLabel) e.getSource()).repaint();
}
}
}
@Override
protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY) {
View v = (l != null) ? (View) l.getClientProperty("html") : null;
if (v != null) {
super.paintEnabledText(l, g, s, textX, textY);
}
else {
paintStyledText((StyledLabel) l, g, textX, textY);
}
}
@Override
protected void paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY) {
View v = (l != null) ? (View) l.getClientProperty("html") : null;
if (v != null) {
super.paintDisabledText(l, g, s, textX, textY);
}
else {
paintStyledText((StyledLabel) l, g, textX, textY);
}
}
protected void buildStyledText(StyledLabel label) {
synchronized (_styledTexts) {
_styledTexts.clear();
StyleRange[] styleRanges = label.getStyleRanges();
if (_comparator == null) {
_comparator = new Comparator<StyleRange>() {
public int compare(StyleRange r1, StyleRange r2) {
if (r1.getStart() < r2.getStart()) {
return -1;
}
else if (r1.getStart() > r2.getStart()) {
return 1;
}
else {
return 0;
}
}
};
}
Arrays.sort(styleRanges, _comparator);
String s = label.getText();
if (s != null && s.length() > 0) { // do not do anything if the text is empty
int index = 0;
for (StyleRange styleRange : styleRanges) {
if (styleRange.getStart() > index) { // fill in the gap
String text = s.substring(index, styleRange.getStart());
StyleRange newRange = new StyleRange(index, styleRange.getStart() - index, -1);
addStyledTexts(text, newRange);
index = styleRange.getStart();
}
if (styleRange.getStart() == index) { // exactly on
if (styleRange.getLength() == -1) {
String text = s.substring(index);
addStyledTexts(text, styleRange);
index = s.length();
}
else {
String text = s.substring(index, Math.min(index + styleRange.getLength(), s.length()));
addStyledTexts(text, styleRange);
index += styleRange.getLength();
}
}
else if (styleRange.getStart() < index) { // overlap
// ignore
}
}
if (index < s.length()) {
String text = s.substring(index, s.length());
StyleRange range = new StyleRange(index, s.length() - index, -1);
addStyledTexts(text, range);
}
}
}
}
private void addStyledTexts(String text, StyleRange range) {
range = new StyleRange(range); // keep the passed-in parameter no change
int index1 = text.indexOf('\r');
int index2 = text.indexOf('\n');
while (index1 >= 0 || index2 >= 0) {
int index = index1 >= 0 ? index1 : -1;
if (index2 >= 0 && (index2 < index1 || index < 0)) {
index = index2;
}
String subString = text.substring(0, index);
StyleRange newRange = new StyleRange(range);
newRange.setStart(range.getStart());
newRange.setLength(index);
_styledTexts.add(new StyledText(subString, newRange));
int length = 1;
if (text.charAt(index) == '\r' && index + 1 < text.length() && text.charAt(index + 1) == '\n') {
length++;
}
newRange = new StyleRange(range);
newRange.setStart(range.getStart() + index);
newRange.setLength(length);
_styledTexts.add(new StyledText(text.substring(index, index + length), newRange));
text = text.substring(index + length);
range.setStart(range.getStart() + index + length);
range.setLength(range.getLength() - index - length);
index1 = text.indexOf('\r');
index2 = text.indexOf('\n');
}
if (text.length() > 0) {
_styledTexts.add(new StyledText(text, range));
}
}
@Override
protected String layoutCL(JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) {
Dimension size = null;
if (label instanceof StyledLabel) {
int oldPreferredWidth = ((StyledLabel) label).getPreferredWidth();
int oldRows = ((StyledLabel) label).getRows();
try {
if (((StyledLabel) label).isLineWrap() && label.getWidth() > 0) {
((StyledLabel) label).setPreferredWidth(label.getWidth());
}
size = getPreferredSize((StyledLabel) label);
if (((StyledLabel) label).isLineWrap() && ((StyledLabel) label).getMinRows() > 0) {
((StyledLabel) label).setPreferredWidth(0);
((StyledLabel) label).setRows(0);
Dimension minSize = getPreferredSize((StyledLabel) label);
if (minSize.height > size.height) {
size = minSize;
}
}
}
finally {
((StyledLabel) label).setPreferredWidth(oldPreferredWidth);
((StyledLabel) label).setRows(oldRows);
}
}
else {
size = label.getPreferredSize();
}
textR.width = size.width;
textR.height = size.height;
return layoutCompoundLabel(
label,
fontMetrics,
text,
icon,
label.getVerticalAlignment(),
label.getHorizontalAlignment(),
label.getVerticalTextPosition(),
label.getHorizontalTextPosition(),
viewR,
iconR,
textR,
label.getIconTextGap());
}
protected Dimension getPreferredSize(StyledLabel label) {
buildStyledText(label);
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
int defaultFontSize = font.getSize();
boolean lineWrap = label.isLineWrap() || (label.getText() != null && (label.getText().contains("\r") || label.getText().contains("\n")));
synchronized (_styledTexts) {
StyledText[] texts = _styledTexts.toArray(new StyledText[_styledTexts.size()]);
// get maximum row height first by comparing all fonts of styled texts
int maxRowHeight = fm.getHeight();
for (StyledText styledText : texts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
int styleHeight = fm.getHeight();
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
styleHeight = fm2.getHeight();
}
styleHeight++;
/*
if (style != null) {
if (style.isWaved()) {
styleHeight += 4;
}
else if (style.isDotted()) {
styleHeight += 3;
}
else if (style.isUnderlined()) {
styleHeight += 2;
}
}
*/
maxRowHeight = Math.max(maxRowHeight, styleHeight);
}
int naturalRowCount = 1;
int nextRowStartIndex = 0;
int width = 0;
int maxWidth = 0;
// get one line width
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
String s = styledText.text.substring(nextRowStartIndex);
if (s.startsWith("\r") || s.startsWith("\n")) {
maxWidth = Math.max(width, maxWidth);
width = 0;
naturalRowCount++;
continue;
}
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
width += fm2.stringWidth(s);
}
else {
// fm2 = fm;
width += fm.stringWidth(s);
}
}
maxWidth = Math.max(width, maxWidth);
_preferredRowCount = naturalRowCount;
// if getPreferredWidth() is not set but getRows() is set, get maximum width and row count based on the required rows.
if (lineWrap && label.getPreferredWidth() <= 0 && label.getRows() > 0) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getRows());
}
// if calculated maximum width is larger than label's maximum size, wrap again to get the updated row count and use the label's maximum width as the maximum width.
if (lineWrap && label.getPreferredWidth() > 0 && maxWidth > label.getPreferredWidth()) {
maxWidth = getLayoutWidth(label, label.getPreferredWidth());
}
// label.getPreferredWidth() <= 0 && label.getMaxRows() > 0 && rowCount > label.getMaxRows(), recalculate the maximum width according to the maximum rows
if (lineWrap && label.getMaxRows() > 0 && _preferredRowCount > label.getMaxRows()) {
if (label.getPreferredWidth() <= 0) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getMaxRows());
}
else {
_preferredRowCount = label.getMaxRows();
}
}
// label.getPreferredWidth() <= 0 && label.getMinRows() > 0 && rowCount < label.getMinRows(), recalculate the maximum width according to the minimum rows
if (lineWrap && label.getPreferredWidth() <= 0 && label.getMinRows() > 0 && _preferredRowCount < label.getMinRows()) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getMinRows());
}
Insets insets = label.getInsets();
Dimension dimension = new Dimension(maxWidth, (maxRowHeight + Math.max(0, label.getRowGap())) * _preferredRowCount);
if (insets == null) {
return dimension;
}
else {
return new Dimension(dimension.width + insets.left + insets.right, dimension.height + insets.top + insets.bottom);
}
}
}
private int getLayoutWidth(StyledLabel label, int maxWidth) {
int nextRowStartIndex;
Font font = getFont(label);
int defaultFontSize = font.getSize();
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
nextRowStartIndex = 0;
int x = 0;
_preferredRowCount = 1;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
x = 0;
_preferredRowCount++;
continue;
}
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label); // cannot omit this one
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
String s = styledText.text.substring(nextRowStartIndex);
int strWidth = fm2.stringWidth(s);
boolean wrapped = false;
int widthLeft = maxWidth - x;
if (widthLeft < strWidth) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != 0) {
x = 0;
i--;
_preferredRowCount++;
if (label.getMaxRows() > 0 && _preferredRowCount >= label.getMaxRows()) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 5) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
nextRowStartIndex = 0;
}
if (wrapped) {
_preferredRowCount++;
x = 0;
i--;
}
else {
x += strWidth;
}
}
return maxWidth;
}
private int getMaximumWidth(StyledLabel label, int maxWidth, int naturalRowCount, int limitedRows) {
if (naturalRowCount > 1) {
int proposedMaxWidthMin = 1;
int proposedMaxWidthMax = maxWidth;
_preferredRowCount = naturalRowCount;
while (proposedMaxWidthMin < proposedMaxWidthMax) {
int middle = (proposedMaxWidthMax + proposedMaxWidthMin) / 2;
maxWidth = getLayoutWidth(label, middle);
if (_preferredRowCount > limitedRows) {
proposedMaxWidthMin = middle + 1;
_preferredRowCount = naturalRowCount;
}
else {
proposedMaxWidthMax = middle - 1;
}
}
return maxWidth + maxWidth / 20;
}
int estimatedWidth = maxWidth / limitedRows + 1;
int x = 0;
int nextRowStartIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
int defaultFontSize = font.getSize();
FontMetrics fm2;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
String s = styledText.text.substring(nextRowStartIndex);
int strWidth = fm2.stringWidth(s);
int widthLeft = estimatedWidth - x;
if (widthLeft < strWidth) {
int availLength = s.length() * widthLeft / strWidth + 1;
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
int nextWordStartIndex = findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (nextWordStartIndex < s.length()) {
firstRowWordEndIndex = findFirstRowWordEndIndex(s.substring(0, nextWordStartIndex));
}
else {
firstRowWordEndIndex = nextWordStartIndex;
}
}
int nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
nextRowStartIndexInSubString++;
if (strWidth >= widthLeft) {
break;
}
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
nextRowStartIndex += nextRowStartIndexInSubString;
if (x + strWidth >= maxWidth) {
x = Math.max(x, strWidth);
break;
}
if (x + strWidth >= estimatedWidth) {
x += strWidth;
break;
}
i--;
}
x += strWidth;
}
int paintWidth = x;
if (label.getInsets() != null) {
paintWidth += label.getInsets().left + label.getInsets().right;
}
int paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
if (paintRows != limitedRows) {
maxWidth = Math.min(maxWidth, label.getWidth() - label.getInsets().left - label.getInsets().right);
while (paintRows > limitedRows && paintWidth < maxWidth) {
paintWidth += 2;
paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
}
while (paintRows < limitedRows && paintWidth > 0) {
paintWidth -= 2;
paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
}
x = paintWidth;
if (label.getInsets() != null) {
x -= label.getInsets().left + label.getInsets().right;
}
}
_preferredRowCount = limitedRows;
return x;
}
/**
* Gets the font from the label.
*
* @param label the label.
* @return the font. If label's getFont is null, we will use Label.font instead.
*/
protected Font getFont(StyledLabel label) {
Font font = label.getFont();
if (font == null) {
font = UIDefaultsLookup.getFont("Label.font");
}
return font;
}
protected void paintStyledText(StyledLabel label, Graphics g, int textX, int textY) {
label.setTruncated(false);
int paintWidth = label.getWidth();
if (label.isLineWrap()) {
int oldPreferredWidth = label.getPreferredWidth();
int oldRows = label.getRows();
try {
label.setRows(0);
paintWidth = getPreferredSize(label).width;
label.setPreferredWidth(label.getWidth());
Dimension sizeOnWidth = getPreferredSize(label);
if (sizeOnWidth.width < paintWidth) {
paintWidth = sizeOnWidth.width;
}
}
finally {
label.setPreferredWidth(oldPreferredWidth);
label.setRows(oldRows);
}
}
Color oldColor = g.getColor();
paintWidth = Math.min(paintWidth, label.getWidth() - label.getInsets().left - label.getInsets().right);
internalPaintStyledText(label, g, textX, textY, paintWidth);
g.setColor(oldColor);
}
private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
int startX = textX < label.getInsets().left ? label.getInsets().left : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
if (label.isLineWrap() && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
rowCount++;
rowStartOffset = style.getStart() + style.getLength();
if (lastRow) {
break;
}
nextRowStartIndex = 0;
+ if (i < _styledTexts.size() - 1) {
+ StyledText nextStyledText = _styledTexts.get(i + 1);
+ StyleRange nextStyle = nextStyledText.styleRange;
+ int size = (nextStyle != null && (nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
+ font = getFont(label);
+ if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
+ font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
+ nextFm2 = label.getFontMetrics(font);
+ }
+ else {
+ nextFm2 = fm;
+ }
+ }
continue;
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
int strWidth = fm2.stringWidth(s);
boolean stop = false;
boolean wrapped = false;
int widthLeft = endX - x;
if (widthLeft < strWidth) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows();
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 5) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !label.isLineWrap() || textY >= labelHeight || (label.getMaxRows() > 0 && rowCount + 1 >= label.getMaxRows());
}
else if (label.isLineWrap()) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
width += 2;
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
private void paintRow(StyledLabel label, Graphics g, int textX, int textY, int startOffset, int endOffset, int paintWidth, boolean lastRow) {
if (g == null) {
return;
}
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
int x = textX;
for (int i = 0; i < _styledTexts.size() && (endOffset < 0 || charDisplayed < endOffset); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
int length = style.getLength();
if (length < 0) {
length = styledText.text.length();
}
if (style.getStart() + length <= startOffset) {
charDisplayed += length;
continue;
}
int nextRowStartIndex = style.getStart() >= startOffset ? 0 : startOffset - style.getStart();
charDisplayed += nextRowStartIndex;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
} else {
displayMnemonic = false;
}
int paintLength = styledText.text.length() - nextRowStartIndex;
if (endOffset >= 0 && charDisplayed + paintLength >= endOffset) {
paintLength = endOffset - charDisplayed;
}
charDisplayed += paintLength;
int y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
} else {
fm2 = fm;
}
} else {
fm2 = nextFm2;
}
g.setFont(font);
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
if (startOffset > 0 && x == textX && s.startsWith(" ")) {
s = s.substring(1);
}
if (s.length() > paintLength) {
s = s.substring(0, paintLength);
}
int strWidth = fm2.stringWidth(s);
int widthLeft = paintWidth + textX - x;
if (widthLeft < strWidth) {
if (label.isLineWrap() && !lastRow) {
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x == textX) {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 5) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
} else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
} else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, label.getHeight()), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
} else if (label.isLineWrap()) {
nextRowStartIndex = 0;
} else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
} else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
String nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, label.getHeight()), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, label.getHeight()), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
}
}
// start of actual painting
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
} else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
// end of actual painting
x += strWidth;
}
}
private int findNextWordStartIndex(String string, int firstRowEndIndex) {
boolean skipFirstWord = firstRowEndIndex < 0;
for (int i = firstRowEndIndex + 1; i < string.length(); i++) {
char c = string.charAt(i);
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
if (!skipFirstWord) {
return i;
}
}
else {
skipFirstWord = false;
}
}
return string.length();
}
private int findFirstRowWordEndIndex(String string) {
boolean spaceFound = false;
for (int i = string.length() - 1; i >= 0; i--) {
char c = string.charAt(i);
if (!spaceFound) {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
spaceFound = true;
}
}
else {
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
return i;
}
}
}
return -1;
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. The
* JComponents orientation (LEADING/TRAILING) will also be taken into account and translated into LEFT/RIGHT values
* accordingly.
*
* @param c the component
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
public static String layoutCompoundLabel(JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
boolean orientationIsLeftToRight = true;
int hAlign = horizontalAlignment;
int hTextPos = horizontalTextPosition;
if (c != null) {
if (!(c.getComponentOrientation().isLeftToRight())) {
orientationIsLeftToRight = false;
}
}
// Translate LEADING/TRAILING values in horizontalAlignment
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalAlignment) {
case LEADING:
hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
// Translate LEADING/TRAILING values in horizontalTextPosition
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalTextPosition) {
case LEADING:
hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
return layoutCompoundLabelImpl(c,
fm,
text,
icon,
verticalAlignment,
hAlign,
verticalTextPosition,
hTextPos,
viewR,
iconR,
textR,
textIconGap);
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. This
* layoutCompoundLabel() does not know how to handle LEADING/TRAILING values in horizontalTextPosition (they will
* default to RIGHT) and in horizontalAlignment (they will default to CENTER). Use the other version of
* layoutCompoundLabel() instead.
*
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
public static String layoutCompoundLabel(
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
return layoutCompoundLabelImpl(null, fm, text, icon,
verticalAlignment,
horizontalAlignment,
verticalTextPosition,
horizontalTextPosition,
viewR, iconR, textR, textIconGap);
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. This
* layoutCompoundLabel() does not know how to handle LEADING/TRAILING values in horizontalTextPosition (they will
* default to RIGHT) and in horizontalAlignment (they will default to CENTER). Use the other version of
* layoutCompoundLabel() instead.
*
* @param c the component
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
@SuppressWarnings({"UnusedDeclaration"})
private static String layoutCompoundLabelImpl(
JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
/* Initialize the icon bounds rectangle iconR.
*/
if (icon != null) {
iconR.width = icon.getIconWidth();
iconR.height = icon.getIconHeight();
}
else {
iconR.width = iconR.height = 0;
}
/* Initialize the text bounds rectangle textR. If a null
* or and empty String was specified we substitute "" here
* and use 0,0,0,0 for textR.
*/
boolean textIsEmpty = (text == null) || text.equals("");
int lsb = 0;
/* Unless both text and icon are non-null, we effectively ignore
* the value of textIconGap.
*/
int gap;
View v;
if (textIsEmpty) {
textR.width = textR.height = 0;
text = "";
gap = 0;
}
else {
int availTextWidth;
gap = (icon == null) ? 0 : textIconGap;
if (horizontalTextPosition == CENTER) {
availTextWidth = viewR.width;
}
else {
availTextWidth = viewR.width - (iconR.width + gap);
}
v = (c != null) ? (View) c.getClientProperty("html") : null;
if (v != null) {
textR.width = Math.min(availTextWidth, (int) v.getPreferredSpan(View.X_AXIS));
textR.height = (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// this is only place that is changed for StyledLabel
// textR.width = SwingUtilities2.stringWidth(c, fm, text);
// lsb = SwingUtilities2.getLeftSideBearing(c, fm, text);
// if (lsb < 0) {
// // If lsb is negative, add it to the width and later
// // adjust the x location. This gives more space than is
// // actually needed.
// // This is done like this for two reasons:
// // 1. If we set the width to the actual bounds all
// // callers would have to account for negative lsb
// // (pref size calculations ONLY look at width of
// // textR)
// // 2. You can do a drawString at the returned location
// // and the text won't be clipped.
// textR.width -= lsb;
// }
// if (textR.width > availTextWidth) {
// text = SwingUtilities2.clipString(c, fm, text,
// availTextWidth);
// textR.width = SwingUtilities2.stringWidth(c, fm, text);
// }
// textR.height = fm.getHeight();
}
}
/* Compute textR.x,y given the verticalTextPosition and
* horizontalTextPosition properties
*/
if (verticalTextPosition == TOP) {
if (horizontalTextPosition != CENTER) {
textR.y = 0;
}
else {
textR.y = -(textR.height + gap);
}
}
else if (verticalTextPosition == CENTER) {
textR.y = (iconR.height / 2) - (textR.height / 2);
}
else { // (verticalTextPosition == BOTTOM)
if (horizontalTextPosition != CENTER) {
textR.y = iconR.height - textR.height;
}
else {
textR.y = (iconR.height + gap);
}
}
if (horizontalTextPosition == LEFT) {
textR.x = -(textR.width + gap);
}
else if (horizontalTextPosition == CENTER) {
textR.x = (iconR.width / 2) - (textR.width / 2);
}
else { // (horizontalTextPosition == RIGHT)
textR.x = (iconR.width + gap);
}
/* labelR is the rectangle that contains iconR and textR.
* Move it to its proper position given the labelAlignment
* properties.
*
* To avoid actually allocating a Rectangle, Rectangle.union
* has been inlined below.
*/
int labelR_x = Math.min(iconR.x, textR.x);
int labelR_width = Math.max(iconR.x + iconR.width,
textR.x + textR.width) - labelR_x;
int labelR_y = Math.min(iconR.y, textR.y);
int labelR_height = Math.max(iconR.y + iconR.height,
textR.y + textR.height) - labelR_y;
int dx, dy;
if (verticalAlignment == TOP) {
dy = viewR.y - labelR_y;
}
else if (verticalAlignment == CENTER) {
dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2));
}
else { // (verticalAlignment == BOTTOM)
dy = (viewR.y + viewR.height) - (labelR_y + labelR_height);
}
if (horizontalAlignment == LEFT) {
dx = viewR.x - labelR_x;
}
else if (horizontalAlignment == RIGHT) {
dx = (viewR.x + viewR.width) - (labelR_x + labelR_width);
}
else { // (horizontalAlignment == CENTER)
dx = (viewR.x + (viewR.width / 2)) -
(labelR_x + (labelR_width / 2));
}
/* Translate textR and glypyR by dx,dy.
*/
textR.x += dx;
textR.y += dy;
iconR.x += dx;
iconR.y += dy;
if (lsb < 0) {
// lsb is negative. Shift the x location so that the text is
// visually drawn at the right location.
textR.x -= lsb;
}
return text;
}
}
| true | true | private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
int startX = textX < label.getInsets().left ? label.getInsets().left : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
if (label.isLineWrap() && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
rowCount++;
rowStartOffset = style.getStart() + style.getLength();
if (lastRow) {
break;
}
nextRowStartIndex = 0;
continue;
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
int strWidth = fm2.stringWidth(s);
boolean stop = false;
boolean wrapped = false;
int widthLeft = endX - x;
if (widthLeft < strWidth) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows();
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 5) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !label.isLineWrap() || textY >= labelHeight || (label.getMaxRows() > 0 && rowCount + 1 >= label.getMaxRows());
}
else if (label.isLineWrap()) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
width += 2;
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
| private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
int startX = textX < label.getInsets().left ? label.getInsets().left : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
if (label.isLineWrap() && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
rowCount++;
rowStartOffset = style.getStart() + style.getLength();
if (lastRow) {
break;
}
nextRowStartIndex = 0;
if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null && (nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
}
continue;
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
int strWidth = fm2.stringWidth(s);
boolean stop = false;
boolean wrapped = false;
int widthLeft = endX - x;
if (widthLeft < strWidth) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows();
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 5) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !label.isLineWrap() || textY >= labelHeight || (label.getMaxRows() > 0 && rowCount + 1 >= label.getMaxRows());
}
else if (label.isLineWrap()) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows()) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), width, lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
int newStartX = startX;
int width = x;
if (horizontalAlignment == RIGHT) {
width = x - newStartX;
newStartX = label.getWidth() - width;
if (label.getInsets() != null) {
newStartX -= label.getInsets().right;
}
}
else if (horizontalAlignment == CENTER) {
if (label.isLineWrap()) {
if (newStartX == 0) {
newStartX += (label.getWidth() - width) / 2;
}
else {
newStartX += (endX - width) / 2;
}
}
width += 2;
if (label.getInsets() != null) {
width -= label.getInsets().right / 2;
}
}
paintRow(label, g, newStartX, textY, rowStartOffset, -1, width, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
|
diff --git a/src/main/java/org/candlepin/thumbslug/HttpServerPipelineFactory.java b/src/main/java/org/candlepin/thumbslug/HttpServerPipelineFactory.java
index 20ef2cb..0f563d3 100644
--- a/src/main/java/org/candlepin/thumbslug/HttpServerPipelineFactory.java
+++ b/src/main/java/org/candlepin/thumbslug/HttpServerPipelineFactory.java
@@ -1,66 +1,67 @@
/**
* Copyright (c) 2011 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.thumbslug;
import static org.jboss.netty.channel.Channels.*;
import javax.net.ssl.SSLEngine;
import org.candlepin.thumbslug.ssl.SslContextFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.ssl.SslHandler;
/**
* HttpServerPipelineFactory
*/
public class HttpServerPipelineFactory implements ChannelPipelineFactory {
private Config config;
public HttpServerPipelineFactory(Config config) {
this.config = config;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (config.getBoolean("ssl")) {
SSLEngine engine =
SslContextFactory.getServerContext(config.getProperty("ssl.keystore"),
config.getProperty("ssl.keystore.password")).createSSLEngine();
engine.setUseClientMode(false);
+ engine.setNeedClientAuth(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("logger", new HttpRequestLogger(config.getProperty("log.access")));
pipeline.addLast("handler", new HttpRequestHandler(config));
return pipeline;
}
}
| true | true | public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (config.getBoolean("ssl")) {
SSLEngine engine =
SslContextFactory.getServerContext(config.getProperty("ssl.keystore"),
config.getProperty("ssl.keystore.password")).createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("logger", new HttpRequestLogger(config.getProperty("log.access")));
pipeline.addLast("handler", new HttpRequestHandler(config));
return pipeline;
}
| public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (config.getBoolean("ssl")) {
SSLEngine engine =
SslContextFactory.getServerContext(config.getProperty("ssl.keystore"),
config.getProperty("ssl.keystore.password")).createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("logger", new HttpRequestLogger(config.getProperty("log.access")));
pipeline.addLast("handler", new HttpRequestHandler(config));
return pipeline;
}
|
diff --git a/app/models/domain/Tag.java b/app/models/domain/Tag.java
index d98543f..f3b6dbf 100644
--- a/app/models/domain/Tag.java
+++ b/app/models/domain/Tag.java
@@ -1,18 +1,18 @@
package models.domain;
/**
* User: Knut Haugen <[email protected]>
* 2011-09-25
*/
public class Tag {
private String name;
private String url;
private int id;
public Tag(int id, String name, String url) {
this.id = id;
this.name = name;
- this.url = name;
+ this.url = url;
}
}
| true | true | public Tag(int id, String name, String url) {
this.id = id;
this.name = name;
this.url = name;
}
| public Tag(int id, String name, String url) {
this.id = id;
this.name = name;
this.url = url;
}
|
diff --git a/src/com/ds/avare/instruments/CDI.java b/src/com/ds/avare/instruments/CDI.java
index 35c81bf2..0d7bd29b 100644
--- a/src/com/ds/avare/instruments/CDI.java
+++ b/src/com/ds/avare/instruments/CDI.java
@@ -1,253 +1,253 @@
/*
Copyright (c) 2012, Apps4Av Inc. (apps4av.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ds.avare.instruments;
import com.ds.avare.gps.GpsParams;
import com.ds.avare.place.Destination;
import com.ds.avare.position.Projection;
import com.ds.avare.utils.Helper;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
/***
* Implementation of a Course Deviation Indicator
*/
public class CDI {
Paint mCDIPaint; // Our very own paint object
Rect mTextSize; // Used to determine text bounds
int mBarCount; // How many bars to display
float mBarWidth; // Display width of 1 bar
float mBarHeight; // How tall is each bar
float mBarSpace; // Width of the space between bars
float mInstWidth; // Total width of the instrument
float mInstHeight; // Total height of the instrument
float mInstTop; // The top line of the CDI
float mInstLeft; // Left position of the CDI
final int mColorLeft = Color.RED;
final int mColorRight = Color.rgb(0x00,0xa0,0x00);
final int mColorCenter = Color.BLACK;
private float mBarDegrees = BAR_DEGREES_VOR;
// Calc'd instrument values
float mDspOffset; // Display offset value for deviation
double mDeviation; // How far off course are we
int mBackColor; // Background color of inst
private static final float BAR_DEGREES_VOR = 2f;
private static final float BAR_DEGREES_LOC = 0.5f;
/***
* Return the actual course deviation value. It's an absolute
* number without any direction information
* @return How many miles/km/hm off the course line
*/
public double getDeviation() {
return mDeviation;
}
/***
* Course Deviation Indicator
*/
public CDI() { }
/***
* Allocate the paint object and figuring out how
* large the instrument is on the display based upon the text size in the
* source paint object
* @param textPaint Used to figure out our overall size
*/
public void setSize(Paint textPaint)
{
// A total of 9 bars
mBarCount = 11;
// The height of each bar is the basis for the entire instrument size
mBarHeight = textPaint.getTextSize() * (float) 0.5;
// Width is 1/4 of the height
mBarWidth = mBarHeight / 4;
// Space between bars is 3x the width of the bar
mBarSpace = 3 * mBarWidth;
// Width of the entire instrument
mInstWidth = mBarCount * mBarWidth + // The bars themselves
(mBarCount - 1) * mBarSpace + // Space between the bars
2 * mBarWidth; // Space to the left and right of the end bars
// Height of the entire instrument
mInstHeight = mBarHeight + // The main bar itself
mBarHeight / 2 + // The triangle indicator height
mBarWidth * 3; // Border padding at top/bottom/middle
// Allocate some objects to save time during draw cycle
mCDIPaint = new Paint(textPaint);
mTextSize = new Rect();
}
/***
* Draw the instrument on the canvas given the current screen size
* This is called during the screen refresh/repaint - be quick about it; no "new" calls.
* @param canvas What to draw upon
* @param screenX Total width of the display canvas
* @param screenY Total height of the display canvas
*/
public void drawCDI(Canvas canvas, float screenX, float screenY)
{
// Calculate the left position of the instrument
mInstLeft = (screenX - mInstWidth) / 2;
// Now where is the top of it
mInstTop = screenY * 3 / 4;
// Draw the background
mCDIPaint.setColor(mBackColor); // Color
mCDIPaint.setAlpha(0x5F); // Make it see-thru
mCDIPaint.setStrokeWidth(mInstHeight); // How tall the inst is
mCDIPaint.setStyle(Paint.Style.STROKE); // Type of brush
// Draw the background of the instrument. This is a horo swipe left to right,
// so we need to specify the vertical middle as the source Y, not the top
float instCenterY = mInstTop + mInstHeight / 2;
canvas.drawLine(mInstLeft, instCenterY, mInstLeft + mInstWidth, instCenterY, mCDIPaint);
// Draw all of the vertical bars
mCDIPaint.setColor(Color.WHITE); // white
mCDIPaint.setStrokeWidth(mBarWidth); // Width of each bar
for(int idx = 0; idx < mBarCount; idx++) {
float extend = (idx == (int)(mBarCount / 2)) ? mInstHeight / 3 : 0;
float barLeft = mInstLeft + mBarWidth * (float) 1.5 +
idx * (mBarWidth + mBarSpace);
canvas.drawLine(barLeft, mInstTop + mBarWidth, barLeft,
mInstTop + mBarHeight + mBarWidth + extend, mCDIPaint);
}
// Now draw the needle indicator at the horizontal center
drawIndicator(canvas, screenX / 2 - mDspOffset);
}
/***
* Draw the triangle position indicator under the bar
* @param canvas what to draw upon
* @param posX left/right center position of the pointer
*/
private void drawIndicator(Canvas canvas, float posX)
{
// Top point
float X1 = posX;
float Y1 = mInstTop + mBarHeight + 2 * mBarWidth;
// Bottom right point
float X2 = X1 + mBarHeight / 4;
float Y2 = Y1 + mBarHeight / 2;
// Bottom left point
float X3 = X1 - mBarHeight / 4;
float Y3 = Y2;
mCDIPaint.setColor(Color.WHITE); // white
mCDIPaint.setStrokeWidth(5); // Line width
// Draw
canvas.drawLine(X1, Y1, X2, Y2, mCDIPaint); // Right leg
canvas.drawLine(X2, Y2, X3, Y3, mCDIPaint); // base
canvas.drawLine(X3, Y3, X1, Y1, mCDIPaint); // Left leg
}
/***
* Calculate the deviation of our current position from
* the plotted course
* @param gpsParams where we are
* @param dest what our destination is
*/
public void calcDeviation(GpsParams gpsParams, Destination dest)
{
// Assume an on-course display
mDspOffset = 0;
mBackColor = mColorCenter;
// If either of these objects are null, there is nothing
// we can do
if(dest == null || gpsParams == null) {
return;
}
// Get the bearing from the original source when this destination was
// set. THIS DOES NOT WORK SINCE THE BEARING IS NOT SAVED WHEN THE DEST
// BEARING WAS CREATED.
//float brgOrg = dest.getLocationInit().getBearing();
// Use the global Projection class to get the static bearing from the
// start to the end point of the course line
double brgOrg = Projection.getStaticBearing(
dest.getLocationInit().getLongitude(),
dest.getLocationInit().getLatitude(),
dest.getLocation().getLongitude(),
dest.getLocation().getLatitude());
// The bearing from our CURRENT location to the target
double brgCur = dest.getBearing();
// Relative bearing we are FROM destination is the difference
// of these two
double brgDif = Helper.angularDifference(brgOrg, brgCur);
// Distance from our CURRENT position to the destination
double dstCur = dest.getDistance();
/*
* Within 20 miles convert to Localizer
* This must match the distance for Glide slope.
*/
if(dstCur > VNAV.APPROACH_DISTANCE) {
mBarDegrees = BAR_DEGREES_VOR;
}
else {
mBarDegrees = BAR_DEGREES_LOC;
}
// Distance we are from the direct course line
mDeviation = dstCur * Math.sin(Math.toRadians(brgDif));
// The amount of display offset varies depending upon how large the deviation is
if(brgDif > mBarDegrees * ((float)mBarCount - 1) / 2f) {
brgDif = mBarDegrees * ((float)mBarCount - 1) / 2f;
}
mDspOffset = (mBarWidth + mBarSpace) * (float) (brgDif / mBarDegrees);
// Assume we are to the RIGHT of the courseline
mBackColor = mColorRight;
// Now determine whether we are LEFT. That will
// dictate the color of the shadow and the sign of the mDeviation.
// Account for REVERSE SENSING if we are already BEYOND the target (>90deg)
boolean bLeftOfCourseLine = Helper.leftOfCourseLine(brgCur, brgOrg);
if ((bLeftOfCourseLine && brgDif <= 90) || (!bLeftOfCourseLine && brgDif >= 90)) {
mBackColor = mColorLeft;
mDspOffset = -mDspOffset;
}
/*
* One bar width is OK, show no color
*/
- if(brgDif <= mBarWidth) {
+ if(brgDif <= mBarDegrees) {
mBackColor = mColorCenter;
}
}
}
| true | true | public void calcDeviation(GpsParams gpsParams, Destination dest)
{
// Assume an on-course display
mDspOffset = 0;
mBackColor = mColorCenter;
// If either of these objects are null, there is nothing
// we can do
if(dest == null || gpsParams == null) {
return;
}
// Get the bearing from the original source when this destination was
// set. THIS DOES NOT WORK SINCE THE BEARING IS NOT SAVED WHEN THE DEST
// BEARING WAS CREATED.
//float brgOrg = dest.getLocationInit().getBearing();
// Use the global Projection class to get the static bearing from the
// start to the end point of the course line
double brgOrg = Projection.getStaticBearing(
dest.getLocationInit().getLongitude(),
dest.getLocationInit().getLatitude(),
dest.getLocation().getLongitude(),
dest.getLocation().getLatitude());
// The bearing from our CURRENT location to the target
double brgCur = dest.getBearing();
// Relative bearing we are FROM destination is the difference
// of these two
double brgDif = Helper.angularDifference(brgOrg, brgCur);
// Distance from our CURRENT position to the destination
double dstCur = dest.getDistance();
/*
* Within 20 miles convert to Localizer
* This must match the distance for Glide slope.
*/
if(dstCur > VNAV.APPROACH_DISTANCE) {
mBarDegrees = BAR_DEGREES_VOR;
}
else {
mBarDegrees = BAR_DEGREES_LOC;
}
// Distance we are from the direct course line
mDeviation = dstCur * Math.sin(Math.toRadians(brgDif));
// The amount of display offset varies depending upon how large the deviation is
if(brgDif > mBarDegrees * ((float)mBarCount - 1) / 2f) {
brgDif = mBarDegrees * ((float)mBarCount - 1) / 2f;
}
mDspOffset = (mBarWidth + mBarSpace) * (float) (brgDif / mBarDegrees);
// Assume we are to the RIGHT of the courseline
mBackColor = mColorRight;
// Now determine whether we are LEFT. That will
// dictate the color of the shadow and the sign of the mDeviation.
// Account for REVERSE SENSING if we are already BEYOND the target (>90deg)
boolean bLeftOfCourseLine = Helper.leftOfCourseLine(brgCur, brgOrg);
if ((bLeftOfCourseLine && brgDif <= 90) || (!bLeftOfCourseLine && brgDif >= 90)) {
mBackColor = mColorLeft;
mDspOffset = -mDspOffset;
}
/*
* One bar width is OK, show no color
*/
if(brgDif <= mBarWidth) {
mBackColor = mColorCenter;
}
}
| public void calcDeviation(GpsParams gpsParams, Destination dest)
{
// Assume an on-course display
mDspOffset = 0;
mBackColor = mColorCenter;
// If either of these objects are null, there is nothing
// we can do
if(dest == null || gpsParams == null) {
return;
}
// Get the bearing from the original source when this destination was
// set. THIS DOES NOT WORK SINCE THE BEARING IS NOT SAVED WHEN THE DEST
// BEARING WAS CREATED.
//float brgOrg = dest.getLocationInit().getBearing();
// Use the global Projection class to get the static bearing from the
// start to the end point of the course line
double brgOrg = Projection.getStaticBearing(
dest.getLocationInit().getLongitude(),
dest.getLocationInit().getLatitude(),
dest.getLocation().getLongitude(),
dest.getLocation().getLatitude());
// The bearing from our CURRENT location to the target
double brgCur = dest.getBearing();
// Relative bearing we are FROM destination is the difference
// of these two
double brgDif = Helper.angularDifference(brgOrg, brgCur);
// Distance from our CURRENT position to the destination
double dstCur = dest.getDistance();
/*
* Within 20 miles convert to Localizer
* This must match the distance for Glide slope.
*/
if(dstCur > VNAV.APPROACH_DISTANCE) {
mBarDegrees = BAR_DEGREES_VOR;
}
else {
mBarDegrees = BAR_DEGREES_LOC;
}
// Distance we are from the direct course line
mDeviation = dstCur * Math.sin(Math.toRadians(brgDif));
// The amount of display offset varies depending upon how large the deviation is
if(brgDif > mBarDegrees * ((float)mBarCount - 1) / 2f) {
brgDif = mBarDegrees * ((float)mBarCount - 1) / 2f;
}
mDspOffset = (mBarWidth + mBarSpace) * (float) (brgDif / mBarDegrees);
// Assume we are to the RIGHT of the courseline
mBackColor = mColorRight;
// Now determine whether we are LEFT. That will
// dictate the color of the shadow and the sign of the mDeviation.
// Account for REVERSE SENSING if we are already BEYOND the target (>90deg)
boolean bLeftOfCourseLine = Helper.leftOfCourseLine(brgCur, brgOrg);
if ((bLeftOfCourseLine && brgDif <= 90) || (!bLeftOfCourseLine && brgDif >= 90)) {
mBackColor = mColorLeft;
mDspOffset = -mDspOffset;
}
/*
* One bar width is OK, show no color
*/
if(brgDif <= mBarDegrees) {
mBackColor = mColorCenter;
}
}
|
diff --git a/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/importer/Bpmn2ModelImport.java b/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/importer/Bpmn2ModelImport.java
index 552bdbe5..9c0c6ff2 100755
--- a/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/importer/Bpmn2ModelImport.java
+++ b/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/importer/Bpmn2ModelImport.java
@@ -1,545 +1,546 @@
/*******************************************************************************
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* camunda services GmbH - initial API and implementation
*
******************************************************************************/
package org.eclipse.bpmn2.modeler.core.importer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.bpmn2.Activity;
import org.eclipse.bpmn2.Artifact;
import org.eclipse.bpmn2.BaseElement;
import org.eclipse.bpmn2.CallActivity;
import org.eclipse.bpmn2.Collaboration;
import org.eclipse.bpmn2.DataStoreReference;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.DocumentRoot;
import org.eclipse.bpmn2.Event;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.FlowElementsContainer;
import org.eclipse.bpmn2.FlowNode;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.Lane;
import org.eclipse.bpmn2.LaneSet;
import org.eclipse.bpmn2.MessageFlow;
import org.eclipse.bpmn2.Participant;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.RootElement;
import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.bpmn2.SubProcess;
import org.eclipse.bpmn2.Task;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.eclipse.bpmn2.di.BPMNEdge;
import org.eclipse.bpmn2.di.BPMNPlane;
import org.eclipse.bpmn2.di.BPMNShape;
import org.eclipse.bpmn2.modeler.core.Activator;
import org.eclipse.bpmn2.modeler.core.di.DIUtils;
import org.eclipse.bpmn2.modeler.core.importer.handlers.AbstractDiagramElementHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.AbstractShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.ArtifactShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.DatastoreReferenceShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.FlowNodeShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.LaneShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.MessageFlowShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.ParticipantShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.SequenceFlowShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.SubProcessShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.handlers.TaskShapeHandler;
import org.eclipse.bpmn2.modeler.core.importer.util.ModelCreator;
import org.eclipse.bpmn2.modeler.core.preferences.Bpmn2Preferences;
import org.eclipse.bpmn2.modeler.core.utils.ModelUtil;
import org.eclipse.bpmn2.util.Bpmn2Resource;
import org.eclipse.dd.di.DiagramElement;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.graphiti.dt.IDiagramTypeProvider;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.ILayoutFeature;
import org.eclipse.graphiti.features.context.impl.LayoutContext;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.platform.IDiagramEditor;
/**
*
* @author Nico Rehwaldt
* @author Daniel Meyer
*/
public class Bpmn2ModelImport {
protected IFeatureProvider featureProvider;
protected Bpmn2Resource resource;
protected IDiagramTypeProvider diagramTypeProvider;
protected Bpmn2Preferences preferences;
// in this map we collect all DiagramElements (BPMN DI) indexed by the IDs of the ProcessElements they reference.
protected Map<String, DiagramElement> diagramElementMap = new HashMap<String, DiagramElement>();
// this list collects DI elements that do not reference bpmn model elements. (for instance, lables only)
protected List<DiagramElement> nonModelElements = new ArrayList<DiagramElement>();
// this list collects the created PictogramElements (Graphiti) indexed by bpmn model elements
protected HashMap<BaseElement, PictogramElement> pictogramElements = new HashMap<BaseElement, PictogramElement>();
public Bpmn2ModelImport(IDiagramTypeProvider diagramTypeProvider, Bpmn2Resource resource) {
this.diagramTypeProvider = diagramTypeProvider;
this.resource = resource;
featureProvider = diagramTypeProvider.getFeatureProvider();
preferences = Bpmn2Preferences.getInstance(resource);
}
public void execute() {
EList<EObject> contents = resource.getContents();
if (contents.isEmpty()) {
throw new Bpmn2ImportException("No document root");
} else {
handleDocumentRoot((DocumentRoot) contents.get(0));
}
// TODO: is there a possibility for a resource to have multiple DocumentRoots?
}
protected void handleDocumentRoot(DocumentRoot documentRoot) {
Definitions definitions = documentRoot.getDefinitions();
if (definitions == null) {
throw new Bpmn2ImportException("Document Root has no definitions");
} else {
handleDefinitions(definitions);
}
}
protected void handleDefinitions(Definitions definitions) {
// first we process the DI diagrams and associate them with the process elements
List<BPMNDiagram> diagrams = definitions.getDiagrams();
for (BPMNDiagram bpmnDiagram : diagrams) {
handleDIBpmnDiagram(bpmnDiagram);
}
// copied from old DIImport
// iterates over all elements in the diagram -> may be bad but is there another solution?
- // first: add all IDs to our ID mapping table
+ // add all ids to the mapping table so that they won't be used when
+ // new ids are generated later
TreeIterator<EObject> iter = definitions.eAllContents();
while (iter.hasNext()) {
ModelUtil.addID(iter.next());
}
- // copied from old DIImport
+ // end copied from old DIImport
// next, process the BPMN model elements and start building the Graphiti diagram
// first check if we display a single process or collaboration
List<RootElement> rootElements = definitions.getRootElements();
List<Process> processes = new ArrayList<Process>();
Collaboration collaboration = null;
for (RootElement rootElement: rootElements) {
if (rootElement instanceof Process) {
processes.add((Process) rootElement);
} else if (rootElement instanceof Collaboration) {
if (collaboration != null) {
throw new Bpmn2ImportException("Multiple collaborations not supported");
}
collaboration = (Collaboration) rootElement;
} else {
System.out.println("Unhandled RootElement: " + rootElement);
}
}
if (collaboration != null) {
// we display a collaboration
if (diagrams.isEmpty()) {
BPMNDiagram newDiagram = ModelCreator.create(resource, BPMNDiagram.class);
diagrams.add(newDiagram);
}
BPMNDiagram element = diagrams.get(0);
// create diagram for collaboration
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
handleCollaboration(collaboration, rootDiagram);
} else if (!processes.isEmpty()) {
// we display one or more processes
BPMNDiagram element = diagrams.get(0);
// create diagram for process(es)
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
for (Process process : processes) {
List<BaseElement> unhandledElements = new ArrayList<BaseElement>();
handleProcess(process, rootDiagram);
if (!unhandledElements.isEmpty()) {
throw new Bpmn2ImportException("Unhandled elements: " + unhandledElements);
}
}
} else {
// We have no root process or collaboration
createNewDiagramAndHandleIt(definitions);
}
// finally layout all elements
performLayout();
}
protected void createNewDiagramAndHandleIt(Definitions definitions) {
// create process
Process process = ModelCreator.create(resource, Process.class);
definitions.getRootElements().add(process);
// create bpmn di elements
BPMNPlane plane = ModelCreator.create(resource, BPMNPlane.class); // BpmnDiFactory.eINSTANCE.createBPMNPlane();
plane.setBpmnElement(process);
BPMNDiagram bpmnDiagramElement = ModelCreator.create(resource, BPMNDiagram.class);
bpmnDiagramElement.setPlane(plane);
ModelUtil.setID(plane, resource);
ModelUtil.setID(bpmnDiagramElement, resource);
definitions.getDiagrams().add(bpmnDiagramElement);
// create diagram and handle it
Diagram diagram = createRootDiagram((BPMNDiagram) bpmnDiagramElement);
featureProvider.link(diagram, bpmnDiagramElement);
}
protected Diagram createRootDiagram(BPMNDiagram bpmnDiagram) {
IDiagramEditor diagramEditor = diagramTypeProvider.getDiagramEditor();
Diagram diagram = DIUtils.getOrCreateDiagram(diagramEditor,bpmnDiagram);
diagramTypeProvider.init(diagram, diagramEditor);
return diagram;
}
protected void performLayout() {
// finally layout all elements
for (Entry<BaseElement, PictogramElement> entry : pictogramElements.entrySet()) {
BaseElement baseElement = entry.getKey();
PictogramElement pictogramElement = entry.getValue();
if (baseElement instanceof SubProcess) {
// we need the layout to hide children if collapsed
LayoutContext context = new LayoutContext(pictogramElement);
ILayoutFeature feature = featureProvider.getLayoutFeature(context);
if (feature != null && feature.canLayout(context)) {
feature.layout(context);
}
} else if (baseElement instanceof FlowNode) {
LayoutContext context = new LayoutContext(pictogramElement);
ILayoutFeature feature = featureProvider.getLayoutFeature(context);
if (feature != null && feature.canLayout(context)) {
feature.layout(context);
}
}
}
}
// handling of BPMN Model Elements ///////////////////////////////////////////////////////////////
protected void handleCollaboration(Collaboration collaboration, ContainerShape container) {
List<Participant> participants = collaboration.getParticipants();
for (Participant participant : participants) {
handleParticipant(participant, container);
}
for (MessageFlow messageFlow: collaboration.getMessageFlows()) {
handleMessageFlow(messageFlow, container);
}
}
/**
* This draws a participant (Pool) in a Collaboration
*
* @param participant
* @param container
*/
protected void handleParticipant(Participant participant, ContainerShape container) {
Process process = participant.getProcessRef();
if (process == null || process.eIsProxy()) {
return;
}
// draw the participant (pool)
ParticipantShapeHandler shapeHander = new ParticipantShapeHandler(this);
ContainerShape participantContainer = (ContainerShape) handleDiagramElement(participant, container, shapeHander);
List<LaneSet> laneSets = process.getLaneSets();
if (laneSets.isEmpty()) {
// if there are no lanes, simply draw the process into the pool (including sequence flows)
handleProcess(process, participantContainer);
} else {
// draw the lanes (possibly nested). The lanes reference the task elements they contain, but not the sequence flows.
for (LaneSet laneSet: laneSets) {
handleLaneSet(laneSet, process, participantContainer);
}
// draw the sequence flows:
handleSequenceFlows(participantContainer, process.getFlowElements());
}
}
protected void handleSequenceFlows(ContainerShape participantContainer, List<FlowElement> flowElements) {
for (FlowElement flowElement : flowElements) {
if (flowElement instanceof SequenceFlow) {
handleSequenceFlow((SequenceFlow) flowElement, participantContainer);
}
}
}
protected void handleLaneSet(LaneSet laneSet, FlowElementsContainer scope, ContainerShape container) {
for (Lane lane: laneSet.getLanes()) {
handleLane(lane, scope, container);
}
}
protected void handleLane(Lane lane, FlowElementsContainer scope, ContainerShape container) {
AbstractShapeHandler<Lane> shapeHandler = new LaneShapeHandler(this);
// TODO: Draw lane the right way
DiagramElement diagramElement = getDiagramElement(lane);
ContainerShape thisContainer = (ContainerShape) shapeHandler.handleDiagramElement(lane, diagramElement, container);
pictogramElements.put(lane, thisContainer);
LaneSet childLaneSet = lane.getChildLaneSet();
if (childLaneSet != null) {
handleLaneSet(childLaneSet, scope, thisContainer);
} else {
List<FlowNode> referencedNodes = lane.getFlowNodeRefs();
handleFlowElements(thisContainer, (List)referencedNodes);
}
}
protected void handleProcess(Process process, ContainerShape container) {
// handle direct children of the process element (not displaying lanes)
List<FlowElement> flowElements = process.getFlowElements();
handleFlowElements(container, flowElements);
handleSequenceFlows(container, flowElements);
List<Artifact> artifacts = process.getArtifacts();
handleArtifacts(container, artifacts);
}
protected void handleArtifacts(ContainerShape container, List<Artifact> artifacts) {
for (Artifact artifact : artifacts) {
handleArtifact(artifact, container);
}
}
/**
* processes all {@link FlowElement FlowElements} in a given scope.
*
* @param scope
* @param container
* @param unhandledElements
*/
protected void handleFlowElements(ContainerShape container, List<FlowElement> flowElementsToBeDrawn) {
for (FlowElement flowElement : flowElementsToBeDrawn) {
if (flowElement instanceof Gateway) {
handleGateway((Gateway) flowElement, container);
} else if (flowElement instanceof SubProcess) {
handleSubProcess((SubProcess) flowElement, container);
} else if (flowElement instanceof CallActivity) {
handleCallActivity((CallActivity) flowElement, container);
} else if (flowElement instanceof Task) {
handleTask((Task) flowElement, container);
} else if (flowElement instanceof Event) {
handleEvent((Event) flowElement, container);
} else if (flowElement instanceof DataStoreReference) {
handleDataStoreReference((DataStoreReference) flowElement, container);
}
}
}
protected void handleActivity(Activity flowElement,
ContainerShape container) {
handleDiagramElement(flowElement, container, new FlowNodeShapeHandler(this));
}
protected void handleSubProcess(SubProcess subProcess, ContainerShape container) {
// draw subprocess shape
ContainerShape subProcessContainer = (ContainerShape) handleDiagramElement(subProcess, container, new SubProcessShapeHandler(this));
// descend into scope
List<FlowElement> flowElements = subProcess.getFlowElements();
handleFlowElements(subProcessContainer, flowElements);
handleSequenceFlows(subProcessContainer, flowElements);
}
protected void handleArtifact(Artifact artifact, ContainerShape container) {
handleDiagramElement(artifact, container, new ArtifactShapeHandler(this));
}
protected void handleGateway(Gateway flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new FlowNodeShapeHandler(this));
}
protected void handleMessageFlow(MessageFlow flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new MessageFlowShapeHandler(this));
}
protected void handleSequenceFlow(SequenceFlow flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new SequenceFlowShapeHandler(this));
}
protected void handleEvent(Event flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new FlowNodeShapeHandler(this));
}
protected void handleCallActivity(CallActivity flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new FlowNodeShapeHandler(this));
}
protected void handleTask(Task flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new TaskShapeHandler(this));
}
protected void handleDataStoreReference(DataStoreReference flowElement, ContainerShape container) {
handleDiagramElement(flowElement, container, new DatastoreReferenceShapeHandler(this));
}
public <T extends BaseElement> PictogramElement handleDiagramElement(T flowElement, ContainerShape container,
AbstractDiagramElementHandler<T> flowNodeShapeHandler) {
DiagramElement diagramElement = getDiagramElement(flowElement);
PictogramElement pictogramElement = flowNodeShapeHandler.handleDiagramElement(flowElement, diagramElement, container);
pictogramElements.put(flowElement, pictogramElement);
return pictogramElement;
}
// handling of DI Elements ///////////////////////////////////////////////////////////////
protected void handleDIBpmnDiagram(BPMNDiagram bpmnDiagram) {
BPMNPlane plane = bpmnDiagram.getPlane();
if (plane == null) {
throw new Bpmn2ImportException("BPMNDiagram " + bpmnDiagram + " has no BPMNPlane");
} else {
handleDIBpmnPlane(plane);
}
}
protected void handleDIBpmnPlane(BPMNPlane plane) {
BaseElement bpmnElement = plane.getBpmnElement();
if (bpmnElement.eIsProxy()) {
throw new Bpmn2ImportException("BPMNPlane " + plane + " references unexisting bpmnElement '" + bpmnElement + "'.");
}
List<DiagramElement> planeElement = plane.getPlaneElement();
for (DiagramElement diagramElement : planeElement) {
handleDIDiagramElement(diagramElement);
}
}
protected void handleDIDiagramElement(DiagramElement diagramElement) {
if (diagramElement instanceof BPMNShape) {
handleDIShape((BPMNShape) diagramElement);
} else if(diagramElement instanceof BPMNEdge) {
handleDIEdge((BPMNEdge) diagramElement);
} else {
nonModelElements.add(diagramElement);
}
}
protected void handleDIEdge(BPMNEdge diagramElement) {
BaseElement bpmnElement = diagramElement.getBpmnElement();
if (bpmnElement == null || bpmnElement.eIsProxy()) {
Activator.logError(new Bpmn2ImportException("BPMNEdge references unexisting bpmnElement '"+bpmnElement+"'."));
} else {
diagramElementMap.put(bpmnElement.getId(), diagramElement);
}
}
protected void handleDIShape(BPMNShape diagramElement) {
BaseElement bpmnElement = diagramElement.getBpmnElement();
if (bpmnElement == null || bpmnElement.eIsProxy()) {
Activator.logError(new Bpmn2ImportException("BPMNShape references unexisting bpmnElement '"+bpmnElement+"'."));
} else {
diagramElementMap.put(bpmnElement.getId(), diagramElement);
}
}
// Getters //////////////////////////////////////////////////
public IFeatureProvider getFeatureProvider() {
return featureProvider;
}
public DiagramElement getDiagramElement(BaseElement bpmnElement) {
DiagramElement element = diagramElementMap.get(bpmnElement.getId());
if (element == null) {
throw new Bpmn2ImportException("Not yet processed: " + bpmnElement);
}
return element;
}
public IDiagramTypeProvider getDiagramTypeProvider() {
return diagramTypeProvider;
}
public Bpmn2Resource getResource() {
return resource;
}
public Map<String, DiagramElement> getDiagramElementMap() {
return diagramElementMap;
}
public List<DiagramElement> getNonModelElements() {
return nonModelElements;
}
public Bpmn2Preferences getPreferences() {
return preferences;
}
public PictogramElement getPictogramElement(BaseElement node) {
PictogramElement element = pictogramElements.get(node);
if (element == null) {
throw new Bpmn2ImportException("Not yet processed: " + node);
}
return element;
}
}
| false | true | protected void handleDefinitions(Definitions definitions) {
// first we process the DI diagrams and associate them with the process elements
List<BPMNDiagram> diagrams = definitions.getDiagrams();
for (BPMNDiagram bpmnDiagram : diagrams) {
handleDIBpmnDiagram(bpmnDiagram);
}
// copied from old DIImport
// iterates over all elements in the diagram -> may be bad but is there another solution?
// first: add all IDs to our ID mapping table
TreeIterator<EObject> iter = definitions.eAllContents();
while (iter.hasNext()) {
ModelUtil.addID(iter.next());
}
// copied from old DIImport
// next, process the BPMN model elements and start building the Graphiti diagram
// first check if we display a single process or collaboration
List<RootElement> rootElements = definitions.getRootElements();
List<Process> processes = new ArrayList<Process>();
Collaboration collaboration = null;
for (RootElement rootElement: rootElements) {
if (rootElement instanceof Process) {
processes.add((Process) rootElement);
} else if (rootElement instanceof Collaboration) {
if (collaboration != null) {
throw new Bpmn2ImportException("Multiple collaborations not supported");
}
collaboration = (Collaboration) rootElement;
} else {
System.out.println("Unhandled RootElement: " + rootElement);
}
}
if (collaboration != null) {
// we display a collaboration
if (diagrams.isEmpty()) {
BPMNDiagram newDiagram = ModelCreator.create(resource, BPMNDiagram.class);
diagrams.add(newDiagram);
}
BPMNDiagram element = diagrams.get(0);
// create diagram for collaboration
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
handleCollaboration(collaboration, rootDiagram);
} else if (!processes.isEmpty()) {
// we display one or more processes
BPMNDiagram element = diagrams.get(0);
// create diagram for process(es)
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
for (Process process : processes) {
List<BaseElement> unhandledElements = new ArrayList<BaseElement>();
handleProcess(process, rootDiagram);
if (!unhandledElements.isEmpty()) {
throw new Bpmn2ImportException("Unhandled elements: " + unhandledElements);
}
}
} else {
// We have no root process or collaboration
createNewDiagramAndHandleIt(definitions);
}
// finally layout all elements
performLayout();
}
| protected void handleDefinitions(Definitions definitions) {
// first we process the DI diagrams and associate them with the process elements
List<BPMNDiagram> diagrams = definitions.getDiagrams();
for (BPMNDiagram bpmnDiagram : diagrams) {
handleDIBpmnDiagram(bpmnDiagram);
}
// copied from old DIImport
// iterates over all elements in the diagram -> may be bad but is there another solution?
// add all ids to the mapping table so that they won't be used when
// new ids are generated later
TreeIterator<EObject> iter = definitions.eAllContents();
while (iter.hasNext()) {
ModelUtil.addID(iter.next());
}
// end copied from old DIImport
// next, process the BPMN model elements and start building the Graphiti diagram
// first check if we display a single process or collaboration
List<RootElement> rootElements = definitions.getRootElements();
List<Process> processes = new ArrayList<Process>();
Collaboration collaboration = null;
for (RootElement rootElement: rootElements) {
if (rootElement instanceof Process) {
processes.add((Process) rootElement);
} else if (rootElement instanceof Collaboration) {
if (collaboration != null) {
throw new Bpmn2ImportException("Multiple collaborations not supported");
}
collaboration = (Collaboration) rootElement;
} else {
System.out.println("Unhandled RootElement: " + rootElement);
}
}
if (collaboration != null) {
// we display a collaboration
if (diagrams.isEmpty()) {
BPMNDiagram newDiagram = ModelCreator.create(resource, BPMNDiagram.class);
diagrams.add(newDiagram);
}
BPMNDiagram element = diagrams.get(0);
// create diagram for collaboration
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
handleCollaboration(collaboration, rootDiagram);
} else if (!processes.isEmpty()) {
// we display one or more processes
BPMNDiagram element = diagrams.get(0);
// create diagram for process(es)
Diagram rootDiagram = createRootDiagram((BPMNDiagram) element);
for (Process process : processes) {
List<BaseElement> unhandledElements = new ArrayList<BaseElement>();
handleProcess(process, rootDiagram);
if (!unhandledElements.isEmpty()) {
throw new Bpmn2ImportException("Unhandled elements: " + unhandledElements);
}
}
} else {
// We have no root process or collaboration
createNewDiagramAndHandleIt(definitions);
}
// finally layout all elements
performLayout();
}
|
diff --git a/weka/src/main/java/weka/core/KPrototypes_DistanceFunction.java b/weka/src/main/java/weka/core/KPrototypes_DistanceFunction.java
index 457d3e3..81a09d4 100644
--- a/weka/src/main/java/weka/core/KPrototypes_DistanceFunction.java
+++ b/weka/src/main/java/weka/core/KPrototypes_DistanceFunction.java
@@ -1,161 +1,160 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package weka.core;
import java.util.Vector;
/**
*
* @author Todor Tsonkov
*/
public class KPrototypes_DistanceFunction extends NormalizableDistance
implements Cloneable {
private double m_Gamma;
/** for serialization. */
private static final long serialVersionUID = 1068606253458807903L;
public KPrototypes_DistanceFunction( double gamma){
m_Gamma = gamma;
}
public KPrototypes_DistanceFunction() {
super();
m_Gamma = 0.5;
}
public KPrototypes_DistanceFunction(Instances data, double gamma) {
super(data);
m_Gamma = gamma;
}
/**
* Returns a string describing this object.
*
* @return a description of the evaluator suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Implementing KPrototypes distance (or similarity) function.\n\n"
+ "One object defines not one distance but the data model in which "
+ "the distances between objects of that data model can be computed.\n\n"
+ "Attention: For efficiency reasons the use of consistency checks "
+ "(like are the data models of the two instances exactly the same), "
+ "is low.\n\n";
}
//MOST IMPORTANT PART!
/**
* Calculates the distance between two instances.
*
* @param first the first instance
* @param second the second instance
* @return the distance between the two given instances
*/
@Override
public double distance(Instance first, Instance second) {
double sum_nominal = 0.0;
double sum_continuous = 0.0;
for(int i = 0; i < first.numAttributes(); i++){
if(first.attribute(i).isNominal()){
if(!first.attribute(i).equals(second.attribute(i)) )
sum_nominal+=1.0;
}else
if (first.attribute(i).isNumeric()){
- sum_continuous += (first.attribute(i).weight() - second.attribute(i).weight())*
- (first.attribute(i).weight() - second.attribute(i).weight());
+ sum_continuous += Math.pow(first.m_AttValues[i] - second.m_AttValues[i], 2);
}
}
return sum_continuous + m_Gamma * sum_nominal;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String gamma() {
return "gamma parameter";
}
/**
* fet the gamma parameter
*
* @return the gamma parameter
*/
public double getGamma()
{
return m_Gamma;
}
/**
* set the gamma parameter
*
* @param g the gamma parameter
*/
public void setGamma(double g)
{
m_Gamma = g;
}
/**
* Gets the current settings of BisectingKMeans
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
Vector<String> result;
String[] options;
result = new Vector<String>();
result.add("-G");
result.add("" + getGamma());
options = super.getOptions();
for (int i = 0; i < options.length; i++)
result.add(options[i]);
//result.
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String optionString;
optionString = Utils.getOption("G", options);
setGamma(Double.parseDouble(optionString));
super.setOptions(options);
}
//TODO: IMPLEMENT?
protected double updateDistance(double currDist, double diff) {
double result;
result = currDist;
result += diff * diff;
return result;
}
public String getRevision() {
return RevisionUtils.extract("$Revision: 1.13 $");
}
}
| true | true | public double distance(Instance first, Instance second) {
double sum_nominal = 0.0;
double sum_continuous = 0.0;
for(int i = 0; i < first.numAttributes(); i++){
if(first.attribute(i).isNominal()){
if(!first.attribute(i).equals(second.attribute(i)) )
sum_nominal+=1.0;
}else
if (first.attribute(i).isNumeric()){
sum_continuous += (first.attribute(i).weight() - second.attribute(i).weight())*
(first.attribute(i).weight() - second.attribute(i).weight());
}
}
return sum_continuous + m_Gamma * sum_nominal;
}
| public double distance(Instance first, Instance second) {
double sum_nominal = 0.0;
double sum_continuous = 0.0;
for(int i = 0; i < first.numAttributes(); i++){
if(first.attribute(i).isNominal()){
if(!first.attribute(i).equals(second.attribute(i)) )
sum_nominal+=1.0;
}else
if (first.attribute(i).isNumeric()){
sum_continuous += Math.pow(first.m_AttValues[i] - second.m_AttValues[i], 2);
}
}
return sum_continuous + m_Gamma * sum_nominal;
}
|
diff --git a/Fanorona/src/team01/Board.java b/Fanorona/src/team01/Board.java
index a65fcc5..b441755 100644
--- a/Fanorona/src/team01/Board.java
+++ b/Fanorona/src/team01/Board.java
@@ -1,74 +1,74 @@
package team01;
import java.util.*;
public class Board {
static final int ROW_SIZE = 5;
static final int COL_SIZE = 9;
static final int BOARD_SIZE = ROW_SIZE * COL_SIZE;
// board states
static final int EMPTY = 0;
static final int WHITE = 1;
static final int BLACK = 2;
private List <Integer> board;
private int nWhite;
private int nBlack;
// new game
public Board() {
board = new ArrayList <Integer>(BOARD_SIZE);
nWhite = nBlack = 22;
// first 2 rows
- for (int i = 0; i < 2*ROW_SIZE; i++) {
+ for (int i = 0; i < 2*COL_SIZE; i++) {
this.setPosition(i, BLACK);
}
// middle row
this.setPosition(18,BLACK);
this.setPosition(19,WHITE);
this.setPosition(20,BLACK);
this.setPosition(21,WHITE);
this.setPosition(22,EMPTY);
this.setPosition(23,BLACK);
this.setPosition(24,WHITE);
this.setPosition(25,BLACK);
this.setPosition(26,WHITE);
// last 2 rows
- for (int i = 3*ROW_SIZE; i < BOARD_SIZE; i++) {
+ for (int i = 3*COL_SIZE; i < BOARD_SIZE; i++) {
this.setPosition(i, WHITE);
}
}
int numWhite() {
return nWhite;
}
int numBlack() {
return nBlack;
}
int numEmpty() {
return BOARD_SIZE - nWhite - nBlack;
}
boolean isEmpty(int pos) {
return board.get(pos) == EMPTY;
}
boolean isWhite(int pos) {
return board.get(pos) == WHITE;
}
boolean isBlack(int pos) {
return board.get(pos) == BLACK;
}
void setPosition(int pos, int state) {
board.set(pos, state);
}
}
| false | true | public Board() {
board = new ArrayList <Integer>(BOARD_SIZE);
nWhite = nBlack = 22;
// first 2 rows
for (int i = 0; i < 2*ROW_SIZE; i++) {
this.setPosition(i, BLACK);
}
// middle row
this.setPosition(18,BLACK);
this.setPosition(19,WHITE);
this.setPosition(20,BLACK);
this.setPosition(21,WHITE);
this.setPosition(22,EMPTY);
this.setPosition(23,BLACK);
this.setPosition(24,WHITE);
this.setPosition(25,BLACK);
this.setPosition(26,WHITE);
// last 2 rows
for (int i = 3*ROW_SIZE; i < BOARD_SIZE; i++) {
this.setPosition(i, WHITE);
}
}
| public Board() {
board = new ArrayList <Integer>(BOARD_SIZE);
nWhite = nBlack = 22;
// first 2 rows
for (int i = 0; i < 2*COL_SIZE; i++) {
this.setPosition(i, BLACK);
}
// middle row
this.setPosition(18,BLACK);
this.setPosition(19,WHITE);
this.setPosition(20,BLACK);
this.setPosition(21,WHITE);
this.setPosition(22,EMPTY);
this.setPosition(23,BLACK);
this.setPosition(24,WHITE);
this.setPosition(25,BLACK);
this.setPosition(26,WHITE);
// last 2 rows
for (int i = 3*COL_SIZE; i < BOARD_SIZE; i++) {
this.setPosition(i, WHITE);
}
}
|
diff --git a/tubular-core/src/main/java/org/trancecode/xproc/step/AbstractCompoundStepProcessor.java b/tubular-core/src/main/java/org/trancecode/xproc/step/AbstractCompoundStepProcessor.java
index 744d3652..1d6874b9 100644
--- a/tubular-core/src/main/java/org/trancecode/xproc/step/AbstractCompoundStepProcessor.java
+++ b/tubular-core/src/main/java/org/trancecode/xproc/step/AbstractCompoundStepProcessor.java
@@ -1,127 +1,128 @@
/*
* Copyright (C) 2008 TranceCode Software
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id$
*/
package org.trancecode.xproc.step;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import org.trancecode.concurrent.TcFutures;
import org.trancecode.logging.Logger;
import org.trancecode.xproc.Environment;
/**
* @author Herve Quiroz
*/
public abstract class AbstractCompoundStepProcessor implements StepProcessor
{
private static final Logger LOG = Logger.getLogger(AbstractCompoundStepProcessor.class);
@Override
public Environment run(final Step step, final Environment environment)
{
LOG.trace("step = {}", step.getName());
assert step.isCompoundStep();
environment.setCurrentEnvironment();
final Environment stepEnvironment = environment.newFollowingStepEnvironment(step);
final Environment resultEnvironment = runSteps(step.getSubpipeline(), stepEnvironment);
return stepEnvironment.setupOutputPorts(step, resultEnvironment);
}
protected Environment runSteps(final Iterable<Step> steps, final Environment environment)
{
LOG.trace("steps = {}", steps);
final Environment initialEnvironment = environment.newChildStepEnvironment();
final Map<Step, Step> stepDependencies = Step.getSubpipelineStepDependencies(steps);
final Map<Step, Future<Environment>> stepResults = new ConcurrentHashMap<Step, Future<Environment>>();
final List<Future<Environment>> results = Lists.newArrayList();
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
for (final Step step : steps)
{
final Future<Environment> result = environment.getPipelineContext().getExecutor()
.submit(new Callable<Environment>()
{
@Override
public Environment call() throws Exception
{
// shortcut in case an error was reported by another
// task
if (error.get() != null)
{
throw new IllegalStateException(error.get());
}
final Step dependency = stepDependencies.get(step);
final Environment inputEnvironment;
if (dependency != null)
{
try
{
inputEnvironment = stepResults.get(dependency).get();
}
catch (final ExecutionException e)
{
throw Throwables.propagate(e.getCause());
}
}
else
{
inputEnvironment = initialEnvironment;
}
Environment.setCurrentNamespaceContext(step.getNode());
inputEnvironment.setCurrentEnvironment();
return step.run(inputEnvironment);
}
});
stepResults.put(step, result);
results.add(result);
}
final Iterable<Environment> resultEnvironments;
try
{
resultEnvironments = TcFutures.get(results);
}
catch (final ExecutionException e)
{
+ TcFutures.cancel(results);
throw Throwables.propagate(e.getCause());
}
catch (final InterruptedException e)
{
throw new IllegalStateException(e);
}
return Iterables.getLast(resultEnvironments, initialEnvironment);
}
}
| true | true | protected Environment runSteps(final Iterable<Step> steps, final Environment environment)
{
LOG.trace("steps = {}", steps);
final Environment initialEnvironment = environment.newChildStepEnvironment();
final Map<Step, Step> stepDependencies = Step.getSubpipelineStepDependencies(steps);
final Map<Step, Future<Environment>> stepResults = new ConcurrentHashMap<Step, Future<Environment>>();
final List<Future<Environment>> results = Lists.newArrayList();
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
for (final Step step : steps)
{
final Future<Environment> result = environment.getPipelineContext().getExecutor()
.submit(new Callable<Environment>()
{
@Override
public Environment call() throws Exception
{
// shortcut in case an error was reported by another
// task
if (error.get() != null)
{
throw new IllegalStateException(error.get());
}
final Step dependency = stepDependencies.get(step);
final Environment inputEnvironment;
if (dependency != null)
{
try
{
inputEnvironment = stepResults.get(dependency).get();
}
catch (final ExecutionException e)
{
throw Throwables.propagate(e.getCause());
}
}
else
{
inputEnvironment = initialEnvironment;
}
Environment.setCurrentNamespaceContext(step.getNode());
inputEnvironment.setCurrentEnvironment();
return step.run(inputEnvironment);
}
});
stepResults.put(step, result);
results.add(result);
}
final Iterable<Environment> resultEnvironments;
try
{
resultEnvironments = TcFutures.get(results);
}
catch (final ExecutionException e)
{
throw Throwables.propagate(e.getCause());
}
catch (final InterruptedException e)
{
throw new IllegalStateException(e);
}
return Iterables.getLast(resultEnvironments, initialEnvironment);
}
| protected Environment runSteps(final Iterable<Step> steps, final Environment environment)
{
LOG.trace("steps = {}", steps);
final Environment initialEnvironment = environment.newChildStepEnvironment();
final Map<Step, Step> stepDependencies = Step.getSubpipelineStepDependencies(steps);
final Map<Step, Future<Environment>> stepResults = new ConcurrentHashMap<Step, Future<Environment>>();
final List<Future<Environment>> results = Lists.newArrayList();
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
for (final Step step : steps)
{
final Future<Environment> result = environment.getPipelineContext().getExecutor()
.submit(new Callable<Environment>()
{
@Override
public Environment call() throws Exception
{
// shortcut in case an error was reported by another
// task
if (error.get() != null)
{
throw new IllegalStateException(error.get());
}
final Step dependency = stepDependencies.get(step);
final Environment inputEnvironment;
if (dependency != null)
{
try
{
inputEnvironment = stepResults.get(dependency).get();
}
catch (final ExecutionException e)
{
throw Throwables.propagate(e.getCause());
}
}
else
{
inputEnvironment = initialEnvironment;
}
Environment.setCurrentNamespaceContext(step.getNode());
inputEnvironment.setCurrentEnvironment();
return step.run(inputEnvironment);
}
});
stepResults.put(step, result);
results.add(result);
}
final Iterable<Environment> resultEnvironments;
try
{
resultEnvironments = TcFutures.get(results);
}
catch (final ExecutionException e)
{
TcFutures.cancel(results);
throw Throwables.propagate(e.getCause());
}
catch (final InterruptedException e)
{
throw new IllegalStateException(e);
}
return Iterables.getLast(resultEnvironments, initialEnvironment);
}
|
diff --git a/TeaLeaf/src/com/tealeaf/EventQueue.java b/TeaLeaf/src/com/tealeaf/EventQueue.java
index de6fe96..46db083 100644
--- a/TeaLeaf/src/com/tealeaf/EventQueue.java
+++ b/TeaLeaf/src/com/tealeaf/EventQueue.java
@@ -1,61 +1,61 @@
package com.tealeaf;
import java.util.Queue;
import com.tealeaf.event.Event;
public class EventQueue {
private static Queue<String> events = new java.util.concurrent.ConcurrentLinkedQueue<String>();
private static Object lock = new Object();
public static void pushEvent(Event e) {
synchronized (lock) {
events.add(e.pack());
}
}
protected static String popEvent() {
return events.poll();
}
private static String[] getEvents() {
String[] ret;
synchronized (lock) {
ret = new String[events.size()];
events.toArray(ret);
events.clear();
}
return ret;
}
public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
- if (len & 255) {
+ if ((len & 255) > 0) {
int batchLength = len & 255;
String[] batch = new String[batchLength];
System.arraycopy(e, len & ~255, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
}
| true | true | public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
if (len & 255) {
int batchLength = len & 255;
String[] batch = new String[batchLength];
System.arraycopy(e, len & ~255, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
| public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
if ((len & 255) > 0) {
int batchLength = len & 255;
String[] batch = new String[batchLength];
System.arraycopy(e, len & ~255, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
|
diff --git a/freeplane_ant/src/org/freeplane/ant/FormatTranslation.java b/freeplane_ant/src/org/freeplane/ant/FormatTranslation.java
index 505b470b0..9b8e9a005 100644
--- a/freeplane_ant/src/org/freeplane/ant/FormatTranslation.java
+++ b/freeplane_ant/src/org/freeplane/ant/FormatTranslation.java
@@ -1,309 +1,318 @@
/**
* FormatTranslation.java
*
* Copyright (C) 2010, Volker Boerchers
*
* FormatTranslation.java is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* FormatTranslation.java 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 for more details.
*/
package org.freeplane.ant;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Pattern;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
/** formats a translation file and writes the result to another file.
* The following transformations are made:
* <ol>
* <li> sort lines (case insensitive)
* <li> remove duplicates
* <li> if a key is present multiple times entries marked as [translate me]
* and [auto] are removed in favor of normal entries.
* <li> newline style is changed to <eolStyle>.
* </ol>
*
* Attributes:
* <ul>
* <li> dir: the input directory (default: ".")
* <li> outputDir: the output directory. Overwrites existing files if outputDir
* equals the input directory (default: the input directory)
* <li> includes: wildcard pattern (default: all regular files).
* <li> excludes: wildcard pattern, overrules includes (default: no excludes).
* <li> eolStyle: unix|mac|windows (default: platform default).
* </ul>
*
* Build messages:
* <table border=1>
* <tr><th>Message</th><th>Action</th><th>Description</th></tr>
* <tr><td><file>: no key/val: <line></td><td>drop line</td><td>broken line with an empty key or without an '=' sign</td></tr>
* <tr><td><file>: drop duplicate: <line></td><td>drop line</td><td>two completely identical lines</td></tr>
* <tr><td><file>: drop: <line></td><td>drop line</td>
* <td>this translation is dropped since a better one was found
* (quality: [translate me] -> [auto] -> manually translated)
* </td>
* </tr>
* <tr><td><file>: drop one of two of equal quality (revisit!):keep: <line></td><td>keep line</td>
* <td>for one key two manual translations were found. This one (arbitrarily chosen) will be kept.
* Printout of the complete line allows to correct an action of FormatTranslation via Copy and Past
* if it chose the wrong tranlation.
* </td>
* </tr>
* <tr><td><file>: drop one of two of equal quality (revisit!):drop: <line></td><td>drop line</td>
* <td>accompanies the :keep: line: This is the line that is dropped.
* </td>
* </tr>
* </table>
* Note that CheckTranslation does not remove anything but produces the same messages!
*/
public class FormatTranslation extends Task {
static Comparator<String> KEY_COMPARATOR = new Comparator<String>() {
public int compare(String s1, String s2) {
int n1 = s1.length(), n2 = s2.length();
for (int i1 = 0, i2 = 0; i1 < n1 && i2 < n2; i1++, i2++) {
char c1 = s1.charAt(i1);
char c2 = s2.charAt(i2);
boolean c1Terminated = c1 == ' ' || c1 == '\t' || c1 == '=';
boolean c2Terminated = c2 == ' ' || c2 == '\t' || c2 == '=';
if (c1Terminated && c2Terminated)
return 0;
if (c1Terminated && !c2Terminated)
return -1;
if (c2Terminated && !c1Terminated)
return 1;
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
return c1 - c2;
}
}
}
}
return n1 - n2;
}
};
private final static int QUALITY_NULL = 0; // for empty values
private final static int QUALITY_TRANSLATE_ME = 1;
private final static int QUALITY_AUTO_TRANSLATED = 2;
private final static int QUALITY_MANUALLY_TRANSLATED = 3;
private File outputDir;
private boolean writeIfUnchanged = false;
private File inputDir = new File(".");
private ArrayList<Pattern> includePatterns = new ArrayList<Pattern>();
private ArrayList<Pattern> excludePatterns = new ArrayList<Pattern>();
private String lineSeparator = System.getProperty("line.separator");
public void execute() {
final int countFormatted = executeImpl(false);
log(inputDir + ": formatted " + countFormatted + " file" + (countFormatted == 1 ? "" : "s"));
}
public int checkOnly() {
return executeImpl(true);
}
/** returns the number of unformatted files. */
private int executeImpl(boolean checkOnly) {
validate();
File[] inputFiles = inputDir.listFiles(new TaskUtils.IncludeFileFilter(includePatterns, excludePatterns));
return process(inputFiles, checkOnly);
}
static public void main(final String argc[]) {
File[] inputFiles = new File[argc.length];
int i = 0;
for (String arg : argc) {
inputFiles[i++] = new File(arg);
}
new FormatTranslation().process(inputFiles, false);
}
private int process(File[] inputFiles, boolean checkOnly) {
try {
int countFormattingRequired = 0;
for (int i = 0; i < inputFiles.length; i++) {
File inputFile = inputFiles[i];
log("processing " + inputFile + "...", Project.MSG_DEBUG);
final String input = TaskUtils.readFile(inputFile);
final ArrayList<String> lines = new ArrayList<String>(2048);
boolean eolStyleMatches = TaskUtils.checkEolStyleAndReadLines(input, lines, lineSeparator);
final ArrayList<String> sortedLines = processLines(inputFile.getName(), new ArrayList<String>(lines));
final boolean contentChanged = !lines.equals(sortedLines);
final boolean formattingRequired = !eolStyleMatches || contentChanged;
if (formattingRequired) {
++countFormattingRequired;
if (checkOnly)
warn(inputFile + " requires formatting - " + formatCause(contentChanged, eolStyleMatches));
else
log(inputFile + "formatted - " + formatCause(contentChanged, eolStyleMatches),
Project.MSG_DEBUG);
}
if (!checkOnly && (formattingRequired || writeIfUnchanged)) {
File outputFile = new File(outputDir, inputFile.getName());
TaskUtils.writeFile(outputFile, sortedLines, lineSeparator);
}
}
return countFormattingRequired;
}
catch (IOException e) {
throw new BuildException(e);
}
}
private String formatCause(boolean contentChanged, boolean eolStyleMatches) {
final String string1 = eolStyleMatches ? "" : "wrong eol style";
final String string2 = contentChanged ? "content changed" : "";
return string1 + (string1.length() > 0 && string2.length() > 0 ? ", " : "") + string2;
}
private void validate() {
if (inputDir == null)
throw new BuildException("missing attribute 'dir'");
if (outputDir == null)
outputDir = inputDir;
if (!inputDir.isDirectory())
throw new BuildException("input directory '" + inputDir + "' does not exist");
if (!outputDir.isDirectory() && !outputDir.mkdirs())
throw new BuildException("cannot create output directory '" + outputDir + "'");
}
ArrayList<String> processLines(final String filename, ArrayList<String> lines) {
Collections.sort(lines, KEY_COMPARATOR);
ArrayList<String> result = new ArrayList<String>(lines.size());
String lastKey = null;
String lastValue = null;
for (final String line : lines) {
if (line.indexOf('#') == 0 || line.matches("\\s*"))
continue;
final String[] keyValue = line.split("\\s*=\\s*", 2);
if (keyValue.length != 2 || keyValue[0].length() == 0) {
// broken line: no '=' sign or empty key (we had " = ======")
warn(filename + ": no key/val: " + line);
continue;
}
final String thisKey = keyValue[0];
- final String thisValue = keyValue[1];
+ String thisValue = keyValue[1];
if (thisValue.matches("(\\[auto\\]|\\[translate me\\])?")) {
warn(filename + ": empty translation: " + line);
}
if (thisValue.indexOf("{1}") != -1 && keyValue[1].indexOf("{0}") == -1) {
warn(filename + ": errorneous placeholders usage: {1} used without {0}: " + line);
}
if (thisValue.matches(".*\\$\\d.*")) {
warn(filename + ": use '{0}' instead of '$1' as placeholder! (likewise for $2...): " + line);
+ thisValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
+ }
+ if (thisValue.matches(".*\\{\\d[^},]*")) {
+ warn(filename + ": mismatched braces in placeholder: '{' not closed by '}': " + line);
+ }
+ if (thisValue.matches(".*[^']'[^'].*\\{\\d\\}.*") || thisValue.matches(".*\\{\\d\\}.*[^']'[^'].*")) {
+ warn(filename + ": replaced single quotes in strings containing placeholders by two: "
+ + "\"'{0}' n'a\" -> \"''{0}'' n''a\": " + line);
+ thisValue = thisValue.replaceAll("([^'])'([^'])", "$1''$2");
}
if (lastKey != null && thisKey.equals(lastKey)) {
if (quality(thisValue) < quality(lastValue)) {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
continue;
}
else if (quality(thisValue) == quality(lastValue)) {
if (thisValue.equals(lastValue)) {
log(filename + ": drop duplicate " + TaskUtils.toLine(lastKey, thisValue));
}
else if (quality(thisValue) == QUALITY_MANUALLY_TRANSLATED) {
warn(filename //
+ ": drop one of two of equal quality (revisit!):keep: "
+ TaskUtils.toLine(lastKey, lastValue));
warn(filename //
+ ": drop one of two of equal quality (revisit!):drop: "
+ TaskUtils.toLine(thisKey, thisValue));
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
}
continue;
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, lastValue));
}
- lastValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
+ lastValue = thisValue;
}
else {
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
lastKey = thisKey;
- lastValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
+ lastValue = thisValue;
}
}
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
return result;
}
private int quality(String value) {
if (value.length() == 0)
return QUALITY_NULL;
if (value.indexOf("[translate me]") > 0)
return QUALITY_TRANSLATE_ME;
if (value.indexOf("[auto]") > 0)
return QUALITY_AUTO_TRANSLATED;
return QUALITY_MANUALLY_TRANSLATED;
}
private void warn(String msg) {
log(msg, Project.MSG_WARN);
}
/** per default output files will only be created if the output would
* differ from the input file. Set attribute <code>writeIfUnchanged</code>
* to "true" to enforce file creation. */
public void setWriteIfUnchanged(boolean writeIfUnchanged) {
this.writeIfUnchanged = writeIfUnchanged;
}
public void setDir(String inputDir) {
setDir(new File(inputDir));
}
public void setDir(File inputDir) {
this.inputDir = inputDir;
}
public void setIncludes(String pattern) {
includePatterns.add(Pattern.compile(TaskUtils.wildcardToRegex(pattern)));
}
public void setExcludes(String pattern) {
excludePatterns.add(Pattern.compile(TaskUtils.wildcardToRegex(pattern)));
}
/** parameter is set in the build file via the attribute "outputDir" */
public void setOutputDir(String outputDir) {
setOutputDir(new File(outputDir));
}
/** parameter is set in the build file via the attribute "outputDir" */
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
/** parameter is set in the build file via the attribute "eolStyle" */
public void setEolStyle(String eolStyle) {
if (eolStyle.toLowerCase().startsWith("unix"))
lineSeparator = "\n";
else if (eolStyle.toLowerCase().startsWith("win"))
lineSeparator = "\r\n";
else if (eolStyle.toLowerCase().startsWith("mac"))
lineSeparator = "\r";
else
throw new BuildException("unknown eolStyle, known: unix|win|mac");
}
}
| false | true | ArrayList<String> processLines(final String filename, ArrayList<String> lines) {
Collections.sort(lines, KEY_COMPARATOR);
ArrayList<String> result = new ArrayList<String>(lines.size());
String lastKey = null;
String lastValue = null;
for (final String line : lines) {
if (line.indexOf('#') == 0 || line.matches("\\s*"))
continue;
final String[] keyValue = line.split("\\s*=\\s*", 2);
if (keyValue.length != 2 || keyValue[0].length() == 0) {
// broken line: no '=' sign or empty key (we had " = ======")
warn(filename + ": no key/val: " + line);
continue;
}
final String thisKey = keyValue[0];
final String thisValue = keyValue[1];
if (thisValue.matches("(\\[auto\\]|\\[translate me\\])?")) {
warn(filename + ": empty translation: " + line);
}
if (thisValue.indexOf("{1}") != -1 && keyValue[1].indexOf("{0}") == -1) {
warn(filename + ": errorneous placeholders usage: {1} used without {0}: " + line);
}
if (thisValue.matches(".*\\$\\d.*")) {
warn(filename + ": use '{0}' instead of '$1' as placeholder! (likewise for $2...): " + line);
}
if (lastKey != null && thisKey.equals(lastKey)) {
if (quality(thisValue) < quality(lastValue)) {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
continue;
}
else if (quality(thisValue) == quality(lastValue)) {
if (thisValue.equals(lastValue)) {
log(filename + ": drop duplicate " + TaskUtils.toLine(lastKey, thisValue));
}
else if (quality(thisValue) == QUALITY_MANUALLY_TRANSLATED) {
warn(filename //
+ ": drop one of two of equal quality (revisit!):keep: "
+ TaskUtils.toLine(lastKey, lastValue));
warn(filename //
+ ": drop one of two of equal quality (revisit!):drop: "
+ TaskUtils.toLine(thisKey, thisValue));
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
}
continue;
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, lastValue));
}
lastValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
}
else {
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
lastKey = thisKey;
lastValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
}
}
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
return result;
}
| ArrayList<String> processLines(final String filename, ArrayList<String> lines) {
Collections.sort(lines, KEY_COMPARATOR);
ArrayList<String> result = new ArrayList<String>(lines.size());
String lastKey = null;
String lastValue = null;
for (final String line : lines) {
if (line.indexOf('#') == 0 || line.matches("\\s*"))
continue;
final String[] keyValue = line.split("\\s*=\\s*", 2);
if (keyValue.length != 2 || keyValue[0].length() == 0) {
// broken line: no '=' sign or empty key (we had " = ======")
warn(filename + ": no key/val: " + line);
continue;
}
final String thisKey = keyValue[0];
String thisValue = keyValue[1];
if (thisValue.matches("(\\[auto\\]|\\[translate me\\])?")) {
warn(filename + ": empty translation: " + line);
}
if (thisValue.indexOf("{1}") != -1 && keyValue[1].indexOf("{0}") == -1) {
warn(filename + ": errorneous placeholders usage: {1} used without {0}: " + line);
}
if (thisValue.matches(".*\\$\\d.*")) {
warn(filename + ": use '{0}' instead of '$1' as placeholder! (likewise for $2...): " + line);
thisValue = thisValue.replaceAll("\\$1", "{0}").replaceAll("\\$2", "{1}");
}
if (thisValue.matches(".*\\{\\d[^},]*")) {
warn(filename + ": mismatched braces in placeholder: '{' not closed by '}': " + line);
}
if (thisValue.matches(".*[^']'[^'].*\\{\\d\\}.*") || thisValue.matches(".*\\{\\d\\}.*[^']'[^'].*")) {
warn(filename + ": replaced single quotes in strings containing placeholders by two: "
+ "\"'{0}' n'a\" -> \"''{0}'' n''a\": " + line);
thisValue = thisValue.replaceAll("([^'])'([^'])", "$1''$2");
}
if (lastKey != null && thisKey.equals(lastKey)) {
if (quality(thisValue) < quality(lastValue)) {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
continue;
}
else if (quality(thisValue) == quality(lastValue)) {
if (thisValue.equals(lastValue)) {
log(filename + ": drop duplicate " + TaskUtils.toLine(lastKey, thisValue));
}
else if (quality(thisValue) == QUALITY_MANUALLY_TRANSLATED) {
warn(filename //
+ ": drop one of two of equal quality (revisit!):keep: "
+ TaskUtils.toLine(lastKey, lastValue));
warn(filename //
+ ": drop one of two of equal quality (revisit!):drop: "
+ TaskUtils.toLine(thisKey, thisValue));
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, thisValue));
}
continue;
}
else {
log(filename + ": drop " + TaskUtils.toLine(lastKey, lastValue));
}
lastValue = thisValue;
}
else {
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
lastKey = thisKey;
lastValue = thisValue;
}
}
if (lastKey != null)
result.add(TaskUtils.toLine(lastKey, lastValue));
return result;
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 6560c5d3..cc595387 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1397 +1,1397 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import com.android.launcher.R;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList;
private IconCache mIconCache;
private Bitmap mDefaultIcon;
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app, IconCache iconCache) {
mApp = app;
mAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
app.getPackageManager().getDefaultActivityIcon(), app);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
}
Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR);
Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
- info.setIcon(icon);
break;
default:
- info.setIcon(getFallbackIcon());
+ icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
+ info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
}
Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR);
Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
info.setIcon(icon);
break;
default:
info.setIcon(getFallbackIcon());
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
}
Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR);
Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
|
diff --git a/src/java/net/sf/picard/analysis/CollectRnaSeqMetrics.java b/src/java/net/sf/picard/analysis/CollectRnaSeqMetrics.java
index b6867eb..5b5929f 100644
--- a/src/java/net/sf/picard/analysis/CollectRnaSeqMetrics.java
+++ b/src/java/net/sf/picard/analysis/CollectRnaSeqMetrics.java
@@ -1,173 +1,178 @@
/*
* The MIT License
*
* Copyright (c) 2011 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.analysis;
import net.sf.picard.annotation.Gene;
import net.sf.picard.annotation.GeneAnnotationReader;
import net.sf.picard.annotation.LocusFunction;
import net.sf.picard.annotation.Transcript;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.picard.util.Interval;
import net.sf.picard.util.IntervalList;
import net.sf.picard.util.Log;
import net.sf.picard.util.OverlapDetector;
import net.sf.samtools.*;
import net.sf.samtools.util.CoordMath;
import java.io.File;
import java.util.Collection;
import java.util.List;
//import net.sf.picard.analysis.LocusFunction.*;
/**
* Program to collect metrics about the alignment of RNA to the various functional classes of loci in the genome:
* coding, intronic, UTR, intragenic.
*/
public class CollectRnaSeqMetrics extends SinglePassSamProgram {
private static final Log LOG = Log.getInstance(CollectRnaSeqMetrics.class);
public enum StrandSpecificity {NONE, FIRST_READ_TRANSCRIPTION_STRAND, SECOND_READ_TRANSCRIPTION_STRAND}
@Option(doc="Gene annotations in refFlat form")
public File REF_FLAT;
@Option(doc="Location of rRNA sequences in genome, in interval_list format")
public File RIBOSOMAL_INTERVALS;
@Option(shortName = StandardOptionDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME)
public File SEQUENCE_DICTIONARY;
@Option(shortName = "STRAND", doc="For strand-specific library prep")
public StrandSpecificity STRAND_SPECIFICITY;
@Option
public boolean STRIP_LEADING_CHR_IN_REF_FLAT = true;
private OverlapDetector<Gene> geneOverlapDetector;
private final OverlapDetector<Interval> ribosomalSequenceOverlapDetector = new OverlapDetector<Interval>(0, 0);
private RnaSeqMetrics metrics;
/** Required main method implementation. */
public static void main(final String[] argv) {
new CollectRnaSeqMetrics().instanceMainWithExit(argv);
}
@Override
protected void setup(final SAMFileHeader header, final File samFile) {
final SAMSequenceDictionary sequenceDictionary = new SAMFileReader(SEQUENCE_DICTIONARY).getFileHeader().getSequenceDictionary();
geneOverlapDetector = GeneAnnotationReader.loadRefFlat(REF_FLAT, sequenceDictionary, STRIP_LEADING_CHR_IN_REF_FLAT);
LOG.info("Loaded " + geneOverlapDetector.getAll().size() + " genes.");
final IntervalList ribosomalIntervals = IntervalList.fromFile(RIBOSOMAL_INTERVALS);
ribosomalIntervals.unique();
final List<Interval> intervals = ribosomalIntervals.getIntervals();
ribosomalSequenceOverlapDetector.addAll(intervals, intervals);
metrics = new RnaSeqMetrics();
}
@Override
protected void acceptRead(final SAMRecord rec, final ReferenceSequence ref) {
if (rec.getReadUnmappedFlag() || rec.getReadFailsVendorQualityCheckFlag() || rec.getNotPrimaryAlignmentFlag()) return;
final Interval readInterval = new Interval(rec.getReferenceName(), rec.getAlignmentStart(), rec.getAlignmentEnd());
final Collection<Gene> overlappingGenes = geneOverlapDetector.getOverlaps(readInterval);
final Collection<Interval> overlappingRibosomalIntervals = ribosomalSequenceOverlapDetector.getOverlaps(readInterval);
final List<AlignmentBlock> alignmentBlocks = rec.getAlignmentBlocks();
boolean overlapsExon = false;
for (final AlignmentBlock alignmentBlock : alignmentBlocks) {
final LocusFunction[] locusFunctions = new LocusFunction[alignmentBlock.getLength()];
for (int i = 0; i < locusFunctions.length; ++i) locusFunctions[i] = LocusFunction.INTERGENIC;
for (final Interval ribosomalInterval : overlappingRibosomalIntervals) {
assignValueForOverlappingRange(ribosomalInterval, alignmentBlock.getReferenceStart(),
locusFunctions, LocusFunction.RIBOSOMAL);
}
for (final Gene gene : overlappingGenes) {
for (final Transcript transcript : gene) {
transcript.getLocusFunctionForRange(alignmentBlock.getReferenceStart(), locusFunctions);
}
}
for (final LocusFunction locusFunction : locusFunctions) {
++metrics.ALIGNED_PF_BASES;
switch (locusFunction) {
case INTERGENIC:
++metrics.INTERGENIC_BASES;
break;
case INTRONIC:
++metrics.INTRONIC_BASES;
break;
case UTR:
++metrics.UTR_BASES;
overlapsExon = true;
break;
case CODING:
++metrics.CODING_BASES;
overlapsExon = true;
break;
case RIBOSOMAL:
++metrics.RIBOSOMAL_BASES;
break;
}
}
}
- if (overlapsExon && STRAND_SPECIFICITY != StrandSpecificity.NONE && overlappingGenes.size() == 1) {
+ if (rec.getReadPairedFlag() && overlapsExon && STRAND_SPECIFICITY != StrandSpecificity.NONE && overlappingGenes.size() == 1) {
final boolean negativeTranscriptionStrand = overlappingGenes.iterator().next().isNegativeStrand();
final boolean negativeReadStrand = rec.getReadNegativeStrandFlag();
- if (negativeReadStrand == negativeTranscriptionStrand &&
- rec.getFirstOfPairFlag() == (STRAND_SPECIFICITY == StrandSpecificity.FIRST_READ_TRANSCRIPTION_STRAND)) {
+ // If the read strand is the same as the strand of the transcript, and the end is the one that is supposed to agree,
+ // then the strand specificity for this read is correct.
+ // -- OR --
+ // If the read strand is not the same as the strand of the transcript, and the end is not the one that is supposed
+ // to agree, then the strand specificity for this read is correct.
+ if ((negativeReadStrand == negativeTranscriptionStrand) ==
+ (rec.getFirstOfPairFlag() == (STRAND_SPECIFICITY == StrandSpecificity.FIRST_READ_TRANSCRIPTION_STRAND))) {
++metrics.CORRECT_STRAND_READS;
} else {
++metrics.INCORRECT_STRAND_READS;
}
}
}
@Override
protected void finish() {
if (metrics.ALIGNED_PF_BASES > 0) {
metrics.PCT_RIBOSOMAL_BASES = metrics.RIBOSOMAL_BASES / (double) metrics.ALIGNED_PF_BASES;
metrics.PCT_CODING_BASES = metrics.CODING_BASES / (double) metrics.ALIGNED_PF_BASES;
metrics.PCT_UTR_BASES = metrics.UTR_BASES / (double) metrics.ALIGNED_PF_BASES;
metrics.PCT_INTRONIC_BASES = metrics.INTRONIC_BASES / (double) metrics.ALIGNED_PF_BASES;
metrics.PCT_INTERGENIC_BASES = metrics.INTERGENIC_BASES / (double) metrics.ALIGNED_PF_BASES;
}
if (metrics.CORRECT_STRAND_READS > 0 || metrics.INCORRECT_STRAND_READS > 0) {
metrics.PCT_CORRECT_STRAND_READS = metrics.CORRECT_STRAND_READS/(double)(metrics.CORRECT_STRAND_READS + metrics.INCORRECT_STRAND_READS);
}
final MetricsFile<RnaSeqMetrics, Integer> file = getMetricsFile();
file.addMetric(metrics);
file.write(OUTPUT);
}
private void assignValueForOverlappingRange(final Interval interval, final int start,
final LocusFunction[] locusFunctions, final LocusFunction valueToAssign) {
for (int i = Math.max(start, interval.getStart());
i <= Math.min(interval.getEnd(), CoordMath.getEnd(start, locusFunctions.length)); ++i) {
locusFunctions[i - start] = valueToAssign;
}
}
}
| false | true | protected void acceptRead(final SAMRecord rec, final ReferenceSequence ref) {
if (rec.getReadUnmappedFlag() || rec.getReadFailsVendorQualityCheckFlag() || rec.getNotPrimaryAlignmentFlag()) return;
final Interval readInterval = new Interval(rec.getReferenceName(), rec.getAlignmentStart(), rec.getAlignmentEnd());
final Collection<Gene> overlappingGenes = geneOverlapDetector.getOverlaps(readInterval);
final Collection<Interval> overlappingRibosomalIntervals = ribosomalSequenceOverlapDetector.getOverlaps(readInterval);
final List<AlignmentBlock> alignmentBlocks = rec.getAlignmentBlocks();
boolean overlapsExon = false;
for (final AlignmentBlock alignmentBlock : alignmentBlocks) {
final LocusFunction[] locusFunctions = new LocusFunction[alignmentBlock.getLength()];
for (int i = 0; i < locusFunctions.length; ++i) locusFunctions[i] = LocusFunction.INTERGENIC;
for (final Interval ribosomalInterval : overlappingRibosomalIntervals) {
assignValueForOverlappingRange(ribosomalInterval, alignmentBlock.getReferenceStart(),
locusFunctions, LocusFunction.RIBOSOMAL);
}
for (final Gene gene : overlappingGenes) {
for (final Transcript transcript : gene) {
transcript.getLocusFunctionForRange(alignmentBlock.getReferenceStart(), locusFunctions);
}
}
for (final LocusFunction locusFunction : locusFunctions) {
++metrics.ALIGNED_PF_BASES;
switch (locusFunction) {
case INTERGENIC:
++metrics.INTERGENIC_BASES;
break;
case INTRONIC:
++metrics.INTRONIC_BASES;
break;
case UTR:
++metrics.UTR_BASES;
overlapsExon = true;
break;
case CODING:
++metrics.CODING_BASES;
overlapsExon = true;
break;
case RIBOSOMAL:
++metrics.RIBOSOMAL_BASES;
break;
}
}
}
if (overlapsExon && STRAND_SPECIFICITY != StrandSpecificity.NONE && overlappingGenes.size() == 1) {
final boolean negativeTranscriptionStrand = overlappingGenes.iterator().next().isNegativeStrand();
final boolean negativeReadStrand = rec.getReadNegativeStrandFlag();
if (negativeReadStrand == negativeTranscriptionStrand &&
rec.getFirstOfPairFlag() == (STRAND_SPECIFICITY == StrandSpecificity.FIRST_READ_TRANSCRIPTION_STRAND)) {
++metrics.CORRECT_STRAND_READS;
} else {
++metrics.INCORRECT_STRAND_READS;
}
}
}
| protected void acceptRead(final SAMRecord rec, final ReferenceSequence ref) {
if (rec.getReadUnmappedFlag() || rec.getReadFailsVendorQualityCheckFlag() || rec.getNotPrimaryAlignmentFlag()) return;
final Interval readInterval = new Interval(rec.getReferenceName(), rec.getAlignmentStart(), rec.getAlignmentEnd());
final Collection<Gene> overlappingGenes = geneOverlapDetector.getOverlaps(readInterval);
final Collection<Interval> overlappingRibosomalIntervals = ribosomalSequenceOverlapDetector.getOverlaps(readInterval);
final List<AlignmentBlock> alignmentBlocks = rec.getAlignmentBlocks();
boolean overlapsExon = false;
for (final AlignmentBlock alignmentBlock : alignmentBlocks) {
final LocusFunction[] locusFunctions = new LocusFunction[alignmentBlock.getLength()];
for (int i = 0; i < locusFunctions.length; ++i) locusFunctions[i] = LocusFunction.INTERGENIC;
for (final Interval ribosomalInterval : overlappingRibosomalIntervals) {
assignValueForOverlappingRange(ribosomalInterval, alignmentBlock.getReferenceStart(),
locusFunctions, LocusFunction.RIBOSOMAL);
}
for (final Gene gene : overlappingGenes) {
for (final Transcript transcript : gene) {
transcript.getLocusFunctionForRange(alignmentBlock.getReferenceStart(), locusFunctions);
}
}
for (final LocusFunction locusFunction : locusFunctions) {
++metrics.ALIGNED_PF_BASES;
switch (locusFunction) {
case INTERGENIC:
++metrics.INTERGENIC_BASES;
break;
case INTRONIC:
++metrics.INTRONIC_BASES;
break;
case UTR:
++metrics.UTR_BASES;
overlapsExon = true;
break;
case CODING:
++metrics.CODING_BASES;
overlapsExon = true;
break;
case RIBOSOMAL:
++metrics.RIBOSOMAL_BASES;
break;
}
}
}
if (rec.getReadPairedFlag() && overlapsExon && STRAND_SPECIFICITY != StrandSpecificity.NONE && overlappingGenes.size() == 1) {
final boolean negativeTranscriptionStrand = overlappingGenes.iterator().next().isNegativeStrand();
final boolean negativeReadStrand = rec.getReadNegativeStrandFlag();
// If the read strand is the same as the strand of the transcript, and the end is the one that is supposed to agree,
// then the strand specificity for this read is correct.
// -- OR --
// If the read strand is not the same as the strand of the transcript, and the end is not the one that is supposed
// to agree, then the strand specificity for this read is correct.
if ((negativeReadStrand == negativeTranscriptionStrand) ==
(rec.getFirstOfPairFlag() == (STRAND_SPECIFICITY == StrandSpecificity.FIRST_READ_TRANSCRIPTION_STRAND))) {
++metrics.CORRECT_STRAND_READS;
} else {
++metrics.INCORRECT_STRAND_READS;
}
}
}
|
diff --git a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java
index 213a4793b..1037f337e 100644
--- a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java
+++ b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java
@@ -1,338 +1,338 @@
package fi.csc.microarray.client.visualisation.methods.gbrowser.track;
import java.awt.Color;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import fi.csc.microarray.client.visualisation.methods.gbrowser.DataSource;
import fi.csc.microarray.client.visualisation.methods.gbrowser.GenomeBrowserConstants;
import fi.csc.microarray.client.visualisation.methods.gbrowser.View;
import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.AreaRequestHandler;
import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.Drawable;
import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.RectDrawable;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ColumnType;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.Strand;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AreaResult;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.Cigar;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.ReadPart;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.RegionContent;
import fi.csc.microarray.client.visualisation.methods.gbrowser.utils.Sequence;
/**
* Track that shows actual content of reads using color coding.
*
*/
public class SeqBlockTrack extends Track {
public static final Color[] charColors = new Color[] {
new Color(64, 192, 64, 128), // A
new Color(64, 64, 192, 128), // C
new Color(128, 128, 128, 128), // G
new Color(192, 64, 64, 128) // T
};
private Collection<RegionContent> reads = new TreeSet<RegionContent>();
private List<Integer> occupiedSpace = new ArrayList<Integer>();
private long maxBpLength;
private long minBpLength;
private DataSource refData;
private Collection<RegionContent> refReads = new TreeSet<RegionContent>();
private boolean highlightSNP = false;
public SeqBlockTrack(View view, DataSource file, Class<? extends AreaRequestHandler> handler, Color fontColor, long minBpLength, long maxBpLength) {
super(view, file, handler);
this.minBpLength = minBpLength;
this.maxBpLength = maxBpLength;
}
@Override
public Collection<Drawable> getDrawables() {
Collection<Drawable> drawables = getEmptyDrawCollection();
occupiedSpace.clear();
// If SNP highlight mode is on, we need reference sequence data
char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null;
// Main loop: Iterate over RegionContent objects (one object corresponds to one read)
Iterator<RegionContent> iter = reads.iterator();
while (iter.hasNext()) {
RegionContent read = iter.next();
// Remove reads that are not in this view
if (!read.region.intersects(getView().getBpRegion())) {
iter.remove();
continue;
}
// Collect relevant data for this read
// Split read into continuous blocks (elements) by using the cigar
List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read);
for (ReadPart visibleRegion : visibleRegions) {
// Skip elements that are not in this view
if (!visibleRegion.intersects(getView().getBpRegion())) {
continue;
}
// Width in basepairs
long widthInBps = visibleRegion.getLength();
// Create rectangle covering the correct screen area (x-axis)
Rectangle rect = new Rectangle();
rect.x = getView().bpToTrack(visibleRegion.start);
rect.width = (int) Math.round(getView().bpWidth() * widthInBps);
// Do not draw invisible rectangles
if (rect.width < 2) {
rect.width = 2;
}
// Read parts are drawn in order and placed in layers
int layer = 0;
while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) {
layer++;
}
// Read part reserves the space of the layer from end to left corner of the screen
int end = rect.x + rect.width;
if (occupiedSpace.size() > layer) {
occupiedSpace.set(layer, end);
} else {
occupiedSpace.add(end);
}
// Now we can decide the y coordinate
rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT);
rect.height = GenomeBrowserConstants.READ_HEIGHT;
// Check if we are about to go over the edge of the drawing area
boolean lastBeforeMaxStackingDepthCut = false; //getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight();
// Check if we are over the edge of the drawing area
if (rect.y > getHeight()) {
-// continue;
+ continue;
}
// Check if we have enough space for the actual sequence (at least pixel per nucleotide)
String seq = visibleRegion.getSequencePart();
Cigar cigar = (Cigar) read.values.get(ColumnType.CIGAR);
if (rect.width < seq.length()) {
// Too little space - only show one rectangle for each read part
Color color = Color.gray;
// Mark last line that will be drawn
if (lastBeforeMaxStackingDepthCut) {
color = color.brighter();
}
drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString()));
} else {
// Enough space - show color coding for each nucleotide
// Complement the read if on reverse strand
if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) {
StringBuffer buf = new StringBuffer(seq.toUpperCase());
// Complement
seq = buf.toString().replace('A', 'x'). // switch A and T
replace('T', 'A').replace('x', 'T').
replace('C', 'x'). // switch C and G
replace('G', 'C').replace('x', 'G');
}
// Prepare to draw single nucleotides
float increment = getView().bpWidth();
float startX = getView().bpToTrackFloat(visibleRegion.start);
// Draw each nucleotide
for (int j = 0; j < seq.length(); j++) {
char letter = seq.charAt(j);
long refIndex = j;
// Choose a color depending on viewing mode
Color bg = Color.white;
long posInRef = visibleRegion.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue();
if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) {
bg = Color.gray;
} else {
switch (letter) {
case 'A':
bg = charColors[0];
break;
case 'C':
bg = charColors[1];
break;
case 'G':
bg = charColors[2];
break;
case 'T':
bg = charColors[3];
break;
}
}
// Tell that we have reached max. stacking depth
if (lastBeforeMaxStackingDepthCut) {
bg = bg.brighter();
}
// Draw rectangle
int x1 = Math.round(startX + ((float)refIndex) * increment);
int x2 = Math.round(startX + ((float)refIndex + 1f) * increment);
int width = Math.max(x2 - x1, 1);
drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString()));
}
}
}
}
return drawables;
}
private int getYCoord(int layer, int height) {
return (int) ((layer + 1) * (height + GenomeBrowserConstants.SPACE_BETWEEN_READS));
}
public void processAreaResult(AreaResult<RegionContent> areaResult) {
// Check that areaResult has same concised status (currently always false) and correct strand
if (areaResult.status.file == file && areaResult.status.concise == isConcised() && areaResult.content.values.get(ColumnType.STRAND) == getStrand()) {
// Add this to queue of RegionContents to be processed
this.reads.add(areaResult.content);
getView().redraw();
}
// "Spy" on reference sequence data, if available
if (areaResult.status.file == refData) {
this.refReads.add(areaResult.content);
}
}
@Override
public Integer getHeight() {
if (isVisible()) {
return super.getHeight();
} else {
return 0;
}
}
@Override
public boolean isStretchable() {
return isVisible(); // Stretchable unless hidden
}
@Override
public boolean isVisible() {
// visible region is not suitable
return (super.isVisible() && getView().getBpRegion().getLength() > minBpLength && getView().getBpRegion().getLength() <= maxBpLength);
}
@Override
public Map<DataSource, Set<ColumnType>> requestedData() {
HashMap<DataSource, Set<ColumnType>> datas = new HashMap<DataSource, Set<ColumnType>>();
datas.put(file, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE, ColumnType.STRAND, ColumnType.CIGAR })));
// We might also need reference sequence data
if (highlightSNP) {
datas.put(refData, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE })));
}
return datas;
}
@Override
public boolean isConcised() {
return false;
}
/**
* Enable SNP highlighting and set reference data.
*
* @param highlightSNP
* @see SeqBlockTrack.setReferenceSeq
*/
public void enableSNPHighlight(DataSource file, Class<? extends AreaRequestHandler> handler) {
// turn on highlighting mode
highlightSNP = true;
// set reference data
refData = file;
view.getQueueManager().createQueue(file, handler);
view.getQueueManager().addResultListener(file, this);
}
/**
* Disable SNP highlighting.
*
* @param file
*/
public void disableSNPHiglight(DataSource file) {
// turn off highlighting mode
highlightSNP = false;
}
/**
* Convert reference sequence reads to a char array.
*/
public static char[] getReferenceArray(Collection<RegionContent> refReads, View view, Strand strand) {
char[] refSeq = new char[0];
Iterator<RegionContent> iter = refReads.iterator();
refSeq = new char[view.getBpRegion().getLength().intValue() + 1];
int startBp = view.getBpRegion().start.bp.intValue();
int endBp = view.getBpRegion().end.bp.intValue();
RegionContent read;
while (iter.hasNext()) {
read = iter.next();
if (!read.region.intersects(view.getBpRegion())) {
iter.remove();
continue;
}
// we might need to reverse reference sequence
char[] readBases;
if (strand == Strand.REVERSED) {
readBases = Sequence.complement((String) read.values.get(ColumnType.SEQUENCE)).toCharArray();
} else {
readBases = ((String) read.values.get(ColumnType.SEQUENCE)).toCharArray();
}
int readStart = read.region.start.bp.intValue();
int readNum = 0;
int nextPos = 0;
for (char c : readBases) {
nextPos = readStart + readNum++;
if (nextPos >= startBp && nextPos <= endBp) {
refSeq[nextPos - startBp] = c;
}
}
}
return refSeq;
}
@Override
public String getName() {
return "Reads";
}
}
| true | true | public Collection<Drawable> getDrawables() {
Collection<Drawable> drawables = getEmptyDrawCollection();
occupiedSpace.clear();
// If SNP highlight mode is on, we need reference sequence data
char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null;
// Main loop: Iterate over RegionContent objects (one object corresponds to one read)
Iterator<RegionContent> iter = reads.iterator();
while (iter.hasNext()) {
RegionContent read = iter.next();
// Remove reads that are not in this view
if (!read.region.intersects(getView().getBpRegion())) {
iter.remove();
continue;
}
// Collect relevant data for this read
// Split read into continuous blocks (elements) by using the cigar
List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read);
for (ReadPart visibleRegion : visibleRegions) {
// Skip elements that are not in this view
if (!visibleRegion.intersects(getView().getBpRegion())) {
continue;
}
// Width in basepairs
long widthInBps = visibleRegion.getLength();
// Create rectangle covering the correct screen area (x-axis)
Rectangle rect = new Rectangle();
rect.x = getView().bpToTrack(visibleRegion.start);
rect.width = (int) Math.round(getView().bpWidth() * widthInBps);
// Do not draw invisible rectangles
if (rect.width < 2) {
rect.width = 2;
}
// Read parts are drawn in order and placed in layers
int layer = 0;
while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) {
layer++;
}
// Read part reserves the space of the layer from end to left corner of the screen
int end = rect.x + rect.width;
if (occupiedSpace.size() > layer) {
occupiedSpace.set(layer, end);
} else {
occupiedSpace.add(end);
}
// Now we can decide the y coordinate
rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT);
rect.height = GenomeBrowserConstants.READ_HEIGHT;
// Check if we are about to go over the edge of the drawing area
boolean lastBeforeMaxStackingDepthCut = false; //getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight();
// Check if we are over the edge of the drawing area
if (rect.y > getHeight()) {
// continue;
}
// Check if we have enough space for the actual sequence (at least pixel per nucleotide)
String seq = visibleRegion.getSequencePart();
Cigar cigar = (Cigar) read.values.get(ColumnType.CIGAR);
if (rect.width < seq.length()) {
// Too little space - only show one rectangle for each read part
Color color = Color.gray;
// Mark last line that will be drawn
if (lastBeforeMaxStackingDepthCut) {
color = color.brighter();
}
drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString()));
} else {
// Enough space - show color coding for each nucleotide
// Complement the read if on reverse strand
if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) {
StringBuffer buf = new StringBuffer(seq.toUpperCase());
// Complement
seq = buf.toString().replace('A', 'x'). // switch A and T
replace('T', 'A').replace('x', 'T').
replace('C', 'x'). // switch C and G
replace('G', 'C').replace('x', 'G');
}
// Prepare to draw single nucleotides
float increment = getView().bpWidth();
float startX = getView().bpToTrackFloat(visibleRegion.start);
// Draw each nucleotide
for (int j = 0; j < seq.length(); j++) {
char letter = seq.charAt(j);
long refIndex = j;
// Choose a color depending on viewing mode
Color bg = Color.white;
long posInRef = visibleRegion.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue();
if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) {
bg = Color.gray;
} else {
switch (letter) {
case 'A':
bg = charColors[0];
break;
case 'C':
bg = charColors[1];
break;
case 'G':
bg = charColors[2];
break;
case 'T':
bg = charColors[3];
break;
}
}
// Tell that we have reached max. stacking depth
if (lastBeforeMaxStackingDepthCut) {
bg = bg.brighter();
}
// Draw rectangle
int x1 = Math.round(startX + ((float)refIndex) * increment);
int x2 = Math.round(startX + ((float)refIndex + 1f) * increment);
int width = Math.max(x2 - x1, 1);
drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString()));
}
}
}
}
return drawables;
}
| public Collection<Drawable> getDrawables() {
Collection<Drawable> drawables = getEmptyDrawCollection();
occupiedSpace.clear();
// If SNP highlight mode is on, we need reference sequence data
char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null;
// Main loop: Iterate over RegionContent objects (one object corresponds to one read)
Iterator<RegionContent> iter = reads.iterator();
while (iter.hasNext()) {
RegionContent read = iter.next();
// Remove reads that are not in this view
if (!read.region.intersects(getView().getBpRegion())) {
iter.remove();
continue;
}
// Collect relevant data for this read
// Split read into continuous blocks (elements) by using the cigar
List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read);
for (ReadPart visibleRegion : visibleRegions) {
// Skip elements that are not in this view
if (!visibleRegion.intersects(getView().getBpRegion())) {
continue;
}
// Width in basepairs
long widthInBps = visibleRegion.getLength();
// Create rectangle covering the correct screen area (x-axis)
Rectangle rect = new Rectangle();
rect.x = getView().bpToTrack(visibleRegion.start);
rect.width = (int) Math.round(getView().bpWidth() * widthInBps);
// Do not draw invisible rectangles
if (rect.width < 2) {
rect.width = 2;
}
// Read parts are drawn in order and placed in layers
int layer = 0;
while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) {
layer++;
}
// Read part reserves the space of the layer from end to left corner of the screen
int end = rect.x + rect.width;
if (occupiedSpace.size() > layer) {
occupiedSpace.set(layer, end);
} else {
occupiedSpace.add(end);
}
// Now we can decide the y coordinate
rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT);
rect.height = GenomeBrowserConstants.READ_HEIGHT;
// Check if we are about to go over the edge of the drawing area
boolean lastBeforeMaxStackingDepthCut = false; //getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight();
// Check if we are over the edge of the drawing area
if (rect.y > getHeight()) {
continue;
}
// Check if we have enough space for the actual sequence (at least pixel per nucleotide)
String seq = visibleRegion.getSequencePart();
Cigar cigar = (Cigar) read.values.get(ColumnType.CIGAR);
if (rect.width < seq.length()) {
// Too little space - only show one rectangle for each read part
Color color = Color.gray;
// Mark last line that will be drawn
if (lastBeforeMaxStackingDepthCut) {
color = color.brighter();
}
drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString()));
} else {
// Enough space - show color coding for each nucleotide
// Complement the read if on reverse strand
if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) {
StringBuffer buf = new StringBuffer(seq.toUpperCase());
// Complement
seq = buf.toString().replace('A', 'x'). // switch A and T
replace('T', 'A').replace('x', 'T').
replace('C', 'x'). // switch C and G
replace('G', 'C').replace('x', 'G');
}
// Prepare to draw single nucleotides
float increment = getView().bpWidth();
float startX = getView().bpToTrackFloat(visibleRegion.start);
// Draw each nucleotide
for (int j = 0; j < seq.length(); j++) {
char letter = seq.charAt(j);
long refIndex = j;
// Choose a color depending on viewing mode
Color bg = Color.white;
long posInRef = visibleRegion.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue();
if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) {
bg = Color.gray;
} else {
switch (letter) {
case 'A':
bg = charColors[0];
break;
case 'C':
bg = charColors[1];
break;
case 'G':
bg = charColors[2];
break;
case 'T':
bg = charColors[3];
break;
}
}
// Tell that we have reached max. stacking depth
if (lastBeforeMaxStackingDepthCut) {
bg = bg.brighter();
}
// Draw rectangle
int x1 = Math.round(startX + ((float)refIndex) * increment);
int x2 = Math.round(startX + ((float)refIndex + 1f) * increment);
int width = Math.max(x2 - x1, 1);
drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString()));
}
}
}
}
return drawables;
}
|
diff --git a/tools/host/src/com/android/cts/CtsTestResult.java b/tools/host/src/com/android/cts/CtsTestResult.java
index 0aea74b3..851b07d3 100644
--- a/tools/host/src/com/android/cts/CtsTestResult.java
+++ b/tools/host/src/com/android/cts/CtsTestResult.java
@@ -1,203 +1,209 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.cts;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import java.util.Enumeration;
import java.util.HashMap;
/**
* Store the result of a specific test.
*/
public class CtsTestResult {
private int mResultCode;
private String mFailedMessage;
private String mStackTrace;
public static final int CODE_INIT = -1;
public static final int CODE_NOT_EXECUTED = 0;
public static final int CODE_PASS = 1;
public static final int CODE_FAIL = 2;
public static final int CODE_ERROR = 3;
public static final int CODE_TIMEOUT = 4;
public static final int CODE_OMITTED = 5;
public static final int CODE_FIRST = CODE_INIT;
public static final int CODE_LAST = CODE_OMITTED;
public static final String STR_ERROR = "error";
public static final String STR_TIMEOUT = "timeout";
public static final String STR_NOT_EXECUTED = "notExecuted";
public static final String STR_OMITTED = "omitted";
public static final String STR_FAIL = "fail";
public static final String STR_PASS = "pass";
private static HashMap<Integer, String> sCodeToResultMap;
private static HashMap<String, Integer> sResultToCodeMap;
static {
sCodeToResultMap = new HashMap<Integer, String>();
sCodeToResultMap.put(CODE_NOT_EXECUTED, STR_NOT_EXECUTED);
sCodeToResultMap.put(CODE_PASS, STR_PASS);
sCodeToResultMap.put(CODE_FAIL, STR_FAIL);
sCodeToResultMap.put(CODE_ERROR, STR_ERROR);
sCodeToResultMap.put(CODE_TIMEOUT, STR_TIMEOUT);
sCodeToResultMap.put(CODE_OMITTED, STR_OMITTED);
sResultToCodeMap = new HashMap<String, Integer>();
for (int code : sCodeToResultMap.keySet()) {
sResultToCodeMap.put(sCodeToResultMap.get(code), code);
}
}
public CtsTestResult(int resCode) {
mResultCode = resCode;
}
public CtsTestResult(int resCode, final String failedMessage, final String stackTrace) {
mResultCode = resCode;
mFailedMessage = failedMessage;
mStackTrace = stackTrace;
}
public CtsTestResult(final String result, final String failedMessage,
final String stackTrace) throws InvalidTestResultStringException {
if (!sResultToCodeMap.containsKey(result)) {
throw new InvalidTestResultStringException(result);
}
mResultCode = sResultToCodeMap.get(result);
mFailedMessage = failedMessage;
mStackTrace = stackTrace;
}
/**
* Check if the result indicates failure.
*
* @return If failed, return true; else, return false.
*/
public boolean isFail() {
return mResultCode == CODE_FAIL;
}
/**
* Check if the result indicates pass.
*
* @return If pass, return true; else, return false.
*/
public boolean isPass() {
return mResultCode == CODE_PASS;
}
/**
* Check if the result indicates not executed.
*
* @return If not executed, return true; else, return false.
*/
public boolean isNotExecuted() {
return mResultCode == CODE_NOT_EXECUTED;
}
/**
* Get result code of the test.
*
* @return The result code of the test.
* The following is the possible result codes:
* <ul>
* <li> notExecuted
* <li> pass
* <li> fail
* <li> error
* <li> timeout
* </ul>
*/
public int getResultCode() {
return mResultCode;
}
/**
* Get the failed message.
*
* @return The failed message.
*/
public String getFailedMessage() {
return mFailedMessage;
}
/**
* Get the stack trace.
*
* @return The stack trace.
*/
public String getStackTrace() {
return mStackTrace;
}
/**
* Set the result.
*
* @param testResult The result in the form of JUnit test result.
*/
@SuppressWarnings("unchecked")
public void setResult(TestResult testResult) {
int resCode = CODE_PASS;
String failedMessage = null;
String stackTrace = null;
- if ((testResult != null) && (testResult.failureCount() > 0)) {
+ if ((testResult != null) && (testResult.failureCount() > 0 || testResult.errorCount() > 0)) {
resCode = CODE_FAIL;
Enumeration<TestFailure> failures = testResult.failures();
while (failures.hasMoreElements()) {
TestFailure failure = failures.nextElement();
failedMessage += failure.exceptionMessage();
stackTrace += failure.trace();
}
+ Enumeration<TestFailure> errors = testResult.errors();
+ while (errors.hasMoreElements()) {
+ TestFailure failure = errors.nextElement();
+ failedMessage += failure.exceptionMessage();
+ stackTrace += failure.trace();
+ }
}
mResultCode = resCode;
mFailedMessage = failedMessage;
mStackTrace = stackTrace;
}
/**
* Reverse the result code.
*/
public void reverse() {
if (isPass()) {
mResultCode = CtsTestResult.CODE_FAIL;
} else if (isFail()){
mResultCode = CtsTestResult.CODE_PASS;
}
}
/**
* Get the test result as string.
*
* @return The readable result string.
*/
public String getResultString() {
return sCodeToResultMap.get(mResultCode);
}
/**
* Check if the given resultType is a valid result type defined..
*
* @param resultType The result type to be checked.
* @return If valid, return true; else, return false.
*/
static public boolean isValidResultType(final String resultType) {
return sResultToCodeMap.containsKey(resultType);
}
}
| false | true | public void setResult(TestResult testResult) {
int resCode = CODE_PASS;
String failedMessage = null;
String stackTrace = null;
if ((testResult != null) && (testResult.failureCount() > 0)) {
resCode = CODE_FAIL;
Enumeration<TestFailure> failures = testResult.failures();
while (failures.hasMoreElements()) {
TestFailure failure = failures.nextElement();
failedMessage += failure.exceptionMessage();
stackTrace += failure.trace();
}
}
mResultCode = resCode;
mFailedMessage = failedMessage;
mStackTrace = stackTrace;
}
| public void setResult(TestResult testResult) {
int resCode = CODE_PASS;
String failedMessage = null;
String stackTrace = null;
if ((testResult != null) && (testResult.failureCount() > 0 || testResult.errorCount() > 0)) {
resCode = CODE_FAIL;
Enumeration<TestFailure> failures = testResult.failures();
while (failures.hasMoreElements()) {
TestFailure failure = failures.nextElement();
failedMessage += failure.exceptionMessage();
stackTrace += failure.trace();
}
Enumeration<TestFailure> errors = testResult.errors();
while (errors.hasMoreElements()) {
TestFailure failure = errors.nextElement();
failedMessage += failure.exceptionMessage();
stackTrace += failure.trace();
}
}
mResultCode = resCode;
mFailedMessage = failedMessage;
mStackTrace = stackTrace;
}
|
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index b0926e2d..fbde39ee 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -1,67 +1,68 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os.cts;
import dalvik.annotation.TestTargetClass;
import android.os.Build;
import android.util.Log;
import junit.framework.TestCase;
@TestTargetClass(Build.VERSION.class)
public class BuildVersionTest extends TestCase {
private static final String LOG_TAG = "BuildVersionTest";
private static final String EXPECTED_RELEASE = "1.6";
private static final String EXPECTED_SDK = "4";
public void testReleaseVersion() {
// Applications may rely on the exact release version
assertEquals(EXPECTED_RELEASE, Build.VERSION.RELEASE);
assertEquals(EXPECTED_SDK, Build.VERSION.SDK);
}
/**
* Verifies {@link Build.FINGERPRINT} follows expected format:
* <p/>
* <code>
* (BRAND)/(PRODUCT)/(DEVICE)/(BOARD):(VERSION.RELEASE)/(BUILD_ID)/
* (BUILD_NUMBER):(BUILD_VARIANT)/(TAGS)
* </code>
*/
public void testBuildFingerprint() {
final String fingerprint = Build.FINGERPRINT;
Log.i(LOG_TAG, String.format("Testing fingerprint %s", fingerprint));
assertEquals("Build fingerprint must not include whitespace", -1,
fingerprint.indexOf(' '));
final String[] fingerprintSegs = fingerprint.split("/");
assertEquals("Build fingerprint does not match expected format", 7, fingerprintSegs.length);
assertEquals(Build.BRAND, fingerprintSegs[0]);
assertEquals(Build.PRODUCT, fingerprintSegs[1]);
assertEquals(Build.DEVICE, fingerprintSegs[2]);
// parse BOARD:VERSION_RELEASE
String[] bootloaderPlat = fingerprintSegs[3].split(":");
assertEquals(Build.BOARD, bootloaderPlat[0]);
assertEquals(Build.VERSION.RELEASE, bootloaderPlat[1]);
assertEquals(Build.ID, fingerprintSegs[4]);
// no requirements for BUILD_NUMBER and BUILD_VARIANT
assertTrue(fingerprintSegs[5].contains(":"));
- assertEquals(Build.TAGS, fingerprintSegs[6]);
+ // no strict requirement for TAGS
+ //assertEquals(Build.TAGS, fingerprintSegs[6]);
}
}
| true | true | public void testBuildFingerprint() {
final String fingerprint = Build.FINGERPRINT;
Log.i(LOG_TAG, String.format("Testing fingerprint %s", fingerprint));
assertEquals("Build fingerprint must not include whitespace", -1,
fingerprint.indexOf(' '));
final String[] fingerprintSegs = fingerprint.split("/");
assertEquals("Build fingerprint does not match expected format", 7, fingerprintSegs.length);
assertEquals(Build.BRAND, fingerprintSegs[0]);
assertEquals(Build.PRODUCT, fingerprintSegs[1]);
assertEquals(Build.DEVICE, fingerprintSegs[2]);
// parse BOARD:VERSION_RELEASE
String[] bootloaderPlat = fingerprintSegs[3].split(":");
assertEquals(Build.BOARD, bootloaderPlat[0]);
assertEquals(Build.VERSION.RELEASE, bootloaderPlat[1]);
assertEquals(Build.ID, fingerprintSegs[4]);
// no requirements for BUILD_NUMBER and BUILD_VARIANT
assertTrue(fingerprintSegs[5].contains(":"));
assertEquals(Build.TAGS, fingerprintSegs[6]);
}
| public void testBuildFingerprint() {
final String fingerprint = Build.FINGERPRINT;
Log.i(LOG_TAG, String.format("Testing fingerprint %s", fingerprint));
assertEquals("Build fingerprint must not include whitespace", -1,
fingerprint.indexOf(' '));
final String[] fingerprintSegs = fingerprint.split("/");
assertEquals("Build fingerprint does not match expected format", 7, fingerprintSegs.length);
assertEquals(Build.BRAND, fingerprintSegs[0]);
assertEquals(Build.PRODUCT, fingerprintSegs[1]);
assertEquals(Build.DEVICE, fingerprintSegs[2]);
// parse BOARD:VERSION_RELEASE
String[] bootloaderPlat = fingerprintSegs[3].split(":");
assertEquals(Build.BOARD, bootloaderPlat[0]);
assertEquals(Build.VERSION.RELEASE, bootloaderPlat[1]);
assertEquals(Build.ID, fingerprintSegs[4]);
// no requirements for BUILD_NUMBER and BUILD_VARIANT
assertTrue(fingerprintSegs[5].contains(":"));
// no strict requirement for TAGS
//assertEquals(Build.TAGS, fingerprintSegs[6]);
}
|
diff --git a/src/org/odk/collect/android/tasks/DownloadFormListTask.java b/src/org/odk/collect/android/tasks/DownloadFormListTask.java
index 2a42ed8..95da20f 100644
--- a/src/org/odk/collect/android/tasks/DownloadFormListTask.java
+++ b/src/org/odk/collect/android/tasks/DownloadFormListTask.java
@@ -1,296 +1,296 @@
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.tasks;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HttpContext;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Element;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormListDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.utilities.DocumentFetchResult;
import org.odk.collect.android.utilities.WebUtils;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.HashMap;
/**
* Background task for downloading forms from urls or a formlist from a url. We overload this task a
* bit so that we don't have to keep track of two separate downloading tasks and it simplifies
* interfaces. If LIST_URL is passed to doInBackground(), we fetch a form list. If a hashmap
* containing form/url pairs is passed, we download those forms.
*
* @author carlhartung
*/
public class DownloadFormListTask extends AsyncTask<Void, String, HashMap<String, FormDetails>> {
private static final String t = "DownloadFormsTask";
// used to store error message if one occurs
public static final String DL_ERROR_MSG = "dlerrormessage";
public static final String DL_AUTH_REQUIRED = "dlauthrequired";
private FormListDownloaderListener mStateListener;
private static final String NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST =
"http://openrosa.org/xforms/xformsList";
private boolean isXformsListNamespacedElement(Element e) {
return e.getNamespace().equalsIgnoreCase(NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST);
}
@Override
protected HashMap<String, FormDetails> doInBackground(Void... values) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
String downloadListUrl =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
String downloadPath =
settings.getString(PreferencesActivity.KEY_FORMLIST_URL, "/formlist");
downloadListUrl += downloadPath;
// We populate this with available forms from the specified server.
// <formname, details>
HashMap<String, FormDetails> formList = new HashMap<String, FormDetails>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(downloadListUrl, localContext, httpclient);
// If we can't get the document, return the error, cancel the task
if (result.errorMessage != null) {
if (result.responseCode == 401) {
formList.put(DL_AUTH_REQUIRED, new FormDetails(result.errorMessage));
} else {
formList.put(DL_ERROR_MSG, new FormDetails(result.errorMessage));
}
return formList;
}
if (result.isOpenRosaResponse) {
// Attempt OpenRosa 1.0 parsing
Element xformsElement = result.doc.getRootElement();
if (!xformsElement.getName().equals("xforms")) {
String error = "root element is not <xforms> : " + xformsElement.getName();
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
String namespace = xformsElement.getNamespace();
if (!isXformsListNamespacedElement(xformsElement)) {
String error = "root element namespace is incorrect:" + namespace;
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
int nElements = xformsElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (xformsElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element xformElement = (Element) xformsElement.getElement(i);
if (!isXformsListNamespacedElement(xformElement)) {
// someone else's extension?
continue;
}
String name = xformElement.getName();
if (!name.equalsIgnoreCase("xform")) {
// someone else's extension?
continue;
}
// this is something we know how to interpret
String formId = null;
String formName = null;
String majorMinorVersion = null;
String description = null;
String downloadUrl = null;
String manifestUrl = null;
// don't process descriptionUrl
int fieldCount = xformElement.getChildCount();
for (int j = 0; j < fieldCount; ++j) {
if (xformElement.getType(j) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = xformElement.getElement(j);
if (!isXformsListNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
} else if (tag.equals("name")) {
formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
} else if (tag.equals("majorMinorVersion")) {
majorMinorVersion = XFormParser.getXMLText(child, true);
if (majorMinorVersion != null && majorMinorVersion.length() == 0) {
majorMinorVersion = null;
}
} else if (tag.equals("descriptionText")) {
description = XFormParser.getXMLText(child, true);
if (description != null && description.length() == 0) {
description = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
} else if (tag.equals("manifestUrl")) {
manifestUrl = XFormParser.getXMLText(child, true);
if (manifestUrl != null && manifestUrl.length() == 0) {
manifestUrl = null;
}
}
}
if (formId == null || downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing one or more tags: formId, name, or downloadUrl";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
/*
* TODO: We currently don't care about major/minor version. maybe someday we will.
*/
// Integer modelVersion = null;
// Integer uiVersion = null;
// try {
// if (majorMinorVersion == null || majorMinorVersion.length() == 0) {
// modelVersion = null;
// uiVersion = null;
// } else {
// int idx = majorMinorVersion.indexOf(".");
// if (idx == -1) {
// modelVersion = Integer.parseInt(majorMinorVersion);
// uiVersion = null;
// } else {
// modelVersion = Integer.parseInt(majorMinorVersion.substring(0, idx));
// uiVersion =
// (idx == majorMinorVersion.length() - 1) ? null : Integer
// .parseInt(majorMinorVersion.substring(idx + 1));
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// String error = "Forms list entry " + Integer.toString(i) +
// " has an invalid majorMinorVersion: " + majorMinorVersion;
// Log.e(t, "Parsing OpenRosa reply -- " + error);
// formList.clear();
// formList.put(DL_ERROR_MSG, new FormDetails(
// Collect.getInstance().getString(R.string.parse_openrosa_formlist_failed,
// error)));
// return formList;
// }
formList.put(formId, new FormDetails(formName, downloadUrl, manifestUrl, formId));
}
} else {
// Aggregate 0.9.x mode...
// populate HashMap with form names and urls
Element formsElement = result.doc.getRootElement();
int formsCount = formsElement.getChildCount();
for (int i = 0; i < formsCount; ++i) {
if (formsElement.getType(i) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = formsElement.getElement(i);
String tag = child.getName();
String formId = null;
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
}
if (tag.equalsIgnoreCase("form")) {
String formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
String downloadUrl = child.getAttributeValue(null, "url");
downloadUrl = downloadUrl.trim();
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
if (downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing form name or url attribute";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_legacy_formlist_failed, error)));
return formList;
}
- formList.put(formId, new FormDetails(formName, downloadUrl, null, formId));
+ formList.put(formName, new FormDetails(formName, downloadUrl, null, formName));
}
}
}
return formList;
}
@Override
protected void onPostExecute(HashMap<String, FormDetails> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.formListDownloadingComplete(value);
}
}
}
public void setDownloaderListener(FormListDownloaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| true | true | protected HashMap<String, FormDetails> doInBackground(Void... values) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
String downloadListUrl =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
String downloadPath =
settings.getString(PreferencesActivity.KEY_FORMLIST_URL, "/formlist");
downloadListUrl += downloadPath;
// We populate this with available forms from the specified server.
// <formname, details>
HashMap<String, FormDetails> formList = new HashMap<String, FormDetails>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(downloadListUrl, localContext, httpclient);
// If we can't get the document, return the error, cancel the task
if (result.errorMessage != null) {
if (result.responseCode == 401) {
formList.put(DL_AUTH_REQUIRED, new FormDetails(result.errorMessage));
} else {
formList.put(DL_ERROR_MSG, new FormDetails(result.errorMessage));
}
return formList;
}
if (result.isOpenRosaResponse) {
// Attempt OpenRosa 1.0 parsing
Element xformsElement = result.doc.getRootElement();
if (!xformsElement.getName().equals("xforms")) {
String error = "root element is not <xforms> : " + xformsElement.getName();
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
String namespace = xformsElement.getNamespace();
if (!isXformsListNamespacedElement(xformsElement)) {
String error = "root element namespace is incorrect:" + namespace;
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
int nElements = xformsElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (xformsElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element xformElement = (Element) xformsElement.getElement(i);
if (!isXformsListNamespacedElement(xformElement)) {
// someone else's extension?
continue;
}
String name = xformElement.getName();
if (!name.equalsIgnoreCase("xform")) {
// someone else's extension?
continue;
}
// this is something we know how to interpret
String formId = null;
String formName = null;
String majorMinorVersion = null;
String description = null;
String downloadUrl = null;
String manifestUrl = null;
// don't process descriptionUrl
int fieldCount = xformElement.getChildCount();
for (int j = 0; j < fieldCount; ++j) {
if (xformElement.getType(j) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = xformElement.getElement(j);
if (!isXformsListNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
} else if (tag.equals("name")) {
formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
} else if (tag.equals("majorMinorVersion")) {
majorMinorVersion = XFormParser.getXMLText(child, true);
if (majorMinorVersion != null && majorMinorVersion.length() == 0) {
majorMinorVersion = null;
}
} else if (tag.equals("descriptionText")) {
description = XFormParser.getXMLText(child, true);
if (description != null && description.length() == 0) {
description = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
} else if (tag.equals("manifestUrl")) {
manifestUrl = XFormParser.getXMLText(child, true);
if (manifestUrl != null && manifestUrl.length() == 0) {
manifestUrl = null;
}
}
}
if (formId == null || downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing one or more tags: formId, name, or downloadUrl";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
/*
* TODO: We currently don't care about major/minor version. maybe someday we will.
*/
// Integer modelVersion = null;
// Integer uiVersion = null;
// try {
// if (majorMinorVersion == null || majorMinorVersion.length() == 0) {
// modelVersion = null;
// uiVersion = null;
// } else {
// int idx = majorMinorVersion.indexOf(".");
// if (idx == -1) {
// modelVersion = Integer.parseInt(majorMinorVersion);
// uiVersion = null;
// } else {
// modelVersion = Integer.parseInt(majorMinorVersion.substring(0, idx));
// uiVersion =
// (idx == majorMinorVersion.length() - 1) ? null : Integer
// .parseInt(majorMinorVersion.substring(idx + 1));
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// String error = "Forms list entry " + Integer.toString(i) +
// " has an invalid majorMinorVersion: " + majorMinorVersion;
// Log.e(t, "Parsing OpenRosa reply -- " + error);
// formList.clear();
// formList.put(DL_ERROR_MSG, new FormDetails(
// Collect.getInstance().getString(R.string.parse_openrosa_formlist_failed,
// error)));
// return formList;
// }
formList.put(formId, new FormDetails(formName, downloadUrl, manifestUrl, formId));
}
} else {
// Aggregate 0.9.x mode...
// populate HashMap with form names and urls
Element formsElement = result.doc.getRootElement();
int formsCount = formsElement.getChildCount();
for (int i = 0; i < formsCount; ++i) {
if (formsElement.getType(i) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = formsElement.getElement(i);
String tag = child.getName();
String formId = null;
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
}
if (tag.equalsIgnoreCase("form")) {
String formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
String downloadUrl = child.getAttributeValue(null, "url");
downloadUrl = downloadUrl.trim();
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
if (downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing form name or url attribute";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_legacy_formlist_failed, error)));
return formList;
}
formList.put(formId, new FormDetails(formName, downloadUrl, null, formId));
}
}
}
return formList;
}
| protected HashMap<String, FormDetails> doInBackground(Void... values) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
String downloadListUrl =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
String downloadPath =
settings.getString(PreferencesActivity.KEY_FORMLIST_URL, "/formlist");
downloadListUrl += downloadPath;
// We populate this with available forms from the specified server.
// <formname, details>
HashMap<String, FormDetails> formList = new HashMap<String, FormDetails>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(downloadListUrl, localContext, httpclient);
// If we can't get the document, return the error, cancel the task
if (result.errorMessage != null) {
if (result.responseCode == 401) {
formList.put(DL_AUTH_REQUIRED, new FormDetails(result.errorMessage));
} else {
formList.put(DL_ERROR_MSG, new FormDetails(result.errorMessage));
}
return formList;
}
if (result.isOpenRosaResponse) {
// Attempt OpenRosa 1.0 parsing
Element xformsElement = result.doc.getRootElement();
if (!xformsElement.getName().equals("xforms")) {
String error = "root element is not <xforms> : " + xformsElement.getName();
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
String namespace = xformsElement.getNamespace();
if (!isXformsListNamespacedElement(xformsElement)) {
String error = "root element namespace is incorrect:" + namespace;
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
int nElements = xformsElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (xformsElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element xformElement = (Element) xformsElement.getElement(i);
if (!isXformsListNamespacedElement(xformElement)) {
// someone else's extension?
continue;
}
String name = xformElement.getName();
if (!name.equalsIgnoreCase("xform")) {
// someone else's extension?
continue;
}
// this is something we know how to interpret
String formId = null;
String formName = null;
String majorMinorVersion = null;
String description = null;
String downloadUrl = null;
String manifestUrl = null;
// don't process descriptionUrl
int fieldCount = xformElement.getChildCount();
for (int j = 0; j < fieldCount; ++j) {
if (xformElement.getType(j) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = xformElement.getElement(j);
if (!isXformsListNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
} else if (tag.equals("name")) {
formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
} else if (tag.equals("majorMinorVersion")) {
majorMinorVersion = XFormParser.getXMLText(child, true);
if (majorMinorVersion != null && majorMinorVersion.length() == 0) {
majorMinorVersion = null;
}
} else if (tag.equals("descriptionText")) {
description = XFormParser.getXMLText(child, true);
if (description != null && description.length() == 0) {
description = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
} else if (tag.equals("manifestUrl")) {
manifestUrl = XFormParser.getXMLText(child, true);
if (manifestUrl != null && manifestUrl.length() == 0) {
manifestUrl = null;
}
}
}
if (formId == null || downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing one or more tags: formId, name, or downloadUrl";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
/*
* TODO: We currently don't care about major/minor version. maybe someday we will.
*/
// Integer modelVersion = null;
// Integer uiVersion = null;
// try {
// if (majorMinorVersion == null || majorMinorVersion.length() == 0) {
// modelVersion = null;
// uiVersion = null;
// } else {
// int idx = majorMinorVersion.indexOf(".");
// if (idx == -1) {
// modelVersion = Integer.parseInt(majorMinorVersion);
// uiVersion = null;
// } else {
// modelVersion = Integer.parseInt(majorMinorVersion.substring(0, idx));
// uiVersion =
// (idx == majorMinorVersion.length() - 1) ? null : Integer
// .parseInt(majorMinorVersion.substring(idx + 1));
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// String error = "Forms list entry " + Integer.toString(i) +
// " has an invalid majorMinorVersion: " + majorMinorVersion;
// Log.e(t, "Parsing OpenRosa reply -- " + error);
// formList.clear();
// formList.put(DL_ERROR_MSG, new FormDetails(
// Collect.getInstance().getString(R.string.parse_openrosa_formlist_failed,
// error)));
// return formList;
// }
formList.put(formId, new FormDetails(formName, downloadUrl, manifestUrl, formId));
}
} else {
// Aggregate 0.9.x mode...
// populate HashMap with form names and urls
Element formsElement = result.doc.getRootElement();
int formsCount = formsElement.getChildCount();
for (int i = 0; i < formsCount; ++i) {
if (formsElement.getType(i) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = formsElement.getElement(i);
String tag = child.getName();
String formId = null;
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
}
if (tag.equalsIgnoreCase("form")) {
String formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
String downloadUrl = child.getAttributeValue(null, "url");
downloadUrl = downloadUrl.trim();
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
if (downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing form name or url attribute";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_legacy_formlist_failed, error)));
return formList;
}
formList.put(formName, new FormDetails(formName, downloadUrl, null, formName));
}
}
}
return formList;
}
|
diff --git a/sensor/src/org/concord/sensor/device/impl/JavaDeviceFactory.java b/sensor/src/org/concord/sensor/device/impl/JavaDeviceFactory.java
index 0d51ffc..d466e89 100644
--- a/sensor/src/org/concord/sensor/device/impl/JavaDeviceFactory.java
+++ b/sensor/src/org/concord/sensor/device/impl/JavaDeviceFactory.java
@@ -1,288 +1,288 @@
/*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* END LICENSE */
/*
* Last modification information:
* $Revision: 1.25 $
* $Date: 2007-06-06 13:02:38 $
* $Author: scytacki $
*
* Licence Information
* Copyright 2004 The Concord Consortium
*/
package org.concord.sensor.device.impl;
import java.util.Hashtable;
import java.util.logging.Logger;
import org.concord.framework.text.UserMessageHandler;
import org.concord.sensor.DeviceConfig;
import org.concord.sensor.device.DeviceFactory;
import org.concord.sensor.device.DeviceIdAware;
import org.concord.sensor.device.DeviceService;
import org.concord.sensor.device.DeviceServiceAware;
import org.concord.sensor.device.SensorDevice;
import org.concord.sensor.impl.Ticker;
import org.concord.sensor.serial.SensorSerialPort;
/**
* JavaDeviceFactory
* Class name and description
*
* Date created: Dec 1, 2004
*
* @author scott<p>
*
*/
public class JavaDeviceFactory
implements DeviceFactory, DeviceID, DeviceService
{
private static final Logger logger = Logger.getLogger(JavaDeviceFactory.class.getCanonicalName());
Ticker ticker = null;
Hashtable deviceTable = new Hashtable();
Hashtable configTable = new Hashtable();
/*
*
new DeviceID( 0, "Pseudo Device" ,null),
new DeviceID(10, "Vernier GoLink" ,null),
new DeviceID(11, "Vernier LabPro" ,null),
new DeviceID(12, "Vernier LabQuest" ,null),
new DeviceID(20, "TI Connect" ,null),
new DeviceID(30, "Fourier" ,null),
new DeviceID(40, "Data Harvest USB" ,null),
new DeviceID(45, "Data Harvest CF" ,null),
new DeviceID(41, "Data Harvest Advanced" ,null),
new DeviceID(42, "Data Harvest QAdvanced" ,null),
new DeviceID(50, "ImagiWorks Serial" ,null),
new DeviceID(55, "ImagiWorks SD" ,null),
new DeviceID(60, "Pasco Serial" ,null),
new DeviceID(61, "Pasco Airlink" ,null),
new DeviceID(70, "CCProbe Version 0" ,null),
new DeviceID(71, "CCProbe Version 1" ,null),
new DeviceID(72, "CCProbe Version 2" ,null),
new DeviceID(80, "Coach" ,null),
*/
/**
*
*/
public JavaDeviceFactory()
{
ticker = new JavaTicker();
}
/* (non-Javadoc)
* @see org.concord.sensor.DeviceFactory#createDevice(org.concord.sensor.DeviceConfig)
*/
public SensorDevice createDevice(DeviceConfig config)
{
int id = config.getDeviceId();
String configStr = config.getConfigString();
String deviceConfigId = "" + id + ":" + configStr;
SensorDevice existingDevice =
(SensorDevice)deviceTable.get(deviceConfigId);
if(existingDevice != null) {
return existingDevice;
}
String className = null;
SensorDevice device = null;
switch(id) {
case PSEUDO_DEVICE:
className = "org.concord.sensor.pseudo.PseudoSensorDevice";
break;
case VERNIER_GO_LINK:
className = "org.concord.sensor.nativelib.NativeVernierSensorDevice";
break;
case VERNIER_LAB_PRO:
className = "org.concord.sensor.vernier.labpro.LabProSensorDevice";
break;
case VERNIER_LAB_QUEST:
className = "org.concord.sensor.vernier.labquest.LabQuestSensorDevice";
break;
case TI_CONNECT:
className = "org.concord.sensor.nativelib.NativeTISensorDevice";
break;
case FOURIER:
case DATA_HARVEST_USB:
case DATA_HARVEST_ADVANCED:
case DATA_HARVEST_QADVANCED:
className = "org.concord.sensor.dataharvest.DataHarvestSensorDevice";
break;
case PASCO_SERIAL:
className = "org.concord.sensor.pasco.SW500SensorDevice";
break;
case PASCO_AIRLINK:
className = "org.concord.sensor.pasco.AirLinkSensorDevice";
break;
case PASCO_USB:
className = "org.concord.sensor.pasco.PascoUsbSensorDevice";
break;
case DATA_HARVEST_CF:
case IMAGIWORKS_SERIAL:
case IMAGIWORKS_SD:
case COACH:
device = null;
break;
// TODO: need to handle config string so
// the serial port can be specified
case CCPROBE_VERSION_0:
className = "org.concord.sensor.cc.CCInterface0";
break;
case CCPROBE_VERSION_1:
className = "org.concord.sensor.cc.CCInterface1";
break;
case CCPROBE_VERSION_2:
- className = "org.concord.sensor.cc.CCinterface2";
+ className = "org.concord.sensor.cc.CCInterface2";
break;
}
if(className == null) {
// We didn't get a class for this device so warn the user
// at least in the console
System.err.println("Unknown Sensor Interface type: " + id);
return null;
}
try {
System.out.println("Loading sensor device: " + className);
Class sensDeviceClass =
getClass().getClassLoader().loadClass(className);
device = (SensorDevice) sensDeviceClass.newInstance();
if(device instanceof DeviceIdAware) {
((DeviceIdAware)device).setDeviceId(id);
}
if(device instanceof DeviceServiceAware) {
((DeviceServiceAware)device).setDeviceService(this);
}
device.open(config.getConfigString());
} catch (Exception e) {
e.printStackTrace();
}
deviceTable.put(deviceConfigId, device);
configTable.put(device, deviceConfigId);
return device;
}
public void destroyDevice(SensorDevice device)
{
device.close();
String configStr = (String)configTable.get(device);
deviceTable.remove(configStr);
configTable.remove(device);
}
public int getOSType()
{
String osName = System.getProperty("os.name");
if(osName.startsWith("Windows")){
return OS_WINDOWS;
}
if(osName.startsWith("Linux")){
return OS_LINUX;
}
if(osName.startsWith("Mac OS X")){
return OS_OSX;
}
return OS_UNKNOWN;
}
public SensorSerialPort getSerialPort(String name, SensorSerialPort oldPort)
{
String portClassName = null;
if(FTDI_SERIAL_PORT.equals(name)){
portClassName = "org.concord.sensor.dataharvest.SensorSerialPortFTDI";
} else if(OS_SERIAL_PORT.equals(name)) {
portClassName = "org.concord.sensor.serial.SensorSerialPortRXTX";
} else if(LABPROUSB_SERIAL_PORT.equals(name)) {
portClassName = "org.concord.sensor.vernier.labpro.SensorSerialPortLabProUSB";
}
try {
Class portClass = getClass().getClassLoader().loadClass(portClassName);
if(!portClass.isInstance(oldPort)){
return(SensorSerialPort) portClass.newInstance();
} else {
return oldPort;
}
} catch (Exception e) {
System.err.println("Can't load serial port driver class: " +
portClassName);
}
return null;
}
public void log(String message)
{
logger.info(message);
}
public void sleep(int millis)
{
try{
Thread.sleep(millis);
} catch (InterruptedException e){
e.printStackTrace();
}
}
public long currentTimeMillis()
{
return System.currentTimeMillis();
}
public float intBitsToFloat(int valueInt)
{
return Float.intBitsToFloat(valueInt);
}
public boolean isValidFloat(float val)
{
return !Float.isNaN(val);
}
public UserMessageHandler getMessageHandler()
{
// TODO Auto-generated method stub
return null;
}
}
| true | true | public SensorDevice createDevice(DeviceConfig config)
{
int id = config.getDeviceId();
String configStr = config.getConfigString();
String deviceConfigId = "" + id + ":" + configStr;
SensorDevice existingDevice =
(SensorDevice)deviceTable.get(deviceConfigId);
if(existingDevice != null) {
return existingDevice;
}
String className = null;
SensorDevice device = null;
switch(id) {
case PSEUDO_DEVICE:
className = "org.concord.sensor.pseudo.PseudoSensorDevice";
break;
case VERNIER_GO_LINK:
className = "org.concord.sensor.nativelib.NativeVernierSensorDevice";
break;
case VERNIER_LAB_PRO:
className = "org.concord.sensor.vernier.labpro.LabProSensorDevice";
break;
case VERNIER_LAB_QUEST:
className = "org.concord.sensor.vernier.labquest.LabQuestSensorDevice";
break;
case TI_CONNECT:
className = "org.concord.sensor.nativelib.NativeTISensorDevice";
break;
case FOURIER:
case DATA_HARVEST_USB:
case DATA_HARVEST_ADVANCED:
case DATA_HARVEST_QADVANCED:
className = "org.concord.sensor.dataharvest.DataHarvestSensorDevice";
break;
case PASCO_SERIAL:
className = "org.concord.sensor.pasco.SW500SensorDevice";
break;
case PASCO_AIRLINK:
className = "org.concord.sensor.pasco.AirLinkSensorDevice";
break;
case PASCO_USB:
className = "org.concord.sensor.pasco.PascoUsbSensorDevice";
break;
case DATA_HARVEST_CF:
case IMAGIWORKS_SERIAL:
case IMAGIWORKS_SD:
case COACH:
device = null;
break;
// TODO: need to handle config string so
// the serial port can be specified
case CCPROBE_VERSION_0:
className = "org.concord.sensor.cc.CCInterface0";
break;
case CCPROBE_VERSION_1:
className = "org.concord.sensor.cc.CCInterface1";
break;
case CCPROBE_VERSION_2:
className = "org.concord.sensor.cc.CCinterface2";
break;
}
if(className == null) {
// We didn't get a class for this device so warn the user
// at least in the console
System.err.println("Unknown Sensor Interface type: " + id);
return null;
}
try {
System.out.println("Loading sensor device: " + className);
Class sensDeviceClass =
getClass().getClassLoader().loadClass(className);
device = (SensorDevice) sensDeviceClass.newInstance();
if(device instanceof DeviceIdAware) {
((DeviceIdAware)device).setDeviceId(id);
}
if(device instanceof DeviceServiceAware) {
((DeviceServiceAware)device).setDeviceService(this);
}
device.open(config.getConfigString());
} catch (Exception e) {
e.printStackTrace();
}
deviceTable.put(deviceConfigId, device);
configTable.put(device, deviceConfigId);
return device;
}
| public SensorDevice createDevice(DeviceConfig config)
{
int id = config.getDeviceId();
String configStr = config.getConfigString();
String deviceConfigId = "" + id + ":" + configStr;
SensorDevice existingDevice =
(SensorDevice)deviceTable.get(deviceConfigId);
if(existingDevice != null) {
return existingDevice;
}
String className = null;
SensorDevice device = null;
switch(id) {
case PSEUDO_DEVICE:
className = "org.concord.sensor.pseudo.PseudoSensorDevice";
break;
case VERNIER_GO_LINK:
className = "org.concord.sensor.nativelib.NativeVernierSensorDevice";
break;
case VERNIER_LAB_PRO:
className = "org.concord.sensor.vernier.labpro.LabProSensorDevice";
break;
case VERNIER_LAB_QUEST:
className = "org.concord.sensor.vernier.labquest.LabQuestSensorDevice";
break;
case TI_CONNECT:
className = "org.concord.sensor.nativelib.NativeTISensorDevice";
break;
case FOURIER:
case DATA_HARVEST_USB:
case DATA_HARVEST_ADVANCED:
case DATA_HARVEST_QADVANCED:
className = "org.concord.sensor.dataharvest.DataHarvestSensorDevice";
break;
case PASCO_SERIAL:
className = "org.concord.sensor.pasco.SW500SensorDevice";
break;
case PASCO_AIRLINK:
className = "org.concord.sensor.pasco.AirLinkSensorDevice";
break;
case PASCO_USB:
className = "org.concord.sensor.pasco.PascoUsbSensorDevice";
break;
case DATA_HARVEST_CF:
case IMAGIWORKS_SERIAL:
case IMAGIWORKS_SD:
case COACH:
device = null;
break;
// TODO: need to handle config string so
// the serial port can be specified
case CCPROBE_VERSION_0:
className = "org.concord.sensor.cc.CCInterface0";
break;
case CCPROBE_VERSION_1:
className = "org.concord.sensor.cc.CCInterface1";
break;
case CCPROBE_VERSION_2:
className = "org.concord.sensor.cc.CCInterface2";
break;
}
if(className == null) {
// We didn't get a class for this device so warn the user
// at least in the console
System.err.println("Unknown Sensor Interface type: " + id);
return null;
}
try {
System.out.println("Loading sensor device: " + className);
Class sensDeviceClass =
getClass().getClassLoader().loadClass(className);
device = (SensorDevice) sensDeviceClass.newInstance();
if(device instanceof DeviceIdAware) {
((DeviceIdAware)device).setDeviceId(id);
}
if(device instanceof DeviceServiceAware) {
((DeviceServiceAware)device).setDeviceService(this);
}
device.open(config.getConfigString());
} catch (Exception e) {
e.printStackTrace();
}
deviceTable.put(deviceConfigId, device);
configTable.put(device, deviceConfigId);
return device;
}
|
diff --git a/src/com/zygon/trade/Service.java b/src/com/zygon/trade/Service.java
index e6e035a..38b70e8 100755
--- a/src/com/zygon/trade/Service.java
+++ b/src/com/zygon/trade/Service.java
@@ -1,112 +1,112 @@
/**
*
*/
package com.zygon.trade;
import java.io.File;
import java.sql.SQLException;
import java.util.Date;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author zygon
*/
public class Service implements Daemon {
private static final Logger log = LoggerFactory.getLogger(Service.class);
private final ConnectionManager connectionManager;
private ConfigurationManager configurationManager;
private ModuleSet moduleSet;
private Module kernel;
public Service() throws ClassNotFoundException {
this.connectionManager = new ConnectionManager("org.apache.derby.jdbc.EmbeddedDriver");
}
@Override
public void init(DaemonContext dc) throws DaemonInitException, Exception {
log.info(new Date(System.currentTimeMillis())+": Initializing");
if (this.kernel != null) {
throw new IllegalStateException("Kernel is already initialized");
}
// TODO: pass in root dir
- System.setProperty("trade.rootdir", File.pathSeparator + "home" + File.pathSeparator +
- "zygon" + File.pathSeparator + "opt" + File.pathSeparator + "trade");
+ System.setProperty("trade.rootdir", File.separator + "home" + File.separator +
+ "zygon" + File.separator + "opt" + File.separator + "trade");
// ConfigurationManager is a bump on a log right now.
this.configurationManager = new ConfigurationManager(new InMemoryInstallableStorage());
this.moduleSet = new ModuleSet(this.configurationManager.getStorage());
Module[] modules = this.moduleSet.getModules();
this.kernel = new Kernel(modules);
this.kernel.setParents();
this.moduleSet.configure();
this.kernel.doHook();
}
private final Object initLock = new Object();
@Override
public void start() throws Exception {
log.info(new Date(System.currentTimeMillis())+": Starting");
synchronized (this.initLock) {
new Thread() {
@Override
public void run() {
// Call privileged init method
kernel.doInit();
}
}.start();
// The main thread waits indefinitely
initLock.wait();
}
}
@Override
public void stop() throws Exception {
log.info(new Date(System.currentTimeMillis())+": Stopping");
synchronized (this.initLock) {
initLock.notify();
}
// Call privileged uninit method
this.kernel.doUninit();
this.kernel.doUnHook();
}
@Override
public void destroy() {
log.info(new Date(System.currentTimeMillis())+": Destroying");
try {
this.connectionManager.close();
} catch (SQLException e) {
// Not sure what else to do..
e.printStackTrace(System.err);
}
synchronized (this.initLock) {
initLock.notifyAll();
}
this.kernel = null;
}
}
| true | true | public void init(DaemonContext dc) throws DaemonInitException, Exception {
log.info(new Date(System.currentTimeMillis())+": Initializing");
if (this.kernel != null) {
throw new IllegalStateException("Kernel is already initialized");
}
// TODO: pass in root dir
System.setProperty("trade.rootdir", File.pathSeparator + "home" + File.pathSeparator +
"zygon" + File.pathSeparator + "opt" + File.pathSeparator + "trade");
// ConfigurationManager is a bump on a log right now.
this.configurationManager = new ConfigurationManager(new InMemoryInstallableStorage());
this.moduleSet = new ModuleSet(this.configurationManager.getStorage());
Module[] modules = this.moduleSet.getModules();
this.kernel = new Kernel(modules);
this.kernel.setParents();
this.moduleSet.configure();
this.kernel.doHook();
}
| public void init(DaemonContext dc) throws DaemonInitException, Exception {
log.info(new Date(System.currentTimeMillis())+": Initializing");
if (this.kernel != null) {
throw new IllegalStateException("Kernel is already initialized");
}
// TODO: pass in root dir
System.setProperty("trade.rootdir", File.separator + "home" + File.separator +
"zygon" + File.separator + "opt" + File.separator + "trade");
// ConfigurationManager is a bump on a log right now.
this.configurationManager = new ConfigurationManager(new InMemoryInstallableStorage());
this.moduleSet = new ModuleSet(this.configurationManager.getStorage());
Module[] modules = this.moduleSet.getModules();
this.kernel = new Kernel(modules);
this.kernel.setParents();
this.moduleSet.configure();
this.kernel.doHook();
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
index 5def8e0dd..263dca219 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
@@ -1,228 +1,228 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.DatePicker;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.DateRange;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
/**
* @author Rob Elves
*/
public class ScheduleDatePicker extends Composite {
private Text scheduledDateText;
private Button pickButton;
private final List<SelectionListener> pickerListeners = new LinkedList<SelectionListener>();
private final String initialText = DatePicker.LABEL_CHOOSE;
private final List<IRepositoryElement> tasks;
private final ScheduleTaskMenuContributor contributor;
private DateRange scheduledDate;
private final boolean isFloating = false;
private ImageHyperlink clearControl;
public ScheduleDatePicker(Composite parent, AbstractTask task, int style) {
super(parent, style);
if (task != null) {
if (task.getScheduledForDate() != null) {
this.scheduledDate = task.getScheduledForDate();
}
}
initialize((style & SWT.FLAT) > 0 ? SWT.FLAT : 0);
contributor = new ScheduleTaskMenuContributor() {
@Override
protected DateRange getScheduledForDate(AbstractTask singleTaskSelection) {
return ScheduleDatePicker.this.scheduledDate;
}
@Override
protected void setScheduledDate(DateRange dateRange) {
if (dateRange != null) {
scheduledDate = dateRange;
} else {
scheduledDate = null;
}
updateDateText();
notifyPickerListeners();
}
};
tasks = new ArrayList<IRepositoryElement>();
tasks.add(task);
}
private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
+ dateTextGridData.heightHint = 5;
dateTextGridData.grabExcessHorizontalSpace = true;
- dateTextGridData.widthHint = SWT.FILL;
- dateTextGridData.verticalIndent = 0;
+ dateTextGridData.verticalAlignment = SWT.FILL;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
private void updateClearControlVisibility() {
if (clearControl != null && clearControl.getLayoutData() instanceof GridData) {
GridData gd = (GridData) clearControl.getLayoutData();
gd.exclude = scheduledDate == null;
clearControl.getParent().layout();
}
}
public void addPickerSelectionListener(SelectionListener listener) {
pickerListeners.add(listener);
}
@Override
public void setForeground(Color color) {
pickButton.setForeground(color);
scheduledDateText.setForeground(color);
super.setForeground(color);
}
@Override
public void setBackground(Color backgroundColor) {
pickButton.setBackground(backgroundColor);
scheduledDateText.setBackground(backgroundColor);
super.setBackground(backgroundColor);
}
private void notifyPickerListeners() {
for (SelectionListener listener : pickerListeners) {
listener.widgetSelected(null);
}
}
private void updateDateText() {
if (scheduledDate != null) {
scheduledDateText.setText(scheduledDate.toString());
} else {
scheduledDateText.setEnabled(false);
scheduledDateText.setText(DatePicker.LABEL_CHOOSE);
scheduledDateText.setEnabled(true);
}
updateClearControlVisibility();
}
@Override
public void setEnabled(boolean enabled) {
scheduledDateText.setEnabled(enabled);
pickButton.setEnabled(enabled);
clearControl.setEnabled(enabled);
super.setEnabled(enabled);
}
public DateRange getScheduledDate() {
return scheduledDate;
}
public void setScheduledDate(DateRange date) {
scheduledDate = date;
updateDateText();
}
public boolean isFloatingDate() {
return isFloating;
}
}
| false | true | private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.widthHint = SWT.FILL;
dateTextGridData.verticalIndent = 0;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
| private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.heightHint = 5;
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
|
diff --git a/src/test/org/apache/hadoop/dfs/TestDatanodeBlockScanner.java b/src/test/org/apache/hadoop/dfs/TestDatanodeBlockScanner.java
index e2eb59ca4..d547119d0 100644
--- a/src/test/org/apache/hadoop/dfs/TestDatanodeBlockScanner.java
+++ b/src/test/org/apache/hadoop/dfs/TestDatanodeBlockScanner.java
@@ -1,228 +1,228 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.dfs;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.dfs.FSConstants.DatanodeReportType;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import junit.framework.TestCase;
/**
* This test verifies that block verification occurs on the datanode
*/
public class TestDatanodeBlockScanner extends TestCase {
private static final Log LOG =
LogFactory.getLog(TestDatanodeBlockScanner.class);
private static String urlGet(URL url) {
try {
URLConnection conn = url.openConnection();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copyBytes(conn.getInputStream(), out, 4096, true);
return out.toString();
} catch (IOException e) {
LOG.warn("Failed to fetch " + url.toString() + " : " +
e.getMessage());
}
return "";
}
private static Pattern pattern =
Pattern.compile(".*?(blk_[-]*\\d+).*?scan time\\s*:\\s*(\\d+)");
/**
* This connects to datanode and fetches block verification data.
* It repeats this until the given block has a verification time > 0.
*/
private static long waitForVerification(DatanodeInfo dn, FileSystem fs,
Path file) throws IOException {
URL url = new URL("http://localhost:" + dn.getInfoPort() +
"/blockScannerReport?listblocks");
long lastWarnTime = System.currentTimeMillis();
long verificationTime = 0;
String block = DFSTestUtil.getFirstBlock(fs, file).getBlockName();
while (verificationTime <= 0) {
String response = urlGet(url);
for(Matcher matcher = pattern.matcher(response); matcher.find();) {
if (block.equals(matcher.group(1))) {
verificationTime = Long.parseLong(matcher.group(2));
break;
}
}
if (verificationTime <= 0) {
long now = System.currentTimeMillis();
if ((now - lastWarnTime) >= 5*1000) {
LOG.info("Waiting for verification of " + block);
lastWarnTime = now;
}
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
}
}
return verificationTime;
}
public void testDatanodeBlockScanner() throws IOException {
long startTime = System.currentTimeMillis();
Configuration conf = new Configuration();
MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
cluster.waitActive();
FileSystem fs = cluster.getFileSystem();
Path file1 = new Path("/tmp/testBlockVerification/file1");
Path file2 = new Path("/tmp/testBlockVerification/file2");
/*
* Write the first file and restart the cluster.
*/
DFSTestUtil.createFile(fs, file1, 10, (short)1, 0);
cluster.shutdown();
cluster = new MiniDFSCluster(conf, 1, false, null);
cluster.waitActive();
DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
fs = cluster.getFileSystem();
DatanodeInfo dn = dfsClient.datanodeReport(DatanodeReportType.LIVE)[0];
/*
* The cluster restarted. The block should be verified by now.
*/
assertTrue(waitForVerification(dn, fs, file1) > startTime);
/*
* Create a new file and read the block. The block should be marked
* verified since the client reads the block and verifies checksum.
*/
DFSTestUtil.createFile(fs, file2, 10, (short)1, 0);
IOUtils.copyBytes(fs.open(file2), new IOUtils.NullOutputStream(),
conf, true);
assertTrue(waitForVerification(dn, fs, file2) > startTime);
cluster.shutdown();
}
void corruptReplica(String blockName, int replica) throws IOException {
Random random = new Random();
File baseDir = new File(System.getProperty("test.build.data"), "dfs/data");
for (int i=replica*2; i<replica*2+2; i++) {
File blockFile = new File(baseDir, "data" + (i+1)+ "/current/" +
blockName);
if (blockFile.exists()) {
// Corrupt replica by writing random bytes into replica
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int)channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
}
}
public void testBlockCorruptionPolicy() throws IOException {
Configuration conf = new Configuration();
Random random = new Random();
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int blockCount = 0;
MiniDFSCluster cluster = new MiniDFSCluster(conf, 3, true, null);
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/tmp/testBlockVerification/file1");
DFSTestUtil.createFile(fs, file1, 1024, (short)3, 0);
- String block = DFSTestUtil.getFirstBlock(fs, file1).toString();
+ String block = DFSTestUtil.getFirstBlock(fs, file1).getBlockName();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue(blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt random replica of block
corruptReplica(block, random.nextInt(3));
cluster.shutdown();
// Restart the cluster hoping the corrupt block to be reported
// We have 2 good replicas and block is not corrupt
cluster = new MiniDFSCluster(conf, 3, false, null);
cluster.waitActive();
fs = cluster.getFileSystem();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 2);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt all replicas. Now, block should be marked as corrupt
// and we should get all the replicas
corruptReplica(block, 0);
corruptReplica(block, 1);
corruptReplica(block, 2);
// Read the file to trigger reportBadBlocks by client
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(),
conf, true);
} catch (IOException e) {
// Ignore exception
}
// We now have he blocks to be marked as corrup and we get back all
// its replicas
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == true);
cluster.shutdown();
}
}
| true | true | public void testBlockCorruptionPolicy() throws IOException {
Configuration conf = new Configuration();
Random random = new Random();
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int blockCount = 0;
MiniDFSCluster cluster = new MiniDFSCluster(conf, 3, true, null);
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/tmp/testBlockVerification/file1");
DFSTestUtil.createFile(fs, file1, 1024, (short)3, 0);
String block = DFSTestUtil.getFirstBlock(fs, file1).toString();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue(blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt random replica of block
corruptReplica(block, random.nextInt(3));
cluster.shutdown();
// Restart the cluster hoping the corrupt block to be reported
// We have 2 good replicas and block is not corrupt
cluster = new MiniDFSCluster(conf, 3, false, null);
cluster.waitActive();
fs = cluster.getFileSystem();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 2);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt all replicas. Now, block should be marked as corrupt
// and we should get all the replicas
corruptReplica(block, 0);
corruptReplica(block, 1);
corruptReplica(block, 2);
// Read the file to trigger reportBadBlocks by client
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(),
conf, true);
} catch (IOException e) {
// Ignore exception
}
// We now have he blocks to be marked as corrup and we get back all
// its replicas
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == true);
cluster.shutdown();
}
| public void testBlockCorruptionPolicy() throws IOException {
Configuration conf = new Configuration();
Random random = new Random();
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int blockCount = 0;
MiniDFSCluster cluster = new MiniDFSCluster(conf, 3, true, null);
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/tmp/testBlockVerification/file1");
DFSTestUtil.createFile(fs, file1, 1024, (short)3, 0);
String block = DFSTestUtil.getFirstBlock(fs, file1).getBlockName();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue(blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt random replica of block
corruptReplica(block, random.nextInt(3));
cluster.shutdown();
// Restart the cluster hoping the corrupt block to be reported
// We have 2 good replicas and block is not corrupt
cluster = new MiniDFSCluster(conf, 3, false, null);
cluster.waitActive();
fs = cluster.getFileSystem();
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 2);
assertTrue(blocks.get(0).isCorrupt() == false);
// Corrupt all replicas. Now, block should be marked as corrupt
// and we should get all the replicas
corruptReplica(block, 0);
corruptReplica(block, 1);
corruptReplica(block, 2);
// Read the file to trigger reportBadBlocks by client
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(),
conf, true);
} catch (IOException e) {
// Ignore exception
}
// We now have he blocks to be marked as corrup and we get back all
// its replicas
blocks = dfsClient.namenode.
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
blockCount = blocks.get(0).getLocations().length;
assertTrue (blockCount == 3);
assertTrue(blocks.get(0).isCorrupt() == true);
cluster.shutdown();
}
|
diff --git a/src/main/java/com/jcraft/jzlib/DeflaterOutputStream.java b/src/main/java/com/jcraft/jzlib/DeflaterOutputStream.java
index 4c9f0d2..3c18836 100644
--- a/src/main/java/com/jcraft/jzlib/DeflaterOutputStream.java
+++ b/src/main/java/com/jcraft/jzlib/DeflaterOutputStream.java
@@ -1,181 +1,181 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
public class DeflaterOutputStream extends FilterOutputStream {
protected final Deflater deflater;
protected byte[] buffer;
private boolean closed = false;
private boolean syncFlush = false;
private final byte[] buf1 = new byte[1];
protected boolean mydeflater = false;
private boolean close_out = true;
protected static final int DEFAULT_BUFSIZE = 512;
public DeflaterOutputStream(OutputStream out) throws IOException {
this(out,
new Deflater(JZlib.Z_DEFAULT_COMPRESSION),
DEFAULT_BUFSIZE, true);
mydeflater = true;
}
public DeflaterOutputStream(OutputStream out, Deflater def) throws IOException {
this(out, def, DEFAULT_BUFSIZE, true);
}
public DeflaterOutputStream(OutputStream out,
Deflater deflater,
int size) throws IOException {
this(out, deflater, size, true);
}
public DeflaterOutputStream(OutputStream out,
Deflater deflater,
int size,
boolean close_out) throws IOException {
super(out);
if (out == null || deflater == null) {
throw new NullPointerException();
}
else if (size <= 0) {
throw new IllegalArgumentException("buffer size must be greater than 0");
}
this.deflater = deflater;
buffer = new byte[size];
this.close_out = close_out;
}
public void write(int b) throws IOException {
buf1[0] = (byte)(b & 0xff);
write(buf1, 0, 1);
}
public void write(byte[] b, int off, int len) throws IOException {
if (deflater.finished()) {
throw new IOException("finished");
}
else if (off<0 | len<0 | off+len>b.length) {
throw new IndexOutOfBoundsException();
}
else if (len == 0) {
return;
}
else {
int flush = syncFlush ? JZlib.Z_SYNC_FLUSH : JZlib.Z_NO_FLUSH;
deflater.setInput(b, off, len, true);
while (deflater.avail_in>0) {
int err = deflate(flush);
if (err == JZlib.Z_STREAM_END)
break;
}
}
}
public void finish() throws IOException {
while (!deflater.finished()) {
deflate(JZlib.Z_FINISH);
}
}
public void close() throws IOException {
if (!closed) {
finish();
if (mydeflater){
deflater.end();
}
if(close_out)
out.close();
closed = true;
}
}
protected int deflate(int flush) throws IOException {
deflater.setOutput(buffer, 0, buffer.length);
int err = deflater.deflate(flush);
switch(err) {
case JZlib.Z_OK:
case JZlib.Z_STREAM_END:
break;
case JZlib.Z_BUF_ERROR:
if(deflater.avail_in<=0 && flush!=JZlib.Z_FINISH){
// flush() without any data
break;
}
default:
- throw new IOException("failed to deflate");
+ throw new IOException("failed to deflate: error="+err+" avail_out="+deflater.avail_out);
}
int len = deflater.next_out_index;
if (len > 0) {
out.write(buffer, 0, len);
}
return err;
}
public void flush() throws IOException {
if (syncFlush && !deflater.finished()) {
while (true) {
int err = deflate(JZlib.Z_SYNC_FLUSH);
if (deflater.next_out_index < buffer.length)
break;
if (err == JZlib.Z_STREAM_END)
break;
}
}
out.flush();
}
public long getTotalIn() {
return deflater.getTotalIn();
}
public long getTotalOut() {
return deflater.getTotalOut();
}
public void setSyncFlush(boolean syncFlush){
this.syncFlush = syncFlush;
}
public boolean getSyncFlush(){
return this.syncFlush;
}
public Deflater getDeflater(){
return deflater;
}
}
| true | true | protected int deflate(int flush) throws IOException {
deflater.setOutput(buffer, 0, buffer.length);
int err = deflater.deflate(flush);
switch(err) {
case JZlib.Z_OK:
case JZlib.Z_STREAM_END:
break;
case JZlib.Z_BUF_ERROR:
if(deflater.avail_in<=0 && flush!=JZlib.Z_FINISH){
// flush() without any data
break;
}
default:
throw new IOException("failed to deflate");
}
int len = deflater.next_out_index;
if (len > 0) {
out.write(buffer, 0, len);
}
return err;
}
| protected int deflate(int flush) throws IOException {
deflater.setOutput(buffer, 0, buffer.length);
int err = deflater.deflate(flush);
switch(err) {
case JZlib.Z_OK:
case JZlib.Z_STREAM_END:
break;
case JZlib.Z_BUF_ERROR:
if(deflater.avail_in<=0 && flush!=JZlib.Z_FINISH){
// flush() without any data
break;
}
default:
throw new IOException("failed to deflate: error="+err+" avail_out="+deflater.avail_out);
}
int len = deflater.next_out_index;
if (len > 0) {
out.write(buffer, 0, len);
}
return err;
}
|
diff --git a/src/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/org/bukkit/craftbukkit/entity/CraftPlayer.java
index c7beec1..9fd1751 100644
--- a/src/org/bukkit/craftbukkit/entity/CraftPlayer.java
+++ b/src/org/bukkit/craftbukkit/entity/CraftPlayer.java
@@ -1,1097 +1,1098 @@
package org.bukkit.craftbukkit.entity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import keepcalm.mods.bukkit.BukkitContainer;
import keepcalm.mods.bukkit.forgeHandler.ForgeEventHandler;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.PlayerCapabilities;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerBeacon;
import net.minecraft.inventory.ContainerBrewingStand;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.ContainerDispenser;
import net.minecraft.inventory.ContainerEnchantment;
import net.minecraft.inventory.ContainerFurnace;
import net.minecraft.inventory.ContainerMerchant;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.ContainerRepair;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet131MapData;
import net.minecraft.network.packet.Packet200Statistic;
import net.minecraft.network.packet.Packet202PlayerAbilities;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.network.packet.Packet3Chat;
import net.minecraft.network.packet.Packet43Experience;
import net.minecraft.network.packet.Packet4UpdateTime;
import net.minecraft.network.packet.Packet53BlockChange;
import net.minecraft.network.packet.Packet54PlayNoteBlock;
import net.minecraft.network.packet.Packet61DoorChange;
import net.minecraft.network.packet.Packet62LevelSound;
import net.minecraft.network.packet.Packet6SpawnPosition;
import net.minecraft.network.packet.Packet70GameEvent;
import net.minecraft.server.management.BanEntry;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.world.EnumGameType;
import net.minecraft.world.WorldServer;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.Validate;
import org.bukkit.Achievement;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Instrument;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.DelegateDeserialization;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.conversations.ManuallyAbandonedConversationCanceller;
import org.bukkit.craftbukkit.CraftConversationTracker;
import org.bukkit.craftbukkit.CraftEffect;
import org.bukkit.craftbukkit.CraftOfflinePlayer;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.CraftSound;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.map.CraftMapView;
import org.bukkit.craftbukkit.map.RenderData;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerRegisterChannelEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerUnregisterChannelEvent;
import org.bukkit.inventory.InventoryView.Property;
import org.bukkit.map.MapView;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.StandardMessenger;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MapMaker;
import cpw.mods.fml.common.network.FMLNetworkHandler;
@DelegateDeserialization(CraftOfflinePlayer.class)
public class CraftPlayer extends CraftEntityHuman implements Player, CommandSender {
private long firstPlayed = 0;
private long lastPlayed = 0;
//private boolean hasPlayedBefore = false;
private final CraftConversationTracker conversationTracker = new CraftConversationTracker();
private final Set<String> channels = new HashSet<String>();
private final Map<String, Player> hiddenPlayers = new MapMaker().softValues().makeMap();
private int hash = 0;
private long playerOffset;
//private long playerCurrentTime;
private boolean isTimeRelative;
public CraftPlayer(CraftServer server, EntityPlayerMP entity) {
super(server, entity);
perm.recalculatePermissions();
}
public CraftPlayer(EntityPlayerMP player) {
this((CraftServer) Bukkit.getServer(), player);
}
@Override
public String getName() {
return getHandle().username;
}
@Override
public boolean isOp() {
try {
return server.getHandle().getConfigurationManager().getOps().contains(getName().toLowerCase());
}
catch (NullPointerException e) {
return false;
}
}
@Override
public void setOp(boolean value) {
if (value == isOp()) return;
if (value) {
server.getHandle().getConfigurationManager().addOp(getName().toLowerCase());
} else {
server.getHandle().getConfigurationManager().removeOp(getName().toLowerCase());
}
perm.recalculatePermissions();
}
public boolean isOnline() {
for (Object obj : server.getHandle().getConfigurationManager().playerEntityList) {
EntityPlayerMP player = (EntityPlayerMP) obj;
if (player.username.equalsIgnoreCase(getName())) {
return true;
}
}
return false;
}
public InetSocketAddress getAddress() {
if (getHandle().playerNetServerHandler == null) return null;
SocketAddress addr = getHandle().playerNetServerHandler.netManager.getSocketAddress();
if (addr instanceof InetSocketAddress) {
return (InetSocketAddress) addr;
} else {
return null;
}
}
@Override
public double getEyeHeight() {
return getEyeHeight(false);
}
@Override
public double getEyeHeight(boolean ignoreSneaking) {
if (ignoreSneaking) {
return 1.62D;
} else {
if (isSneaking()) {
return 1.54D;
} else {
return 1.62D;
}
}
}
public void sendRawMessage(String message) {
if (getHandle().playerNetServerHandler == null) return;
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet3Chat(message));
}
public void sendMessage(String message) {
if (!conversationTracker.isConversingModaly()) {
this.sendRawMessage(message);
}
}
public void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
}
public String getDisplayName() {
return ForgeEventHandler.playerDisplayNames.containsKey(getHandle().username) ? ForgeEventHandler.playerDisplayNames.get(getHandle().username) : getHandle().username;
}
public void setDisplayName(final String name) {
ForgeEventHandler.playerDisplayNames.put(getHandle().username, name);
}
public String getPlayerListName() {
return getHandle().username;
}
public void setPlayerListName(String name) {
/* String oldName = getHandle().getEntityName();
if (name == null) {
name = getName();
}
if (oldName.equals(name)) {
return;
}
if (name.length() > 16) {
throw new IllegalArgumentException("Player list names can only be a maximum of 16 characters long");
}
// Collisions will make for invisible people
for (int i = 0; i < server.getHandle().getConfigurationManager().playerEntityList.size(); ++i) {
if (((EntityPlayerMP) server.getHandle().getConfigurationManager().playerEntityList.get(i)).getEntityName().equals(name)) {
throw new IllegalArgumentException(name + " is already assigned as a player list name for someone");
}
}
//getHandle().listName = name;
// Change the name on the client side
Packet201PlayerInfo oldpacket = new Packet201PlayerInfo(oldName, false, 9999);
Packet201PlayerInfo packet = new Packet201PlayerInfo(name, true, getHandle().ping);
for (int i = 0; i < server.getHandle().getConfigurationManager().playerEntityList.size(); ++i) {
EntityPlayerMP EntityPlayerMP = (EntityPlayerMP) server.getHandle().getConfigurationManager().playerEntityList.get(i);
if (EntityPlayerMP.playerNetServerHandler == null) continue;
if (this.getEntity(server, EntityPlayerMP).canSee(this)) {
EntityPlayerMP.playerNetServerHandler.sendPacketToPlayer(oldpacket);
((NetServerHandler) EntityPlayerMP.playerNetServerHandler).sendPacketToPlayer(packet);
}
}*/
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof OfflinePlayer)) {
return false;
}
OfflinePlayer other = (OfflinePlayer) obj;
if ((this.getName() == null) || (other.getName() == null)) {
return false;
}
boolean nameEquals = this.getName().equalsIgnoreCase(other.getName());
boolean idEquals = true;
if (other instanceof CraftPlayer) {
idEquals = this.getEntityId() == ((CraftPlayer) other).getEntityId();
}
return nameEquals && idEquals;
}
public void kickPlayer(String message) {
if (getHandle().playerNetServerHandler == null) return;
getHandle().playerNetServerHandler.kickPlayerFromServer(message == null ? "" : message);
}
public void setCompassTarget(Location loc) {
if (getHandle().playerNetServerHandler == null) return;
// Do not directly assign here, from the packethandler we'll assign it.
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet6SpawnPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
public Location getCompassTarget() {
return new Location(CraftServer.instance().getWorld(getHandle().worldObj.getWorldInfo().getDimension()), getHandle().getHomePosition().posX, getHandle().getHomePosition().posY, getHandle().getHomePosition().posZ);
}
public void chat(String msg) {
if (getHandle().playerNetServerHandler == null) return;
getHandle().playerNetServerHandler.handleChat(new Packet3Chat(msg));
//getHandle().playerNetServerHandler.(msg, false);
}
public boolean performCommand(String command) {
return server.dispatchCommand(this, command);
}
public void playNote(Location loc, byte instrument, byte note) {
if (getHandle().playerNetServerHandler == null) return;
int id = getHandle().worldObj.getBlockId(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet54PlayNoteBlock(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), id, instrument, note));
}
public void playNote(Location loc, Instrument instrument, Note note) {
if (getHandle().playerNetServerHandler == null) return;
int id = getHandle().worldObj.getBlockId(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet54PlayNoteBlock(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), id, instrument.getType(), note.getId()));
}
public void playSound(Location loc, Sound sound, float volume, float pitch) {
if (loc == null || sound == null || getHandle().playerNetServerHandler == null) return;
double x = loc.getBlockX() + 0.5;
double y = loc.getBlockY() + 0.5;
double z = loc.getBlockZ() + 0.5;
Packet62LevelSound packet = new Packet62LevelSound(CraftSound.getSound(sound), x, y, z, volume, pitch);
getHandle().playerNetServerHandler.sendPacketToPlayer(packet);
}
public void playEffect(Location loc, Effect effect, int data) {
if (getHandle().playerNetServerHandler == null) return;
int packetData = effect.getId();
Packet61DoorChange packet = new Packet61DoorChange(packetData, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), data, false);
getHandle().playerNetServerHandler.sendPacketToPlayer(packet);
}
public <T> void playEffect(Location loc, Effect effect, T data) {
if (data != null) {
Validate.isTrue(data.getClass().equals(effect.getData()), "Wrong kind of data for this effect!");
} else {
Validate.isTrue(effect.getData() == null, "Wrong kind of data for this effect!");
}
int datavalue = data == null ? 0 : CraftEffect.getDataValue(effect, data);
playEffect(loc, effect, datavalue);
}
/*public void sendBlockChange(Location loc, Material material, byte data) {
sendBlockChange(loc, material.getId(), data);
}*/
public void sendBlockChange(Location loc, int material, byte data) {
if (getHandle().playerNetServerHandler == null) return;
Packet53BlockChange packet = new Packet53BlockChange(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), ((CraftWorld) loc.getWorld()).getHandle());
packet.type = material;
packet.metadata = data;
getHandle().playerNetServerHandler.sendPacketToPlayer(packet);
}
public boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data) {
if (getHandle().playerNetServerHandler == null) return false;
/*
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
int cx = x >> 4;
int cz = z >> 4;
if (sx <= 0 || sy <= 0 || sz <= 0) {
return false;
}
if ((x + sx - 1) >> 4 != cx || (z + sz - 1) >> 4 != cz || y < 0 || y + sy > 128) {
return false;
}
if (data.length != (sx * sy * sz * 5) / 2) {
return false;
}
Packet51MapChunk packet = new Packet51MapChunk(x, y, z, sx, sy, sz, data);
getHandle().playerNetServerHandler.sendPacket(packet);
return true;
*/
throw new NotImplementedException("Chunk changes do not yet work"); // TODO: Chunk changes.
}
public void sendMap(MapView map) {
if (getHandle().playerNetServerHandler == null) return;
RenderData data = ((CraftMapView) map).render(this);
for (int x = 0; x < 128; ++x) {
byte[] bytes = new byte[131];
bytes[1] = (byte) x;
for (int y = 0; y < 128; ++y) {
bytes[y + 3] = data.buffer[y * 128 + x];
}
Packet131MapData packet = new Packet131MapData((short) Material.MAP.getId(), map.getId(), bytes);
getHandle().playerNetServerHandler.sendPacketToPlayer(packet);
}
}
@Override
public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) {
net.minecraft.entity.player.EntityPlayerMP/*was:EntityPlayer*/ entity = getHandle();
if (getHealth() == 0 || entity.isDead/*was:dead*/) {
return false;
}
if (entity.playerNetServerHandler/*was:playerConnection*/ == null || entity.playerNetServerHandler/*was:playerConnection*/.connectionClosed/*was:disconnected*/) {
return false;
}
if (entity.ridingEntity/*was:vehicle*/ != null || entity.riddenByEntity/*was:passenger*/ != null) {
return false;
}
// From = Players current Location
Location from = this.getLocation();
// To = Players new Location if Teleport is Successful
Location to = location;
// Create & Call the Teleport Event.
PlayerTeleportEvent event = new PlayerTeleportEvent((Player) this, from, to, cause);
server.getPluginManager().callEvent(event);
// Return False to inform the Plugin that the Teleport was unsuccessful/cancelled.
if (event.isCancelled()) {
return false;
}
// Update the From Location
from = event.getFrom();
// Grab the new To Location dependent on whether the event was cancelled.
to = event.getTo();
// Grab the To and From World Handles.
CraftWorld fromWorld = (CraftWorld) from.getWorld();
CraftWorld toWorld = (CraftWorld) to.getWorld();
// Check if the fromWorld and toWorld are the same.
if (fromWorld.getName().equals(toWorld.getName())) {
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw());
} else {
// Close any foreign inventory
if (getHandle().openContainer != getHandle().inventoryContainer)
getHandle().closeInventory();
//toWorld.getHandle().spawnEntityInWorld(entity); // does something cool
//toWorld.getHandle().updateEntityWithOptionalForce(entity, false); // Update entity properties
/* entity.setWorld(toWorld.getHandle()); // Sets the current world obj
fromWorld.getHandle().removeEntity(entity);
Entity e = EntityList.createEntityByName(entity.getEntityName(), toWorld.getHandle());
if (e != null) {
e.copyDataFrom(entity, true);
entity.setDead();
toWorld.getHandle().spawnEntityInWorld(e);
fromWorld.getHandle().resetUpdateEntityTick();
toWorld.getHandle().resetUpdateEntityTick();
this.setHandle(e);
}
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!*/
//server.getHandle().getConfigurationManager().transferPlayerToDimension(entity, toWorld.getHandle().getWorldInfo().getDimension(), new CraftTeleporter(toWorld.getHandle()));
//entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!
toWorld.getHandle().spawnEntityInWorld(entity);
entity.setWorld(toWorld.getHandle());
+ fromWorld.getHandle().removeEntity(entity);
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
entity.mcServer.getConfigurationManager().func_72375_a(entity, toWorld.getHandle());
entity.playerNetServerHandler.setPlayerLocation(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
WorldServer newWorld = toWorld.getHandle();
entity.theItemInWorldManager.setWorld((WorldServer)newWorld);
entity.mcServer.getConfigurationManager().updateTimeAndWeatherForPlayer(entity, (WorldServer)newWorld);
entity.mcServer.getConfigurationManager().syncPlayerInventory(entity);
entity.playerNetServerHandler.sendPacketToPlayer(new Packet43Experience(entity.experience, entity.experienceTotal, entity.experienceLevel));
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
}
return true;
}
public void setSneaking(boolean sneak) {
getHandle().setSneaking(sneak);
}
public boolean isSneaking() {
return getHandle().isSneaking();
}
public boolean isSprinting() {
return getHandle().isSprinting();
}
public void setSprinting(boolean sprinting) {
getHandle().setSprinting(sprinting);
}
public void loadData() {
server.getHandle().getConfigurationManager().playerNBTManagerObj.readPlayerData(getHandle());
}
public void saveData() {
server.getHandle().getConfigurationManager().playerNBTManagerObj.writePlayerData(getHandle());
}
public void updateInventory() {
//getHandle().updateInventory(getHandle().craftingInventory);f
getHandle().updateHeldItem();
}
public void setSleepingIgnored(boolean isSleeping) {
// FIXME - this will explode MC
//getHandle().sleeping = isSleeping;
//((CraftWorld) getWorld()).getHandle().updateAllPlayersSleepingFlag();
CraftServer.setPlayerFauxSleeping(getName(), isSleeping);
}
public boolean isSleepingIgnored() {
return CraftServer.instance().isFauxSleeping(this.getName());
}
public void awardAchievement(Achievement achievement) {
sendStatistic(achievement.getId(), 1);
}
public void incrementStatistic(Statistic statistic) {
incrementStatistic(statistic, 1);
}
public void incrementStatistic(Statistic statistic, int amount) {
sendStatistic(statistic.getId(), amount);
}
public void incrementStatistic(Statistic statistic, Material material) {
incrementStatistic(statistic, material, 1);
}
public void incrementStatistic(Statistic statistic, Material material, int amount) {
if (!statistic.isSubstatistic()) {
throw new IllegalArgumentException("Given statistic is not a substatistic");
}
if (statistic.isBlock() != material.isBlock()) {
throw new IllegalArgumentException("Given material is not valid for this substatistic");
}
int mat = material.getId();
if (!material.isBlock()) {
mat -= 255;
}
sendStatistic(statistic.getId() + mat, amount);
}
private void sendStatistic(int id, int amount) {
if (getHandle().playerNetServerHandler == null) return;
while (amount > Byte.MAX_VALUE) {
sendStatistic(id, Byte.MAX_VALUE);
amount -= Byte.MAX_VALUE;
}
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet200Statistic(id, amount));
}
public void setPlayerTime(long time, boolean relative) {
//getHandle().time = time;
//getHandle().relativeTime = relative;
Packet4UpdateTime p = new Packet4UpdateTime();
this.isTimeRelative = relative;
p.time = relative ? getHandle().getServerForPlayer().getWorldTime() + time : time;
this.playerOffset = time - getHandle().getServerForPlayer().getWorldTime();
getHandle().playerNetServerHandler.sendPacketToPlayer(p);
}
public long getPlayerTimeOffset() {
return this.playerOffset;
}
public long getPlayerTime() {
return getHandle().getServerForPlayer().getWorldTime() + playerOffset;
}
public boolean isPlayerTimeRelative() {
return isTimeRelative;
}
public void resetPlayerTime() {
setPlayerTime(0, true);
}
public boolean isBanned() {
return server.getHandle().getConfigurationManager().getBannedPlayers().isBanned(getName().toLowerCase());
}
public void setBanned(boolean value) {
if (value) {
BanEntry entry = new BanEntry(getName().toLowerCase());
server.getHandle().getConfigurationManager().getBannedPlayers().put(entry);
} else {
server.getHandle().getConfigurationManager().getBannedPlayers().remove(getName().toLowerCase());
}
server.getHandle().getConfigurationManager().getBannedPlayers().saveToFileWithHeader();
}
public boolean isWhitelisted() {
return server.getHandle().getConfigurationManager().getWhiteListedPlayers().contains(getName().toLowerCase());
}
public void setWhitelisted(boolean value) {
if (value) {
server.getHandle().getConfigurationManager().addToWhiteList(getName().toLowerCase());
} else {
server.getHandle().getConfigurationManager().removeFromWhitelist(getName().toLowerCase());
}
}
@Override
public void setGameMode(GameMode mode) {
if (getHandle().playerNetServerHandler == null) return;
if (mode == null) {
throw new IllegalArgumentException("Mode cannot be null");
}
if (mode != getGameMode()) {
PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(this, mode);
server.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
getHandle().theItemInWorldManager.setGameType(EnumGameType.getByID(mode.getValue()));
getHandle().playerNetServerHandler.sendPacketToPlayer(new Packet70GameEvent(3, mode.getValue()));
}
}
@Override
public GameMode getGameMode() {
return GameMode.getByValue(getHandle().theItemInWorldManager.getGameType().getID());
}
public void giveExp(int exp) {
getHandle().experienceTotal += (exp);
}
public float getExp() {
return getHandle().experience;
}
public void setExp(float exp) {
getHandle().experience = exp;
//getHandle().xp = -1;
}
public int getLevel() {
return getHandle().experienceLevel;
}
public void setLevel(int level) {
getHandle().experienceLevel = level;
//getHandle().lastSentExp = -1;
}
public int getTotalExperience() {
return getHandle().experienceTotal;
}
public void setTotalExperience(int exp) {
getHandle().experienceTotal = exp;
}
public float getExhaustion() {
return getHandle().getFoodStats().foodExhaustionLevel;
}
public void setExhaustion(float value) {
getHandle().getFoodStats().foodExhaustionLevel = value;
}
public float getSaturation() {
return getHandle().getFoodStats().getSaturationLevel();
}
public void setSaturation(float value) {
getHandle().getFoodStats().setFoodSaturationLevel(value);
}
public int getFoodLevel() {
return getHandle().getFoodStats().getFoodLevel();
}
public void setFoodLevel(int value) {
NBTTagCompound nbt = new NBTTagCompound();
getHandle().getFoodStats().writeNBT(nbt);
nbt.setInteger("foodLevel", value);
getHandle().getFoodStats().readNBT(nbt);
}
public Location getBedSpawnLocation() {
World world = ((CraftServer)getServer()).getWorld(0);
if ((world != null) && (getHandle().getHomePosition() != null)) {
return new Location(world, getHandle().getHomePosition().posX, getHandle().getHomePosition().posY, getHandle().getHomePosition().posZ);
}
return null;
}
public void setBedSpawnLocation(Location location) {
/* what does spawnForced mean? */
getHandle().setSpawnChunk(new ChunkCoordinates(location.getBlockX(), location.getBlockY(), location.getBlockZ()), false);
//getHandle().spawnWorld = location.getWorld().getName();
}
public void hidePlayer(Player player) {
}
public void showPlayer(Player player) {
Validate.notNull(player, "hidden player cannot be null");
if (getHandle().playerNetServerHandler/*was:playerConnection*/ == null) return;
if (equals(player)) return;
if (hiddenPlayers.containsKey(player.getName())) return;
hiddenPlayers.put(player.getName(), player);
//remove this player from the hidden player's EntityTrackerEntry
net.minecraft.entity.EntityTracker/*was:EntityTracker*/ tracker = ((net.minecraft.world.WorldServer/*was:WorldServer*/) entity.worldObj/*was:world*/).getEntityTracker();
net.minecraft.entity.player.EntityPlayerMP/*was:EntityPlayer*/ other = ((CraftPlayer) player).getHandle();
net.minecraft.entity.EntityTrackerEntry/*was:EntityTrackerEntry*/ entry = (net.minecraft.entity.EntityTrackerEntry/*was:EntityTrackerEntry*/) tracker.trackedEntityIDs/*was:trackedEntities*/.lookup/*was:get*/(other.entityId/*was:id*/);
if (entry != null) {
entry.removePlayerFromTracker/*was:clear*/(getHandle());
}
//remove the hidden player from this player user list
getHandle().playerNetServerHandler/*was:playerConnection*/.sendPacketToPlayer/*was:sendPacket*/(new net.minecraft.network.packet.Packet201PlayerInfo/*was:Packet201PlayerInfo*/(player.getPlayerListName(), false, 9999)); }
public boolean canSee(Player player) {
return !hiddenPlayers.containsKey(player.getName());
}
public Map<String, Object> serialize() {
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("name", getName());
return result;
}
public Player getPlayer() {
return this;
}
@Override
public EntityPlayerMP getHandle() {
return (EntityPlayerMP) entity;
}
public void setHandle(final EntityPlayerMP entity) {
super.setHandle(entity);
}
@Override
public String toString() {
return "CraftPlayer{" + "name=" + getName() + '}';
}
@Override
public int hashCode() {
if (hash == 0 || hash == 485) {
hash = 97 * 5 + (this.getName() != null ? this.getName().toLowerCase().hashCode() : 0);
}
return hash;
}
public long getFirstPlayed() {
return firstPlayed;
}
public long getLastPlayed() {
return lastPlayed;
}
public boolean hasPlayedBefore() {
return BukkitContainer.users.containsKey(getName().toLowerCase());
}
public void setFirstPlayed(long firstPlayed) {
this.firstPlayed = firstPlayed;
}
public void readExtraData(NBTTagCompound nbttagcompound) {
if (nbttagcompound.hasKey("bukkit")) {
NBTTagCompound data = nbttagcompound.getCompoundTag("bukkit");
if (data.hasKey("firstPlayed")) {
firstPlayed = data.getLong("firstPlayed");
lastPlayed = data.getLong("lastPlayed");
}
if (data.hasKey("newExp")) {
EntityPlayerMP handle = getHandle();
handle.experienceValue = data.getInteger("newExp");
handle.experienceTotal = data.getInteger("newTotalExp");
handle.experienceLevel = data.getInteger("newLevel");
//handle.exp = data.getInteger("expToDrop");
//handle.exp = data.getBoolean("keepLevel");
}
}
}
public void setExtraData(NBTTagCompound nbttagcompound) {
if (!nbttagcompound.hasKey("bukkit")) {
nbttagcompound.setCompoundTag("bukkit", new NBTTagCompound());
}
NBTTagCompound data = nbttagcompound.getCompoundTag("bukkit");
EntityPlayerMP handle = getHandle();
data.setInteger("newExp", handle.experienceValue);
data.setInteger("newTotalExp", handle.experienceTotal);
data.setInteger("newLevel", handle.experienceLevel);
//data.setInt("expToDrop", handle.expToDrop);
//data.setBoolean("keepLevel", handle.keepLevel);
data.setLong("firstPlayed", getFirstPlayed());
data.setLong("lastPlayed", System.currentTimeMillis());
}
public boolean beginConversation(Conversation conversation) {
return conversationTracker.beginConversation(conversation);
}
public void abandonConversation(Conversation conversation) {
conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller()));
}
public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
conversationTracker.abandonConversation(conversation, details);
}
public void acceptConversationInput(String input) {
conversationTracker.acceptConversationInput(input);
}
public boolean isConversing() {
return conversationTracker.isConversing();
}
public void sendPluginMessage(Plugin source, String channel, byte[] message) {
StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message);
if (getHandle().playerNetServerHandler == null) return;
if (channels.contains(channel)) {
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = channel;
packet.length = message.length;
packet.data = message;
FMLNetworkHandler.handlePacket250Packet(packet,
getHandle().playerNetServerHandler.netManager,
getHandle().playerNetServerHandler);
//getHandle().playerNetServerHandler.sendPacketToPlayer(packet);
}
}
public void addChannel(String channel) {
if (channels.add(channel)) {
server.getPluginManager().callEvent(new PlayerRegisterChannelEvent(this, channel));
}
}
public void removeChannel(String channel) {
if (channels.remove(channel)) {
server.getPluginManager().callEvent(new PlayerUnregisterChannelEvent(this, channel));
}
}
public Set<String> getListeningPluginChannels() {
return ImmutableSet.copyOf(channels);
}
public void sendSupportedChannels() {
if (getHandle().playerNetServerHandler == null) return;
Set<String> listening = server.getMessenger().getIncomingChannels();
if (!listening.isEmpty()) {
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = "REGISTER";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
for (String channel : listening) {
try {
stream.write(channel.getBytes("UTF8"));
stream.write((byte) 0);
} catch (IOException ex) {
Logger.getLogger(CraftPlayer.class.getName()).log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex);
}
}
packet.data = stream.toByteArray();
packet.length = packet.data.length;
FMLNetworkHandler.handlePacket250Packet(packet, getHandle().playerNetServerHandler.netManager, getHandle().playerNetServerHandler);
}
}
public EntityType getType() {
return EntityType.PLAYER;
}
public void setMetadata(String metadataKey, MetadataValue newMetadataValue) {
server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue);
}
@Override
public List<MetadataValue> getMetadata(String metadataKey) {
return server.getPlayerMetadata().getMetadata(this, metadataKey);
}
@Override
public boolean hasMetadata(String metadataKey) {
return server.getPlayerMetadata().hasMetadata(this, metadataKey);
}
@Override
public void removeMetadata(String metadataKey, Plugin owningPlugin) {
server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin);
}
@Override
/**
* TODO - Involes making lots of tileEntityxxxs in Containers public
*/
public boolean setWindowProperty(Property prop, int value) {
Container container = getHandle().openContainer;
InventoryType type;
if (container instanceof ContainerRepair) {
type = InventoryType.ANVIL;
// nothing to do
return true;
}
else if (container instanceof ContainerBeacon) {
type = InventoryType.BEACON;
return true;
}
else if (container instanceof ContainerBrewingStand) {
type = InventoryType.BREWING;
//ContainerBrewingStand brew = (ContainerBrewingStand) container;
}
else if (container instanceof ContainerChest) {
type = InventoryType.CHEST;
}
else if (container instanceof ContainerDispenser) {
type = InventoryType.DISPENSER;
}
else if (container instanceof ContainerEnchantment) {
type = InventoryType.ENCHANTING;
}
else if (container instanceof ContainerFurnace) {
type = InventoryType.FURNACE;
}
else if (container instanceof ContainerMerchant) {
type = InventoryType.MERCHANT;
}
else if (container instanceof ContainerPlayer) {
type = InventoryType.PLAYER;
}
else if (container instanceof ContainerWorkbench) {
type = InventoryType.WORKBENCH;
}
else {
// fail
return true;
}
return true;
}
public void disconnect(String reason) {
conversationTracker.abandonAllConversations();
perm.clearPermissions();
}
public boolean isFlying() {
return getHandle().capabilities.isFlying;
}
public void setFlying(boolean value) {
if (!getAllowFlight() && value) {
throw new IllegalArgumentException("Cannot make player fly if getAllowFlight() is false");
}
Packet202PlayerAbilities pack = getAbilitiesPacket();
pack.setFlying(value);
this.updateAbilities(pack);
}
private void updateAbilities(Packet202PlayerAbilities j) {
//Packet202PlayerAbilities j = new Packet202PlayerAbilities(getHandle().capabilities);
getHandle().playerNetServerHandler.handlePlayerAbilities(j);
PlayerCapabilities pl = getHandle().capabilities;
pl.allowFlying = j.getAllowFlying();
pl.disableDamage = j.getDisableDamage();
pl.isCreativeMode = j.isCreativeMode();
//pl.setFlySpeed(j.getFlySpeed());
}
private Packet202PlayerAbilities getAbilitiesPacket() {
return new Packet202PlayerAbilities(getHandle().capabilities);
}
public boolean getAllowFlight() {
return getHandle().capabilities.allowFlying;
}
public void setAllowFlight(boolean value) {
Packet202PlayerAbilities able = getAbilitiesPacket();
able.setAllowFlying(value);
updateAbilities(able);
}
@Override
public int getNoDamageTicks() {
if (getHandle().hurtResistantTime > 0) {
return Math.max(getHandle().maxHurtResistantTime, getHandle().hurtResistantTime);
} else {
return getHandle().hurtResistantTime;
}
}
public void setFlySpeed(float value) {
validateSpeed(value);
Packet202PlayerAbilities pack = getAbilitiesPacket();
pack.setFlySpeed(value);
updateAbilities(pack);
}
public void setWalkSpeed(float value) {
validateSpeed(value);
Packet202PlayerAbilities pack = getAbilitiesPacket();
pack.setWalkSpeed(value);
updateAbilities(pack);
}
public float getFlySpeed() {
return getHandle().capabilities.getFlySpeed() * 2f;
}
public float getWalkSpeed() {
return getHandle().capabilities.walkSpeed * 2f;
}
private void validateSpeed(float value) {
if (value < 0) {
if (value < -1f) {
throw new IllegalArgumentException(value + " is too low");
}
} else {
if (value > 1f) {
throw new IllegalArgumentException(value + " is too high");
}
}
}
@Override
public void sendBlockChange(Location loc, Material material, byte data) {
this.sendBlockChange(loc, material.getId(), data);
}
@Override
public void giveExpLevels(int amount) {
getHandle().experienceLevel += amount;
}
@Override
public void setBedSpawnLocation(Location location, boolean force) {
getHandle().setSpawnChunk(new ChunkCoordinates(location.getBlockX(), location.getBlockY(), location.getBlockZ()), force);
}
@Override
public void setTexturePack(String url) {
// assume 16
getHandle().requestTexturePackLoad(url, 16);
}
}
| true | true | public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) {
net.minecraft.entity.player.EntityPlayerMP/*was:EntityPlayer*/ entity = getHandle();
if (getHealth() == 0 || entity.isDead/*was:dead*/) {
return false;
}
if (entity.playerNetServerHandler/*was:playerConnection*/ == null || entity.playerNetServerHandler/*was:playerConnection*/.connectionClosed/*was:disconnected*/) {
return false;
}
if (entity.ridingEntity/*was:vehicle*/ != null || entity.riddenByEntity/*was:passenger*/ != null) {
return false;
}
// From = Players current Location
Location from = this.getLocation();
// To = Players new Location if Teleport is Successful
Location to = location;
// Create & Call the Teleport Event.
PlayerTeleportEvent event = new PlayerTeleportEvent((Player) this, from, to, cause);
server.getPluginManager().callEvent(event);
// Return False to inform the Plugin that the Teleport was unsuccessful/cancelled.
if (event.isCancelled()) {
return false;
}
// Update the From Location
from = event.getFrom();
// Grab the new To Location dependent on whether the event was cancelled.
to = event.getTo();
// Grab the To and From World Handles.
CraftWorld fromWorld = (CraftWorld) from.getWorld();
CraftWorld toWorld = (CraftWorld) to.getWorld();
// Check if the fromWorld and toWorld are the same.
if (fromWorld.getName().equals(toWorld.getName())) {
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw());
} else {
// Close any foreign inventory
if (getHandle().openContainer != getHandle().inventoryContainer)
getHandle().closeInventory();
//toWorld.getHandle().spawnEntityInWorld(entity); // does something cool
//toWorld.getHandle().updateEntityWithOptionalForce(entity, false); // Update entity properties
/* entity.setWorld(toWorld.getHandle()); // Sets the current world obj
fromWorld.getHandle().removeEntity(entity);
Entity e = EntityList.createEntityByName(entity.getEntityName(), toWorld.getHandle());
if (e != null) {
e.copyDataFrom(entity, true);
entity.setDead();
toWorld.getHandle().spawnEntityInWorld(e);
fromWorld.getHandle().resetUpdateEntityTick();
toWorld.getHandle().resetUpdateEntityTick();
this.setHandle(e);
}
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!*/
//server.getHandle().getConfigurationManager().transferPlayerToDimension(entity, toWorld.getHandle().getWorldInfo().getDimension(), new CraftTeleporter(toWorld.getHandle()));
//entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!
toWorld.getHandle().spawnEntityInWorld(entity);
entity.setWorld(toWorld.getHandle());
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
entity.mcServer.getConfigurationManager().func_72375_a(entity, toWorld.getHandle());
entity.playerNetServerHandler.setPlayerLocation(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
WorldServer newWorld = toWorld.getHandle();
entity.theItemInWorldManager.setWorld((WorldServer)newWorld);
entity.mcServer.getConfigurationManager().updateTimeAndWeatherForPlayer(entity, (WorldServer)newWorld);
entity.mcServer.getConfigurationManager().syncPlayerInventory(entity);
entity.playerNetServerHandler.sendPacketToPlayer(new Packet43Experience(entity.experience, entity.experienceTotal, entity.experienceLevel));
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
}
return true;
}
| public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) {
net.minecraft.entity.player.EntityPlayerMP/*was:EntityPlayer*/ entity = getHandle();
if (getHealth() == 0 || entity.isDead/*was:dead*/) {
return false;
}
if (entity.playerNetServerHandler/*was:playerConnection*/ == null || entity.playerNetServerHandler/*was:playerConnection*/.connectionClosed/*was:disconnected*/) {
return false;
}
if (entity.ridingEntity/*was:vehicle*/ != null || entity.riddenByEntity/*was:passenger*/ != null) {
return false;
}
// From = Players current Location
Location from = this.getLocation();
// To = Players new Location if Teleport is Successful
Location to = location;
// Create & Call the Teleport Event.
PlayerTeleportEvent event = new PlayerTeleportEvent((Player) this, from, to, cause);
server.getPluginManager().callEvent(event);
// Return False to inform the Plugin that the Teleport was unsuccessful/cancelled.
if (event.isCancelled()) {
return false;
}
// Update the From Location
from = event.getFrom();
// Grab the new To Location dependent on whether the event was cancelled.
to = event.getTo();
// Grab the To and From World Handles.
CraftWorld fromWorld = (CraftWorld) from.getWorld();
CraftWorld toWorld = (CraftWorld) to.getWorld();
// Check if the fromWorld and toWorld are the same.
if (fromWorld.getName().equals(toWorld.getName())) {
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw());
} else {
// Close any foreign inventory
if (getHandle().openContainer != getHandle().inventoryContainer)
getHandle().closeInventory();
//toWorld.getHandle().spawnEntityInWorld(entity); // does something cool
//toWorld.getHandle().updateEntityWithOptionalForce(entity, false); // Update entity properties
/* entity.setWorld(toWorld.getHandle()); // Sets the current world obj
fromWorld.getHandle().removeEntity(entity);
Entity e = EntityList.createEntityByName(entity.getEntityName(), toWorld.getHandle());
if (e != null) {
e.copyDataFrom(entity, true);
entity.setDead();
toWorld.getHandle().spawnEntityInWorld(e);
fromWorld.getHandle().resetUpdateEntityTick();
toWorld.getHandle().resetUpdateEntityTick();
this.setHandle(e);
}
entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!*/
//server.getHandle().getConfigurationManager().transferPlayerToDimension(entity, toWorld.getHandle().getWorldInfo().getDimension(), new CraftTeleporter(toWorld.getHandle()));
//entity.playerNetServerHandler.setPlayerLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); // Set location!
toWorld.getHandle().spawnEntityInWorld(entity);
entity.setWorld(toWorld.getHandle());
fromWorld.getHandle().removeEntity(entity);
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
entity.mcServer.getConfigurationManager().func_72375_a(entity, toWorld.getHandle());
entity.playerNetServerHandler.setPlayerLocation(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
toWorld.getHandle().updateEntityWithOptionalForce(entity, false);
WorldServer newWorld = toWorld.getHandle();
entity.theItemInWorldManager.setWorld((WorldServer)newWorld);
entity.mcServer.getConfigurationManager().updateTimeAndWeatherForPlayer(entity, (WorldServer)newWorld);
entity.mcServer.getConfigurationManager().syncPlayerInventory(entity);
entity.playerNetServerHandler.sendPacketToPlayer(new Packet43Experience(entity.experience, entity.experienceTotal, entity.experienceLevel));
entity.setLocationAndAngles(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch());
}
return true;
}
|
diff --git a/src/main/java/com/tehbeard/map/schematic/bukkit/BukkitSchematicLoader.java b/src/main/java/com/tehbeard/map/schematic/bukkit/BukkitSchematicLoader.java
index 38175a3..3af303e 100644
--- a/src/main/java/com/tehbeard/map/schematic/bukkit/BukkitSchematicLoader.java
+++ b/src/main/java/com/tehbeard/map/schematic/bukkit/BukkitSchematicLoader.java
@@ -1,267 +1,272 @@
package com.tehbeard.map.schematic.bukkit;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BrewingStand;
import org.bukkit.block.Chest;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Furnace;
import org.bukkit.block.Jukebox;
import org.bukkit.block.NoteBlock;
import org.bukkit.block.Sign;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import com.tehbeard.map.misc.ItemEnchantment;
import com.tehbeard.map.misc.Item;
import com.tehbeard.map.misc.MapUtils;
import com.tehbeard.map.misc.WorldVector;
import com.tehbeard.map.schematic.BlockType;
import com.tehbeard.map.schematic.Schematic;
import com.tehbeard.map.schematic.bukkit.worldedit.BlockData;
import com.tehbeard.map.tileEntities.TileCauldron;
import com.tehbeard.map.tileEntities.TileChest;
import com.tehbeard.map.tileEntities.TileEntity;
import com.tehbeard.map.tileEntities.TileFurnace;
import com.tehbeard.map.tileEntities.TileNoteBlock;
import com.tehbeard.map.tileEntities.TileRecordPlayer;
import com.tehbeard.map.tileEntities.TileSign;
import com.tehbeard.map.tileEntities.TileSpawner;
import com.tehbeard.map.tileEntities.TileTrap;
public class BukkitSchematicLoader {
private Schematic schematic;
public BukkitSchematicLoader(Schematic schematic){
this.schematic = schematic;
}
public void paste(Location location,int rotations,byte[] layers){
WorldVector l = new WorldVector(location.getBlockX(),location.getBlockY(),location.getBlockZ(),location.getWorld().getName());
addBlocks(l,0,rotations,layers);
addBlocks(l,1,rotations,layers);
addBlocks(l,2,rotations,layers);
World w = Bukkit.getWorld(l.getWorldName());
for(TileEntity t:schematic.getTileEntities()){
+ if(layers != null){
+ if(!inArray(layers, schematic.getLayer(t.getX(), t.getY(), t.getZ()))){
+ continue;
+ }
+ }
WorldVector relVector = new WorldVector(schematic.getOffset());
relVector.addVector(new WorldVector(t.getX(), t.getY(),t.getZ(), null));
relVector.rotateVector(rotations);
Block b = w.getBlockAt(location.clone().add(
relVector.getX(),
relVector.getY(),
relVector.getZ()
)
);
if(t instanceof TileChest){
placeChest(b,(TileChest) t);
}
if(t instanceof TileTrap){
placeDispenser(b,(TileTrap)t);
}
if(t instanceof TileSign){
placeSign(b,(TileSign)t);
}
if(t instanceof TileNoteBlock){
placeNoteBlock(b,(TileNoteBlock)t);
}
if(t instanceof TileFurnace){
placeFurnace(b,(TileFurnace)t);
}
if(t instanceof TileCauldron){
placeBrewStand(b,(TileCauldron)t);
}
if(t instanceof TileRecordPlayer){
placeJukebox(b,(TileRecordPlayer)t);
}
if(t instanceof TileSpawner){
placeSpawner(b, (TileSpawner) t);
}
}
}
private void addBlocks(WorldVector l,int blockOrder,int rotations,byte[] layers){
World w = Bukkit.getWorld(l.getWorldName());
WorldVector baseVector = new WorldVector(0, 0, 0, l.getWorldName());
baseVector.addVector(l);
for(int y = 0;y<schematic.getHeight();y++){
for(int z = 0;z<schematic.getLength();z++){
for(int x = 0;x<schematic.getWidth();x++){
if(BlockType.getOrder(schematic.getBlockId(x, y, z)) == blockOrder){
if(layers != null){
if(!inArray(layers, schematic.getLayer(x, y, z))){
continue;
}
}
WorldVector relVector = new WorldVector(schematic.getOffset());
relVector.addVector(new WorldVector(x, y, z, null));
relVector.rotateVector(rotations);
relVector.addVector(baseVector);
Block b = w.getBlockAt(
relVector.getBlockX(),
relVector.getBlockY(),
relVector.getBlockZ()
);
int type = schematic.getBlockId(x, y, z) & 0xFF;
byte data = schematic.getBlockData(x, y, z);
for(int i =0;i<rotations;i++){
data = (byte) BlockData.rotate90(type, data);
}
b.setTypeId(type,false);
b.setData(data,false);
b.getState().update();
}
}
}
}
}
private boolean inArray(byte[] layers,byte b){
for(byte c : layers){
if(c==b){return true;}
}
return false;
}
private static void placeChest(Block b,TileChest chest){
Chest c = (Chest)b.getState();
Inventory i = c.getBlockInventory();
doInventory(i, chest.getItems());
c.update(true);
}
private static void placeDispenser(Block b, TileTrap trap) {
Dispenser c = (Dispenser)b.getState();
Inventory i = c.getInventory();
doInventory(i, trap.getItems());
c.update(true);
}
private static void placeSign(Block b, TileSign t) {
Sign s = (Sign) b.getState();
int i =0;
for(String l : t.getLines()){
s.setLine(i,l);
i++;
}
s.update(true);
}
private static void placeNoteBlock(Block b, TileNoteBlock t) {
NoteBlock s = (NoteBlock) b.getState();
s.setRawNote(t.getNote());
s.update(true);
}
private static void placeFurnace(Block b, TileFurnace t) {
Furnace f = (Furnace) b.getState();
f.setBurnTime(t.getBurn());
f.setCookTime(t.getCook());
doInventory(f.getInventory(), t.getItems());
f.update(true);
}
private static void placeBrewStand(Block b, TileCauldron t) {
BrewingStand bs = (BrewingStand)b.getState();
bs.setBrewingTime(t.getBrew());
doInventory(bs.getInventory(), t.getItems());
bs.update(true);
}
private static void placeJukebox(Block b, TileRecordPlayer t) {
Jukebox jb = (Jukebox)b.getState();
jb.setRawData(t.getRecord());
jb.update(true);
}
private static void placeSpawner(Block b,TileSpawner t){
CreatureSpawner spawner = (CreatureSpawner) b.getState();
spawner.setCreatureTypeByName(t.getId());
}
private static ItemStack makeItemStack(Item item){
ItemStack is = new ItemStack(item.getId(),item.getCount(),item.getDamage());
ItemMeta meta = is.getItemMeta();
for(ItemEnchantment e : item.getEnchantments()){
meta.addEnchant(Enchantment.getById(e.getType()), e.getLvl(),true);
}
if(item.getName()!=null){
meta.setDisplayName(item.getName());
}
if(item.getLore()!=null){
meta.setLore(item.getLore());
}
switch(is.getType()){
case BOOK_AND_QUILL:
case WRITTEN_BOOK:
BookMeta bookMeta = (BookMeta)meta;
bookMeta.setPages(item.getBookPages());
if(is.getType() == Material.WRITTEN_BOOK){
bookMeta.setAuthor(item.getBookAuthor());
bookMeta.setTitle(item.getBookTitle());
}
break;
case SKULL_ITEM:
if(item.getSkullOwner() !=null){
((SkullMeta)meta).setOwner(item.getSkullOwner());
}
break;
}
is.setItemMeta(meta);
return is;
}
private static void doInventory(Inventory inv, Item[] items){
for(Item item : items){
if(item == null){continue;}
inv.setItem(item.getSlot(),makeItemStack(item));
}
}
}
| true | true | public void paste(Location location,int rotations,byte[] layers){
WorldVector l = new WorldVector(location.getBlockX(),location.getBlockY(),location.getBlockZ(),location.getWorld().getName());
addBlocks(l,0,rotations,layers);
addBlocks(l,1,rotations,layers);
addBlocks(l,2,rotations,layers);
World w = Bukkit.getWorld(l.getWorldName());
for(TileEntity t:schematic.getTileEntities()){
WorldVector relVector = new WorldVector(schematic.getOffset());
relVector.addVector(new WorldVector(t.getX(), t.getY(),t.getZ(), null));
relVector.rotateVector(rotations);
Block b = w.getBlockAt(location.clone().add(
relVector.getX(),
relVector.getY(),
relVector.getZ()
)
);
if(t instanceof TileChest){
placeChest(b,(TileChest) t);
}
if(t instanceof TileTrap){
placeDispenser(b,(TileTrap)t);
}
if(t instanceof TileSign){
placeSign(b,(TileSign)t);
}
if(t instanceof TileNoteBlock){
placeNoteBlock(b,(TileNoteBlock)t);
}
if(t instanceof TileFurnace){
placeFurnace(b,(TileFurnace)t);
}
if(t instanceof TileCauldron){
placeBrewStand(b,(TileCauldron)t);
}
if(t instanceof TileRecordPlayer){
placeJukebox(b,(TileRecordPlayer)t);
}
if(t instanceof TileSpawner){
placeSpawner(b, (TileSpawner) t);
}
}
}
| public void paste(Location location,int rotations,byte[] layers){
WorldVector l = new WorldVector(location.getBlockX(),location.getBlockY(),location.getBlockZ(),location.getWorld().getName());
addBlocks(l,0,rotations,layers);
addBlocks(l,1,rotations,layers);
addBlocks(l,2,rotations,layers);
World w = Bukkit.getWorld(l.getWorldName());
for(TileEntity t:schematic.getTileEntities()){
if(layers != null){
if(!inArray(layers, schematic.getLayer(t.getX(), t.getY(), t.getZ()))){
continue;
}
}
WorldVector relVector = new WorldVector(schematic.getOffset());
relVector.addVector(new WorldVector(t.getX(), t.getY(),t.getZ(), null));
relVector.rotateVector(rotations);
Block b = w.getBlockAt(location.clone().add(
relVector.getX(),
relVector.getY(),
relVector.getZ()
)
);
if(t instanceof TileChest){
placeChest(b,(TileChest) t);
}
if(t instanceof TileTrap){
placeDispenser(b,(TileTrap)t);
}
if(t instanceof TileSign){
placeSign(b,(TileSign)t);
}
if(t instanceof TileNoteBlock){
placeNoteBlock(b,(TileNoteBlock)t);
}
if(t instanceof TileFurnace){
placeFurnace(b,(TileFurnace)t);
}
if(t instanceof TileCauldron){
placeBrewStand(b,(TileCauldron)t);
}
if(t instanceof TileRecordPlayer){
placeJukebox(b,(TileRecordPlayer)t);
}
if(t instanceof TileSpawner){
placeSpawner(b, (TileSpawner) t);
}
}
}
|
diff --git a/src/org/geworkbench/bison/datastructure/bioobjects/markers/CSGeneMarker.java b/src/org/geworkbench/bison/datastructure/bioobjects/markers/CSGeneMarker.java
index 71084ce2..50fae0d4 100755
--- a/src/org/geworkbench/bison/datastructure/bioobjects/markers/CSGeneMarker.java
+++ b/src/org/geworkbench/bison/datastructure/bioobjects/markers/CSGeneMarker.java
@@ -1,262 +1,264 @@
package org.geworkbench.bison.datastructure.bioobjects.markers;
import org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser.AnnotationParser;
import org.geworkbench.bison.datastructure.properties.CSUnigene;
import org.geworkbench.bison.datastructure.properties.DSUnigene;
import java.io.*;
/**
* <p>
* Title: Bioworks
* </p>
* <p>
* Description: Modular Application Framework for Gene Expession, Sequence and
* Genotype Analysis
* </p>
* <p>
* Copyright: Copyright (c) 2003 -2004
* </p>
* <p>
* Company: Columbia University
* </p>
*
* @author not attributable
* @version $Id$
*/
public class CSGeneMarker implements DSGeneMarker, Serializable {
private static final long serialVersionUID = -8778666154593978009L;
protected String label = null;
protected String description = null;
protected String abrev = null;
protected int markerId = 0;
protected int geneId = -1;
protected int[] geneIds;
protected DSUnigene unigene = new CSUnigene();
private String geneName = null;
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// Shouldn't happen
e.printStackTrace();
return null;
}
}
public CSGeneMarker() {
}
public CSGeneMarker(String label) {
this.label = label;
}
/**
* getLabel
*
* @return String
*/
public String getDescription() {
return description;
}
public void setDescription(String label) {
this.description = new String(label);
}
/**
* getAccession
*
* @return String
*/
public String getLabel() {
return label;
}
public int getGeneId() {
return geneId;
}
public void setLabel(String label) {
this.label = new String(label);
}
public void setGeneId(int locusLink) {
this.geneId = locusLink;
geneIds = new int[1];
geneIds[0] = geneId;
}
public void setGeneName(String geneName) {
this.geneName = geneName;
}
/**
* getSerial
*
* @return int
*/
public int getSerial() {
return markerId;
}
public void setSerial(int id) {
markerId = id;
}
protected void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
}
protected void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
ois.defaultReadObject();
}
public boolean equals(Object marker) {
if (marker instanceof CSGeneMarker) {
CSGeneMarker mInfo = (CSGeneMarker) marker;
String markerLabel = mInfo.getLabel();
if (markerLabel != null) {
return markerLabel.equals(label);
} else {
return (label == null);
}
}
return false;
}
/**
* Implementation of the <code>Comparable</code> interface.
*
* @param o
* @return
*/
public int compareTo(DSGeneMarker marker) {
return label.compareToIgnoreCase(marker.getLabel());
}
public String toString() {
return getCanonicalLabel();
}
// The behavior of this method depends on <code>currentDataSet</code> in AnnotationParser. That is bad.
public String getShortName() {
String name = label;
try {
String[] geneSymbol = AnnotationParser.getInfo(label, AnnotationParser.GENE_SYMBOL);
name = geneSymbol[0];
for(int i=1; i<geneSymbol.length; i++)
name += " /// "+geneSymbol[i];
} catch (NullPointerException e) {
// do thing. keep label.
}
return name;
}
public int hashCode() {
// watkin -- made consistent with equals()
return label.hashCode();
}
public void write(BufferedWriter writer) throws IOException {
writer.write(label);
writer.write('\t');
writer.write(description);
}
public DSUnigene getUnigene() {
return unigene;
}
public String getGeneName() {
if (geneName == null) {
geneName = getShortName();
}
return geneName;
}
public DSGeneMarker deepCopy() {
CSGeneMarker copy = null;
try {
copy = (CSGeneMarker) this.getClass().newInstance();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InstantiationException ie) {
ie.printStackTrace();
}
copy.setLabel(getLabel());
copy.setSerial(markerId);
copy.setDescription(description);
copy.abrev = abrev;
copy.geneId = geneId;
copy.unigene = unigene;
return copy;
}
private String getCanonicalLabel() {
String text0 = "";
- try {
- String[] descriptions = AnnotationParser.getInfo(label,
- AnnotationParser.DESCRIPTION);
- String text1 = "";
- if (descriptions != null && descriptions.length > 0) {
- text1 = descriptions[0];
- }
+ String[] descriptions = AnnotationParser.getInfo(label,
+ AnnotationParser.DESCRIPTION);
+ String text1 = "";
+ if (descriptions != null && descriptions.length > 0) {
+ text1 = descriptions[0];
+ }
+ String[] geneSymbol = AnnotationParser.getInfo(label,
+ AnnotationParser.GENE_SYMBOL);
+ if (geneSymbol != null) {
text0 = label + ": (" + getShortName() + ") " + text1;
- } catch (Exception ex) {
+ } else { // no gene symbol
text0 = this.getDescription();
if (text0 != null) {
int index = text0.indexOf("/DEFINITION");
if (index >= 0) {
String text = text0.substring(index + 12);
text0 = label + ": " + text.replace('"', ' ').trim();
} else {
String text = new String(text0);
if (text0.indexOf("Cluster Incl.") >= 0) {
index = text0.indexOf(":");
text = text.substring(index + 1);
}
String[] labels = text.split("/");
if (labels != null && labels.length > 0)
text0 = label + ": "
+ labels[0].replace('"', ' ').trim();
}
}
}
if (text0 == null || text0.length() == 0) {
return label;
} else {
return text0;
}
}
public int[] getGeneIds() {
if (geneIds == null)
return new int[] { geneId };
else
return geneIds;
}
public String[] getShortNames() {
if (label == null)
return new String[0];
String[] names = getShortName().split(AnnotationParser.MAIN_DELIMITER);
for (int i = 0; i < names.length; i++) {
if (names[i] != null)
names[i] = names[i].trim();
}
return names;
}
}
| false | true | private String getCanonicalLabel() {
String text0 = "";
try {
String[] descriptions = AnnotationParser.getInfo(label,
AnnotationParser.DESCRIPTION);
String text1 = "";
if (descriptions != null && descriptions.length > 0) {
text1 = descriptions[0];
}
text0 = label + ": (" + getShortName() + ") " + text1;
} catch (Exception ex) {
text0 = this.getDescription();
if (text0 != null) {
int index = text0.indexOf("/DEFINITION");
if (index >= 0) {
String text = text0.substring(index + 12);
text0 = label + ": " + text.replace('"', ' ').trim();
} else {
String text = new String(text0);
if (text0.indexOf("Cluster Incl.") >= 0) {
index = text0.indexOf(":");
text = text.substring(index + 1);
}
String[] labels = text.split("/");
if (labels != null && labels.length > 0)
text0 = label + ": "
+ labels[0].replace('"', ' ').trim();
}
}
}
if (text0 == null || text0.length() == 0) {
return label;
} else {
return text0;
}
}
| private String getCanonicalLabel() {
String text0 = "";
String[] descriptions = AnnotationParser.getInfo(label,
AnnotationParser.DESCRIPTION);
String text1 = "";
if (descriptions != null && descriptions.length > 0) {
text1 = descriptions[0];
}
String[] geneSymbol = AnnotationParser.getInfo(label,
AnnotationParser.GENE_SYMBOL);
if (geneSymbol != null) {
text0 = label + ": (" + getShortName() + ") " + text1;
} else { // no gene symbol
text0 = this.getDescription();
if (text0 != null) {
int index = text0.indexOf("/DEFINITION");
if (index >= 0) {
String text = text0.substring(index + 12);
text0 = label + ": " + text.replace('"', ' ').trim();
} else {
String text = new String(text0);
if (text0.indexOf("Cluster Incl.") >= 0) {
index = text0.indexOf(":");
text = text.substring(index + 1);
}
String[] labels = text.split("/");
if (labels != null && labels.length > 0)
text0 = label + ": "
+ labels[0].replace('"', ' ').trim();
}
}
}
if (text0 == null || text0.length() == 0) {
return label;
} else {
return text0;
}
}
|
diff --git a/XServer/src/au/com/darkside/XServer/Drawable.java b/XServer/src/au/com/darkside/XServer/Drawable.java
index 6dae91e..cef7e46 100644
--- a/XServer/src/au/com/darkside/XServer/Drawable.java
+++ b/XServer/src/au/com/darkside/XServer/Drawable.java
@@ -1,968 +1,968 @@
/**
* This class implements an X drawable.
*/
package au.com.darkside.XServer;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
/**
* @author Matthew Kwan
*
* This class implements an X drawable.
*/
public class Drawable {
private final Bitmap _bitmap;
private final Canvas _canvas;
private final int _depth;
/**
* Constructor.
*
* @param width The drawable width.
* @param height The drawable height.
* @param depth The drawable depth.
* @param color Fill the bitmap with this color.
*/
public Drawable (
int width,
int height,
int depth,
int color
) {
_bitmap = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);
_canvas = new Canvas (_bitmap);
_depth = depth;
_bitmap.eraseColor (color);
}
/**
* Return the drawable's width.
*
* @return The drawable's width.
*/
public int
getWidth () {
return _bitmap.getWidth ();
}
/**
* Return the drawable's height.
*
* @return The drawable's height.
*/
public int
getHeight () {
return _bitmap.getHeight ();
}
/**
* Return the drawable's depth.
*
* @return The drawable's depth.
*/
public int
getDepth () {
return _depth;
}
/**
* Return the drawable's bitmap.
*
* @return The drawable's bitmap.
*/
public Bitmap
getBitmap () {
return _bitmap;
}
/**
* Process an X request relating to this drawable.
*
* @param xServer The X server.
* @param io The input/output stream.
* @param id The ID of the pixmap or window using this drawable.
* @param sequenceNumber The request sequence number.
* @param opcode The request's opcode.
* @param arg Optional first argument.
* @param bytesRemaining Bytes yet to be read in the request.
* @return True if the drawable has been changed.
* @throws IOException
*/
public boolean
processRequest (
XServer xServer,
InputOutput io,
int id,
int sequenceNumber,
byte opcode,
int arg,
int bytesRemaining
) throws IOException {
boolean changed = false;
switch (opcode) {
case RequestCode.CopyArea:
if (bytesRemaining != 20) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
int did = io.readInt (); // Dest drawable.
int gcid = io.readInt (); // GC.
short sx = (short) io.readShort (); // Src X.
short sy = (short) io.readShort (); // Src Y.
short dx = (short) io.readShort (); // Dst X.
short dy = (short) io.readShort (); // Dst Y.
int width = io.readShort (); // Width.
int height = io.readShort (); // Height.
Resource r1 = xServer.getResource (did);
Resource r2 = xServer.getResource (gcid);
if (r1 == null || !r1.isDrawable ()) {
ErrorCode.write (io, ErrorCode.Drawable,
sequenceNumber, opcode, did);
} else if (r2 == null
|| r2.getType () != Resource.GCONTEXT) {
ErrorCode.write (io, ErrorCode.GContext,
sequenceNumber, opcode, gcid);
} else if (width > 0 && height > 0){
copyArea (io, sequenceNumber, sx, sy, width, height,
r1, dx, dy, (GContext) r2);
}
}
break;
case RequestCode.CopyPlane:
if (bytesRemaining != 24) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, id);
} else {
int did = io.readInt (); // Dest drawable.
int gcid = io.readInt (); // GC.
short sx = (short) io.readShort (); // Src X.
short sy = (short) io.readShort (); // Src Y.
short dx = (short) io.readShort (); // Dst X.
short dy = (short) io.readShort (); // Dst Y.
int width = io.readShort (); // Width.
int height = io.readShort (); // Height.
int bitPlane = io.readInt (); // Bit plane.
Resource r1 = xServer.getResource (did);
Resource r2 = xServer.getResource (gcid);
if (r1 == null || !r1.isDrawable ()) {
ErrorCode.write (io, ErrorCode.Drawable,
sequenceNumber, opcode, did);
} else if (r2 == null
|| r2.getType () != Resource.GCONTEXT) {
ErrorCode.write (io, ErrorCode.GContext,
sequenceNumber, opcode, gcid);
} else {
if (_depth != 32)
copyPlane (io, sequenceNumber, sx, sy, width,
height, bitPlane, r1, dx, dy,
(GContext) r2);
else
copyArea (io, sequenceNumber, sx, sy, width,
height, r1, dx, dy, (GContext) r2);
}
}
break;
case RequestCode.GetImage:
if (bytesRemaining != 12) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
processGetImageRequest (io, sequenceNumber, arg);
}
break;
case RequestCode.QueryBestSize:
if (bytesRemaining != 4) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
int width = io.readShort (); // Width.
int height = io.readShort (); // Height.
synchronized (io) {
Util.writeReplyHeader (io, 0, sequenceNumber);
io.writeInt (0); // Reply length.
io.writeShort ((short) width); // Width.
io.writeShort ((short) height); // Height.
io.writePadBytes (20); // Unused.
}
io.flush ();
}
break;
case RequestCode.PolyPoint:
case RequestCode.PolyLine:
case RequestCode.PolySegment:
case RequestCode.PolyRectangle:
case RequestCode.PolyArc:
case RequestCode.FillPoly:
case RequestCode.PolyFillRectangle:
case RequestCode.PolyFillArc:
case RequestCode.PutImage:
case RequestCode.PolyText8:
case RequestCode.PolyText16:
case RequestCode.ImageText8:
case RequestCode.ImageText16:
if (bytesRemaining < 4) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
int gcid = io.readInt (); // GContext.
Resource r = xServer.getResource (gcid);
bytesRemaining -= 4;
if (r == null || r.getType () != Resource.GCONTEXT) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.GContext,
sequenceNumber, opcode, 0);
} else {
changed = processGCRequest (xServer, io, id,
(GContext) r, sequenceNumber, opcode, arg,
bytesRemaining);
}
}
break;
default:
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Implementation,
sequenceNumber, opcode, 0);
break;
}
return changed;
}
/**
* Process a GetImage request.
*
* @param io The input/output stream.
* @param sequenceNumber The request sequence number.
* @param format 1=XYPixmap, 2=ZPixmap.
* @throws IOException
*/
private void
processGetImageRequest (
InputOutput io,
int sequenceNumber,
int format
) throws IOException {
short x = (short) io.readShort (); // X.
short y = (short) io.readShort (); // Y.
int width = io.readShort (); // Width.
int height = io.readShort (); // Height.
int planeMask = io.readInt (); // Plane mask.
int wh = width * height;
int n, pad;
int[] pixels = new int[wh];
byte[] bytes = null;
_bitmap.getPixels (pixels, 0, width, x, y, width, height);
if (format == 2) // ZPixmap.
n = wh * 3;
else { // XYPixmap.
int planes = Util.bitcount (planeMask);
int rightPad = -width & 7;
int xmax = width + rightPad;
int offset = 0;
n = planes * height * (width + rightPad) / 8;
bytes = new byte[n];
for (int plane = 0; plane < 32; plane++) {
if ((plane & planeMask) == 0)
continue;
byte b = 0;
for (int yi = 0; yi < height; yi++) {
for (int xi = 0; xi < xmax; xi++) {
b <<= 1;
if (xi < width
&& (pixels[yi * width + xi] & planeMask) != 0)
b |= 1;
if ((xi & 7) == 7) {
bytes[offset++] = b;
b = 0;
}
}
}
}
}
pad = -n & 3;
synchronized (io) {
Util.writeReplyHeader (io, 32, sequenceNumber);
io.writeInt ((n + pad) / 4); // Reply length.
io.writeInt (0); // Visual ID.
io.writePadBytes (20); // Unused.
if (format == 2) {
for (int i = 0; i < wh; i++) {
n = pixels[i] & planeMask;
io.writeByte ((byte) (n & 0xff));
io.writeByte ((byte) ((n >> 8) & 0xff));
io.writeByte ((byte) ((n >> 16) & 0xff));
}
} else {
io.writeBytes (bytes, 0, n);
}
io.writePadBytes (pad); // Unused.
}
io.flush ();
}
/**
* Clear a rectangular region of the drawable.
*
* @param x X coordinate of the rectangle.
* @param y Y coordinate of the rectangle.
* @param width Width of the rectangle.
* @param height Height of the rectangle.
* @param background The color to draw in the cleared area.
*/
public void
clearArea (
int x,
int y,
int width,
int height,
int background
) {
Rect r = new Rect (x, y, x + width, y + height);
Paint paint = new Paint ();
paint.setColor (background);
paint.setStyle (Paint.Style.FILL);
_canvas.drawRect (r, paint);
}
/**
* Copy a rectangle from this drawable to another.
*
* @param io The input/output stream.
* @param sequenceNumber The request sequence number.
* @param sx X coordinate of this rectangle.
* @param sy Y coordinate of this rectangle.
* @param width Width of the rectangle.
* @param height Height of the rectangle.
* @param dr The pixmap or window to draw the rectangle in.
* @param dx The destination X coordinate.
* @param dy The destination Y coordinate.
* @param gc The GContext.
* @throws IOException
*/
private void
copyArea (
InputOutput io,
int sequenceNumber,
int sx,
int sy,
int width,
int height,
Resource dr,
int dx,
int dy,
GContext gc
) throws IOException {
Drawable dst;
if (dr.getType () == Resource.PIXMAP)
dst = ((Pixmap) dr).getDrawable ();
else
dst = ((Window) dr).getDrawable ();
Bitmap bm = Bitmap.createBitmap (_bitmap, sx, sy, width, height);
dst._canvas.drawBitmap (bm, dx, dy, gc.getPaint ());
if (dr.getType () == Resource.WINDOW)
((Window) dr).invalidate (dx, dy, width, height);
if (gc.getGraphicsExposure ())
EventCode.sendNoExposure (dr.getClientComms (), dr,
RequestCode.CopyArea);
}
/**
* Copy a rectangle from a plane of this drawable to another rectangle.
*
* @param io The input/output stream.
* @param sequenceNumber The request sequence number.
* @param sx X coordinate of this rectangle.
* @param sy Y coordinate of this rectangle.
* @param width Width of the rectangle.
* @param height Height of the rectangle.
* @param bitPlane The bit plane being copied.
* @param dr The pixmap or window to draw the rectangle in.
* @param dx The destination X coordinate.
* @param dy The destination Y coordinate.
* @param gc The GContext.
* @throws IOException
*/
private void
copyPlane (
InputOutput io,
int sequenceNumber,
int sx,
int sy,
int width,
int height,
int bitPlane,
Resource dr,
int dx,
int dy,
GContext gc
) throws IOException {
Drawable dst;
if (dr.getType () == Resource.PIXMAP)
dst = ((Pixmap) dr).getDrawable ();
else
dst = ((Window) dr).getDrawable ();
int fg = (_depth == 1) ? 0xffffffff : gc.getForegroundColor ();
int bg = (_depth == 1) ? 0 : gc.getBackgroundColor ();
int[] pixels = new int [width * height];
_bitmap.getPixels (pixels, 0, width, sx, sy, width, height);
for (int i = 0; i < pixels.length; i++)
pixels[i] = ((pixels[i] & bitPlane) != 0) ? fg : bg;
dst._canvas.drawBitmap (pixels, 0, width, dx, dy, width, height,
true, gc.getPaint ());
if (dr.getType () == Resource.WINDOW)
((Window) dr).invalidate (dx, dy, width, height);
if (gc.getGraphicsExposure ())
EventCode.sendNoExposure (dr.getClientComms(), dr,
RequestCode.CopyPlane);
}
/**
* Process an X request relating to this drawable using the
* GContext provided.
*
* @param xServer The X server.
* @param io The input/output stream.
* @param id The ID of the pixmap or window using this drawable.
* @param gc The GContext to use for drawing.
* @param sequenceNumber The request sequence number.
* @param opcode The request's opcode.
* @param arg Optional first argument.
* @param bytesRemaining Bytes yet to be read in the request.
* @return True if the drawable is modified.
* @throws IOException
*/
public boolean
processGCRequest (
XServer xServer,
InputOutput io,
int id,
GContext gc,
int sequenceNumber,
byte opcode,
int arg,
int bytesRemaining
) throws IOException {
Paint paint = gc.getPaint ();
boolean changed = false;
int originalColor = paint.getColor ();
_canvas.save ();
gc.applyClipRectangles (_canvas);
if (_depth == 1)
paint.setColor (0xffffffff);
switch (opcode) {
case RequestCode.PolyPoint:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
float p = (short) io.readShort ();
bytesRemaining -= 2;
if (arg == 0 || i < 2) // Relative to origin.
points[i] = p;
else
points[i] = points[i - 2] + p; // Rel to previous.
i++;
}
_canvas.drawPoints (points, paint);
changed = true;
}
break;
case RequestCode.PolyLine:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
Path path = new Path ();
int i = 0;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (arg == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
paint.setStyle (Paint.Style.STROKE);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolySegment:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
points[i++] = (short) io.readShort ();
bytesRemaining -= 2;
}
_canvas.drawLines (points, paint);
changed = true;
}
break;
case RequestCode.PolyRectangle:
case RequestCode.PolyFillRectangle:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
if (opcode == RequestCode.PolyRectangle)
paint.setStyle (Paint.Style.STROKE);
else
paint.setStyle (Paint.Style.FILL);
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
bytesRemaining -= 8;
_canvas.drawRect(x, y, x + width, y + height, paint);
changed = true;
}
}
break;
case RequestCode.FillPoly:
if (bytesRemaining < 4 || (bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
io.readByte (); // Shape.
int mode = io.readByte (); // Coordinate mode.
Path path = new Path ();
int i = 0;
io.readSkip (2); // Unused.
bytesRemaining -= 4;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (mode == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
path.close ();
path.setFillType (gc.getFillType ());
paint.setStyle (Paint.Style.FILL);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolyArc:
case RequestCode.PolyFillArc:
if ((bytesRemaining % 12) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
boolean useCenter = false;
if (opcode == RequestCode.PolyArc) {
paint.setStyle (Paint.Style.STROKE);
} else {
paint.setStyle (Paint.Style.FILL);
if (gc.getArcMode () == 1) // Pie slice.
useCenter = true;
}
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
float angle1 = (short) io.readShort ();
float angle2 = (short) io.readShort ();
RectF r = new RectF (x, y, x + width, y + height);
bytesRemaining -= 12;
_canvas.drawArc (r, angle1 / -64.0f, angle2 / -64.0f,
useCenter, paint);
changed = true;
}
}
break;
case RequestCode.PutImage:
changed = processPutImage (io, sequenceNumber, gc, arg,
bytesRemaining);
break;
case RequestCode.PolyText8:
case RequestCode.PolyText16:
changed = processPolyText (io, sequenceNumber, gc, opcode,
bytesRemaining);
break;
case RequestCode.ImageText8:
if (bytesRemaining != 4 + arg + (-arg & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = -arg & 3;
byte[] bytes = new byte[arg];
io.readBytes (bytes, 0, arg);
io.readSkip (pad);
_canvas.drawText (new String (bytes), x, y, paint);
changed = true;
}
break;
case RequestCode.ImageText16:
if (bytesRemaining != 4 + 2 * arg + (-(2 * arg) & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = (-2 * arg) & 3;
char[] chars = new char[arg];
for (int i = 0; i < arg; i++) {
int b1 = io.readByte ();
int b2 = io.readByte ();
- chars[i++] = (char) ((b1 << 8) | b2);
+ chars[i] = (char) ((b1 << 8) | b2);
}
io.readSkip (pad);
_canvas.drawText (new String (chars), x, y, paint);
changed = true;
}
break;
default:
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Implementation,
sequenceNumber, opcode, 0);
break;
}
if (_depth == 1)
paint.setColor (originalColor);
_canvas.restore (); // Undo any clip rectangles.
return changed;
}
/**
* Process a PutImage request.
*
* @param io The input/output stream.
* @param sequenceNumber The request sequence number.
* @param gc The GContext to use for drawing.
* @param bytesRemaining Bytes yet to be read in the request.
* @return True if the drawable is modified.
* @throws IOException
*/
private boolean
processPutImage (
InputOutput io,
int sequenceNumber,
GContext gc,
int format,
int bytesRemaining
) throws IOException {
if (bytesRemaining < 12) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
RequestCode.PutImage, 0);
return false;
}
int width = io.readShort ();
int height = io.readShort ();
float dstX = (short) io.readShort ();
float dstY = (short) io.readShort ();
int leftPad = io.readByte ();
int depth = io.readByte ();
int n, pad, rightPad;
io.readSkip(2); // Unused.
bytesRemaining -= 12;
if (format == 2) {
rightPad = 0;
n = 3 * width * height;
} else {
rightPad = -(width + leftPad) & 7;
n = (width + leftPad + rightPad) * height * depth / 8;
}
pad = -n & 3;
if (bytesRemaining != n + pad) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
RequestCode.PutImage, 0);
return false;
}
boolean badMatch = false;
if (format == 0) { // Bitmap.
if (depth != 1)
badMatch = true;
} else if (format == 1) { // XYPixmap.
if (depth != 1 && depth != 32)
badMatch = true;
} else if (format == 2) { // ZPixmap.
if (depth != 32 || leftPad != 0)
badMatch = true;
} else { // Invalid format.
badMatch = true;
}
if (badMatch) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Match, sequenceNumber,
RequestCode.PutImage, 0);
return false;
}
int[] colors = new int[width * height];
if (depth == 1) { // Bitmap.
int fg = gc.getForegroundColor ();
int bg = gc.getBackgroundColor ();
int offset = 0;
int count = 0;
int x = 0;
int y = 0;
int mask = 128;
int val = 0;
for (;;) {
if ((count++ & 7) == 0) {
val = io.readByte ();
mask = 128;
}
if (x >= leftPad && x < leftPad + width)
colors[offset++] = ((val & mask) == 0) ? bg : fg;
mask >>= 1;
if (++x == leftPad + width + rightPad) {
x = 0;
if (++y == height)
break;
}
}
} else if (format == 1) { // 32-bit XYPixmap.
int planeBit = 1 << (depth - 1);
for (int i = 0; i < depth; i++) {
int offset = 0;
int count = 0;
int x = 0;
int y = 0;
int mask = 128;
int val = 0;
for (;;) {
if ((count++ & 7) == 0) {
val = io.readByte ();
mask = 128;
}
if (x >= leftPad && x < leftPad + width)
colors[offset++] |= ((val & mask) == 0) ? 0 : planeBit;
mask >>= 1;
if (++x == leftPad + width + rightPad) {
x = 0;
if (++y == height)
break;
}
}
}
planeBit >>= 1;
} else { // 32-bit ZPixmap.
for (int i = 0; i < colors.length; i++) {
int b = io.readByte ();
int g = io.readByte ();
int r = io.readByte ();
colors[i] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
io.readSkip (pad);
_canvas.drawBitmap (Bitmap.createBitmap (colors, width, height,
Bitmap.Config.ARGB_8888), dstX, dstY, gc.getPaint ());
return true;
}
/**
* Process a PolyText8 or PolyText16 request.
*
* @param io The input/output stream.
* @param sequenceNumber The request sequence number.
* @param gc The GContext to use for drawing.
* @param opcode The request's opcode.
* @param bytesRemaining Bytes yet to be read in the request.
* @return True if the drawable is modified.
* @throws IOException
*/
private boolean
processPolyText (
InputOutput io,
int sequenceNumber,
GContext gc,
byte opcode,
int bytesRemaining
) throws IOException {
if (bytesRemaining < 4) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
return false;
}
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
while (bytesRemaining > 1) {
int length = io.readByte ();
int minBytes;
bytesRemaining--;
if (length == 255) // Font change indicator.
minBytes = 4;
else if (opcode == RequestCode.PolyText8)
minBytes = 1 + length;
else
minBytes = 1 + length * 2;
if (bytesRemaining < minBytes) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
return false;
}
if (length == 255) { // Font change indicator.
int fid = 0;
for (int i = 0; i < 4; i++)
fid = (fid << 8) | io.readByte ();
bytesRemaining -= 4;
if (!gc.setFont (fid))
ErrorCode.write (io, ErrorCode.Font, sequenceNumber,
opcode, fid);
} else { // It's a string.
int delta = io.readByte ();
String s;
bytesRemaining--;
if (opcode == RequestCode.PolyText8) {
byte[] bytes = new byte[length];
io.readBytes (bytes, 0, length);
bytesRemaining -= length;
s = new String (bytes);
} else {
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
int b1 = io.readByte ();
int b2 = io.readByte ();
chars[i++] = (char) ((b1 << 8) | b2);
}
bytesRemaining -= length * 2;
s = new String (chars);
}
Paint paint = gc.getPaint ();
x += delta;
_canvas.drawText (s, x, y, paint);
x += paint.measureText (s);
}
}
io.readSkip (bytesRemaining);
return true;
}
}
| true | true | public boolean
processGCRequest (
XServer xServer,
InputOutput io,
int id,
GContext gc,
int sequenceNumber,
byte opcode,
int arg,
int bytesRemaining
) throws IOException {
Paint paint = gc.getPaint ();
boolean changed = false;
int originalColor = paint.getColor ();
_canvas.save ();
gc.applyClipRectangles (_canvas);
if (_depth == 1)
paint.setColor (0xffffffff);
switch (opcode) {
case RequestCode.PolyPoint:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
float p = (short) io.readShort ();
bytesRemaining -= 2;
if (arg == 0 || i < 2) // Relative to origin.
points[i] = p;
else
points[i] = points[i - 2] + p; // Rel to previous.
i++;
}
_canvas.drawPoints (points, paint);
changed = true;
}
break;
case RequestCode.PolyLine:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
Path path = new Path ();
int i = 0;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (arg == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
paint.setStyle (Paint.Style.STROKE);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolySegment:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
points[i++] = (short) io.readShort ();
bytesRemaining -= 2;
}
_canvas.drawLines (points, paint);
changed = true;
}
break;
case RequestCode.PolyRectangle:
case RequestCode.PolyFillRectangle:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
if (opcode == RequestCode.PolyRectangle)
paint.setStyle (Paint.Style.STROKE);
else
paint.setStyle (Paint.Style.FILL);
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
bytesRemaining -= 8;
_canvas.drawRect(x, y, x + width, y + height, paint);
changed = true;
}
}
break;
case RequestCode.FillPoly:
if (bytesRemaining < 4 || (bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
io.readByte (); // Shape.
int mode = io.readByte (); // Coordinate mode.
Path path = new Path ();
int i = 0;
io.readSkip (2); // Unused.
bytesRemaining -= 4;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (mode == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
path.close ();
path.setFillType (gc.getFillType ());
paint.setStyle (Paint.Style.FILL);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolyArc:
case RequestCode.PolyFillArc:
if ((bytesRemaining % 12) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
boolean useCenter = false;
if (opcode == RequestCode.PolyArc) {
paint.setStyle (Paint.Style.STROKE);
} else {
paint.setStyle (Paint.Style.FILL);
if (gc.getArcMode () == 1) // Pie slice.
useCenter = true;
}
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
float angle1 = (short) io.readShort ();
float angle2 = (short) io.readShort ();
RectF r = new RectF (x, y, x + width, y + height);
bytesRemaining -= 12;
_canvas.drawArc (r, angle1 / -64.0f, angle2 / -64.0f,
useCenter, paint);
changed = true;
}
}
break;
case RequestCode.PutImage:
changed = processPutImage (io, sequenceNumber, gc, arg,
bytesRemaining);
break;
case RequestCode.PolyText8:
case RequestCode.PolyText16:
changed = processPolyText (io, sequenceNumber, gc, opcode,
bytesRemaining);
break;
case RequestCode.ImageText8:
if (bytesRemaining != 4 + arg + (-arg & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = -arg & 3;
byte[] bytes = new byte[arg];
io.readBytes (bytes, 0, arg);
io.readSkip (pad);
_canvas.drawText (new String (bytes), x, y, paint);
changed = true;
}
break;
case RequestCode.ImageText16:
if (bytesRemaining != 4 + 2 * arg + (-(2 * arg) & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = (-2 * arg) & 3;
char[] chars = new char[arg];
for (int i = 0; i < arg; i++) {
int b1 = io.readByte ();
int b2 = io.readByte ();
chars[i++] = (char) ((b1 << 8) | b2);
}
io.readSkip (pad);
_canvas.drawText (new String (chars), x, y, paint);
changed = true;
}
break;
default:
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Implementation,
sequenceNumber, opcode, 0);
break;
}
if (_depth == 1)
paint.setColor (originalColor);
_canvas.restore (); // Undo any clip rectangles.
return changed;
}
| public boolean
processGCRequest (
XServer xServer,
InputOutput io,
int id,
GContext gc,
int sequenceNumber,
byte opcode,
int arg,
int bytesRemaining
) throws IOException {
Paint paint = gc.getPaint ();
boolean changed = false;
int originalColor = paint.getColor ();
_canvas.save ();
gc.applyClipRectangles (_canvas);
if (_depth == 1)
paint.setColor (0xffffffff);
switch (opcode) {
case RequestCode.PolyPoint:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
float p = (short) io.readShort ();
bytesRemaining -= 2;
if (arg == 0 || i < 2) // Relative to origin.
points[i] = p;
else
points[i] = points[i - 2] + p; // Rel to previous.
i++;
}
_canvas.drawPoints (points, paint);
changed = true;
}
break;
case RequestCode.PolyLine:
if ((bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
Path path = new Path ();
int i = 0;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (arg == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
paint.setStyle (Paint.Style.STROKE);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolySegment:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float[] points = new float[bytesRemaining / 2];
int i = 0;
while (bytesRemaining > 0) {
points[i++] = (short) io.readShort ();
bytesRemaining -= 2;
}
_canvas.drawLines (points, paint);
changed = true;
}
break;
case RequestCode.PolyRectangle:
case RequestCode.PolyFillRectangle:
if ((bytesRemaining & 7) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
if (opcode == RequestCode.PolyRectangle)
paint.setStyle (Paint.Style.STROKE);
else
paint.setStyle (Paint.Style.FILL);
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
bytesRemaining -= 8;
_canvas.drawRect(x, y, x + width, y + height, paint);
changed = true;
}
}
break;
case RequestCode.FillPoly:
if (bytesRemaining < 4 || (bytesRemaining & 3) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
io.readByte (); // Shape.
int mode = io.readByte (); // Coordinate mode.
Path path = new Path ();
int i = 0;
io.readSkip (2); // Unused.
bytesRemaining -= 4;
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
bytesRemaining -= 4;
if (i == 0)
path.moveTo (x, y);
else if (mode == 0) // Relative to origin.
path.lineTo (x, y);
else // Relative to previous.
path.rLineTo (x, y);
i++;
}
path.close ();
path.setFillType (gc.getFillType ());
paint.setStyle (Paint.Style.FILL);
_canvas.drawPath (path, paint);
changed = true;
}
break;
case RequestCode.PolyArc:
case RequestCode.PolyFillArc:
if ((bytesRemaining % 12) != 0) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
boolean useCenter = false;
if (opcode == RequestCode.PolyArc) {
paint.setStyle (Paint.Style.STROKE);
} else {
paint.setStyle (Paint.Style.FILL);
if (gc.getArcMode () == 1) // Pie slice.
useCenter = true;
}
while (bytesRemaining > 0) {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
float width = io.readShort ();
float height = io.readShort ();
float angle1 = (short) io.readShort ();
float angle2 = (short) io.readShort ();
RectF r = new RectF (x, y, x + width, y + height);
bytesRemaining -= 12;
_canvas.drawArc (r, angle1 / -64.0f, angle2 / -64.0f,
useCenter, paint);
changed = true;
}
}
break;
case RequestCode.PutImage:
changed = processPutImage (io, sequenceNumber, gc, arg,
bytesRemaining);
break;
case RequestCode.PolyText8:
case RequestCode.PolyText16:
changed = processPolyText (io, sequenceNumber, gc, opcode,
bytesRemaining);
break;
case RequestCode.ImageText8:
if (bytesRemaining != 4 + arg + (-arg & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = -arg & 3;
byte[] bytes = new byte[arg];
io.readBytes (bytes, 0, arg);
io.readSkip (pad);
_canvas.drawText (new String (bytes), x, y, paint);
changed = true;
}
break;
case RequestCode.ImageText16:
if (bytesRemaining != 4 + 2 * arg + (-(2 * arg) & 3)) {
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Length, sequenceNumber,
opcode, 0);
} else {
float x = (short) io.readShort ();
float y = (short) io.readShort ();
int pad = (-2 * arg) & 3;
char[] chars = new char[arg];
for (int i = 0; i < arg; i++) {
int b1 = io.readByte ();
int b2 = io.readByte ();
chars[i] = (char) ((b1 << 8) | b2);
}
io.readSkip (pad);
_canvas.drawText (new String (chars), x, y, paint);
changed = true;
}
break;
default:
io.readSkip (bytesRemaining);
ErrorCode.write (io, ErrorCode.Implementation,
sequenceNumber, opcode, 0);
break;
}
if (_depth == 1)
paint.setColor (originalColor);
_canvas.restore (); // Undo any clip rectangles.
return changed;
}
|
diff --git a/src/controller/Main.java b/src/controller/Main.java
index 13a0780..05f1af9 100644
--- a/src/controller/Main.java
+++ b/src/controller/Main.java
@@ -1,47 +1,48 @@
/*
* Copyright (C) 2012 Andreas Halle
*
* This file is part of pplex.
*
* pplex is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* pplex 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 for more details.
*
* You should have received a copy of the GNU General Public license
* along with pplex. If not, see <http://www.gnu.org/licenses/>.
*/
package controller;
import lightshell.Shell;
import controller.shellcommands.Conditions;
import controller.shellcommands.Exit;
import controller.shellcommands.FormatCmd;
import controller.shellcommands.Pivot;
import controller.shellcommands.Read;
import controller.shellcommands.Show;
import controller.shellcommands.Warranty;
class Main {
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("-nogui")) {
Shell shell = new Shell();
shell.setWelcomeMsg(Data.FWELCOME);
+ shell.setPrompt("pplex");
shell.addCommand(new Conditions());
shell.addCommand(new Exit());
shell.addCommand(new FormatCmd());
shell.addCommand(new Pivot());
shell.addCommand(new Read());
shell.addCommand(new Show());
shell.addCommand(new Warranty());
shell.run();
} else {
new GUI();
}
}
}
| true | true | public static void main(String[] args) {
if (args.length > 0 && args[0].equals("-nogui")) {
Shell shell = new Shell();
shell.setWelcomeMsg(Data.FWELCOME);
shell.addCommand(new Conditions());
shell.addCommand(new Exit());
shell.addCommand(new FormatCmd());
shell.addCommand(new Pivot());
shell.addCommand(new Read());
shell.addCommand(new Show());
shell.addCommand(new Warranty());
shell.run();
} else {
new GUI();
}
}
| public static void main(String[] args) {
if (args.length > 0 && args[0].equals("-nogui")) {
Shell shell = new Shell();
shell.setWelcomeMsg(Data.FWELCOME);
shell.setPrompt("pplex");
shell.addCommand(new Conditions());
shell.addCommand(new Exit());
shell.addCommand(new FormatCmd());
shell.addCommand(new Pivot());
shell.addCommand(new Read());
shell.addCommand(new Show());
shell.addCommand(new Warranty());
shell.run();
} else {
new GUI();
}
}
|
diff --git a/src/zombiefu/human/Shop.java b/src/zombiefu/human/Shop.java
index d37e510..2f8047d 100644
--- a/src/zombiefu/human/Shop.java
+++ b/src/zombiefu/human/Shop.java
@@ -1,33 +1,35 @@
package zombiefu.human;
import zombiefu.util.ZombieGame;
import jade.util.datatype.ColoredChar;
import java.util.HashMap;
import zombiefu.exception.CanNotAffordException;
import zombiefu.itembuilder.ItemBuilder;
import zombiefu.player.Player;
public class Shop extends Human {
private HashMap<ItemBuilder, Integer> items;
String name;
public Shop(ColoredChar face, String name, HashMap<ItemBuilder, Integer> inventar) {
super(face, name);
this.items = inventar;
this.name = name;
}
@Override
public void talkToPlayer(Player pl) {
ZombieGame.newMessage("Willkommen im Mensa-Shop. Hier unser Angebot:");
ItemBuilder item = ZombieGame.askPlayerForItemToBuy(items);
try {
- pl.pay(items.get(item));
- pl.obtainItem(item.buildItem());
+ if (item!=null){
+ pl.pay(items.get(item));
+ pl.obtainItem(item.buildItem());
+ }
ZombieGame.newMessage("Bitte beehren sie uns bald wieder.");
} catch (CanNotAffordException ex) {
ZombieGame.newMessage("Das kannst Du Dir nicht leisten.");
}
}
}
| true | true | public void talkToPlayer(Player pl) {
ZombieGame.newMessage("Willkommen im Mensa-Shop. Hier unser Angebot:");
ItemBuilder item = ZombieGame.askPlayerForItemToBuy(items);
try {
pl.pay(items.get(item));
pl.obtainItem(item.buildItem());
ZombieGame.newMessage("Bitte beehren sie uns bald wieder.");
} catch (CanNotAffordException ex) {
ZombieGame.newMessage("Das kannst Du Dir nicht leisten.");
}
}
| public void talkToPlayer(Player pl) {
ZombieGame.newMessage("Willkommen im Mensa-Shop. Hier unser Angebot:");
ItemBuilder item = ZombieGame.askPlayerForItemToBuy(items);
try {
if (item!=null){
pl.pay(items.get(item));
pl.obtainItem(item.buildItem());
}
ZombieGame.newMessage("Bitte beehren sie uns bald wieder.");
} catch (CanNotAffordException ex) {
ZombieGame.newMessage("Das kannst Du Dir nicht leisten.");
}
}
|
diff --git a/java/helpdesk/mvc/Controller/TController.java b/java/helpdesk/mvc/Controller/TController.java
index 6659923..841ef3a 100644
--- a/java/helpdesk/mvc/Controller/TController.java
+++ b/java/helpdesk/mvc/Controller/TController.java
@@ -1,291 +1,285 @@
package mvc.Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import lib.refreshTable;
import mvc.Model.Counter;
import mvc.Model.FullticketTable;
import mvc.Model.HistoryTable;
import mvc.Model.Ticket;
import mvc.View.Ticket_Frame;
import mvc.View.Error_Frame;
import mvc.View.Main_Frame;
public class TController implements Runnable{
private Integer ID;
private FullticketTable f_model;
private HistoryTable h_model;
private Main_Frame main;
private Ticket_Frame _view;
public TController(Integer ID, FullticketTable f_model,HistoryTable h_model, Main_Frame main, Ticket_Frame frame) {
this.ID = ID;
this.f_model = f_model;
this.h_model = h_model;
this.main = main;
this._view = frame;
addListener();
}
@Override
public void run() {
if (this.ID != null) {
searching (this.ID);
}
this._view.init();
}
private void addListener() {
this._view.setbtn_cancelListener(new btn_cancelListener());
this._view.setbtn_searchListener(new btn_csearchListener());
this._view.setbtn_saveListener(new btn_saveListener());
this._view.setchb_newListener(new chb_newListener());
init();
}
private void init() {
_view.cmb_status.setModel(new javax.swing.DefaultComboBoxModel(mvc.Model.Ticket.Ticket_ComboBox(4).toArray(
new Object[mvc.Model.Ticket.Ticket_ComboBox(4).size()])));
_view.cmb_category.setModel(new javax.swing.DefaultComboBoxModel(mvc.Model.Ticket.Ticket_ComboBox(3).toArray(
new Object[mvc.Model.Ticket.Ticket_ComboBox(3).size()])));
_view.cmb_eID.setModel(new javax.swing.DefaultComboBoxModel(mvc.Model.Ticket.Ticket_ComboBox(2).toArray(
new Object[mvc.Model.Ticket.Ticket_ComboBox(2).size()])));
_view.cmb_cID.setModel(new javax.swing.DefaultComboBoxModel(mvc.Model.Ticket.Ticket_ComboBox(1).toArray(
new Object[mvc.Model.Ticket.Ticket_ComboBox(1).size()])));
}
/*************************************
*
* ButtonListener
*
**************************************/
class btn_cancelListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
_view.dispose();
}
}
class btn_csearchListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
try {
Integer ini = null;
String Str = _view.edt_ID.getText();
if (!"".equals(Str)) {
ini = Integer.parseInt (Str);
searching(ini);
}
} catch (NullPointerException E){
Error_Frame.Error("ID not found");
} catch (NumberFormatException E) {
Error_Frame.Error("Please use only number for ID");
}
}
}
class btn_saveListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
try {
//set timestamp for "create tickets" and "update tickets"
Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
//send Error frame if one of these textfield are empty
if ("".equals(_view.edt_topic.getText()) || "".equals(_view.edt_problem.getText())){
Error_Frame.Error("Please fill out: Topic and Problem");
} else {
String sol = null,note = null;
Integer noEm = null;
ID = null;
- if ("".equals(_view.edt_solution.getText())) {
+ if (!"".equals(_view.edt_solution.getText())) {
sol = _view.edt_solution.getText();
}
- if ("".equals(_view.edt_note.getText())) {
+ if (!"".equals(_view.edt_note.getText())) {
note = _view.edt_note.getText();
}
//check checkbox "new Ticket"
if (_view.chb_new.getSelectedObjects() == null) {
String Str = _view.edt_ID.getText();
ID = Integer.parseInt (Str);
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and update ticket
- if ("".equals(_view.edt_solution.getText())) {
- sol = _view.edt_solution.getText();
- }
- if ("".equals(_view.edt_note.getText())) {
- note = _view.edt_note.getText();
- }
Ticket updateTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
- _view.edt_note.getText(),
- _view.edt_solution.getText(),
+ note,
+ sol,
_view.edt_created.getText(),
currentTimestamp.toString());
updateTicket.updateTicket(ID);
} else {
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and create ticket
Ticket newTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
note,
sol,
currentTimestamp.toString(),
currentTimestamp.toString());
newTicket.newTicket();
}
//refresh jtable
refreshTable A1;
A1 = new refreshTable(null, null, f_model, h_model, null);
A1.start();
//count ticket status for fullticket control buttons
//timer to prevent connection link lost
Timer timer = new Timer();
timer.schedule (new Task(), 500);
_view.dispose();
}
} catch (NumberFormatException ev) {
Error_Frame.Error("Please use only number for ID");
} catch (Exception ev) {
Error_Frame.Error(e.toString());
}
}
}
/*************************************
*
* Timer
*
**************************************/
class Task extends TimerTask {
@Override
public void run() {
Counter A2;
A2 = new Counter(main);
A2.start();
}
}
/*************************************
*
* Checkbox - ItemListener
*
**************************************/
class chb_newListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.DESELECTED){
_view.edt_ID.setVisible(true);
} else {
_view.edt_ID.setVisible(false);
_view.edt_ID.setText("");
_view.edt_problem.setText("");
_view.edt_topic.setText("");
_view.edt_note.setText("");
_view.edt_solution.setText("");
_view.edt_created.setText("");
_view.edt_update.setText("");
}
}
}
/**************************
*
* User defined functions
*
***************************/
/*
* search ticket and fill textfield/combobox
*/
public void searching (Integer ID) {
try {
String [] Array = Ticket.searchTicket(ID);
_view.edt_ID.setText(ID.toString());
_view.edt_topic.setText(Array[4]);
_view.edt_problem.setText(Array[5]);
_view.edt_note.setText(Array[6]);
_view.edt_solution.setText(Array[7]);
_view.edt_created.setText(Array[8]);
_view.edt_update.setText(Array[9]);
for (int i=0; i<= _view.cmb_cID.getItemCount()-1;i++) {
if (Array[0].equals(_view.cmb_cID.getItemAt(i).toString())) {
_view.cmb_cID.setSelectedIndex(i);
}
}
if (Array[1]!=null) {
for (int i=0; i<= _view.cmb_eID.getItemCount()-1;i++) {
if (Array[1].equals(_view.cmb_eID.getItemAt(i).toString())) {
_view.cmb_eID.setSelectedIndex(i);
}
}
}
for (int i=0; i<= _view.cmb_category.getItemCount()-1;i++) {
if (Array[2].equals(_view.cmb_category.getItemAt(i).toString())) {
_view.cmb_category.setSelectedIndex(i);
}
}
for (int i=0; i<= _view.cmb_status.getItemCount()-1;i++) {
if (Array[3].equals(_view.cmb_status.getItemAt(i).toString())) {
_view.cmb_status.setSelectedIndex(i);
}
}
} catch (NullPointerException E){
Error_Frame.Error("ID not found");
} catch (NumberFormatException E) {
Error_Frame.Error(E.toString());
}
}
/*****************************************************************
* Count ticket status like open,in process and closed in fulltickettable
* and set counts in fullticket control buttons
********************************************************************/
public void getStatusCount () {
Integer openCount=0,processCount=0,closedCount=0;
Object [] A2 = Counter.getCount();
for (int i=0;i<=A2.length-1;i++) {
if ("Open".equals(A2[i])) {
openCount++;
} else if ("In process".equals(A2[i])) {
processCount++;
} else if ("Closed".equals(A2[i])) {
closedCount++;
}
}
main.btn_setopen.setText("Open [" + openCount+"]");
main.btn_setprocess.setText("In Process [" + processCount +"]");
main.btn_setclosed.setText("Closed [" + closedCount +"]");
}
}
| false | true | public void actionPerformed(ActionEvent e) {
try {
//set timestamp for "create tickets" and "update tickets"
Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
//send Error frame if one of these textfield are empty
if ("".equals(_view.edt_topic.getText()) || "".equals(_view.edt_problem.getText())){
Error_Frame.Error("Please fill out: Topic and Problem");
} else {
String sol = null,note = null;
Integer noEm = null;
ID = null;
if ("".equals(_view.edt_solution.getText())) {
sol = _view.edt_solution.getText();
}
if ("".equals(_view.edt_note.getText())) {
note = _view.edt_note.getText();
}
//check checkbox "new Ticket"
if (_view.chb_new.getSelectedObjects() == null) {
String Str = _view.edt_ID.getText();
ID = Integer.parseInt (Str);
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and update ticket
if ("".equals(_view.edt_solution.getText())) {
sol = _view.edt_solution.getText();
}
if ("".equals(_view.edt_note.getText())) {
note = _view.edt_note.getText();
}
Ticket updateTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
_view.edt_note.getText(),
_view.edt_solution.getText(),
_view.edt_created.getText(),
currentTimestamp.toString());
updateTicket.updateTicket(ID);
} else {
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and create ticket
Ticket newTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
note,
sol,
currentTimestamp.toString(),
currentTimestamp.toString());
newTicket.newTicket();
}
//refresh jtable
refreshTable A1;
A1 = new refreshTable(null, null, f_model, h_model, null);
A1.start();
//count ticket status for fullticket control buttons
//timer to prevent connection link lost
Timer timer = new Timer();
timer.schedule (new Task(), 500);
_view.dispose();
}
} catch (NumberFormatException ev) {
Error_Frame.Error("Please use only number for ID");
} catch (Exception ev) {
Error_Frame.Error(e.toString());
}
}
| public void actionPerformed(ActionEvent e) {
try {
//set timestamp for "create tickets" and "update tickets"
Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
//send Error frame if one of these textfield are empty
if ("".equals(_view.edt_topic.getText()) || "".equals(_view.edt_problem.getText())){
Error_Frame.Error("Please fill out: Topic and Problem");
} else {
String sol = null,note = null;
Integer noEm = null;
ID = null;
if (!"".equals(_view.edt_solution.getText())) {
sol = _view.edt_solution.getText();
}
if (!"".equals(_view.edt_note.getText())) {
note = _view.edt_note.getText();
}
//check checkbox "new Ticket"
if (_view.chb_new.getSelectedObjects() == null) {
String Str = _view.edt_ID.getText();
ID = Integer.parseInt (Str);
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and update ticket
Ticket updateTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
note,
sol,
_view.edt_created.getText(),
currentTimestamp.toString());
updateTicket.updateTicket(ID);
} else {
if (_view.cmb_eID.getSelectedItem() != "") {
noEm = (Integer)_view.cmb_eID.getSelectedItem();
}
//get timestamp and string from textfield and create ticket
Ticket newTicket = new Ticket (ID,
(Integer)_view.cmb_cID.getSelectedItem(),
noEm,
(Integer)_view.cmb_category.getSelectedItem(),
(Integer)_view.cmb_status.getSelectedItem(),
_view.edt_topic.getText(),
_view.edt_problem.getText(),
note,
sol,
currentTimestamp.toString(),
currentTimestamp.toString());
newTicket.newTicket();
}
//refresh jtable
refreshTable A1;
A1 = new refreshTable(null, null, f_model, h_model, null);
A1.start();
//count ticket status for fullticket control buttons
//timer to prevent connection link lost
Timer timer = new Timer();
timer.schedule (new Task(), 500);
_view.dispose();
}
} catch (NumberFormatException ev) {
Error_Frame.Error("Please use only number for ID");
} catch (Exception ev) {
Error_Frame.Error(e.toString());
}
}
|
diff --git a/bupro/src/main/java/cz/cvut/fel/bupro/controller/UserController.java b/bupro/src/main/java/cz/cvut/fel/bupro/controller/UserController.java
index a8e6de1..5de98b9 100644
--- a/bupro/src/main/java/cz/cvut/fel/bupro/controller/UserController.java
+++ b/bupro/src/main/java/cz/cvut/fel/bupro/controller/UserController.java
@@ -1,42 +1,43 @@
package cz.cvut.fel.bupro.controller;
import java.util.List;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import cz.cvut.fel.bupro.model.User;
import cz.cvut.fel.bupro.service.UserService;
@Controller
public class UserController {
private final Log log = LogFactory.getLog(getClass());
@Autowired
private UserService userService;
@ModelAttribute("userList")
public List<User> getUserList() {
return userService.getAllUsers();
}
@RequestMapping({ "/user/list" })
public String showUserList() {
return "user-list";
}
@RequestMapping({ "/user/view/{id}" })
public String showUserDetail(Model model, Locale locale, @PathVariable Long id) {
log.trace("UserController.showUserDetail()");
User user = userService.getUser(id);
+ user.getComments().size(); //force fetch
model.addAttribute("user", user);
return "user-view";
}
}
| true | true | public String showUserDetail(Model model, Locale locale, @PathVariable Long id) {
log.trace("UserController.showUserDetail()");
User user = userService.getUser(id);
model.addAttribute("user", user);
return "user-view";
}
| public String showUserDetail(Model model, Locale locale, @PathVariable Long id) {
log.trace("UserController.showUserDetail()");
User user = userService.getUser(id);
user.getComments().size(); //force fetch
model.addAttribute("user", user);
return "user-view";
}
|
diff --git a/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/UnionPlugIn.java b/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/UnionPlugIn.java
index d0280bd8..0991b4da 100644
--- a/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/UnionPlugIn.java
+++ b/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/UnionPlugIn.java
@@ -1,240 +1,240 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* Copyright (C) 2003 Vivid Solutions
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jump.workbench.ui.plugin.analysis;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JComboBox;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.feature.AttributeType;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureCollection;
import com.vividsolutions.jump.feature.FeatureDataset;
import com.vividsolutions.jump.feature.FeatureDatasetFactory;
import com.vividsolutions.jump.feature.FeatureSchema;
import com.vividsolutions.jump.task.TaskMonitor;
import com.vividsolutions.jump.workbench.model.StandardCategoryNames;
import com.vividsolutions.jump.workbench.plugin.AbstractPlugIn;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import com.vividsolutions.jump.workbench.plugin.ThreadedPlugIn;
import com.vividsolutions.jump.workbench.ui.GUIUtil;
import com.vividsolutions.jump.workbench.ui.MultiInputDialog;
public class UnionPlugIn extends AbstractPlugIn implements ThreadedPlugIn {
private String LAYER = I18N.get("ui.plugin.analysis.UnionPlugIn.layer");
private String SELECTED_ONLY = I18N.get("ui.plugin.analysis.UnionPlugIn.selected-features-only");
private boolean useSelected = false;
private MultiInputDialog dialog;
private JComboBox addLayerComboBox;
public UnionPlugIn() {
}
/*
public void initialize(PlugInContext context) throws Exception {
context.getFeatureInstaller().addMainMenuItem(
this, "Tools", "Find Unaligned Segments...", null, new MultiEnableCheck()
.add(context.getCheckFactory().createWindowWithLayerNamePanelMustBeActiveCheck())
.add(context.getCheckFactory().createAtLeastNLayersMustExistCheck(1)));
}
*/
public boolean execute(PlugInContext context) throws Exception {
//[sstein, 16.07.2006] put here again to load correct language
//[mmichaud 2007-05-20] move to UnionPlugIn constructor to load the string only once
//LAYER = I18N.get("ui.plugin.analysis.UnionPlugIn.layer");
//Unlike ValidatePlugIn, here we always call #initDialog because we want
//to update the layer comboboxes. [Jon Aquino]
int n = context.getLayerViewPanel().getSelectionManager()
.getFeaturesWithSelectedItems().size();
useSelected = (n > 0);
initDialog(context);
dialog.setVisible(true);
if (!dialog.wasOKPressed()) {
return false;
}
return true;
}
private void initDialog(PlugInContext context) {
dialog = new MultiInputDialog(context.getWorkbenchFrame(), I18N.get("ui.plugin.analysis.UnionPlugIn.union"), true);
//dialog.setSideBarImage(IconLoader.icon("Overlay.gif"));
if (useSelected) {
dialog.setSideBarDescription(
I18N.get("ui.plugin.analysis.UnionPlugIn.creates-a-new-layer-containing-the-union-of-selected-features-in-the-input-layer"));
}
else {
dialog.setSideBarDescription(
I18N.get("ui.plugin.analysis.UnionPlugIn.creates-a-new-layer-containing-the-union-of-all-the-features-in-the-input-layer"));
}
String fieldName = LAYER;
if (useSelected) {
dialog.addLabel(SELECTED_ONLY);
}
else {
addLayerComboBox = dialog.addLayerComboBox(fieldName, context.getCandidateLayer(0), null, context.getLayerManager());
}
GUIUtil.centreOnWindow(dialog);
}
public void run(TaskMonitor monitor, PlugInContext context)
throws Exception {
FeatureCollection a;
Collection inputC;
if (useSelected) {
inputC = context.getLayerViewPanel()
.getSelectionManager()
.getFeaturesWithSelectedItems();
FeatureSchema featureSchema = new FeatureSchema();
featureSchema.addAttribute("GEOMETRY", AttributeType.GEOMETRY);
a = new FeatureDataset(inputC, featureSchema);
}
else {
a = dialog.getLayer(LAYER).getFeatureCollectionWrapper();
}
FeatureCollection union = progressiveUnion(monitor, a);
context.getLayerManager().addCategory(StandardCategoryNames.RESULT);
context.addLayer(StandardCategoryNames.RESULT, I18N.get("ui.plugin.analysis.UnionPlugIn.union"), union);
}
// The naive algorithm is not efficient for dataset containing more than one thousand
// features. See a replacement in progressiveUnion [mmichaud 2007-06-10]
private FeatureCollection union(TaskMonitor monitor, FeatureCollection fc) {
monitor.allowCancellationRequests();
monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union"));
List unionGeometryList = new ArrayList();
Geometry currUnion = null;
int size = fc.size();
int count = 1;
for (Iterator i = fc.iterator(); i.hasNext();) {
Feature f = (Feature) i.next();
Geometry geom = f.getGeometry();
if (currUnion == null) {
currUnion = geom;
} else {
currUnion = currUnion.union(geom);
}
monitor.report(count++, size, "features");
}
unionGeometryList.add(currUnion);
return FeatureDatasetFactory.createFromGeometry(unionGeometryList);
}
/**
* New method for union. Instead of the naive algorithm looping over the features and
* unioning each time, this one union small groups of features which are closed to each
* other, then iterates over the result.
* The difference is not so important for small datasets, but for large datasets, the
* difference may of 5 minutes versus 5 hours.
*/
private FeatureCollection progressiveUnion(TaskMonitor monitor, FeatureCollection fc) {
monitor.allowCancellationRequests();
//monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union"));
List unionGeometryList = new ArrayList();
for (Iterator i = fc.iterator(); i.hasNext();) {
unionGeometryList.add(((Feature) i.next()).getGeometry());
}
int iteration = 1;
int nbIteration = 1 + (int)(Math.log(unionGeometryList.size())/Math.log(4));
while (unionGeometryList.size() > 1) {
monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union") + " (" + iteration++ + "/" + nbIteration + ")");
final int cellSize = 1 + (int)Math.sqrt(unionGeometryList.size());
java.util.Comparator comparator = new java.util.Comparator(){
public int compare(Object o1, Object o2) {
if (o1==null || o2==null) return 0;
Envelope env1 = ((Geometry)o1).getEnvelopeInternal();
Envelope env2 = ((Geometry)o2).getEnvelopeInternal();
double indice1 = env1.getMinX()/cellSize + cellSize*((int)env1.getMinY()/cellSize);
double indice2 = env2.getMinX()/cellSize + cellSize*((int)env2.getMinY()/cellSize);
- return indice1>indice2?1:indice1<indice2?-1:0;
+ return indice1>=indice2?1:indice1<indice2?-1:0;
}
public boolean equals(Object obj) {return this.equals(obj);}
};
java.util.TreeSet treeSet = new java.util.TreeSet(comparator);
treeSet.addAll(unionGeometryList);
// Testes with groups of 4, 8 and 16 (4 is better than 8 which is better than 16
// for large datasets).
unionGeometryList = union(monitor, treeSet, 4);
}
return FeatureDatasetFactory.createFromGeometry(unionGeometryList);
}
/**
* Method unioning an ordered set of geometries by small groups.
*
*/
private List union(TaskMonitor monitor, Set set, int groupSize) {
List unionGeometryList = new ArrayList();
Geometry currUnion = null;
int size = set.size();
int count = 0;
for (Iterator i = set.iterator(); i.hasNext();) {
Geometry geom = (Geometry)i.next();
if (count%groupSize==0) currUnion = geom;
else {
currUnion = currUnion.union(geom);
if (groupSize-count%groupSize==1) unionGeometryList.add(currUnion);
}
monitor.report(++count, size, "features");
}
if (groupSize-count%groupSize!=0) {
unionGeometryList.add(currUnion);
}
return unionGeometryList;
}
}
| true | true | private FeatureCollection progressiveUnion(TaskMonitor monitor, FeatureCollection fc) {
monitor.allowCancellationRequests();
//monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union"));
List unionGeometryList = new ArrayList();
for (Iterator i = fc.iterator(); i.hasNext();) {
unionGeometryList.add(((Feature) i.next()).getGeometry());
}
int iteration = 1;
int nbIteration = 1 + (int)(Math.log(unionGeometryList.size())/Math.log(4));
while (unionGeometryList.size() > 1) {
monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union") + " (" + iteration++ + "/" + nbIteration + ")");
final int cellSize = 1 + (int)Math.sqrt(unionGeometryList.size());
java.util.Comparator comparator = new java.util.Comparator(){
public int compare(Object o1, Object o2) {
if (o1==null || o2==null) return 0;
Envelope env1 = ((Geometry)o1).getEnvelopeInternal();
Envelope env2 = ((Geometry)o2).getEnvelopeInternal();
double indice1 = env1.getMinX()/cellSize + cellSize*((int)env1.getMinY()/cellSize);
double indice2 = env2.getMinX()/cellSize + cellSize*((int)env2.getMinY()/cellSize);
return indice1>indice2?1:indice1<indice2?-1:0;
}
public boolean equals(Object obj) {return this.equals(obj);}
};
java.util.TreeSet treeSet = new java.util.TreeSet(comparator);
treeSet.addAll(unionGeometryList);
// Testes with groups of 4, 8 and 16 (4 is better than 8 which is better than 16
// for large datasets).
unionGeometryList = union(monitor, treeSet, 4);
}
return FeatureDatasetFactory.createFromGeometry(unionGeometryList);
}
| private FeatureCollection progressiveUnion(TaskMonitor monitor, FeatureCollection fc) {
monitor.allowCancellationRequests();
//monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union"));
List unionGeometryList = new ArrayList();
for (Iterator i = fc.iterator(); i.hasNext();) {
unionGeometryList.add(((Feature) i.next()).getGeometry());
}
int iteration = 1;
int nbIteration = 1 + (int)(Math.log(unionGeometryList.size())/Math.log(4));
while (unionGeometryList.size() > 1) {
monitor.report(I18N.get("ui.plugin.analysis.UnionPlugIn.computing-union") + " (" + iteration++ + "/" + nbIteration + ")");
final int cellSize = 1 + (int)Math.sqrt(unionGeometryList.size());
java.util.Comparator comparator = new java.util.Comparator(){
public int compare(Object o1, Object o2) {
if (o1==null || o2==null) return 0;
Envelope env1 = ((Geometry)o1).getEnvelopeInternal();
Envelope env2 = ((Geometry)o2).getEnvelopeInternal();
double indice1 = env1.getMinX()/cellSize + cellSize*((int)env1.getMinY()/cellSize);
double indice2 = env2.getMinX()/cellSize + cellSize*((int)env2.getMinY()/cellSize);
return indice1>=indice2?1:indice1<indice2?-1:0;
}
public boolean equals(Object obj) {return this.equals(obj);}
};
java.util.TreeSet treeSet = new java.util.TreeSet(comparator);
treeSet.addAll(unionGeometryList);
// Testes with groups of 4, 8 and 16 (4 is better than 8 which is better than 16
// for large datasets).
unionGeometryList = union(monitor, treeSet, 4);
}
return FeatureDatasetFactory.createFromGeometry(unionGeometryList);
}
|
diff --git a/src/examples/mainTester.java b/src/examples/mainTester.java
index 77a9297..2ff2b0f 100644
--- a/src/examples/mainTester.java
+++ b/src/examples/mainTester.java
@@ -1,15 +1,16 @@
package examples;
import types.FlowData;
import engine.Engine;
public class mainTester {
/**
* @param args
*/
public static void main(String[] args) {
Engine engine = new Engine("src\\generated\\flow.xml");
FlowData data = engine.run();
+ System.out.println(data.getData().toString());
}
}
| true | true | public static void main(String[] args) {
Engine engine = new Engine("src\\generated\\flow.xml");
FlowData data = engine.run();
}
| public static void main(String[] args) {
Engine engine = new Engine("src\\generated\\flow.xml");
FlowData data = engine.run();
System.out.println(data.getData().toString());
}
|
diff --git a/src/quizweb/database/DBConnection.java b/src/quizweb/database/DBConnection.java
index a444d43..4065f08 100644
--- a/src/quizweb/database/DBConnection.java
+++ b/src/quizweb/database/DBConnection.java
@@ -1,54 +1,54 @@
package quizweb.database;
import java.sql.*;
public class DBConnection {
static String account = "ccs108yzzhu";
static String password = "aebaujei";
static String server = "mysql-user-master.stanford.edu";
static String database = "c_cs108_yzzhu";
public static Connection con = initConnection();
private static Connection initConnection() {
Connection thisCon = null;
try {
Class.forName("com.mysql.jdbc.Driver");
thisCon = DriverManager.getConnection("jdbc:mysql://" + server, account ,password);
- Statement stmt = con.createStatement();
+ Statement stmt = thisCon.createStatement();
stmt.executeQuery("USE " + database);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return thisCon;
}
public static ResultSet DBQuery(PreparedStatement stmt) {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static int DBUpdate(PreparedStatement stmt) {
int rs = 0;
try {
rs = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static void DBClose() {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true | true | private static Connection initConnection() {
Connection thisCon = null;
try {
Class.forName("com.mysql.jdbc.Driver");
thisCon = DriverManager.getConnection("jdbc:mysql://" + server, account ,password);
Statement stmt = con.createStatement();
stmt.executeQuery("USE " + database);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return thisCon;
}
| private static Connection initConnection() {
Connection thisCon = null;
try {
Class.forName("com.mysql.jdbc.Driver");
thisCon = DriverManager.getConnection("jdbc:mysql://" + server, account ,password);
Statement stmt = thisCon.createStatement();
stmt.executeQuery("USE " + database);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return thisCon;
}
|
diff --git a/javanet/gnu/cajo/invoke/Remote.java b/javanet/gnu/cajo/invoke/Remote.java
index c6695284..34177d13 100644
--- a/javanet/gnu/cajo/invoke/Remote.java
+++ b/javanet/gnu/cajo/invoke/Remote.java
@@ -1,624 +1,624 @@
package gnu.cajo.invoke;
import java.io.*;
import java.net.*;
import java.rmi.*;
import java.util.zip.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.LinkedList;
import java.lang.reflect.Method;
/*
* Generic Item Interface Exporter
* Copyright (c) 1999 John Catherino
*
* For issues or suggestions mailto:[email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, at version 2.1 of the license, or any
* later version. The license differs from the GNU General Public License
* (GPL) to allow this library to be used in proprietary applications. The
* standard GPL would forbid this.
*
* This program 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 for more details.
*
* To receive a copy of the GNU Lesser General Public License visit their
* website at http://www.fsf.org/licenses/lgpl.html or via snail mail at Free
* Software Foundation Inc., 59 Temple Place Suite 330, Boston MA 02111-1307
* USA
*/
/**
* This class takes any object, and allows it to be called from
* remote VMs. This class eliminates the need to maintain multiple
* specialized rmic interface compilations for multiple, application specific
* objects. It effectively allows any object to be remoted, and makes all of
* the object's public methods remotely callable. It also contains several
* very useful utility methods, to further support the invoke package
* paradigm.<p> It can also be run as an application, to load an object from
* a URL, and remote it within a VM.
*
* @version 1.0, 01-Nov-99 Initial release
* @author John Catherino
*/
public final class Remote extends UnicastRemoteObject implements RemoteInvoke {
private static final class RSSF implements RMIServerSocketFactory {
private int port;
private String host;
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ss = host == null ?
RMISocketFactory.getDefaultSocketFactory().
createServerSocket(this.port) :
new ServerSocket(this.port, 50, InetAddress.getByName(host));
if (host == null) host = ss.getInetAddress().getHostName();
if (this.port == 0) {
this.port = ss.getLocalPort();
rcsf.port = this.port;
} else if (rcsf.port == 0) rcsf.port = this.port;
return ss;
}
public boolean equals(Object o) {
return o instanceof RSSF &&
((RSSF)o).host.equals(host) &&
((RSSF)o).port == port;
}
public int hashCode() { return getClass().hashCode() + port; }
}
private static final class RCSF
implements RMIClientSocketFactory, Serializable {
static final long serialVersionUID = 0x6060842L; // ;-) B-52s
private int port;
private String host;
public Socket createSocket(String host, int port) throws IOException {
Socket s;
try {
s = RMISocketFactory.getDefaultSocketFactory().
createSocket(this.host, this.port != 0 ? this.port : port);
} catch(IOException x) { // last ditch attempt try local
s = RMISocketFactory.getDefaultSocketFactory().
createSocket(InetAddress.getLocalHost().getHostName(),
this.port != 0 ? this.port : port);
System.err.print("cajo.invoke.Remote redirecting to localhost ");
System.err.println("instead of " + this.host);
}
s.setKeepAlive(true);
return s;
}
public boolean equals(Object o) {
return o instanceof RCSF &&
((RCSF)o).host.equals(host) &&
((RCSF)o).port == port;
}
public int hashCode() { return getClass().hashCode() + port; }
}
private static Object proxy;
private static Registry registry;
/**
* A global reference to the remote client socket factory. This is the
* factory remote VMs will use to communicate with local items.
*/
public static final RCSF rcsf = new RCSF();
/**
* A global reference to the remote server socket factory. This is the
* factory the local items use to communicate with remote VMs.
*/
public static final RSSF rssf = new RSSF();
static { // provide a default configuration; anonymous port & local name:
try { // equivalent of a Remote.config(null, 0, null, 0);
rssf.host = InetAddress.getLocalHost().getHostName();
rcsf.host = rssf.host;
rssf.port = 0;
rcsf.port = 0;
System.setProperty("java.rmi.server.useLocalHostname", "true");
System.setProperty("java.rmi.server.hostname", rcsf.host);
} catch(Exception x) {}
}
/**
* This method is provided to obtain the server's host name.
* This is useful when the host can have one of multiple addresses, either
* because it has multiple network interface cards, or is multi-homed.
* @return The server address on which the item is remoted.
*/
public static String getServerHost() { return rssf.host; }
/**
* This method is provided to obtain the local server socket port
* number. This can be particularly useful if the host was remoted on an
* anonymous port. If a firewall is in use, this inbound port must be made
* accessible to outside clients.
* @return The local ServerSocket port number on which the item is remoted.
*/
public static int getServerPort() { return rssf.port; }
/**
* This method is provided to obtain the host name remote clients will
* use to contact this server. This can be different from the local server
* name or address if NAT is being used.
* @return The server address clients use to connect to the server.
*/
public static String getClientHost() { return rcsf.host; }
/**
* This method is provided to obtain the socket port number the remote
* client must use to contact the server. This can be different from
* the server port number if NAT port translation is being used.
* @return The port clients must connect on to reach the server.
*/
public static int getClientPort() { return rcsf.port; }
/**
* This method configures the server's TCP parameters for RMI. It allows
* complete specification of client-side and server-side ports and
* hostnames. It used to override the default values, which are anonymous,
* meaning from an unused pool, selected by the OS. It is necessary
* when either VM is either operating behind a firewall, has multiple network
* interfaces, is multi-addressed, or is using NAT. The first two parameters
* control how the sockets will be configured locally, the second two
* control how a remote object's sockets will be configured to communicate
* with this server.
* <p><i><u>Note</u>:</i> If this class is to be configured, it must be
* done <b>before</b> any items are remoted.
* @param serverHost The local domain name, or IP address of this host.
* If null, it will use all network interfaces. Typically it is
* specified when the server has multiple phyisical network interfaces, or
* is multi-homed, i.e. having multiple logical network interfaces.
* @param serverPort Specifies the local port on which the server is
* serving clients. It can be zero, to use an anonymous port. If firewalls
* are being used, it must be an accessible port, into this server. If this
* port is zero, and the ClientPort argument is non-zero, then the
* ClientPort value will automatically substituted.
* @param clientHost The domain name, or IP address the remote client will
* use to communicate with this server. If null, it will be the same as
* serverHost resolution. This would need to be explicitly specified if
* the server is operating behind NAT i.e. when the server's subnet IP
* address is <i>not</i> the same as its address outside the subnet.
* @param clientPort Specifies the particular port on which the client
* will connect to the server. Typically this is the <i>same</i> number
* as the serverPort argument, but could be different, if port translation
* is being used. If the clientPort field is 0, i.e. anonymous, its port
* value will be automatically assigned to match the server, even if the
* server port is anonymous.
* @throws java.net.UnknownHostException If the IP address or name of the
* serverHost can not be resolved.
*/
public static void config(String serverHost, int serverPort,
String clientHost, int clientPort) throws java.net.UnknownHostException {
rssf.host = serverHost;
rcsf.host = clientHost != null ? clientHost : serverHost != null ?
serverHost : InetAddress.getLocalHost().getHostName();
rssf.port =
serverPort != 0 ? serverPort : clientPort != 0 ? clientPort : 0;
rcsf.port = clientPort != 0 ? clientPort : serverPort;
try { // this won't work if running as an applet
System.setProperty("java.rmi.server.useLocalHostname", "true");
System.setProperty("java.rmi.server.hostname", rcsf.host);
} catch(SecurityException x) {}
}
/**
* This method configures the server's TCP parameters for RMI through HTTP
* proxy servers. This is necessary when the client or server, or both are
* behind firewalls, and the only method of access to the internet is
* through HTTP proxy servers. There will be a fairly significant performance
* hit incurred using the HTTP tunnel, but it is better than having no
* connectivity at all. Due to an unfortunate oversight in the design of
* the standard RMISocketFactory, no server network interface can be
* specified, instead it will listen on <i>all</i> network interfaces.
* It is probably not a problem for most, but is probably not desirable for
* multi-homed hosts.
* <p><i><u>Note</u>:</i> If this class is to be configured, it must be
* done <b>before</b> any items are remoted.
* @param serverPort Specifies the local inbound port on which the server is
* serving clients. It can be zero, to use an anonymous port. If a firewall
* is being used, it must be an accessible port, into this server. If this
* port is zero, and the ClientPort argument is non-zero, then the
* ClientPort value will automatically substituted.
* @param clientHost The domain name, or IP address the remote client will
* use to communicate with this server. If null, it will be the server's
* default host name. This would need to be explicitly specified if
* the server is operating behind NAT i.e. when the server's subnet IP
* address is <i>not</i> the same as its address outside the subnet.
* @param clientPort Specifies the particular port on which the client
* will connect to the server. Typically this is the <i>same</i> number
* as the serverPort argument, but could be different, if port translation
* is being used. If the clientPort field is 0, i.e. anonymous, its port
* value will be automatically assigned to match the server, even if the
* server port is anonymous.
* @param proxyHost The name or address of the proxy server used to gain
* HTTP access to the internet.
* @param proxyPort The port number of the proxy server used to gain
* HTTP access to the internet.
* @param username The proxy account user name required for permission, if
* non-null.
* @param password The proxy account password required for permission, if
* required.
* @throws java.net.UnknownHostException If the IP address or name of the
* local host interface can not be determined.
*/
public static void config(int serverPort, String clientHost, int clientPort,
String proxyHost, int proxyPort, final String username,
final String password) throws java.net.UnknownHostException {
rcsf.host = (clientHost != null) ?
clientHost : InetAddress.getLocalHost().getHostName();
rssf.port = (serverPort != 0) ?
serverPort : ((clientPort != 0) ? clientPort : 0);
rcsf.port = (clientPort != 0) ?
clientPort : rssf.port;
try { // this won't work if running as an applet
if (proxyHost != null) {
System.setProperty("proxySet", "true");
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", Integer.toString(proxyPort));
if (username != null) Authenticator.setDefault(
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
username, password.toCharArray());
}
}
);
}
System.setProperty("java.rmi.server.useLocalHostname", "true");
System.setProperty("java.rmi.server.hostname", rcsf.host);
} catch (SecurityException x) {}
}
/**
* A utility method to reconstitute a zipped marshalled object (zedmob)
* into a remote item reference, proxy object, or local object.
* Typically a file containing a zedmob has the file extension .zmob as
* an identifier.<p>
* <i><u>Note</u>:</i> on completion of reading the item from the stream,
* the stream will be automatically closed.
* @param is The input stream containing the zedmob of the item reference.
* @return A reconstituted reference to the item.
* @throws IOException if the zedmob format is invalid.
* @throws ClassNotFoundException if a proxy object was sent, and remote
* class loading was not enabled in this VM.
*/
public static Object zedmob(InputStream is)
throws ClassNotFoundException, IOException {
GZIPInputStream gis = new GZIPInputStream(is);
ObjectInputStream ois = new ObjectInputStream(gis);
MarshalledObject mob = (MarshalledObject)ois.readObject();
ois.close();
return mob.get();
}
/**
* This method will write the local item, remote item reference, or proxy,
* to an output stream as a zipped marshalled object (zedmob). A zedmob is
* the standard serialized format in this paradigm. This can be used to
* <i>'freeze-dry'</i> the object to a file for later use, to send it over
* the network, or to an object archival service, for example.<p>
* <i><u>Note</u>:</i> on completion of writing the item, or reference, the
* stream will be closed. Typically, when saved to a file, a zedmob has the
* file extension .zmob to provide obvious identification.
* @param os The output stream on which to write the reference. It may be
* a file stream, a socket stream, or any other type of stream.
* @param ref The item or reference to be serialized.
* @throws IOException For any stream related writing error.
*/
public static void zedmob(OutputStream os, Object ref) throws IOException {
GZIPOutputStream zos = new GZIPOutputStream(os);
ObjectOutputStream oos = new ObjectOutputStream(zos);
oos.writeObject(new MarshalledObject(ref));
oos.flush();
zos.flush();
oos.close();
}
/**
* A utility method to load either an item, or a zipped marshalled object
* (zedmob) of an item, from a URL, file, or from a remote rmiregistry.
* If the item is in a local file, it can be either inside the server's
* jar file, or on its local file system.<p> Loading an item from a file
* can be specified in one of three ways:<p><ul>
* <li>As a URL; in the format file://path/name.
* <li>As a class file; in the format path/name
* <li>As a serialized item; in the format /path/name</ul><p>
* File loading will first be attempted from within the server's jar file,
* if that fails, it will then look in the local filesystem.<p>
* <i><u>Note</u>:</i> any socket connections made by the incoming item
* cannot be known at compile time, therefore proper operation if this VM
* is behind a firewall could be blocked. Use behind a firewall would
* require knowing all the ports that would be needed in advance, and
* enabling them before loading the proxy.
* @param url The URL where to get the object: file://, http://, ftp://,
* /path/name, path/name, or //[host][:port]/[name]. The host, port,
* and name, are all optional. If missing the host is presumed local, the
* port 1099, and the name "main". The referenced resource can be
* returned as a MarshalledObject, it will be extracted automatically.
* If the URL is null, it will be assumed to be ///.
* @return A reference to the item contained in the URL. It may be either
* local, or remote to this VM.
* @throws RemoteException if the remote registry could not be reached.
* @throws NotBoundException if the requested name is not in the registry.
* @throws IOException if the zedmob format is invalid.
* @throws ClassNotFoundException if a proxy was sent to the VM, and
* proxy hosting was not enabled.
* @throws InstantiationException when the URL specifies a class name
* which cannot be instantiated at runtime.
* @throws IllegalAccessException when the url specifies a class name
* and it does not support a no-arg constructor.
* @throws MalformedURLException if the URL is not in the format explained
*/
public static Object getItem(String url) throws RemoteException,
NotBoundException, IOException, ClassNotFoundException,
InstantiationException, IllegalAccessException, MalformedURLException {
Object item = null;
if (url == null) url = "///main";
else if (url.startsWith("//") && url.endsWith("/")) url += "main";
if (url.startsWith("//")) { // if from an rmiregistry
item = java.rmi.Naming.lookup(url); // get reference
} else if (url.startsWith("/")) { // if from a serialized object file
InputStream ris = Remote.class.getResourceAsStream(url);
if (ris == null) ris = new FileInputStream('.' + url);
item = zedmob(ris);
ris.close();
} else if (url.indexOf(':') == -1) { // from a class file
item = Class.forName(url).newInstance();
} else { // otherwise from a real URL, http:// ftp:// file:// etc.
InputStream uis = new URL(url).openStream();
item = zedmob(uis);
uis.close();
}
return item;
}
/**
* This method emulates server J5SE argument autoboxing. It is used by
* {@link #findBestMethod findBestMethod}. This technique has been most
* graciously championed by project member <b>Zac Wolfe</b>. It allows
* public server methods to use primitive types for arguments, <i>and</i>
* return values.
* @param arg The the argument class to test for boxing. If the argument
* <i>type</i> is primitive, it will be substituted with the corresponding
* primitive <i>class</i> representation.
* @return The corresponding class matching the primitive type, or the
* original argument class, if it is not primitive.
*/
public static Class autobox(Class arg) {
return arg.isPrimitive() ?
arg == Boolean.TYPE ? Boolean.class :
arg == Byte.TYPE ? Byte.class :
arg == Character.TYPE ? Character.class :
arg == Short.TYPE ? Short.class :
arg == Integer.TYPE ? Integer.class :
arg == Long.TYPE ? Long.class :
arg == Float.TYPE ? Float.class : Double.class : arg;
}
/**
* This method attempts to resolve the argument inheritance blindness in
* Java reflection-based method selection. It has been most graciously
* championed by project member <b>Fredrik Larsen</b>, with help from
* project member <b>Li Ma</b>. If more than one matching method is found,
* based on argument polymorphism, it will try to select the most
* applicable one. It works very well if the inheritence trees for the
* arguments are shallow. However, it may <i>not</i> always pick the best
* method if the arguments have deep inheritance trees. Fortunately it
* works for both classes, <i>and</i> interfaces.
* @param item The object on which to find the most applicable public
* method.
* @param method The name of the method, which is to be invoked.
* @param args The class representations of the arguments to be
* provided to the method.
* @return The most applicable method, which will accept all of these
* arguments, or null, if none match.
*/
public static Method findBestMethod(
Object item, String method, Class[] args) {
LinkedList matchList = new LinkedList();
Method[] ms = item.getClass().getMethods();
// Find any matching methods in the item and put them in a list:
list: for(int i = 0; i < ms.length; i++) {
if (ms[i].getName().equals(method) &&
ms[i].getParameterTypes().length == args.length) {
for (int j = 0; j < args.length; j++)
- if (args[j] != null & !autobox(ms[i].getParameterTypes()[j]).
+ if (args[j] != null && !autobox(ms[i].getParameterTypes()[j]).
isAssignableFrom(args[j]))
continue list;
matchList.add(ms[i]);
}
}
// now pick the closest match, if any:
if (matchList.size() > 1) {
Method best = null;
int goodness = -1;
for (int i = 0; i < matchList.size(); i++) {
int closeness = 0;
Method m = (Method)matchList.get(i);
for (int j = 0; j < args.length; j++)
if (args[j] != null && args[j].
isAssignableFrom(autobox(m.getParameterTypes()[j])))
closeness++;
if (closeness == args.length) return m; // closest fit
if (closeness > goodness) {
best = m;
goodness = closeness;
}
}
return best;
} else return matchList.size() > 0 ? (Method)matchList.get(0) : null;
}
/**
* This function may be called reentrantly, so the item object <i>must</i>
* synchronize its critical sections as necessary. The specified method
* will be invoked, with the provided arguments if any, on the internal
* object's public method via the framework Java reflection mechanism, and
* the result returned, if any. The method is declared static to centralize
* the implementation, and allow other derived classes to use this
* mechanism without having to reimplement it. If the arguments are being
* sent to a remote VM, and are not already encapsulated in a
* MarshalledObject, they will be, automatically.
* @param item The object on which to invoke the method. If the item
* implements the {@link Invoke Invoke} interface, the call will be passed
* directly to it.
* @param method The method name to be invoked.
* @param args The arguments to provide to the method for its invocation.
* @return The resulting data, if any, from the invocation.
* @throws IllegalArgumentException If the method argument is null.
* @throws NoSuchMethodException If no matching method can be found.
* @throws Exception If the item rejected the invocation, for application
* specific reasons.
*/
public static Object invoke(Object item, String method, Object args)
throws Exception {
if (item instanceof Invoke) return ((Invoke)item).invoke(method, args);
if (method == null)
throw new IllegalArgumentException("Method argument cannot be null");
if (args instanceof Object[]) {
if (((Object[])args).length == 0)
return item.getClass().getMethod(method, null).invoke(item, null);
Object[] o_args = (Object[])args;
Class[] c_args = new Class[o_args.length];
for(int i = 0; i < o_args.length; i++)
c_args[i] = o_args[i] != null ? o_args[i].getClass() : null;
Method m = findBestMethod(item, method, c_args);
if (m!= null) return m.invoke(item, o_args);
} else if (args != null) {
Method m =
findBestMethod(item, method, new Class[]{ args.getClass() });
if (m != null) return m.invoke(item, new Object[]{ args });
} else return item.getClass().getMethod(method, null).invoke(item, null);
throw new NoSuchMethodException();
}
/**
* This is the reference to the local (or possibly remote) object
* reference being made remotely invokable by this Virtual Machine. It is
* declared public to provide the convenience to refer to both the
* wrapper, and its wrapped object, via a single reference.
*/
public final Object item;
/**
* The constructor takes <i>any</i> object, and allows it to be remotely
* invoked. If the object implements the {@link Invoke Invoke} interface,
* (i.e. it is an <tt>Item</tt>) it will simply route all remote
* invocations directly to it. Otherwise it will use Java reflection to
* attempt to invoke the remote calls directly on the object's public
* methods.
* @param item The object to make remotely callable. It may be an
* arbitrary object of any type, or an <b>Item</b> (either local or remote).
* @throws RemoteExcepiton If the remote instance could not be be created.
*/
public Remote(Object item) throws RemoteException {
super(rssf.port, rcsf, rssf);
this.item = item;
}
/**
* This method is used to check if two Remote objects are holding an
* equavilent inner item. It short-circuit's the invocation, returning the
* result of the internal object's equals invocation.
* @param object A reference to another object to compare for equality.
* @return The result of the equals method called on the internal object.
*/
public boolean equals(Object object) { return item.equals(object); }
/**
* This method is used to identify the internal object. It short-circuit's
* the invocation, returning the result of the internal object's toString
* invocation.
* @return The internal object's cannonical string identifier.
*/
public String toString() { return item.toString(); }
/**
* This method is used to identify the internal object. It short-circuit's
* the invocation, returning the result of the internal item's hashCode
* invocation.
* @return The semi-unique integer identifier for the internal object.
*/
public int hashCode() { return item.hashCode(); }
/**
* The sole generic, multi-purpose interface for communication between VMs.
* This function may be called reentrantly, so the inner object <i>must</i>
* synchronize its critical sections as necessary. Technically, it simply
* passes the call to this class' static invoke method. If the arriving
* arguments are encapsulated in a MarshalledObject, they will be extracted
* here automatically.
* @param method The method to invoke on the internal object.
* @param args The arguments to provide to the method for its invocation.
* It can be a single object, an array of objects, or even null.
* @return The sychronous data, if any, resulting from the invocation.
* @throws java.rmi.RemoteException For network communication related
* reasons.
* @throws IllegalArgumentException If reflection is going to be used,
* and the method argument is null.
* @throws NoSuchMethodException If no matching method can be found.
* @throws Exception If the internal item rejected the invocation, for
* application specific reasons.
*/
public Object invoke(String method, Object args) throws Exception {
return invoke(item, method, args);
}
/**
* This method sends its remote reference to another item, either from a
* URL, file, or from a remote rmiregistry. It will invoke the local
* {@link #getItem getItem} method to obtain a reference to the remote
* item. It will next invoke the received reference's invoke method with
* a "send" value, and a reference to itself as its sole argument.
* @param url The URL where to get the remote host interface: file://,
* http://, ftp://, /path/name, path/name, or //[host][:port]/[name].
* The host, port, and name, are all optional. If missing the host is
* presumed local, the port 1099, and the name "main". If the URL is
* null, it will be assumed to be ///.
* @return Whatever the item returns in receipt of the reference,
* even null.
* @throws Exception Either from the getItem invocation, or if the
* item reference invocation fails.
*/
public Object send(String url) throws Exception {
if (url == null) url = "///main";
else if (url.startsWith("//") && url.endsWith("/")) url += "main";
return invoke(getItem(url), "send", this);
}
/**
* This method will write this remote item reference to an output stream
* as a zipped marshalled object (zedmob). A zedmob is the standard
* serialized format for a remote item reference, in this paradigm.
* This can be used to <i>'freeze-dry'</i> the remote reference, to a file
* for later use, send it over the network, or to an object archival
* service, for example.
* @param os The output stream on which to write the reference. It may be
* a file stream, a socket stream, or any other type of stream.
* @throws IOException For any stream related writing error.
*/
public void zedmob(OutputStream os) throws IOException {
zedmob(os, this);
}
/**
* The application method loads a zipped marshalled object (zedmob) from a
* URL, or a file, and allows it run in this virtual machine. It uses
* the {@link #getItem getItem} method to load the item. Following loading
* of the item, it will also create an rmiregistry, and bind a remote
* reference to it under the name "main". This will also allow remote
* clients to connect to, and interact with it.<p>
* <i><u>Note</u>:</i>It will require a security policy, to define what
* permissions the loaded item will be allowed. There are six optional
* configuration parameters:<ul>
* <li> args[0] The optional URL where to get the object: file:// http://
* ftp:// ..., /path/name <serialized>, path/name <class>, or alternatively;
* //[host][:port]/[name]. If no arguments are provided, the URL will be
* assumed to be //localhost:1099/main.
* <li> args[1] The optional external client host name, if using NAT.
* <li> args[2] The optional external client port number, if using NAT.
* <li> args[3] The optional internal client host name, if multi home/NIC.
* <li> args[4] The optional internal client port number, if using NAT.
* <li> args[5] The optional URL where to get a proxy item: file://
* http:// ftp:// ..., //host:port/name (rmiregistry), /path/name
* (serialized), or path/name (class). It will be passed into the loaded
* proxy as the sole argument to a setItem method invoked on the loaded item.
* </ul>
*/
public static void main(String args[]) {
try {
if (args.length == 0) args = new String[] { "///main" };
String clientHost = args.length > 1 ? args[1] : null;
int clientPort = args.length > 2 ? Integer.parseInt(args[2]) : 0;
String localHost = args.length > 3 ? args[3] : null;
int localPort = args.length > 4 ? Integer.parseInt(args[4]) : 0;
config(localHost, localPort, clientHost, clientPort);
try { System.setProperty("java.rmi.server.disableHttp", "true"); }
catch(SecurityException x) {}
proxy = getItem(args[0]);
if (args.length > 5) invoke(proxy, "setItem", getItem(args[5]));
registry =
LocateRegistry.createRegistry(getServerPort(), rcsf, rssf);
registry.bind("main", new Remote(proxy));
} catch (Exception x) { x.printStackTrace(System.err); }
}
}
| true | true | public static Method findBestMethod(
Object item, String method, Class[] args) {
LinkedList matchList = new LinkedList();
Method[] ms = item.getClass().getMethods();
// Find any matching methods in the item and put them in a list:
list: for(int i = 0; i < ms.length; i++) {
if (ms[i].getName().equals(method) &&
ms[i].getParameterTypes().length == args.length) {
for (int j = 0; j < args.length; j++)
if (args[j] != null & !autobox(ms[i].getParameterTypes()[j]).
isAssignableFrom(args[j]))
continue list;
matchList.add(ms[i]);
}
}
// now pick the closest match, if any:
if (matchList.size() > 1) {
Method best = null;
int goodness = -1;
for (int i = 0; i < matchList.size(); i++) {
int closeness = 0;
Method m = (Method)matchList.get(i);
for (int j = 0; j < args.length; j++)
if (args[j] != null && args[j].
isAssignableFrom(autobox(m.getParameterTypes()[j])))
closeness++;
if (closeness == args.length) return m; // closest fit
if (closeness > goodness) {
best = m;
goodness = closeness;
}
}
return best;
} else return matchList.size() > 0 ? (Method)matchList.get(0) : null;
}
| public static Method findBestMethod(
Object item, String method, Class[] args) {
LinkedList matchList = new LinkedList();
Method[] ms = item.getClass().getMethods();
// Find any matching methods in the item and put them in a list:
list: for(int i = 0; i < ms.length; i++) {
if (ms[i].getName().equals(method) &&
ms[i].getParameterTypes().length == args.length) {
for (int j = 0; j < args.length; j++)
if (args[j] != null && !autobox(ms[i].getParameterTypes()[j]).
isAssignableFrom(args[j]))
continue list;
matchList.add(ms[i]);
}
}
// now pick the closest match, if any:
if (matchList.size() > 1) {
Method best = null;
int goodness = -1;
for (int i = 0; i < matchList.size(); i++) {
int closeness = 0;
Method m = (Method)matchList.get(i);
for (int j = 0; j < args.length; j++)
if (args[j] != null && args[j].
isAssignableFrom(autobox(m.getParameterTypes()[j])))
closeness++;
if (closeness == args.length) return m; // closest fit
if (closeness > goodness) {
best = m;
goodness = closeness;
}
}
return best;
} else return matchList.size() > 0 ? (Method)matchList.get(0) : null;
}
|
diff --git a/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java b/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
index 7601b164a..b7446b885 100644
--- a/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
+++ b/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
@@ -1,832 +1,833 @@
package org.jbei.ice.lib.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jbei.ice.lib.utils.Utils;
import org.jbei.ice.lib.vo.DNAFeature;
import org.jbei.ice.lib.vo.DNAFeatureLocation;
import org.jbei.ice.lib.vo.DNAFeatureNote;
import org.jbei.ice.lib.vo.FeaturedDNASequence;
import org.jbei.ice.lib.vo.IDNASequence;
/**
* Genbank parser and generator.
* The Genbank file format is defined in gbrel.txt located at
* ftp://ftp.ncbi.nlm.nih.gov/genbank/gbrel.txt
*
* This parser also handles some incorrectly formatted and obsolete genbank files.
*
* @author Timothy Ham
*
* */
public class IceGenbankParser extends AbstractParser {
private static final String ICE_GENBANK_PARSER = "IceGenbank";
// genbank tags
public static final String LOCUS_TAG = "LOCUS";
public static final String DEFINITION_TAG = "DEFINITION";
public static final String ACCESSION_TAG = "ACCESSION";
public static final String VERSION_TAG = "VERSION";
public static final String NID_TAG = "NID";
public static final String PROJECT_TAG = "PROJECT";
public static final String DBLINK_TAG = "DBLINK";
public static final String KEYWORDS_TAG = "KEYWORDS";
public static final String SEGMENT_TAG = "SEGMENT";
public static final String SOURCE_TAG = "SOURCE";
public static final String ORGANISM_TAG = "ORGANISM";
public static final String REFERENCE_TAG = "REFERENCE";
public static final String COMMENT_TAG = "COMMENT";
public static final String FEATURES_TAG = "FEATURES";
public static final String BASE_COUNT_TAG = "BASE COUNT";
public static final String CONTIG_TAG = "CONTIG";
public static final String ORIGIN_TAG = "ORIGIN";
public static final String END_TAG = "//";
// tags only under reference tag
public static final String AUTHORS_TAG = "AUTHORS";
public static final String CONSRTM_TAG = "CONSRTM";
public static final String TITLE_TAG = "TITLE";
public static final String JOURNAL_TAG = "JOURNAL";
public static final String MEDLINE_TAG = "MEDLINE";
public static final String PUBMED_TAG = "PUBMED";
public static final String REMARK_TAG = "REMARK";
// obsolete tags
public static final String BASE_TAG = "BASE";
private static final String[] NORMAL_TAGS = { LOCUS_TAG, DEFINITION_TAG, ACCESSION_TAG,
VERSION_TAG, NID_TAG, PROJECT_TAG, DBLINK_TAG, KEYWORDS_TAG, SEGMENT_TAG, SOURCE_TAG,
ORGANISM_TAG, REFERENCE_TAG, COMMENT_TAG, FEATURES_TAG, BASE_COUNT_TAG, CONTIG_TAG,
ORIGIN_TAG, END_TAG, BASE_TAG };
private static final String[] REFERENCE_TAGS = { AUTHORS_TAG, CONSRTM_TAG, TITLE_TAG,
JOURNAL_TAG, MEDLINE_TAG, PUBMED_TAG, REMARK_TAG };
private static final String[] IGNORE_TAGS = { BASE_TAG, };
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
private static final Pattern startStopPattern = Pattern.compile("[<>]*(\\d+)\\.\\.[<>]*(\\d+)");
private static final Pattern startOnlyPattern = Pattern.compile("\\d+");
private Boolean hasErrors = false;
private List<String> errors = new ArrayList<String>();
@Override
public String getName() {
return ICE_GENBANK_PARSER;
}
@Override
public Boolean hasErrors() {
return hasErrors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
@Override
public IDNASequence parse(byte[] bytes) throws InvalidFormatParserException {
return parse(new String(bytes));
}
@Override
public IDNASequence parse(File file) throws FileNotFoundException, IOException,
InvalidFormatParserException {
if (file.canRead()) {
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while (br.ready()) {
sb.append((char) br.read());
}
br.close();
IceGenbankParser iceGenbankParser = new IceGenbankParser();
return iceGenbankParser.parse(sb.toString());
} else {
return null;
}
}
// TODO parse source feature tag with xdb_ref
@Override
public IDNASequence parse(String textSequence) throws InvalidFormatParserException {
textSequence = cleanSequence(textSequence);
FeaturedDNASequence sequence = null;
ArrayList<Tag> tags = splitTags(textSequence, NORMAL_TAGS, IGNORE_TAGS);
tags = parseTags(tags);
sequence = new FeaturedDNASequence();
for (Tag tag : tags) {
if (tag instanceof LocusTag) {
sequence.setName(((LocusTag) tag).getLocusName());
sequence.setIsCircular(((LocusTag) tag).isCircular());
} else if (tag instanceof OriginTag) {
sequence.setSequence(((OriginTag) tag).getSequence());
} else if (tag instanceof FeaturesTag) {
sequence.setFeatures(((FeaturesTag) tag).getFeatures());
}
}
return sequence;
}
private ArrayList<Tag> splitTags(String block, String[] acceptedTags, String[] ignoredTags)
throws InvalidFormatParserException {
ArrayList<Tag> result = new ArrayList<Tag>();
StringBuilder rawBlock = new StringBuilder();
String[] lines = block.split("\n");
String[] lineChunks = null;
Tag currentTag = null;
// see if first two lines contain the "LOCUS" keyword. If not, don't even bother
if (lines.length >= 1 && lines[0].indexOf("LOCUS") == -1) {
if (lines.length == 1 || lines[1].indexOf("LOCUS") == -1) {
throw new InvalidFormatParserException("Not a valid Genbank format: No Locus line.");
}
}
for (String line : lines) {
lineChunks = line.trim().split(" +");
if (lineChunks.length == 0) {
continue;
} else {
String putativeTag = lineChunks[0].trim();
if (Arrays.asList(acceptedTags).contains(putativeTag)) {
if (currentTag != null) { // flush previous tag
currentTag.setRawBody(rawBlock.toString());
if (!Arrays.asList(ignoredTags).contains(currentTag.getKey())) {
result.add(currentTag);
}
}
rawBlock = new StringBuilder();
rawBlock.append(line);
rawBlock.append("\n");
currentTag = new Tag();
currentTag.setKey(putativeTag);
} else {
rawBlock.append(line);
rawBlock.append("\n");
}
}
}
currentTag.setRawBody(rawBlock.toString());
result.add(currentTag); // push the last one
return result;
}
private ArrayList<Tag> parseTags(ArrayList<Tag> tags) throws InvalidFormatParserException {
for (int i = 0; i < tags.size(); i++) {
Tag tag = tags.get(i);
if (ORIGIN_TAG.equals(tag.getKey())) {
tags.set(i, parseOriginTag(tag));
} else if (FEATURES_TAG.equals(tag.getKey())) {
tags.set(i, parseFeaturesTag(tag));
} else if (REFERENCE_TAG.equals(tag.getKey())) {
tags.set(i, parseReferenceTag(tag));
} else if (LOCUS_TAG.equals(tag.getKey())) {
tags.set(i, parseLocusTag(tag));
} else if (SOURCE_TAG.equals(tag.getKey())) {
} else {
parseNormalTag(tag);
}
}
return tags;
}
private Tag parseNormalTag(Tag tag) {
String value = "";
String[] lines = tag.getRawBody().split("\n");
String[] firstLine = lines[0].split(" +");
if (firstLine.length == 1) {
// empty value
tag.setValue("");
} else {
firstLine[0] = "";
value = Utils.join(" ", Arrays.asList(firstLine));
lines[0] = "";
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].trim();
}
value = value + " " + Utils.join(" ", Arrays.asList(lines));
}
tag.setValue(value.trim());
return tag;
}
private OriginTag parseOriginTag(Tag tag) {
OriginTag result = new OriginTag();
String value = "";
StringBuilder sequence = new StringBuilder();
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines[0].startsWith(ORIGIN_TAG)) {
if (lines[0].split(" +").length > 1) { // grab value of origin
value = lines[0].split(" +")[1];
}
}
for (int i = 1; i < lines.length; i++) {
chunks = lines[i].trim().split(" +");
if (chunks[0].matches("\\d*")) { //sometimes sequence block is un-numbered fasta
chunks[0] = "";
}
sequence.append(Utils.join("", Arrays.asList(chunks)).toLowerCase());
}
result.setKey(tag.getKey());
result.setValue(value);
result.setSequence(sequence.toString());
return result;
}
private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
+ complement = false;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
chunk[1] = chunk[1].trim();
chunk[1] = chunk[1].substring(11, chunk[1].length() - 1).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
private List<GenbankLocation> parseGenbankLocation(String input)
throws InvalidFormatParserException {
LinkedList<GenbankLocation> result = new LinkedList<GenbankLocation>();
int genbankStart = 1;
int end = 1;
if (input.startsWith("join")) {
input = input.substring(5, input.length() - 1).trim();
}
String[] chunks = input.split(",");
for (String chunk : chunks) {
chunk = chunk.trim();
Matcher startStopMatcher = startStopPattern.matcher(chunk);
if (startStopMatcher.find()) {
if (startStopMatcher.groupCount() == 2) {
genbankStart = Integer.parseInt(startStopMatcher.group(1));
end = Integer.parseInt(startStopMatcher.group(2));
result.add(new GenbankLocation(genbankStart, end));
}
} else {
Matcher startOnlyMatcher = startOnlyPattern.matcher(chunk);
if (startOnlyMatcher.find()) {
genbankStart = Integer.parseInt(startOnlyMatcher.group(0));
end = Integer.parseInt(startOnlyMatcher.group(0));
result.add(new GenbankLocation(genbankStart, end));
}
}
}
return result;
}
/**
* Represent a contiguous Genbank location, including a single base pair.
*
* @author Timothy Ham
*
*/
public class GenbankLocation {
private int genbankStart = -1;
private int end = -1;
private boolean inbetween = false;
private boolean singleResidue = false;
public GenbankLocation(int genbankStart, int end) {
super();
setGenbankStart(genbankStart);
setEnd(end);
}
public int getGenbankStart() {
return genbankStart;
}
public void setGenbankStart(int genbankStart) {
this.genbankStart = genbankStart;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public void setInbetween(boolean inbetween) {
this.inbetween = inbetween;
}
public boolean isInbetween() {
return inbetween;
}
public void setSingleResidue(boolean singleResidue) {
this.singleResidue = singleResidue;
}
public boolean isSingleResidue() {
return singleResidue;
}
}
private DNAFeature parseQualifiers(String block, DNAFeature dnaFeature) {
/*
* Qualifiers are interesting beasts. The values can be quoted
* or not quoted. They can span multiple lines. Older versions used
* backslash to indicate space ("\\" -> " "). Oh, and it uses two quotes
* in a row to ("") to indicate a literal quote (e.g. "\""). And since each
* genbank feature does not have a specified "label" field, the
* label can be anything. Some software uses "label", another uses
* "notes", and some of the examples in gbrel.txt uses "gene".
* But really, it could be anything. Qualifer "translation" must be handled
* differently from other multi-line fields, as they are expected to be
* concatenated without spaces.
*
* This parser tries to normalize to "label", and preserve quotedness.
*
*/
ArrayList<DNAFeatureNote> notes = new ArrayList<DNAFeatureNote>();
if ("".equals(block)) {
return dnaFeature;
}
DNAFeatureNote dnaFeatureNote = null;
String[] lines = block.split("\n");
String line = null;
String[] chunk;
StringBuilder qualifierItem = new StringBuilder();
String qualifierValue = null;
int apparentQualifierColumn = lines[0].indexOf("/");
for (String line2 : lines) {
line = line2;
if ('/' == line.charAt(apparentQualifierColumn)) { // new tag starts
if (dnaFeatureNote != null) { // flush previous note
qualifierValue = qualifierItem.toString();
if (qualifierValue.startsWith("\"") && qualifierValue.endsWith("\"")) {
dnaFeatureNote.setQuoted(true);
qualifierValue = qualifierValue.substring(1, qualifierValue.length() - 1);
} else {
dnaFeatureNote.setQuoted(false);
}
qualifierValue = qualifierValue.replaceAll("\\\\", " ");
qualifierValue = qualifierValue.replaceAll("\"\"", "\"");
if ("translation".equals(dnaFeatureNote.getName())) {
qualifierValue = Utils.join("", Arrays.asList(qualifierValue.split(" ")))
.trim();
}
dnaFeatureNote.setValue(qualifierValue);
notes.add(dnaFeatureNote);
}
// start a new note
dnaFeatureNote = new DNAFeatureNote();
qualifierItem = new StringBuilder();
chunk = line.split("=");
if (chunk.length < 2) {
getErrors().add("Skipping bad genbank qualifier " + line);
hasErrors = true;
dnaFeatureNote = null;
continue;
} else {
String putativeName = chunk[0].trim().substring(1);
dnaFeatureNote.setName(putativeName);
chunk[0] = "";
qualifierItem.append(Utils.join(" ", Arrays.asList(chunk)).trim());
}
} else {
qualifierItem.append(" ");
qualifierItem.append(line.trim());
}
}
// parse and add the last one
qualifierValue = qualifierItem.toString();
if (qualifierValue.startsWith("\"") && qualifierValue.endsWith("\"")) {
dnaFeatureNote.setQuoted(true);
qualifierValue = qualifierValue.substring(1, qualifierValue.length() - 1);
} else {
dnaFeatureNote.setQuoted(false);
}
qualifierValue = qualifierValue.replaceAll("\\\\", " ");
qualifierValue = qualifierValue.replaceAll("\"\"", "\"");
if ("translation".equals(dnaFeatureNote.getName())) {
qualifierValue = Utils.join("", Arrays.asList(qualifierValue.split(" "))).trim();
}
dnaFeatureNote.setValue(qualifierValue);
notes.add(dnaFeatureNote);
dnaFeature.setNotes(notes);
dnaFeature = populateName(dnaFeature);
return dnaFeature;
}
/**
* Tries to determine the feature name, from a list of possible qualifier keywords that might
* contain it.
*
* @param dnaFeature
* @return
*/
private DNAFeature populateName(DNAFeature dnaFeature) {
String LABEL_QUALIFIER = "label";
String APE_LABEL_QUALIFIER = "apeinfo_label";
String NOTE_QUALIFIER = "note";
String GENE_QUALIFIER = "gene";
String ORGANISM_QUALIFIER = "organism";
String NAME_QUALIFIER = "name";
ArrayList<DNAFeatureNote> notes = (ArrayList<DNAFeatureNote>) dnaFeature.getNotes();
String[] QUALIFIERS = { APE_LABEL_QUALIFIER, NOTE_QUALIFIER, GENE_QUALIFIER,
ORGANISM_QUALIFIER, NAME_QUALIFIER };
String newLabel = null;
if (dnaFeatureContains(notes, LABEL_QUALIFIER) == -1) {
for (String element : QUALIFIERS) {
int foundId = dnaFeatureContains(notes, element);
if (foundId != -1) {
newLabel = notes.get(foundId).getValue();
}
}
if (newLabel == null) {
newLabel = dnaFeature.getType();
}
} else {
newLabel = notes.get(dnaFeatureContains(notes, LABEL_QUALIFIER)).getValue();
}
dnaFeature.setName(newLabel);
return dnaFeature;
}
private int dnaFeatureContains(ArrayList<DNAFeatureNote> notes, String key) {
int result = -1;
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).getName().equals(key)) {
result = i;
return result;
}
}
return result;
}
// TODO
private ReferenceTag parseReferenceTag(Tag tag) throws InvalidFormatParserException {
String lines[] = tag.getRawBody().split("\n");
String putativeValue = lines[0].split(" +")[1];
tag.setValue(putativeValue);
return null;
}
private LocusTag parseLocusTag(Tag tag) {
LocusTag result = new LocusTag();
result.setRawBody(tag.getRawBody());
result.setKey(tag.getKey());
String locusLine = tag.getRawBody();
String[] locusChunks = locusLine.split(" +");
if (Arrays.asList(locusChunks).contains("circular")
|| Arrays.asList(locusChunks).contains("CIRCULAR")) {
result.setCircular(true);
} else {
result.setCircular(false);
}
String dateString = locusChunks[locusChunks.length - 1].trim();
try {
result.setDate(simpleDateFormat.parse(dateString));
} catch (ParseException e1) {
getErrors().add("Invalid date format: " + dateString + ". Setting today's date.");
hasErrors = true;
result.setDate(new Date());
}
if (Arrays.asList(locusChunks).indexOf("bp") == 3) {
result.setLocusName(locusChunks[1]);
} else {
result.setLocusName("undefined");
}
return result;
}
public static void main(String[] args) throws IOException {
/*
File file = new File(
"src/main/java/org/jbei/ice/lib/parsers/examples/AcrR_geneart_badlocus_badsequence.gb");
// "src/main/java/org/jbei/ice/lib/parsers/examples/pcI-LasI_ape_no_locusname.ape");
// "src/main/java/org/jbei/ice/lib/parsers/examples/pUC19.gb");
if (file.canRead()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
while (br.ready()) {
sb.append((char) br.read());
}
IceGenbankParser igp = new IceGenbankParser();
try {
igp.parse(sb.toString());
} catch (InvalidFormatParserException e) {
e.printStackTrace();
}
}
*/
}
private class Tag {
private String key;
private String rawBody;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getRawBody() {
return rawBody;
}
public void setRawBody(String rawBody) {
this.rawBody = rawBody;
}
@SuppressWarnings("unused")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private class OriginTag extends Tag {
private String sequence;
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
}
private class ReferenceTag extends Tag {
private ArrayList<Tag> references = new ArrayList<Tag>();
@SuppressWarnings("unused")
public void setReferences(ArrayList<Tag> references) {
this.references = references;
}
@SuppressWarnings("unused")
public ArrayList<Tag> getReferences() {
return references;
}
}
private class FeaturesTag extends Tag {
private List<DNAFeature> features = new ArrayList<DNAFeature>();
@SuppressWarnings("unused")
public void setFeatures(List<DNAFeature> features) {
this.features = features;
}
public List<DNAFeature> getFeatures() {
return features;
}
}
private class LocusTag extends Tag {
private String locusName = "";
private boolean isCircular = true;
private String naType = "DNA";
private String strandType = "ds";
private String divisionCode = "";
private Date date;
public String getLocusName() {
return locusName;
}
public void setLocusName(String locusName) {
this.locusName = locusName;
}
public boolean isCircular() {
return isCircular;
}
public void setCircular(boolean isCircular) {
this.isCircular = isCircular;
}
@SuppressWarnings("unused")
public String getNaType() {
return naType;
}
@SuppressWarnings("unused")
public void setNaType(String naType) {
this.naType = naType;
}
@SuppressWarnings("unused")
public String getStrandType() {
return strandType;
}
@SuppressWarnings("unused")
public void setStrandType(String strandType) {
this.strandType = strandType;
}
@SuppressWarnings("unused")
public String getDivisionCode() {
return divisionCode;
}
@SuppressWarnings("unused")
public void setDivisionCode(String divisionCode) {
this.divisionCode = divisionCode;
}
@SuppressWarnings("unused")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
}
| true | true | private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
chunk[1] = chunk[1].trim();
chunk[1] = chunk[1].substring(11, chunk[1].length() - 1).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
| private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
complement = false;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
chunk[1] = chunk[1].trim();
chunk[1] = chunk[1].substring(11, chunk[1].length() - 1).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
|
diff --git a/trunk/workflow-processes-core/src/main/java/gov/loc/repository/workflow/decisionhandlers/CheckPackageExistsDecisionHandler.java b/trunk/workflow-processes-core/src/main/java/gov/loc/repository/workflow/decisionhandlers/CheckPackageExistsDecisionHandler.java
index 9755fc55..bcd2863a 100644
--- a/trunk/workflow-processes-core/src/main/java/gov/loc/repository/workflow/decisionhandlers/CheckPackageExistsDecisionHandler.java
+++ b/trunk/workflow-processes-core/src/main/java/gov/loc/repository/workflow/decisionhandlers/CheckPackageExistsDecisionHandler.java
@@ -1,36 +1,43 @@
package gov.loc.repository.workflow.decisionhandlers;
import gov.loc.repository.packagemodeler.packge.Package;
import gov.loc.repository.workflow.AbstractPackageModelerAwareHandler;
import gov.loc.repository.workflow.actionhandlers.annotations.Required;
import gov.loc.repository.workflow.actionhandlers.annotations.Transitions;
import static gov.loc.repository.workflow.WorkflowConstants.*;
@Transitions(transitions={TRANSITION_CONTINUE, TRANSITION_RETRY})
public class CheckPackageExistsDecisionHandler extends AbstractPackageModelerAwareHandler {
private static final long serialVersionUID = 1L;
@Required
public String packageId;
@Required
public String repositoryId;
public CheckPackageExistsDecisionHandler(String actionHandlerConfiguration) {
super(actionHandlerConfiguration);
}
@Override
protected String decide() throws Exception {
Package packge = this.dao.findPackage(Package.class, this.repositoryId, this.packageId);
+ boolean b = true;
+ String packageId = packge.getPackageId();
+ String normalizedPackageId = packageId.replaceAll("_\\d{8}_", "_");
+ if (packageId.equals(normalizedPackageId)) {
+ b = false;
+ }
- if (packge == null || (packge.getProcessInstanceId() != null && packge.getProcessInstanceId() == this.executionContext.getProcessInstance().getId()))
+ if (b && (packge == null || (packge.getProcessInstanceId() != null && packge.getProcessInstanceId() == this.executionContext.getProcessInstance().getId())))
{
return TRANSITION_CONTINUE;
}
+ log.debug("CheckPackageExistsDecisionHandler: packageId: " + packageId + ", normalized: " + normalizedPackageId);
this.executionContext.getContextInstance().setVariable("message", "The package already exists.");
return TRANSITION_RETRY;
}
}
| false | true | protected String decide() throws Exception {
Package packge = this.dao.findPackage(Package.class, this.repositoryId, this.packageId);
if (packge == null || (packge.getProcessInstanceId() != null && packge.getProcessInstanceId() == this.executionContext.getProcessInstance().getId()))
{
return TRANSITION_CONTINUE;
}
this.executionContext.getContextInstance().setVariable("message", "The package already exists.");
return TRANSITION_RETRY;
}
| protected String decide() throws Exception {
Package packge = this.dao.findPackage(Package.class, this.repositoryId, this.packageId);
boolean b = true;
String packageId = packge.getPackageId();
String normalizedPackageId = packageId.replaceAll("_\\d{8}_", "_");
if (packageId.equals(normalizedPackageId)) {
b = false;
}
if (b && (packge == null || (packge.getProcessInstanceId() != null && packge.getProcessInstanceId() == this.executionContext.getProcessInstance().getId())))
{
return TRANSITION_CONTINUE;
}
log.debug("CheckPackageExistsDecisionHandler: packageId: " + packageId + ", normalized: " + normalizedPackageId);
this.executionContext.getContextInstance().setVariable("message", "The package already exists.");
return TRANSITION_RETRY;
}
|
diff --git a/src/hello/FizzBuzz.java b/src/hello/FizzBuzz.java
index b665795..f84a719 100644
--- a/src/hello/FizzBuzz.java
+++ b/src/hello/FizzBuzz.java
@@ -1,21 +1,21 @@
package hello;
public class FizzBuzz {
public static String fizzbuzz(int i) {
String fb = fizz(i) + buzz(i);
if (fb.isEmpty()) return String.valueOf(i);
- else return fb;
+ return fb;
}
public static String fizz(int i) {
if (i % 3 == 0) return "Fizz";
return "";
}
public static String buzz(int i) {
if (i % 5 == 0) return "Buzz";
return "";
}
}
| true | true | public static String fizzbuzz(int i) {
String fb = fizz(i) + buzz(i);
if (fb.isEmpty()) return String.valueOf(i);
else return fb;
}
| public static String fizzbuzz(int i) {
String fb = fizz(i) + buzz(i);
if (fb.isEmpty()) return String.valueOf(i);
return fb;
}
|
diff --git a/test/org/jruby/test/TestRbConfigLibrary.java b/test/org/jruby/test/TestRbConfigLibrary.java
index 5c998644b..5d98a8a56 100644
--- a/test/org/jruby/test/TestRbConfigLibrary.java
+++ b/test/org/jruby/test/TestRbConfigLibrary.java
@@ -1,22 +1,22 @@
package org.jruby.test;
import org.jruby.Ruby;
public class TestRbConfigLibrary extends TestRubyBase {
protected void setUp() throws Exception {
super.setUp();
runtime = Ruby.getDefaultInstance();
}
public void testConfigTargetOs() throws Exception {
String script =
"require 'rbconfig'\n" +
"p Config::CONFIG['target_os']";
if (System.getProperty("os.name").compareTo("Mac OS X") == 0) {
- assertTrue(eval(script).contains("darwin"));
+ assertTrue(eval(script).indexOf("darwin") >= 0);
}
}
}
| true | true | public void testConfigTargetOs() throws Exception {
String script =
"require 'rbconfig'\n" +
"p Config::CONFIG['target_os']";
if (System.getProperty("os.name").compareTo("Mac OS X") == 0) {
assertTrue(eval(script).contains("darwin"));
}
}
| public void testConfigTargetOs() throws Exception {
String script =
"require 'rbconfig'\n" +
"p Config::CONFIG['target_os']";
if (System.getProperty("os.name").compareTo("Mac OS X") == 0) {
assertTrue(eval(script).indexOf("darwin") >= 0);
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/net/ClientProxy.java b/src/powercrystals/minefactoryreloaded/net/ClientProxy.java
index 07cb1fc5..57da6991 100644
--- a/src/powercrystals/minefactoryreloaded/net/ClientProxy.java
+++ b/src/powercrystals/minefactoryreloaded/net/ClientProxy.java
@@ -1,36 +1,38 @@
package powercrystals.minefactoryreloaded.net;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.liquids.LiquidDictionary;
import powercrystals.minefactoryreloaded.MineFactoryReloadedClient;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
public class ClientProxy implements IMFRProxy
{
@Override
public void init()
{
MineFactoryReloadedClient.init();
}
@Override
public void movePlayerToCoordinates(EntityPlayer e, double x, double y, double z)
{
e.setPosition(x, y, z);
}
@Override
@ForgeSubscribe
public void onPostTextureStitch(TextureStitchEvent.Post e)
{
LiquidDictionary.getCanonicalLiquid("milk").setRenderingIcon(MineFactoryReloadedCore.milkLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sludge").setRenderingIcon(MineFactoryReloadedCore.sludgeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sewage").setRenderingIcon(MineFactoryReloadedCore.sewageLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("mobEssence").setRenderingIcon(MineFactoryReloadedCore.essenceLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("biofuel").setRenderingIcon(MineFactoryReloadedCore.biofuelLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("meat").setRenderingIcon(MineFactoryReloadedCore.meatLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("pinkslime").setRenderingIcon(MineFactoryReloadedCore.pinkSlimeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
+ LiquidDictionary.getCanonicalLiquid("chocolatemilk").setRenderingIcon(MineFactoryReloadedCore.chocolateMilkLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
+ LiquidDictionary.getCanonicalLiquid("mushroomsoup").setRenderingIcon(MineFactoryReloadedCore.mushroomSoupLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
}
}
| true | true | public void onPostTextureStitch(TextureStitchEvent.Post e)
{
LiquidDictionary.getCanonicalLiquid("milk").setRenderingIcon(MineFactoryReloadedCore.milkLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sludge").setRenderingIcon(MineFactoryReloadedCore.sludgeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sewage").setRenderingIcon(MineFactoryReloadedCore.sewageLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("mobEssence").setRenderingIcon(MineFactoryReloadedCore.essenceLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("biofuel").setRenderingIcon(MineFactoryReloadedCore.biofuelLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("meat").setRenderingIcon(MineFactoryReloadedCore.meatLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("pinkslime").setRenderingIcon(MineFactoryReloadedCore.pinkSlimeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
}
| public void onPostTextureStitch(TextureStitchEvent.Post e)
{
LiquidDictionary.getCanonicalLiquid("milk").setRenderingIcon(MineFactoryReloadedCore.milkLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sludge").setRenderingIcon(MineFactoryReloadedCore.sludgeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("sewage").setRenderingIcon(MineFactoryReloadedCore.sewageLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("mobEssence").setRenderingIcon(MineFactoryReloadedCore.essenceLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("biofuel").setRenderingIcon(MineFactoryReloadedCore.biofuelLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("meat").setRenderingIcon(MineFactoryReloadedCore.meatLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("pinkslime").setRenderingIcon(MineFactoryReloadedCore.pinkSlimeLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("chocolatemilk").setRenderingIcon(MineFactoryReloadedCore.chocolateMilkLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
LiquidDictionary.getCanonicalLiquid("mushroomsoup").setRenderingIcon(MineFactoryReloadedCore.mushroomSoupLiquid.getBlockTextureFromSide(1)).setTextureSheet("/terrain.png");
}
|
diff --git a/application/app/controllers/user/ResetPasswordController.java b/application/app/controllers/user/ResetPasswordController.java
index 01933c57..a6abe026 100644
--- a/application/app/controllers/user/ResetPasswordController.java
+++ b/application/app/controllers/user/ResetPasswordController.java
@@ -1,246 +1,246 @@
package controllers.user;
import com.avaje.ebean.Ebean;
import controllers.EController;
import controllers.util.PasswordHasher;
import models.EMessages;
import models.data.Link;
import models.dbentities.ClassGroup;
import models.dbentities.UserModel;
import models.mail.EMail;
import models.mail.ForgotPwdMail;
import models.mail.StudentTeacherEmailReset;
import models.user.Independent;
import play.data.Form;
import play.data.validation.Constraints.Required;
import play.mvc.Result;
import views.html.commons.noaccess;
import views.html.forgotPwd;
import views.html.login.resetPwd;
import javax.mail.MessagingException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
public class ResetPasswordController extends EController {
private static SecureRandom secureRandom = new SecureRandom();
/**
* This method is called when a user hits the 'Forgot Password' button.
*
* @return forgot_pwd page
*/
public static Result forgotPwd() {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form(ForgotPwd.class)
));
}
/**
* This method sends an email when the user requests a new password.
* @return page after user tried to request a new pwd
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
- flash("error", EMessages.get("error.text"));
+ flash("error", EMessages.get("error.invalid_id"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
/**
* The method is called when the user clicks in the email on the provided link.
* The purpose of this method is to generate a new time-based token to verify the
* form validity and the provide a new view for the users to enter his new password.
*
* @param token the generated token <url>?token=TOKEN
* @return if the provided token is valid, this method will return a view for the user to set his new password.
*/
public static Result receivePasswordResetToken(String token) {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link(EMessages.get("app.home"), "/"));
breadcrumbs.add(new Link(EMessages.get("app.signUp"), "/signup"));
UserModel userModel = Ebean.find(UserModel.class).where().eq("reset_token", token).findUnique();
if (userModel == null) {
return ok(noaccess.render(breadcrumbs));
} else {
Form<ResetPasswordVerify> reset_form = form(ResetPasswordVerify.class);
// old token that is being re-used?
// generate new token to send back to the client to make sure that we don't get a random request.
// it's import that time is included in this token.
String secure_token = new BigInteger(130, secureRandom).toString(32);
Long unixTime = System.currentTimeMillis() / 1000L;
secure_token = secure_token + unixTime.toString();
userModel.reset_token = secure_token;
// Save new token.
userModel.save();
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
reset_form,
secure_token
));
}
}
/**
* This method is called when the users filled in his new password.
* The purpose of this method is to calculate the new hash value of the password and store it into the database
*
* @return page after try to reset pwd
* @throws Exception
*/
public static Result resetPassword() throws Exception {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link(EMessages.get("app.home"), "/"));
breadcrumbs.add(new Link(EMessages.get("app.signUp"), "/signup"));
Form<ResetPasswordVerify> form = form(ResetPasswordVerify.class).bindFromRequest();
String id = form.get().bebras_id;
String reset_token = form.get().reset_token;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
// We perform some checks on the server side (view can be skipped).
if (userModel == null || userModel.reset_token.isEmpty() || !form.get().r_password.equals(form.get().controle_passwd)) {
return ok(noaccess.render(breadcrumbs));
}
String reset_token_database = userModel.reset_token;
Long time_check = Long.parseLong(reset_token_database.substring(26, reset_token_database.length()));
Long system_time_check = (System.currentTimeMillis() / 1000L);
// 1 min time to fill in new password
if (reset_token.equals(reset_token_database) && (system_time_check - time_check) < 60) {
PasswordHasher.SaltAndPassword sp = PasswordHasher.generateSP(form.get().r_password.toCharArray());
String passwordHEX = sp.password;
String saltHEX = sp.salt;
userModel.password = passwordHEX;
userModel.hash = saltHEX;
userModel.reset_token = "";
userModel.save();
flash("success", EMessages.get("forgot_pwd.reset_success"));
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form,
reset_token
));
} else {
flash("error", EMessages.get("forgot_pwd.reset_fail"));
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form,
reset_token
));
}
}
/**
* Inline class that contains public fields for play forms.
*/
public static class ForgotPwd {
@Required
public String id;
public String email;
}
/**
* Inline class that contains public fields for play forms.
*/
public static class ResetPasswordVerify {
public String bebras_id;
public String r_password;
public String controle_passwd;
public String reset_token;
}
}
| true | true | public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
| public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
flash("error", EMessages.get("error.invalid_id"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
|
diff --git a/src/net/brainvitamins/kerberos/KerberosCallbackArray.java b/src/net/brainvitamins/kerberos/KerberosCallbackArray.java
index 042fedf..701ff37 100644
--- a/src/net/brainvitamins/kerberos/KerberosCallbackArray.java
+++ b/src/net/brainvitamins/kerberos/KerberosCallbackArray.java
@@ -1,47 +1,47 @@
package net.brainvitamins.kerberos;
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import javax.security.auth.callback.Callback;
/**
* A data type the encapsulates the prompts from the native library and a
* reference to the Java intermediary between the UI and the native code.
*
* The Callback type is used because it's built-in: the callback mechanism
* depends on Android Messages, which don't play nicely with the classic
* callback mechanism.
*/
public class KerberosCallbackArray {
Callback[] callbacks;
public Callback[] getCallbacks() {
return callbacks;
}
AuthenticationDialogHandler source;
public AuthenticationDialogHandler getSource() {
return source;
}
- public KerberosCallbackArray(Callback[] callbacks, KinitOperation source) {
+ public KerberosCallbackArray(Callback[] callbacks, AuthenticationDialogHandler source) {
super();
this.callbacks = callbacks;
this.source = source;
}
}
| true | true | public KerberosCallbackArray(Callback[] callbacks, KinitOperation source) {
super();
this.callbacks = callbacks;
this.source = source;
}
| public KerberosCallbackArray(Callback[] callbacks, AuthenticationDialogHandler source) {
super();
this.callbacks = callbacks;
this.source = source;
}
|
diff --git a/src/main/java/org/iplantc/de/client/notifications/views/NotificationListView.java b/src/main/java/org/iplantc/de/client/notifications/views/NotificationListView.java
index b2c12155..e85b5848 100644
--- a/src/main/java/org/iplantc/de/client/notifications/views/NotificationListView.java
+++ b/src/main/java/org/iplantc/de/client/notifications/views/NotificationListView.java
@@ -1,433 +1,436 @@
/**
*
*/
package org.iplantc.de.client.notifications.views;
import java.util.List;
import org.iplantc.core.jsonutil.JsonUtil;
import org.iplantc.core.uicommons.client.ErrorHandler;
import org.iplantc.core.uicommons.client.events.EventBus;
import org.iplantc.core.uicommons.client.info.IplantAnnouncer;
import org.iplantc.core.uicommons.client.widgets.IPlantAnchor;
import org.iplantc.de.client.DeResources;
import org.iplantc.de.client.I18N;
import org.iplantc.de.client.events.NotificationCountUpdateEvent;
import org.iplantc.de.client.events.WindowShowRequestEvent;
import org.iplantc.de.client.notifications.events.DeleteNotificationsUpdateEvent;
import org.iplantc.de.client.notifications.events.DeleteNotificationsUpdateEventHandler;
import org.iplantc.de.client.notifications.models.Notification;
import org.iplantc.de.client.notifications.models.NotificationAutoBeanFactory;
import org.iplantc.de.client.notifications.models.NotificationMessage;
import org.iplantc.de.client.notifications.models.NotificationMessageProperties;
import org.iplantc.de.client.notifications.models.payload.PayloadAnalysis;
import org.iplantc.de.client.notifications.services.MessageServiceFacade;
import org.iplantc.de.client.notifications.services.NotificationCallback;
import org.iplantc.de.client.notifications.util.NotificationHelper;
import org.iplantc.de.client.notifications.util.NotificationHelper.Category;
import org.iplantc.de.client.utils.NotifyInfo;
import org.iplantc.de.client.views.windows.configs.ConfigFactory;
import com.google.common.collect.Lists;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.sencha.gxt.cell.core.client.SimpleSafeHtmlCell;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.XTemplates;
import com.sencha.gxt.core.client.resources.CommonStyles;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.SortDir;
import com.sencha.gxt.data.shared.Store.StoreSortInfo;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.ListViewCustomAppearance;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
/**
* New notifications as list
*
* @author sriram
*
*/
public class NotificationListView implements IsWidget {
private ListView<NotificationMessage, NotificationMessage> view;
private ListStore<NotificationMessage> store;
private int total_unseen;
private final HorizontalPanel hyperlinkPanel;
private boolean unseenNotificationsFetchedOnce;
/**
* @return the unseenNotificationsFetchedOnce
*/
public boolean isUnseenNotificationsFetchedOnce() {
return unseenNotificationsFetchedOnce;
}
/**
* @param unseenNotificationsFetchedOnce the unseenNotificationsFetchedOnce to set
*/
public void setUnseenNotificationsFetchedOnce(boolean unseenNotificationsFetchedOnce) {
this.unseenNotificationsFetchedOnce = unseenNotificationsFetchedOnce;
}
public static final int NEW_NOTIFICATIONS_LIMIT = 10;
final Resources resources = GWT.create(Resources.class);
final DeResources deRes = GWT.create(DeResources.class);
final Style style = resources.css();
final Renderer r = GWT.create(Renderer.class);
private final NotificationAutoBeanFactory notificationFactory = GWT
.create(NotificationAutoBeanFactory.class);
private final EventBus eventBus;
interface Renderer extends XTemplates {
@XTemplate("<div class=\"{style.thumb}\"> {msg.message}</div>")
public SafeHtml renderItem(NotificationMessage msg, Style style);
@XTemplate("<div class=\"{style.thumb_highlight}\"> {msg.message}</div>")
public SafeHtml renderItemWithHighlight(NotificationMessage msg, Style style);
}
interface Style extends CssResource {
String over();
String select();
String thumb();
String thumbWrap();
String thumb_highlight();
}
interface Resources extends ClientBundle {
@Source("NotificationListView.css")
Style css();
}
ModelKeyProvider<NotificationMessage> kp = new ModelKeyProvider<NotificationMessage>() {
@Override
public String getKey(NotificationMessage item) {
return item.getTimestamp() + "";
}
};
ListViewCustomAppearance<NotificationMessage> appearance = new ListViewCustomAppearance<NotificationMessage>(
"." + style.thumbWrap(), style.over(), style.select()) {
@Override
public void renderEnd(SafeHtmlBuilder builder) {
String markup = new StringBuilder("<div class=\"").append(CommonStyles.get().clear())
.append("\"></div>").toString();
builder.appendHtmlConstant(markup);
}
@Override
public void renderItem(SafeHtmlBuilder builder, SafeHtml content) {
builder.appendHtmlConstant("<div class='" + style.thumbWrap() + "'>");
builder.append(content);
builder.appendHtmlConstant("</div>");
}
};
private HorizontalPanel emptyTextPnl;
public NotificationListView(EventBus eventBus) {
this.eventBus = eventBus;
resources.css().ensureInjected();
deRes.css().ensureInjected();
initListeners();
hyperlinkPanel = new HorizontalPanel();
hyperlinkPanel.setSpacing(2);
updateNotificationLink();
}
private void initListeners() {
EventBus.getInstance().addHandler(DeleteNotificationsUpdateEvent.TYPE,
new DeleteNotificationsUpdateEventHandler() {
@Override
public void onDelete(DeleteNotificationsUpdateEvent event) {
if (event.getMessages() != null) {
for (NotificationMessage deleted : event.getMessages()) {
NotificationMessage nm = store.findModel(deleted);
if (nm != null) {
store.remove(nm);
}
}
} else {
store.clear();
}
if (store.getAll().size() == 0) {
emptyTextPnl.setVisible(true);
}
}
});
}
public void highlightNewNotifications() {
// List<NotificationMessage> new_notifications = store.getAll();
// TODO: implement higlight
}
//
public void markAsSeen() {
java.util.List<NotificationMessage> new_notifications = store.getAll();
JSONArray arr = new JSONArray();
int i = 0;
for (NotificationMessage n : new_notifications) {
if (!n.isSeen()) {
arr.set(i++, new JSONString(n.getId().toString()));
n.setSeen(true);
}
}
if (arr.size() > 0) {
JSONObject obj = new JSONObject();
obj.put("uuids", arr);
org.iplantc.de.client.notifications.services.MessageServiceFacade facade = new org.iplantc.de.client.notifications.services.MessageServiceFacade();
facade.markAsSeen(obj, new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
JSONObject obj = JsonUtil.getObject(result);
int new_count = Integer.parseInt(JsonUtil.getString(obj, "count"));
NotificationCountUpdateEvent event = new NotificationCountUpdateEvent(new_count);
EventBus.getInstance().fireEvent(event);
view.refresh();
}
@Override
public void onFailure(Throwable caught) {
org.iplantc.core.uicommons.client.ErrorHandler.post(caught);
}
});
}
}
public void fetchUnseenNotifications() {
MessageServiceFacade facadeMessageService = new MessageServiceFacade();
facadeMessageService.getRecentMessages(new NotificationCallback() {
@Override
public void onSuccess(String result) {
super.onSuccess(result);
processMessages(this.getNotifications());
unseenNotificationsFetchedOnce = true;
}
});
}
/**
* Process notifications
*
* @param list of notifications to be processed.
*/
public void processMessages(final List<Notification> notifications) {
// cache before removing
// KLUDGE Apparently ListStore.getAll in GXT 3.0.1 and GWT 2.5.0 does not really create a copy of
// the store contents.
List<NotificationMessage> temp = Lists.newArrayList(store.getAll());
store.clear();
store.clearSortInfo();
boolean displayInfo = false;
int total_msg_popup = 0;
for (Notification n : notifications) {
NotificationMessage nm = n.getMessage();
nm.setSeen(n.isSeen());
store.add(nm);
if (unseenNotificationsFetchedOnce && !nm.isSeen() && !isExist(temp, nm)
&& total_msg_popup < NEW_NOTIFICATIONS_LIMIT) {
displayNotificationPopup(nm);
total_msg_popup++;
displayInfo = true;
}
}
if (total_unseen > NEW_NOTIFICATIONS_LIMIT && displayInfo) {
NotifyInfo.display(I18N.DISPLAY.newNotificationsAlert());
}
if (store.getAll().size() > 0) {
emptyTextPnl.setVisible(false);
} else {
emptyTextPnl.setVisible(true);
}
NotificationMessageProperties props = GWT.create(NotificationMessageProperties.class);
store.addSortInfo(new StoreSortInfo<NotificationMessage>(props.timestamp(), SortDir.DESC));
highlightNewNotifications();
}
private void displayNotificationPopup(NotificationMessage msg) {
if (Category.ANALYSIS.equals(msg.getCategory())) {
PayloadAnalysis analysisPayload = AutoBeanCodex.decode(notificationFactory,
PayloadAnalysis.class, msg.getContext()).as();
if ("Failed".equals(analysisPayload.getStatus())) { //$NON-NLS-1$
NotifyInfo.displayWarning(msg.getMessage());
return;
}
}
NotifyInfo.display(msg.getMessage());
}
private boolean isExist(List<NotificationMessage> list, NotificationMessage n) {
for (NotificationMessage noti : list) {
if (noti.getId().equals(n.getId())) {
return true;
}
}
return false;
}
public void setUnseenCount(int count) {
this.total_unseen = count;
updateNotificationLink();
}
public void updateNotificationLink() {
hyperlinkPanel.clear();
hyperlinkPanel.add(buildNotificationHyerlink());
if (total_unseen > 0) {
hyperlinkPanel.add(buildAckAllHyperlink());
}
}
private IPlantAnchor buildAckAllHyperlink() {
IPlantAnchor link = new IPlantAnchor(I18N.DISPLAY.markAllasSeen(), -1, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
MessageServiceFacade facade = new MessageServiceFacade();
facade.acknowledgeAll(new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
ErrorHandler.post(caught);
}
@Override
public void onSuccess(String result) {
IplantAnnouncer.getInstance().schedule(I18N.DISPLAY.markAllasSeenSuccess());
}
});
}
});
return link;
}
private IPlantAnchor buildNotificationHyerlink() {
String displayText;
if (total_unseen > 0) {
displayText = I18N.DISPLAY.newNotifications() + " (" + total_unseen + ")";
} else {
displayText = I18N.DISPLAY.allNotifications();
}
IPlantAnchor link = new IPlantAnchor(displayText, -1, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (total_unseen > 0) {
showNotificationWindow(NotificationHelper.Category.NEW);
} else {
showNotificationWindow(NotificationHelper.Category.ALL);
}
}
});
return link;
}
/** Makes the notification window visible and filters by a category */
private void showNotificationWindow(final Category category) {
eventBus.fireEvent(new WindowShowRequestEvent(ConfigFactory.notifyWindowConfig(category)));
}
private HorizontalPanel getEmptyTextPanel() {
emptyTextPnl = new HorizontalPanel();
if (store != null && store.getAll().size() == 0) {
emptyTextPnl.add(new HTML("<span style='font-size:11px;'>"
+ I18N.DISPLAY.noNewNotifications() + "</span>"));
}
emptyTextPnl.setHeight("30px");
return emptyTextPnl;
}
@Override
public Widget asWidget() {
VerticalLayoutContainer container = new VerticalLayoutContainer();
container.setBorders(false);
store = new ListStore<NotificationMessage>(kp);
view = new ListView<NotificationMessage, NotificationMessage>(store,
new IdentityValueProvider<NotificationMessage>(), appearance);
view.getSelectionModel().addSelectionChangedHandler(
new SelectionChangedHandler<NotificationMessage>() {
@Override
public void onSelectionChanged(SelectionChangedEvent<NotificationMessage> event) {
- final NotificationMessage msg = event.getSelection().get(0);
- if (msg != null) {
- NotificationHelper.getInstance().view(msg);
+ List<NotificationMessage> selected = event.getSelection();
+ if (selected != null && !selected.isEmpty()) {
+ NotificationMessage msg = selected.get(0);
+ if (msg != null) {
+ NotificationHelper.getInstance().view(msg);
+ }
}
}
});
view.setCell(new SimpleSafeHtmlCell<NotificationMessage>(
new AbstractSafeHtmlRenderer<NotificationMessage>() {
@Override
public SafeHtml render(NotificationMessage object) {
if (object.isSeen()) {
return r.renderItem(object, style);
} else {
return r.renderItemWithHighlight(object, style);
}
}
}));
view.setSize("250px", "220px");
view.setBorders(false);
container.add(getEmptyTextPanel());
container.add(view);
hyperlinkPanel.setHeight("30px");
container.add(hyperlinkPanel);
return container;
}
}
| true | true | public Widget asWidget() {
VerticalLayoutContainer container = new VerticalLayoutContainer();
container.setBorders(false);
store = new ListStore<NotificationMessage>(kp);
view = new ListView<NotificationMessage, NotificationMessage>(store,
new IdentityValueProvider<NotificationMessage>(), appearance);
view.getSelectionModel().addSelectionChangedHandler(
new SelectionChangedHandler<NotificationMessage>() {
@Override
public void onSelectionChanged(SelectionChangedEvent<NotificationMessage> event) {
final NotificationMessage msg = event.getSelection().get(0);
if (msg != null) {
NotificationHelper.getInstance().view(msg);
}
}
});
view.setCell(new SimpleSafeHtmlCell<NotificationMessage>(
new AbstractSafeHtmlRenderer<NotificationMessage>() {
@Override
public SafeHtml render(NotificationMessage object) {
if (object.isSeen()) {
return r.renderItem(object, style);
} else {
return r.renderItemWithHighlight(object, style);
}
}
}));
view.setSize("250px", "220px");
view.setBorders(false);
container.add(getEmptyTextPanel());
container.add(view);
hyperlinkPanel.setHeight("30px");
container.add(hyperlinkPanel);
return container;
}
| public Widget asWidget() {
VerticalLayoutContainer container = new VerticalLayoutContainer();
container.setBorders(false);
store = new ListStore<NotificationMessage>(kp);
view = new ListView<NotificationMessage, NotificationMessage>(store,
new IdentityValueProvider<NotificationMessage>(), appearance);
view.getSelectionModel().addSelectionChangedHandler(
new SelectionChangedHandler<NotificationMessage>() {
@Override
public void onSelectionChanged(SelectionChangedEvent<NotificationMessage> event) {
List<NotificationMessage> selected = event.getSelection();
if (selected != null && !selected.isEmpty()) {
NotificationMessage msg = selected.get(0);
if (msg != null) {
NotificationHelper.getInstance().view(msg);
}
}
}
});
view.setCell(new SimpleSafeHtmlCell<NotificationMessage>(
new AbstractSafeHtmlRenderer<NotificationMessage>() {
@Override
public SafeHtml render(NotificationMessage object) {
if (object.isSeen()) {
return r.renderItem(object, style);
} else {
return r.renderItemWithHighlight(object, style);
}
}
}));
view.setSize("250px", "220px");
view.setBorders(false);
container.add(getEmptyTextPanel());
container.add(view);
hyperlinkPanel.setHeight("30px");
container.add(hyperlinkPanel);
return container;
}
|
diff --git a/editor/src/main/java/kkckkc/jsourcepad/util/ui/KeyStrokeUtils.java b/editor/src/main/java/kkckkc/jsourcepad/util/ui/KeyStrokeUtils.java
index 45a3275..0015c38 100644
--- a/editor/src/main/java/kkckkc/jsourcepad/util/ui/KeyStrokeUtils.java
+++ b/editor/src/main/java/kkckkc/jsourcepad/util/ui/KeyStrokeUtils.java
@@ -1,32 +1,32 @@
package kkckkc.jsourcepad.util.ui;
import javax.swing.*;
import java.awt.event.KeyEvent;
public class KeyStrokeUtils {
public static boolean matches(KeyStroke keyStroke, KeyEvent ks) {
if (keyStroke == null) return false;
char keyChar = ks.getKeyChar();
int keyCode = ks.getKeyCode();
if (keyChar < 0x20) {
if (keyChar != keyCode) {
keyChar += 0x40;
if ((keyChar >= 'A') && (keyChar <= 'Z')) {
keyChar += 0x20;
}
}
}
return
(keyStroke.getModifiers() & 0xF) == (ks.getModifiers() & 0xF) &&
keyCode != 0 &&
(keyStroke.getKeyCode() == keyCode ||
(keyChar != KeyEvent.CHAR_UNDEFINED && Character.toLowerCase(keyStroke.getKeyChar()) == keyChar) ||
- (KeyEvent.getKeyText(keyCode).charAt(0) == keyStroke.getKeyChar()));
+ (KeyEvent.getKeyText(keyCode).length() == 1 && KeyEvent.getKeyText(keyCode).charAt(0) == keyStroke.getKeyChar()));
}
}
| true | true | public static boolean matches(KeyStroke keyStroke, KeyEvent ks) {
if (keyStroke == null) return false;
char keyChar = ks.getKeyChar();
int keyCode = ks.getKeyCode();
if (keyChar < 0x20) {
if (keyChar != keyCode) {
keyChar += 0x40;
if ((keyChar >= 'A') && (keyChar <= 'Z')) {
keyChar += 0x20;
}
}
}
return
(keyStroke.getModifiers() & 0xF) == (ks.getModifiers() & 0xF) &&
keyCode != 0 &&
(keyStroke.getKeyCode() == keyCode ||
(keyChar != KeyEvent.CHAR_UNDEFINED && Character.toLowerCase(keyStroke.getKeyChar()) == keyChar) ||
(KeyEvent.getKeyText(keyCode).charAt(0) == keyStroke.getKeyChar()));
}
| public static boolean matches(KeyStroke keyStroke, KeyEvent ks) {
if (keyStroke == null) return false;
char keyChar = ks.getKeyChar();
int keyCode = ks.getKeyCode();
if (keyChar < 0x20) {
if (keyChar != keyCode) {
keyChar += 0x40;
if ((keyChar >= 'A') && (keyChar <= 'Z')) {
keyChar += 0x20;
}
}
}
return
(keyStroke.getModifiers() & 0xF) == (ks.getModifiers() & 0xF) &&
keyCode != 0 &&
(keyStroke.getKeyCode() == keyCode ||
(keyChar != KeyEvent.CHAR_UNDEFINED && Character.toLowerCase(keyStroke.getKeyChar()) == keyChar) ||
(KeyEvent.getKeyText(keyCode).length() == 1 && KeyEvent.getKeyText(keyCode).charAt(0) == keyStroke.getKeyChar()));
}
|
diff --git a/lucene/src/java/org/apache/lucene/search/FieldDoc.java b/lucene/src/java/org/apache/lucene/search/FieldDoc.java
index d45ff2687..faf54a079 100644
--- a/lucene/src/java/org/apache/lucene/search/FieldDoc.java
+++ b/lucene/src/java/org/apache/lucene/search/FieldDoc.java
@@ -1,75 +1,75 @@
package org.apache.lucene.search;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Expert: A ScoreDoc which also contains information about
* how to sort the referenced document. In addition to the
* document number and score, this object contains an array
* of values for the document from the field(s) used to sort.
* For example, if the sort criteria was to sort by fields
* "a", "b" then "c", the <code>fields</code> object array
* will have three elements, corresponding respectively to
* the term values for the document in fields "a", "b" and "c".
* The class of each element in the array will be either
* Integer, Float or String depending on the type of values
* in the terms of each field.
*
* <p>Created: Feb 11, 2004 1:23:38 PM
*
* @since lucene 1.4
* @see ScoreDoc
* @see TopFieldDocs
*/
public class FieldDoc extends ScoreDoc {
/** Expert: The values which are used to sort the referenced document.
* The order of these will match the original sort criteria given by a
* Sort object. Each Object will be either an Integer, Float or String,
* depending on the type of values in the terms of the original field.
* @see Sort
* @see Searcher#search(Query,Filter,int,Sort)
*/
public Comparable[] fields;
/** Expert: Creates one of these objects with empty sort information. */
public FieldDoc (int doc, float score) {
super (doc, score);
}
/** Expert: Creates one of these objects with the given sort information. */
public FieldDoc (int doc, float score, Comparable[] fields) {
super (doc, score);
this.fields = fields;
}
// A convenience method for debugging.
@Override
public String toString() {
// super.toString returns the doc and score information, so just add the
// fields information
StringBuilder sb = new StringBuilder(super.toString());
sb.append("[");
for (int i = 0; i < fields.length; i++) {
sb.append(fields[i]).append(", ");
}
sb.setLength(sb.length() - 2); // discard last ", "
sb.append("]");
- return super.toString();
+ return sb.toString();
}
}
| true | true | public String toString() {
// super.toString returns the doc and score information, so just add the
// fields information
StringBuilder sb = new StringBuilder(super.toString());
sb.append("[");
for (int i = 0; i < fields.length; i++) {
sb.append(fields[i]).append(", ");
}
sb.setLength(sb.length() - 2); // discard last ", "
sb.append("]");
return super.toString();
}
| public String toString() {
// super.toString returns the doc and score information, so just add the
// fields information
StringBuilder sb = new StringBuilder(super.toString());
sb.append("[");
for (int i = 0; i < fields.length; i++) {
sb.append(fields[i]).append(", ");
}
sb.setLength(sb.length() - 2); // discard last ", "
sb.append("]");
return sb.toString();
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java
index 9f87dff7..504a4c3a 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java
@@ -1,161 +1,161 @@
package net.sourceforge.vrapper.vim.modes.commandline;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.commands.CloseCommand;
import net.sourceforge.vrapper.vim.commands.Command;
import net.sourceforge.vrapper.vim.commands.CommandExecutionException;
import net.sourceforge.vrapper.vim.commands.ConfigCommand;
import net.sourceforge.vrapper.vim.commands.MotionCommand;
import net.sourceforge.vrapper.vim.commands.RedoCommand;
import net.sourceforge.vrapper.vim.commands.SaveCommand;
import net.sourceforge.vrapper.vim.commands.UndoCommand;
import net.sourceforge.vrapper.vim.commands.VimCommandSequence;
import net.sourceforge.vrapper.vim.commands.motions.GoToLineMotion;
import net.sourceforge.vrapper.vim.modes.AbstractVisualMode;
import net.sourceforge.vrapper.vim.modes.InsertMode;
import net.sourceforge.vrapper.vim.modes.NormalMode;
import net.sourceforge.vrapper.vim.modes.VisualMode;
/**
* Command Line Mode, activated with ':'.
*
* @author Matthias Radig
*/
public class CommandLineParser extends AbstractCommandParser {
private static final EvaluatorMapping mapping;
static {
Evaluator noremap = new KeyMapper.Map(false,
AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME);
Evaluator map = new KeyMapper.Map(true,
AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME);
Evaluator nnoremap = new KeyMapper.Map(false, NormalMode.KEYMAP_NAME);
Evaluator nmap = new KeyMapper.Map(true, NormalMode.KEYMAP_NAME);
Evaluator vnoremap = new KeyMapper.Map(false, VisualMode.KEYMAP_NAME);
Evaluator vmap = new KeyMapper.Map(true, VisualMode.KEYMAP_NAME);
Evaluator inoremap = new KeyMapper.Map(false, InsertMode.KEYMAP_NAME);
Evaluator imap = new KeyMapper.Map(true, InsertMode.KEYMAP_NAME);
Command save = new SaveCommand();
CloseCommand close = new CloseCommand(false);
Command saveAndClose = new VimCommandSequence(save, close);
Evaluator unmap = new KeyMapper.Unmap(AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME);
Evaluator nunmap = new KeyMapper.Unmap(NormalMode.KEYMAP_NAME);
Evaluator vunmap = new KeyMapper.Unmap(AbstractVisualMode.KEYMAP_NAME);
Evaluator iunmap = new KeyMapper.Unmap(InsertMode.KEYMAP_NAME);
Evaluator clear = new KeyMapper.Clear(AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME);
Evaluator nclear = new KeyMapper.Clear(NormalMode.KEYMAP_NAME);
Evaluator vclear = new KeyMapper.Clear(AbstractVisualMode.KEYMAP_NAME);
Evaluator iclear = new KeyMapper.Clear(InsertMode.KEYMAP_NAME);
Command gotoEOF = new MotionCommand(GoToLineMotion.LAST_LINE);
mapping = new EvaluatorMapping();
// options
mapping.add("set", buildConfigEvaluator());
// save, close
mapping.add("w", save);
mapping.add("wq", saveAndClose);
mapping.add("x", saveAndClose);
mapping.add("q", close);
mapping.add("q!", new CloseCommand(true));
// non-recursive mapping
mapping.add("noremap", noremap);
mapping.add("no", noremap);
mapping.add("nnoremap", nnoremap);
mapping.add("nn", nnoremap);
mapping.add("inoremap", inoremap);
mapping.add("ino", inoremap);
mapping.add("vnoremap", vnoremap);
mapping.add("vn", vnoremap);
// recursive mapping
mapping.add("map", map);
mapping.add("nmap", nmap);
mapping.add("nm", nmap);
mapping.add("imap", imap);
mapping.add("im", imap);
mapping.add("vmap", vmap);
mapping.add("vm", vmap);
// unmapping
mapping.add("unmap", unmap);
mapping.add("unm", unmap);
mapping.add("nunmap", nunmap);
mapping.add("nun", nunmap);
mapping.add("vunmap", vunmap);
mapping.add("vu", vunmap);
mapping.add("iunmap", iunmap);
mapping.add("iu", iunmap);
// clearing maps
mapping.add("mapclear", clear);
mapping.add("mapc", clear);
mapping.add("nmapclear", nclear);
mapping.add("nmapc", nclear);
mapping.add("vmapclear", vclear);
mapping.add("vmapc", vclear);
mapping.add("imapclear", iclear);
mapping.add("imapc", iclear);
UndoCommand undo = new UndoCommand();
RedoCommand redo = new RedoCommand();
mapping.add("red", redo);
mapping.add("redo", redo);
mapping.add("undo", undo);
mapping.add("u", undo);
mapping.add("$", new CommandWrapper(gotoEOF));
}
private static Evaluator buildConfigEvaluator() {
EvaluatorMapping config = new EvaluatorMapping();
config.add("autoindent", ConfigCommand.AUTO_INDENT);
config.add("noautoindent", ConfigCommand.NO_AUTO_INDENT);
config.add("smartindent", ConfigCommand.SMART_INDENT);
config.add("nosmartindent", ConfigCommand.NO_SMART_INDENT);
config.add("globalregisters", ConfigCommand.GLOBAL_REGISTERS);
config.add("noglobalregisters", ConfigCommand.LOCAL_REGISTERS);
config.add("linewisemouse", ConfigCommand.LINE_WISE_MOUSE_SELECTION);
config.add("nolinewisemouse", ConfigCommand.NO_LINE_WISE_MOUSE_SELECTION);
config.add("startofline", ConfigCommand.START_OF_LINE);
config.add("nostartofline", ConfigCommand.NO_START_OF_LINE);
config.add("sol", ConfigCommand.START_OF_LINE);
config.add("nosol", ConfigCommand.NO_START_OF_LINE);
return config;
}
public CommandLineParser(EditorAdaptor vim) {
super(vim);
}
@Override
public void parseAndExecute(String first, String command) {
try {
// if the command is a number, jump to the given line
int line = Integer.parseInt(command);
new MotionCommand(GoToLineMotion.FIRST_LINE).execute(editor, line);
return;
} catch (NumberFormatException e) {
// do nothing
} catch (CommandExecutionException e) {
editor.getUserInterfaceService().setErrorMessage(e.getMessage());
return;
}
StringTokenizer nizer = new StringTokenizer(command);
Queue<String> tokens = new LinkedList<String>();
while (nizer.hasMoreTokens()) {
tokens.add(nizer.nextToken().trim());
}
EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands();
- if (platformCommands.contains(tokens.peek())) {
+ if (platformCommands != null && platformCommands.contains(tokens.peek())) {
platformCommands.evaluate(editor, tokens);
} else {
mapping.evaluate(editor, tokens);
}
}
public boolean addCommand(String commandName, Command command, boolean overwrite) {
if (overwrite || !mapping.contains(commandName)) {
mapping.add(commandName, command);
return true;
}
return false;
}
}
| true | true | public void parseAndExecute(String first, String command) {
try {
// if the command is a number, jump to the given line
int line = Integer.parseInt(command);
new MotionCommand(GoToLineMotion.FIRST_LINE).execute(editor, line);
return;
} catch (NumberFormatException e) {
// do nothing
} catch (CommandExecutionException e) {
editor.getUserInterfaceService().setErrorMessage(e.getMessage());
return;
}
StringTokenizer nizer = new StringTokenizer(command);
Queue<String> tokens = new LinkedList<String>();
while (nizer.hasMoreTokens()) {
tokens.add(nizer.nextToken().trim());
}
EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands();
if (platformCommands.contains(tokens.peek())) {
platformCommands.evaluate(editor, tokens);
} else {
mapping.evaluate(editor, tokens);
}
}
| public void parseAndExecute(String first, String command) {
try {
// if the command is a number, jump to the given line
int line = Integer.parseInt(command);
new MotionCommand(GoToLineMotion.FIRST_LINE).execute(editor, line);
return;
} catch (NumberFormatException e) {
// do nothing
} catch (CommandExecutionException e) {
editor.getUserInterfaceService().setErrorMessage(e.getMessage());
return;
}
StringTokenizer nizer = new StringTokenizer(command);
Queue<String> tokens = new LinkedList<String>();
while (nizer.hasMoreTokens()) {
tokens.add(nizer.nextToken().trim());
}
EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands();
if (platformCommands != null && platformCommands.contains(tokens.peek())) {
platformCommands.evaluate(editor, tokens);
} else {
mapping.evaluate(editor, tokens);
}
}
|
diff --git a/src/net/milkbowl/combatevents/CombatPlayer.java b/src/net/milkbowl/combatevents/CombatPlayer.java
index 1400d09..af61f82 100644
--- a/src/net/milkbowl/combatevents/CombatPlayer.java
+++ b/src/net/milkbowl/combatevents/CombatPlayer.java
@@ -1,81 +1,82 @@
package net.milkbowl.combatevents;
import java.util.HashMap;
import java.util.Map;
import net.milkbowl.combatevents.tasks.LeaveCombatTask;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class CombatPlayer {
private Player player;
private Map<Entity, CombatReason> reasons = new HashMap<Entity, CombatReason>(2);
private ItemStack[] inventory;
private Location lastLocation;
private int taskId;
public CombatPlayer(Player player, CombatReason reason, Entity entity, CombatEventsCore plugin) {
this.player = player;
this.lastLocation = player.getLocation();
this.inventory = player.getInventory().getContents();
reasons.put(entity, reason);
+ CombatReason[] combatReasons = new CombatReason[] {reason};
//if we create a new object always force the player into combat so make a new scheduler for leaving combat
- taskId = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new LeaveCombatTask(player, LeaveCombatReason.TIMED, (CombatReason[]) reasons.values().toArray(), plugin), Config.getCombatTime() * 20);
+ taskId = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new LeaveCombatTask(player, LeaveCombatReason.TIMED, combatReasons, plugin), Config.getCombatTime() * 20);
}
public Map<Entity, CombatReason> getReasonMap() {
return reasons;
}
public void addReason(Entity entity, CombatReason reason) {
this.reasons.put(entity, reason);
}
public CombatReason getReason(Entity entity) {
return this.reasons.get(entity);
}
public CombatReason[] getReasons() {
return (CombatReason[]) this.reasons.values().toArray();
}
public CombatReason removeReason(Entity entity) {
return this.reasons.remove(entity);
}
public void clearReasons() {
this.reasons.clear();
}
public ItemStack[] getInventory() {
return inventory;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public Location getLastLocation() {
return lastLocation;
}
public void setLastLocation(Location lastLocation) {
this.lastLocation = lastLocation;
}
public Player getPlayer() {
return player;
}
public int getTaskId() {
return taskId;
}
public void setTaskId(int taskId) {
this.taskId = taskId;
}
}
| false | true | public CombatPlayer(Player player, CombatReason reason, Entity entity, CombatEventsCore plugin) {
this.player = player;
this.lastLocation = player.getLocation();
this.inventory = player.getInventory().getContents();
reasons.put(entity, reason);
//if we create a new object always force the player into combat so make a new scheduler for leaving combat
taskId = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new LeaveCombatTask(player, LeaveCombatReason.TIMED, (CombatReason[]) reasons.values().toArray(), plugin), Config.getCombatTime() * 20);
}
| public CombatPlayer(Player player, CombatReason reason, Entity entity, CombatEventsCore plugin) {
this.player = player;
this.lastLocation = player.getLocation();
this.inventory = player.getInventory().getContents();
reasons.put(entity, reason);
CombatReason[] combatReasons = new CombatReason[] {reason};
//if we create a new object always force the player into combat so make a new scheduler for leaving combat
taskId = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new LeaveCombatTask(player, LeaveCombatReason.TIMED, combatReasons, plugin), Config.getCombatTime() * 20);
}
|
diff --git a/TargetClassification/src/featureselection/MultipleForestRunAndTest.java b/TargetClassification/src/featureselection/MultipleForestRunAndTest.java
index 5dbd12b..281e5b6 100644
--- a/TargetClassification/src/featureselection/MultipleForestRunAndTest.java
+++ b/TargetClassification/src/featureselection/MultipleForestRunAndTest.java
@@ -1,176 +1,199 @@
package featureselection;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import tree.Forest;
import tree.TreeGrowthControl;
public class MultipleForestRunAndTest
{
/**
* @param confusionMatrix
* @param weights
* @param ctrl
* @param inputFile
* @param seeds
* @param repetitions
* @param negClass
* @param posClass
* @param resultsLocation
* @param mccResultsLocation
* @param analysisBeingRun - 1 for weight and mtry, 2 for sample size and 3 for node size.
*/
static void forestTraining(Map<String, Map<String, Double>> confusionMatrix,
Map<String, Double> weights, TreeGrowthControl ctrl, String inputFile, List<Long> seeds, int repetitions,
String negClass, String posClass, String resultsLocation, String mccResultsLocation, int analysisBeingRun)
{
double cumulativeOOBError = 0.0;
List<Double> mccValues = new ArrayList<Double>();
long oobTime = 0l;
Date startTime;
Date endTime;
for (int j = 0; j < repetitions; j++)
{
// Get the seed for this repetition.
long seed = seeds.get(j);
startTime = new Date();
Forest forest;
forest = new Forest(inputFile, ctrl, weights, seed);
cumulativeOOBError += forest.oobErrorEstimate;
Map<String, Map<String, Double>> oobConfMatrix = forest.oobConfusionMatrix;
for (String s : oobConfMatrix.keySet())
{
Double oldTruePos = confusionMatrix.get(s).get("TruePositive");
Double newTruePos = oldTruePos + oobConfMatrix.get(s).get("TruePositive");
confusionMatrix.get(s).put("TruePositive", newTruePos);
Double oldFalsePos = confusionMatrix.get(s).get("FalsePositive");
Double newFalsePos = oldFalsePos + oobConfMatrix.get(s).get("FalsePositive");
confusionMatrix.get(s).put("FalsePositive", newFalsePos);
}
endTime = new Date();
oobTime += endTime.getTime() - startTime.getTime();
Double oobTP = oobConfMatrix.get(posClass).get("TruePositive");
Double oobFP = oobConfMatrix.get(posClass).get("FalsePositive");
Double oobTN = oobConfMatrix.get(negClass).get("TruePositive");
Double oobFN = oobConfMatrix.get(negClass).get("FalsePositive");
mccValues.add((((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN))));
}
oobTime /= (double) repetitions;
// Aggregate OOB results over all the repetitions.
cumulativeOOBError /= repetitions;
Double oobTP = confusionMatrix.get(posClass).get("TruePositive");
Double oobFP = confusionMatrix.get(posClass).get("FalsePositive");
Double oobTN = confusionMatrix.get(negClass).get("TruePositive");
Double oobFN = confusionMatrix.get(negClass).get("FalsePositive");
Double oobSensitivityOrRecall = oobTP / (oobTP + oobFN);
Double oobSpecificity = oobTN / (oobTN + oobFP);
Double oobAccuracy = (oobTP + oobTN) / (oobTP + oobTN + oobFP + oobFN);
Double oobPrecisionOrPPV = oobTP / (oobTP + oobFP);
Double oobNegPredictiveVal = oobTN / (oobTN + oobFN);
Double oobFHalf = (1 + (0.5 * 0.5)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((0.5 * 0.5 * oobPrecisionOrPPV) + oobSensitivityOrRecall));;
Double oobFOne = 2 * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / (oobPrecisionOrPPV + oobSensitivityOrRecall));
Double oobFTwo = (1 + (2 * 2)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((2 * 2 * oobPrecisionOrPPV) + oobSensitivityOrRecall));
Double oobMCC = (((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN)));
// Write out the OOB results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(resultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
if (analysisBeingRun == 1)
{
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Integer.toString(ctrl.mtry));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 2)
{
int sampleSize = 0;
for (String s : ctrl.sampSize.keySet())
{
sampleSize += ctrl.sampSize.get(s);
}
double posClassFraction = ((double) ctrl.sampSize.get(posClass)) / sampleSize;
resultsOutputWriter.write(Integer.toString(sampleSize));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", posClassFraction));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 3)
{
resultsOutputWriter.write(Integer.toString(ctrl.minNodeSize));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.write(String.format("%.5f", oobMCC));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFHalf));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFOne));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFTwo));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobAccuracy));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", cumulativeOOBError));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobPrecisionOrPPV));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSensitivityOrRecall));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSpecificity));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobNegPredictiveVal));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Long.toString(oobTime));
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Write out the MCC results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(mccResultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
- resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
- resultsOutputWriter.write("\t");
- resultsOutputWriter.write(Integer.toString(ctrl.mtry));
- resultsOutputWriter.write("\t");
+ if (analysisBeingRun == 1)
+ {
+ resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
+ resultsOutputWriter.write("\t");
+ resultsOutputWriter.write(Integer.toString(ctrl.mtry));
+ resultsOutputWriter.write("\t");
+ }
+ else if (analysisBeingRun == 2)
+ {
+ int sampleSize = 0;
+ for (String s : ctrl.sampSize.keySet())
+ {
+ sampleSize += ctrl.sampSize.get(s);
+ }
+ double posClassFraction = ((double) ctrl.sampSize.get(posClass)) / sampleSize;
+ resultsOutputWriter.write(Integer.toString(sampleSize));
+ resultsOutputWriter.write("\t");
+ resultsOutputWriter.write(String.format("%.5f", posClassFraction));
+ resultsOutputWriter.write("\t");
+ resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
+ resultsOutputWriter.write("\t");
+ }
+ else if (analysisBeingRun == 3)
+ {
+ resultsOutputWriter.write(Integer.toString(ctrl.minNodeSize));
+ resultsOutputWriter.write("\t");
+ }
for (Double d : mccValues)
{
resultsOutputWriter.write(String.format("%.5f", d));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
| true | true | static void forestTraining(Map<String, Map<String, Double>> confusionMatrix,
Map<String, Double> weights, TreeGrowthControl ctrl, String inputFile, List<Long> seeds, int repetitions,
String negClass, String posClass, String resultsLocation, String mccResultsLocation, int analysisBeingRun)
{
double cumulativeOOBError = 0.0;
List<Double> mccValues = new ArrayList<Double>();
long oobTime = 0l;
Date startTime;
Date endTime;
for (int j = 0; j < repetitions; j++)
{
// Get the seed for this repetition.
long seed = seeds.get(j);
startTime = new Date();
Forest forest;
forest = new Forest(inputFile, ctrl, weights, seed);
cumulativeOOBError += forest.oobErrorEstimate;
Map<String, Map<String, Double>> oobConfMatrix = forest.oobConfusionMatrix;
for (String s : oobConfMatrix.keySet())
{
Double oldTruePos = confusionMatrix.get(s).get("TruePositive");
Double newTruePos = oldTruePos + oobConfMatrix.get(s).get("TruePositive");
confusionMatrix.get(s).put("TruePositive", newTruePos);
Double oldFalsePos = confusionMatrix.get(s).get("FalsePositive");
Double newFalsePos = oldFalsePos + oobConfMatrix.get(s).get("FalsePositive");
confusionMatrix.get(s).put("FalsePositive", newFalsePos);
}
endTime = new Date();
oobTime += endTime.getTime() - startTime.getTime();
Double oobTP = oobConfMatrix.get(posClass).get("TruePositive");
Double oobFP = oobConfMatrix.get(posClass).get("FalsePositive");
Double oobTN = oobConfMatrix.get(negClass).get("TruePositive");
Double oobFN = oobConfMatrix.get(negClass).get("FalsePositive");
mccValues.add((((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN))));
}
oobTime /= (double) repetitions;
// Aggregate OOB results over all the repetitions.
cumulativeOOBError /= repetitions;
Double oobTP = confusionMatrix.get(posClass).get("TruePositive");
Double oobFP = confusionMatrix.get(posClass).get("FalsePositive");
Double oobTN = confusionMatrix.get(negClass).get("TruePositive");
Double oobFN = confusionMatrix.get(negClass).get("FalsePositive");
Double oobSensitivityOrRecall = oobTP / (oobTP + oobFN);
Double oobSpecificity = oobTN / (oobTN + oobFP);
Double oobAccuracy = (oobTP + oobTN) / (oobTP + oobTN + oobFP + oobFN);
Double oobPrecisionOrPPV = oobTP / (oobTP + oobFP);
Double oobNegPredictiveVal = oobTN / (oobTN + oobFN);
Double oobFHalf = (1 + (0.5 * 0.5)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((0.5 * 0.5 * oobPrecisionOrPPV) + oobSensitivityOrRecall));;
Double oobFOne = 2 * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / (oobPrecisionOrPPV + oobSensitivityOrRecall));
Double oobFTwo = (1 + (2 * 2)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((2 * 2 * oobPrecisionOrPPV) + oobSensitivityOrRecall));
Double oobMCC = (((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN)));
// Write out the OOB results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(resultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
if (analysisBeingRun == 1)
{
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Integer.toString(ctrl.mtry));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 2)
{
int sampleSize = 0;
for (String s : ctrl.sampSize.keySet())
{
sampleSize += ctrl.sampSize.get(s);
}
double posClassFraction = ((double) ctrl.sampSize.get(posClass)) / sampleSize;
resultsOutputWriter.write(Integer.toString(sampleSize));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", posClassFraction));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 3)
{
resultsOutputWriter.write(Integer.toString(ctrl.minNodeSize));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.write(String.format("%.5f", oobMCC));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFHalf));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFOne));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFTwo));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobAccuracy));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", cumulativeOOBError));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobPrecisionOrPPV));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSensitivityOrRecall));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSpecificity));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobNegPredictiveVal));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Long.toString(oobTime));
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Write out the MCC results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(mccResultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Integer.toString(ctrl.mtry));
resultsOutputWriter.write("\t");
for (Double d : mccValues)
{
resultsOutputWriter.write(String.format("%.5f", d));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
| static void forestTraining(Map<String, Map<String, Double>> confusionMatrix,
Map<String, Double> weights, TreeGrowthControl ctrl, String inputFile, List<Long> seeds, int repetitions,
String negClass, String posClass, String resultsLocation, String mccResultsLocation, int analysisBeingRun)
{
double cumulativeOOBError = 0.0;
List<Double> mccValues = new ArrayList<Double>();
long oobTime = 0l;
Date startTime;
Date endTime;
for (int j = 0; j < repetitions; j++)
{
// Get the seed for this repetition.
long seed = seeds.get(j);
startTime = new Date();
Forest forest;
forest = new Forest(inputFile, ctrl, weights, seed);
cumulativeOOBError += forest.oobErrorEstimate;
Map<String, Map<String, Double>> oobConfMatrix = forest.oobConfusionMatrix;
for (String s : oobConfMatrix.keySet())
{
Double oldTruePos = confusionMatrix.get(s).get("TruePositive");
Double newTruePos = oldTruePos + oobConfMatrix.get(s).get("TruePositive");
confusionMatrix.get(s).put("TruePositive", newTruePos);
Double oldFalsePos = confusionMatrix.get(s).get("FalsePositive");
Double newFalsePos = oldFalsePos + oobConfMatrix.get(s).get("FalsePositive");
confusionMatrix.get(s).put("FalsePositive", newFalsePos);
}
endTime = new Date();
oobTime += endTime.getTime() - startTime.getTime();
Double oobTP = oobConfMatrix.get(posClass).get("TruePositive");
Double oobFP = oobConfMatrix.get(posClass).get("FalsePositive");
Double oobTN = oobConfMatrix.get(negClass).get("TruePositive");
Double oobFN = oobConfMatrix.get(negClass).get("FalsePositive");
mccValues.add((((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN))));
}
oobTime /= (double) repetitions;
// Aggregate OOB results over all the repetitions.
cumulativeOOBError /= repetitions;
Double oobTP = confusionMatrix.get(posClass).get("TruePositive");
Double oobFP = confusionMatrix.get(posClass).get("FalsePositive");
Double oobTN = confusionMatrix.get(negClass).get("TruePositive");
Double oobFN = confusionMatrix.get(negClass).get("FalsePositive");
Double oobSensitivityOrRecall = oobTP / (oobTP + oobFN);
Double oobSpecificity = oobTN / (oobTN + oobFP);
Double oobAccuracy = (oobTP + oobTN) / (oobTP + oobTN + oobFP + oobFN);
Double oobPrecisionOrPPV = oobTP / (oobTP + oobFP);
Double oobNegPredictiveVal = oobTN / (oobTN + oobFN);
Double oobFHalf = (1 + (0.5 * 0.5)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((0.5 * 0.5 * oobPrecisionOrPPV) + oobSensitivityOrRecall));;
Double oobFOne = 2 * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / (oobPrecisionOrPPV + oobSensitivityOrRecall));
Double oobFTwo = (1 + (2 * 2)) * ((oobPrecisionOrPPV * oobSensitivityOrRecall) / ((2 * 2 * oobPrecisionOrPPV) + oobSensitivityOrRecall));
Double oobMCC = (((oobTP * oobTN) - (oobFP * oobFN)) / Math.sqrt((oobTP + oobFP) * (oobTP + oobFN) * (oobTN + oobFP) * (oobTN + oobFN)));
// Write out the OOB results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(resultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
if (analysisBeingRun == 1)
{
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Integer.toString(ctrl.mtry));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 2)
{
int sampleSize = 0;
for (String s : ctrl.sampSize.keySet())
{
sampleSize += ctrl.sampSize.get(s);
}
double posClassFraction = ((double) ctrl.sampSize.get(posClass)) / sampleSize;
resultsOutputWriter.write(Integer.toString(sampleSize));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", posClassFraction));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 3)
{
resultsOutputWriter.write(Integer.toString(ctrl.minNodeSize));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.write(String.format("%.5f", oobMCC));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFHalf));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFOne));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFTwo));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobAccuracy));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", cumulativeOOBError));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobPrecisionOrPPV));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSensitivityOrRecall));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobSpecificity));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobNegPredictiveVal));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFP));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobTN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", oobFN));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Long.toString(oobTime));
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Write out the MCC results for this set of repetitions.
try
{
FileWriter resultsOutputFile = new FileWriter(mccResultsLocation, true);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
if (analysisBeingRun == 1)
{
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(Integer.toString(ctrl.mtry));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 2)
{
int sampleSize = 0;
for (String s : ctrl.sampSize.keySet())
{
sampleSize += ctrl.sampSize.get(s);
}
double posClassFraction = ((double) ctrl.sampSize.get(posClass)) / sampleSize;
resultsOutputWriter.write(Integer.toString(sampleSize));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", posClassFraction));
resultsOutputWriter.write("\t");
resultsOutputWriter.write(String.format("%.5f", weights.get("Positive")));
resultsOutputWriter.write("\t");
}
else if (analysisBeingRun == 3)
{
resultsOutputWriter.write(Integer.toString(ctrl.minNodeSize));
resultsOutputWriter.write("\t");
}
for (Double d : mccValues)
{
resultsOutputWriter.write(String.format("%.5f", d));
resultsOutputWriter.write("\t");
}
resultsOutputWriter.newLine();
resultsOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
|
diff --git a/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/MorphServiceImpl.java b/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/MorphServiceImpl.java
index 6f0715c..47ea1a0 100644
--- a/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/MorphServiceImpl.java
+++ b/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/MorphServiceImpl.java
@@ -1,74 +1,75 @@
package com.tistory.devyongsik.admin;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.tistory.devyongsik.config.CrescentCollectionHandler;
import com.tistory.devyongsik.domain.CrescentCollection;
import com.tistory.devyongsik.domain.MorphToken;
@Service("morphService")
public class MorphServiceImpl implements MorphService {
private Logger logger = LoggerFactory.getLogger(MorphServiceImpl.class);
@Autowired
@Qualifier("crescentCollectionHandler")
private CrescentCollectionHandler collectionHandler;
@Override
public List<MorphToken> getTokens(String keyword, boolean isIndexingMode, String collectionName) throws IOException {
StringReader reader = new StringReader(keyword);
CrescentCollection crescentCollection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Analyzer analyzer = null;
if(isIndexingMode) {
analyzer = crescentCollection.getIndexingModeAnalyzer();
} else {
analyzer = crescentCollection.getSearchModeAnalyzer();
}
TokenStream stream = analyzer.reusableTokenStream("dummy", reader);
+ stream.reset();
CharTermAttribute charTermAtt = stream.getAttribute(CharTermAttribute.class);
OffsetAttribute offSetAtt = stream.getAttribute(OffsetAttribute.class);
TypeAttribute typeAtt = stream.getAttribute(TypeAttribute.class);
List<MorphToken> resultTokenList = new ArrayList<MorphToken>();
while(stream.incrementToken()) {
Token t = new Token(charTermAtt.toString(), offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type());
logger.debug("termAtt : {}, startOffset : {}, endOffset : {}, typeAtt : {}",
new Object[] {charTermAtt.toString(),offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type()});
MorphToken mt = new MorphToken();
mt.setTerm(t.toString());
mt.setType(t.type());
mt.setStartOffset(t.startOffset());
mt.setEndOffset(t.endOffset());
resultTokenList.add(mt);
}
//analyzer.close();
return resultTokenList;
}
}
| true | true | public List<MorphToken> getTokens(String keyword, boolean isIndexingMode, String collectionName) throws IOException {
StringReader reader = new StringReader(keyword);
CrescentCollection crescentCollection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Analyzer analyzer = null;
if(isIndexingMode) {
analyzer = crescentCollection.getIndexingModeAnalyzer();
} else {
analyzer = crescentCollection.getSearchModeAnalyzer();
}
TokenStream stream = analyzer.reusableTokenStream("dummy", reader);
CharTermAttribute charTermAtt = stream.getAttribute(CharTermAttribute.class);
OffsetAttribute offSetAtt = stream.getAttribute(OffsetAttribute.class);
TypeAttribute typeAtt = stream.getAttribute(TypeAttribute.class);
List<MorphToken> resultTokenList = new ArrayList<MorphToken>();
while(stream.incrementToken()) {
Token t = new Token(charTermAtt.toString(), offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type());
logger.debug("termAtt : {}, startOffset : {}, endOffset : {}, typeAtt : {}",
new Object[] {charTermAtt.toString(),offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type()});
MorphToken mt = new MorphToken();
mt.setTerm(t.toString());
mt.setType(t.type());
mt.setStartOffset(t.startOffset());
mt.setEndOffset(t.endOffset());
resultTokenList.add(mt);
}
//analyzer.close();
return resultTokenList;
}
| public List<MorphToken> getTokens(String keyword, boolean isIndexingMode, String collectionName) throws IOException {
StringReader reader = new StringReader(keyword);
CrescentCollection crescentCollection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Analyzer analyzer = null;
if(isIndexingMode) {
analyzer = crescentCollection.getIndexingModeAnalyzer();
} else {
analyzer = crescentCollection.getSearchModeAnalyzer();
}
TokenStream stream = analyzer.reusableTokenStream("dummy", reader);
stream.reset();
CharTermAttribute charTermAtt = stream.getAttribute(CharTermAttribute.class);
OffsetAttribute offSetAtt = stream.getAttribute(OffsetAttribute.class);
TypeAttribute typeAtt = stream.getAttribute(TypeAttribute.class);
List<MorphToken> resultTokenList = new ArrayList<MorphToken>();
while(stream.incrementToken()) {
Token t = new Token(charTermAtt.toString(), offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type());
logger.debug("termAtt : {}, startOffset : {}, endOffset : {}, typeAtt : {}",
new Object[] {charTermAtt.toString(),offSetAtt.startOffset(), offSetAtt.endOffset(), typeAtt.type()});
MorphToken mt = new MorphToken();
mt.setTerm(t.toString());
mt.setType(t.type());
mt.setStartOffset(t.startOffset());
mt.setEndOffset(t.endOffset());
resultTokenList.add(mt);
}
//analyzer.close();
return resultTokenList;
}
|
diff --git a/loci/formats/in/TCSReader.java b/loci/formats/in/TCSReader.java
index a6545c990..554665dfd 100644
--- a/loci/formats/in/TCSReader.java
+++ b/loci/formats/in/TCSReader.java
@@ -1,627 +1,628 @@
//
// TCSReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.xml.parsers.*;
import loci.formats.*;
import loci.formats.in.TiffReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* TCSReader is the file format reader for Leica TCS TIFF files and their
* companion XML file.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/TCSReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/TCSReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class TCSReader extends FormatReader {
// -- Constants --
/** Factory for generating SAX parsers. */
public static final SAXParserFactory SAX_FACTORY =
SAXParserFactory.newInstance();
// -- Fields --
/** List of TIFF files. */
private Vector tiffs;
/** Helper readers. */
private TiffReader[] tiffReaders;
private Vector seriesNames;
private Vector containerNames;
private Vector containerCounts;
private Vector xcal, ycal, zcal;
private Vector x, y, z, c, t, bits;
// -- Constructor --
public TCSReader() {
super("Leica TCS TIFF", new String[] {"tif", "tiff", "xml"});
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return false;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return tiffReaders[0].get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return tiffReaders[0].get16BitLookupTable();
}
/* @see loci.formats.IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length);
int n = 0;
for (int i=0; i<series; i++) {
n += core.imageCount[i];
}
n += no;
return tiffReaders[n].openBytes(0, buf);
}
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
Vector v = new Vector();
for (int i=0; i<tiffs.size(); i++) {
v.add(tiffs.get(i));
}
return (String[]) v.toArray(new String[0]);
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!super.isThisType(name, open) && !name.toLowerCase().endsWith("xml")) {
return false; // check extension
}
if (!open) return true; // not allowed to check the file contents
if (name.toLowerCase().endsWith("xml")) {
try {
RandomAccessStream ras = new RandomAccessStream(name);
String s = ras.readString(20);
return s.indexOf("Data") != -1;
}
catch (IOException exc) {
return false;
}
}
// just checking the filename isn't enough to differentiate between
// Leica TCS and regular TIFF; open the file and check more thoroughly
try {
RandomAccessStream ras = new RandomAccessStream(name);
Hashtable ifd = TiffTools.getFirstIFD(ras);
ras.close();
if (ifd == null) return false;
String document = (String) ifd.get(new Integer(TiffTools.DOCUMENT_NAME));
if (document == null) document = "";
String software = (String) ifd.get(new Integer(TiffTools.SOFTWARE));
if (software == null) software = "";
return document.startsWith("CHANNEL") || software.trim().equals("TCSNTV");
}
catch (IOException e) { return false; }
}
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
tiffs = null;
tiffReaders = null;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("TCSReader.initFile(" + id + ")");
String lname = id.toLowerCase();
if (lname.endsWith("tiff") || lname.endsWith("tif")) {
// find the associated XML file, if it exists
Location l = new Location(id).getAbsoluteFile();
Location parent = l.getParentFile();
String[] list = parent.list();
for (int i=0; i<list.length; i++) {
if (list[i].toLowerCase().endsWith("xml")) {
initFile(new Location(parent, list[i]).getAbsolutePath());
return;
}
}
}
super.initFile(id);
if (lname.endsWith("xml")) {
in = new RandomAccessStream(id);
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
seriesNames = new Vector();
containerNames = new Vector();
containerCounts = new Vector();
x = new Vector();
y = new Vector();
z = new Vector();
c = new Vector();
t = new Vector();
bits = new Vector();
// parse XML metadata
TCSHandler handler = new TCSHandler();
String prefix = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>";
String suffix = "</LEICA>";
String xml = prefix + in.readString((int) in.length()) + suffix;
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
// look for associated TIFF files
tiffs = new Vector();
Location parent = new Location(id).getAbsoluteFile().getParentFile();
String[] list = parent.list();
Arrays.sort(list);
for (int i=0; i<list.length; i++) {
String lcase = list[i].toLowerCase();
if (lcase.endsWith("tif") || lcase.endsWith("tiff")) {
String file = new Location(parent, list[i]).getAbsolutePath();
Hashtable ifd = TiffTools.getIFDs(new RandomAccessStream(file))[0];
String software =
(String) TiffTools.getIFDValue(ifd, TiffTools.SOFTWARE);
if (software != null && software.trim().equals("TCSNTV")) {
tiffs.add(file);
}
}
}
tiffReaders = new TiffReader[tiffs.size()];
for (int i=0; i<tiffReaders.length; i++) {
tiffReaders[i] = new TiffReader();
tiffReaders[i].setId((String) tiffs.get(i));
}
core = new CoreMetadata(x.size());
for (int i=0; i<x.size(); i++) {
core.sizeX[i] = ((Integer) x.get(i)).intValue();
core.sizeY[i] = ((Integer) y.get(i)).intValue();
if (z.size() > 0) core.sizeZ[i] = ((Integer) z.get(i)).intValue();
else core.sizeZ[i] = 1;
if (c.size() > 0) core.sizeC[i] = ((Integer) c.get(i)).intValue();
else core.sizeC[i] = 1;
if (t.size() > 0) core.sizeT[i] = ((Integer) t.get(i)).intValue();
else core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeC[i] * core.sizeT[i];
int bpp = ((Integer) bits.get(i)).intValue();
while (bpp % 8 != 0) bpp++;
switch (bpp) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
if (tiffs.size() < core.imageCount[i]) {
int div = core.imageCount[i] / core.sizeC[i];
core.imageCount[i] = tiffs.size();
if (div >= core.sizeZ[i]) core.sizeZ[i] /= div;
else if (div >= core.sizeT[i]) core.sizeT[i] /= div;
}
}
Arrays.fill(core.currentOrder,
core.sizeZ[0] > core.sizeT[0] ? "XYCZT" : "XYCTZ");
Arrays.fill(core.metadataComplete, true);
Arrays.fill(core.rgb, false);
Arrays.fill(core.interleaved, false);
Arrays.fill(core.indexed, tiffReaders[0].isIndexed());
Arrays.fill(core.falseColor, true);
MetadataStore store = getMetadataStore();
for (int i=0; i<x.size(); i++) {
store.setImage((String) seriesNames.get(i), null, null, new Integer(i));
}
FormatTools.populatePixels(store, this);
for (int i=0; i<x.size(); i++) {
for (int cc=0; cc<core.sizeC[i]; cc++) {
store.setLogicalChannel(cc, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, new Integer(i));
}
store.setDimensions((Float) xcal.get(i), (Float) ycal.get(i),
(Float) zcal.get(i), null, null, new Integer(i));
}
}
else {
tiffs = new Vector();
tiffs.add(id);
tiffReaders = new TiffReader[1];
tiffReaders[0] = new TiffReader();
tiffReaders[0].setMetadataStore(getMetadataStore());
tiffReaders[0].setId(id);
in = new RandomAccessStream(id);
Hashtable[] ifds = TiffTools.getIFDs(in);
int[] ch = new int[ifds.length];
int[] idx = new int[ifds.length];
long[] stamp = new long[ifds.length];
int channelCount = 0;
SimpleDateFormat fmt = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss.SSS");
for (int i=0; i<ifds.length; i++) {
String document =
(String) ifds[i].get(new Integer(TiffTools.DOCUMENT_NAME));
+ if (document == null) continue;
int index = document.indexOf("INDEX");
String c = document.substring(8, index).trim();
ch[i] = Integer.parseInt(c);
if (ch[i] > channelCount) channelCount = ch[i];
String n = document.substring(index + 6,
document.indexOf(" ", index + 6)).trim();
idx[i] = Integer.parseInt(n);
String date = document.substring(document.indexOf(" ", index + 6),
document.indexOf("FORMAT")).trim();
stamp[i] = fmt.parse(date, new ParsePosition(0)).getTime();
}
core.sizeT[0] = 0;
core.currentOrder[0] = core.rgb[0] ? "XYC" : "XY";
// determine the axis sizes and ordering
boolean unique = true;
for (int i=0; i<stamp.length; i++) {
for (int j=i+1; j<stamp.length; j++) {
if (stamp[j] == stamp[i]) {
unique = false;
break;
}
}
if (unique) {
core.sizeT[0]++;
if (core.currentOrder[0].indexOf("T") < 0) {
core.currentOrder[0] += "T";
}
}
else if (i > 0) {
if ((ch[i] != ch[i - 1]) && core.currentOrder[0].indexOf("C") < 0) {
core.currentOrder[0] += "C";
}
else if (core.currentOrder[0].indexOf("Z") < 0) {
core.currentOrder[0] += "Z";
}
}
unique = true;
}
if (core.currentOrder[0].indexOf("Z") < 0) core.currentOrder[0] += "Z";
if (core.currentOrder[0].indexOf("C") < 0) core.currentOrder[0] += "C";
if (core.currentOrder[0].indexOf("T") < 0) core.currentOrder[0] += "T";
if (core.sizeT[0] == 0) core.sizeT[0] = 1;
if (channelCount == 0) channelCount = 1;
core.sizeZ[0] = ifds.length / (core.sizeT[0] * channelCount);
core.sizeC[0] *= channelCount;
core.imageCount[0] = core.sizeZ[0] * core.sizeT[0] * channelCount;
// cut up comment
String comment =
(String) TiffTools.getIFDValue(ifds[0], TiffTools.IMAGE_DESCRIPTION);
if (comment != null && comment.startsWith("[")) {
StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (!token.startsWith("[")) {
int eq = token.indexOf("=");
String key = token.substring(0, eq);
String value = token.substring(eq + 1);
addMeta(key, value);
}
}
metadata.remove("Comment");
}
core = tiffReaders[0].getCoreMetadata();
}
}
// -- Helper class --
/** SAX handler for parsing XML. */
class TCSHandler extends DefaultHandler {
private String series = "", fullSeries = "";
private int count = 0;
private boolean firstElement = true;
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Element")) {
if (!attributes.getValue("Name").equals("DCROISet") && !firstElement) {
series = attributes.getValue("Name");
containerNames.add(series);
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
else fullSeries = "/" + series;
}
else if (firstElement) firstElement = false;
}
else if (qName.equals("Experiment")) {
for (int i=0; i<attributes.getLength(); i++) {
addMeta(attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("Image")) {
containerNames.remove(series);
if (containerCounts.size() < containerNames.size()) {
containerCounts.add(new Integer(1));
}
else if (containerCounts.size() > 0) {
int ndx = containerCounts.size() - 1;
int n = ((Integer) containerCounts.get(ndx)).intValue();
containerCounts.setElementAt(new Integer(n + 1), ndx);
}
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
seriesNames.add(fullSeries);
}
else if (qName.equals("ChannelDescription")) {
String prefix = "Channel " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
if (c.size() > seriesNames.size() - 1) {
c.setElementAt(new Integer(count), seriesNames.size() - 1);
}
else c.add(new Integer(count));
}
else if (qName.equals("DimensionDescription")) {
String prefix = "Dimension " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + attributes.getQName(i), attributes.getValue(i));
}
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
float size = Float.parseFloat(attributes.getValue("Length"));
if (size < 0) size *= -1;
switch (id) {
case 1:
x.add(new Integer(len));
xcal.add(new Float((size * 1000000) / len));
int b = Integer.parseInt(attributes.getValue("BytesInc"));
bits.add(new Integer(b * 8));
break;
case 2:
y.add(new Integer(len));
ycal.add(new Float((size * 1000000) / len));
break;
case 3:
z.add(new Integer(len));
zcal.add(new Float((size * 1000000) / len));
break;
default:
t.add(new Integer(len));
break;
}
}
else if (qName.equals("ScannerSettingRecord")) {
String key = attributes.getValue("Identifier") + " - " +
attributes.getValue("Description");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
addMeta(key, attributes.getValue("Variant"));
}
else if (qName.equals("FilterSettingRecord")) {
String key = attributes.getValue("ObjectName") + " - " +
attributes.getValue("Description") + " - " +
attributes.getValue("Attribute");
for (int i=0; i<attributes.getLength(); i++) {
addMeta(key + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("ATLConfocalSettingDefinition")) {
if (fullSeries.endsWith("Master sequential setting")) {
fullSeries = fullSeries.replaceAll("Master sequential setting",
"Sequential Setting 0");
}
/* debug */ System.out.println(fullSeries);
if (fullSeries.indexOf("Sequential Setting ") == -1) {
if (fullSeries.equals("")) fullSeries = "Master sequential setting";
else fullSeries += " - Master sequential setting";
}
else {
int ndx = fullSeries.indexOf("Sequential Setting ") + 19;
int n = Integer.parseInt(fullSeries.substring(ndx)) + 1;
fullSeries = fullSeries.substring(0, ndx) + String.valueOf(n);
}
String prefix = "";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - ";
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("Wheel")) {
String prefix = "Wheel " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
}
else if (qName.equals("WheelName")) {
String prefix = "Wheel " + (count - 1) + " - WheelName ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int ndx = 0;
while (getMeta(prefix + ndx) != null) ndx++;
addMeta(prefix + ndx, attributes.getValue("FilterName"));
}
else if (qName.equals("MultiBand")) {
String prefix = "MultiBand Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("LaserLineSetting")) {
String prefix = "LaserLine " + attributes.getValue("LaserLine");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("Detector")) {
String prefix = "Detector Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("Laser")) {
String prefix = "Laser " + attributes.getValue("LaserName");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
high <<= 32;
if ((int) low < 0) {
low &= 0xffffffffL;
}
long stamp = high + low;
long ms = stamp / 10000;
String n = String.valueOf(count);
while (n.length() < 4) n = "0" + n;
addMeta(fullSeries + " - TimeStamp " + n,
DataTools.convertDate(ms, DataTools.COBOL));
count++;
}
else if (qName.equals("ChannelScalingInfo")) {
String prefix = "ChannelScalingInfo " + count;
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(prefix + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("RelTimeStamp")) {
addMeta(fullSeries + " RelTimeStamp " + attributes.getValue("Frame"),
attributes.getValue("Time"));
}
else count = 0;
}
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("TCSReader.initFile(" + id + ")");
String lname = id.toLowerCase();
if (lname.endsWith("tiff") || lname.endsWith("tif")) {
// find the associated XML file, if it exists
Location l = new Location(id).getAbsoluteFile();
Location parent = l.getParentFile();
String[] list = parent.list();
for (int i=0; i<list.length; i++) {
if (list[i].toLowerCase().endsWith("xml")) {
initFile(new Location(parent, list[i]).getAbsolutePath());
return;
}
}
}
super.initFile(id);
if (lname.endsWith("xml")) {
in = new RandomAccessStream(id);
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
seriesNames = new Vector();
containerNames = new Vector();
containerCounts = new Vector();
x = new Vector();
y = new Vector();
z = new Vector();
c = new Vector();
t = new Vector();
bits = new Vector();
// parse XML metadata
TCSHandler handler = new TCSHandler();
String prefix = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>";
String suffix = "</LEICA>";
String xml = prefix + in.readString((int) in.length()) + suffix;
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
// look for associated TIFF files
tiffs = new Vector();
Location parent = new Location(id).getAbsoluteFile().getParentFile();
String[] list = parent.list();
Arrays.sort(list);
for (int i=0; i<list.length; i++) {
String lcase = list[i].toLowerCase();
if (lcase.endsWith("tif") || lcase.endsWith("tiff")) {
String file = new Location(parent, list[i]).getAbsolutePath();
Hashtable ifd = TiffTools.getIFDs(new RandomAccessStream(file))[0];
String software =
(String) TiffTools.getIFDValue(ifd, TiffTools.SOFTWARE);
if (software != null && software.trim().equals("TCSNTV")) {
tiffs.add(file);
}
}
}
tiffReaders = new TiffReader[tiffs.size()];
for (int i=0; i<tiffReaders.length; i++) {
tiffReaders[i] = new TiffReader();
tiffReaders[i].setId((String) tiffs.get(i));
}
core = new CoreMetadata(x.size());
for (int i=0; i<x.size(); i++) {
core.sizeX[i] = ((Integer) x.get(i)).intValue();
core.sizeY[i] = ((Integer) y.get(i)).intValue();
if (z.size() > 0) core.sizeZ[i] = ((Integer) z.get(i)).intValue();
else core.sizeZ[i] = 1;
if (c.size() > 0) core.sizeC[i] = ((Integer) c.get(i)).intValue();
else core.sizeC[i] = 1;
if (t.size() > 0) core.sizeT[i] = ((Integer) t.get(i)).intValue();
else core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeC[i] * core.sizeT[i];
int bpp = ((Integer) bits.get(i)).intValue();
while (bpp % 8 != 0) bpp++;
switch (bpp) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
if (tiffs.size() < core.imageCount[i]) {
int div = core.imageCount[i] / core.sizeC[i];
core.imageCount[i] = tiffs.size();
if (div >= core.sizeZ[i]) core.sizeZ[i] /= div;
else if (div >= core.sizeT[i]) core.sizeT[i] /= div;
}
}
Arrays.fill(core.currentOrder,
core.sizeZ[0] > core.sizeT[0] ? "XYCZT" : "XYCTZ");
Arrays.fill(core.metadataComplete, true);
Arrays.fill(core.rgb, false);
Arrays.fill(core.interleaved, false);
Arrays.fill(core.indexed, tiffReaders[0].isIndexed());
Arrays.fill(core.falseColor, true);
MetadataStore store = getMetadataStore();
for (int i=0; i<x.size(); i++) {
store.setImage((String) seriesNames.get(i), null, null, new Integer(i));
}
FormatTools.populatePixels(store, this);
for (int i=0; i<x.size(); i++) {
for (int cc=0; cc<core.sizeC[i]; cc++) {
store.setLogicalChannel(cc, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, new Integer(i));
}
store.setDimensions((Float) xcal.get(i), (Float) ycal.get(i),
(Float) zcal.get(i), null, null, new Integer(i));
}
}
else {
tiffs = new Vector();
tiffs.add(id);
tiffReaders = new TiffReader[1];
tiffReaders[0] = new TiffReader();
tiffReaders[0].setMetadataStore(getMetadataStore());
tiffReaders[0].setId(id);
in = new RandomAccessStream(id);
Hashtable[] ifds = TiffTools.getIFDs(in);
int[] ch = new int[ifds.length];
int[] idx = new int[ifds.length];
long[] stamp = new long[ifds.length];
int channelCount = 0;
SimpleDateFormat fmt = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss.SSS");
for (int i=0; i<ifds.length; i++) {
String document =
(String) ifds[i].get(new Integer(TiffTools.DOCUMENT_NAME));
int index = document.indexOf("INDEX");
String c = document.substring(8, index).trim();
ch[i] = Integer.parseInt(c);
if (ch[i] > channelCount) channelCount = ch[i];
String n = document.substring(index + 6,
document.indexOf(" ", index + 6)).trim();
idx[i] = Integer.parseInt(n);
String date = document.substring(document.indexOf(" ", index + 6),
document.indexOf("FORMAT")).trim();
stamp[i] = fmt.parse(date, new ParsePosition(0)).getTime();
}
core.sizeT[0] = 0;
core.currentOrder[0] = core.rgb[0] ? "XYC" : "XY";
// determine the axis sizes and ordering
boolean unique = true;
for (int i=0; i<stamp.length; i++) {
for (int j=i+1; j<stamp.length; j++) {
if (stamp[j] == stamp[i]) {
unique = false;
break;
}
}
if (unique) {
core.sizeT[0]++;
if (core.currentOrder[0].indexOf("T") < 0) {
core.currentOrder[0] += "T";
}
}
else if (i > 0) {
if ((ch[i] != ch[i - 1]) && core.currentOrder[0].indexOf("C") < 0) {
core.currentOrder[0] += "C";
}
else if (core.currentOrder[0].indexOf("Z") < 0) {
core.currentOrder[0] += "Z";
}
}
unique = true;
}
if (core.currentOrder[0].indexOf("Z") < 0) core.currentOrder[0] += "Z";
if (core.currentOrder[0].indexOf("C") < 0) core.currentOrder[0] += "C";
if (core.currentOrder[0].indexOf("T") < 0) core.currentOrder[0] += "T";
if (core.sizeT[0] == 0) core.sizeT[0] = 1;
if (channelCount == 0) channelCount = 1;
core.sizeZ[0] = ifds.length / (core.sizeT[0] * channelCount);
core.sizeC[0] *= channelCount;
core.imageCount[0] = core.sizeZ[0] * core.sizeT[0] * channelCount;
// cut up comment
String comment =
(String) TiffTools.getIFDValue(ifds[0], TiffTools.IMAGE_DESCRIPTION);
if (comment != null && comment.startsWith("[")) {
StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (!token.startsWith("[")) {
int eq = token.indexOf("=");
String key = token.substring(0, eq);
String value = token.substring(eq + 1);
addMeta(key, value);
}
}
metadata.remove("Comment");
}
core = tiffReaders[0].getCoreMetadata();
}
}
| protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("TCSReader.initFile(" + id + ")");
String lname = id.toLowerCase();
if (lname.endsWith("tiff") || lname.endsWith("tif")) {
// find the associated XML file, if it exists
Location l = new Location(id).getAbsoluteFile();
Location parent = l.getParentFile();
String[] list = parent.list();
for (int i=0; i<list.length; i++) {
if (list[i].toLowerCase().endsWith("xml")) {
initFile(new Location(parent, list[i]).getAbsolutePath());
return;
}
}
}
super.initFile(id);
if (lname.endsWith("xml")) {
in = new RandomAccessStream(id);
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
seriesNames = new Vector();
containerNames = new Vector();
containerCounts = new Vector();
x = new Vector();
y = new Vector();
z = new Vector();
c = new Vector();
t = new Vector();
bits = new Vector();
// parse XML metadata
TCSHandler handler = new TCSHandler();
String prefix = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>";
String suffix = "</LEICA>";
String xml = prefix + in.readString((int) in.length()) + suffix;
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
// look for associated TIFF files
tiffs = new Vector();
Location parent = new Location(id).getAbsoluteFile().getParentFile();
String[] list = parent.list();
Arrays.sort(list);
for (int i=0; i<list.length; i++) {
String lcase = list[i].toLowerCase();
if (lcase.endsWith("tif") || lcase.endsWith("tiff")) {
String file = new Location(parent, list[i]).getAbsolutePath();
Hashtable ifd = TiffTools.getIFDs(new RandomAccessStream(file))[0];
String software =
(String) TiffTools.getIFDValue(ifd, TiffTools.SOFTWARE);
if (software != null && software.trim().equals("TCSNTV")) {
tiffs.add(file);
}
}
}
tiffReaders = new TiffReader[tiffs.size()];
for (int i=0; i<tiffReaders.length; i++) {
tiffReaders[i] = new TiffReader();
tiffReaders[i].setId((String) tiffs.get(i));
}
core = new CoreMetadata(x.size());
for (int i=0; i<x.size(); i++) {
core.sizeX[i] = ((Integer) x.get(i)).intValue();
core.sizeY[i] = ((Integer) y.get(i)).intValue();
if (z.size() > 0) core.sizeZ[i] = ((Integer) z.get(i)).intValue();
else core.sizeZ[i] = 1;
if (c.size() > 0) core.sizeC[i] = ((Integer) c.get(i)).intValue();
else core.sizeC[i] = 1;
if (t.size() > 0) core.sizeT[i] = ((Integer) t.get(i)).intValue();
else core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeC[i] * core.sizeT[i];
int bpp = ((Integer) bits.get(i)).intValue();
while (bpp % 8 != 0) bpp++;
switch (bpp) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
if (tiffs.size() < core.imageCount[i]) {
int div = core.imageCount[i] / core.sizeC[i];
core.imageCount[i] = tiffs.size();
if (div >= core.sizeZ[i]) core.sizeZ[i] /= div;
else if (div >= core.sizeT[i]) core.sizeT[i] /= div;
}
}
Arrays.fill(core.currentOrder,
core.sizeZ[0] > core.sizeT[0] ? "XYCZT" : "XYCTZ");
Arrays.fill(core.metadataComplete, true);
Arrays.fill(core.rgb, false);
Arrays.fill(core.interleaved, false);
Arrays.fill(core.indexed, tiffReaders[0].isIndexed());
Arrays.fill(core.falseColor, true);
MetadataStore store = getMetadataStore();
for (int i=0; i<x.size(); i++) {
store.setImage((String) seriesNames.get(i), null, null, new Integer(i));
}
FormatTools.populatePixels(store, this);
for (int i=0; i<x.size(); i++) {
for (int cc=0; cc<core.sizeC[i]; cc++) {
store.setLogicalChannel(cc, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, new Integer(i));
}
store.setDimensions((Float) xcal.get(i), (Float) ycal.get(i),
(Float) zcal.get(i), null, null, new Integer(i));
}
}
else {
tiffs = new Vector();
tiffs.add(id);
tiffReaders = new TiffReader[1];
tiffReaders[0] = new TiffReader();
tiffReaders[0].setMetadataStore(getMetadataStore());
tiffReaders[0].setId(id);
in = new RandomAccessStream(id);
Hashtable[] ifds = TiffTools.getIFDs(in);
int[] ch = new int[ifds.length];
int[] idx = new int[ifds.length];
long[] stamp = new long[ifds.length];
int channelCount = 0;
SimpleDateFormat fmt = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss.SSS");
for (int i=0; i<ifds.length; i++) {
String document =
(String) ifds[i].get(new Integer(TiffTools.DOCUMENT_NAME));
if (document == null) continue;
int index = document.indexOf("INDEX");
String c = document.substring(8, index).trim();
ch[i] = Integer.parseInt(c);
if (ch[i] > channelCount) channelCount = ch[i];
String n = document.substring(index + 6,
document.indexOf(" ", index + 6)).trim();
idx[i] = Integer.parseInt(n);
String date = document.substring(document.indexOf(" ", index + 6),
document.indexOf("FORMAT")).trim();
stamp[i] = fmt.parse(date, new ParsePosition(0)).getTime();
}
core.sizeT[0] = 0;
core.currentOrder[0] = core.rgb[0] ? "XYC" : "XY";
// determine the axis sizes and ordering
boolean unique = true;
for (int i=0; i<stamp.length; i++) {
for (int j=i+1; j<stamp.length; j++) {
if (stamp[j] == stamp[i]) {
unique = false;
break;
}
}
if (unique) {
core.sizeT[0]++;
if (core.currentOrder[0].indexOf("T") < 0) {
core.currentOrder[0] += "T";
}
}
else if (i > 0) {
if ((ch[i] != ch[i - 1]) && core.currentOrder[0].indexOf("C") < 0) {
core.currentOrder[0] += "C";
}
else if (core.currentOrder[0].indexOf("Z") < 0) {
core.currentOrder[0] += "Z";
}
}
unique = true;
}
if (core.currentOrder[0].indexOf("Z") < 0) core.currentOrder[0] += "Z";
if (core.currentOrder[0].indexOf("C") < 0) core.currentOrder[0] += "C";
if (core.currentOrder[0].indexOf("T") < 0) core.currentOrder[0] += "T";
if (core.sizeT[0] == 0) core.sizeT[0] = 1;
if (channelCount == 0) channelCount = 1;
core.sizeZ[0] = ifds.length / (core.sizeT[0] * channelCount);
core.sizeC[0] *= channelCount;
core.imageCount[0] = core.sizeZ[0] * core.sizeT[0] * channelCount;
// cut up comment
String comment =
(String) TiffTools.getIFDValue(ifds[0], TiffTools.IMAGE_DESCRIPTION);
if (comment != null && comment.startsWith("[")) {
StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (!token.startsWith("[")) {
int eq = token.indexOf("=");
String key = token.substring(0, eq);
String value = token.substring(eq + 1);
addMeta(key, value);
}
}
metadata.remove("Comment");
}
core = tiffReaders[0].getCoreMetadata();
}
}
|
diff --git a/src/play/modules/jobs/PlayJobsService.java b/src/play/modules/jobs/PlayJobsService.java
index e3b9b85..e835e3d 100644
--- a/src/play/modules/jobs/PlayJobsService.java
+++ b/src/play/modules/jobs/PlayJobsService.java
@@ -1,161 +1,161 @@
/**
* Copyright 2011 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Felipe Oliveira (http://mashup.fm)
*
*/
package play.modules.jobs;
import static play.modules.jobs.util.Exceptions.logError;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// import javax.ws.rs.GET;
// import javax.ws.rs.Path;
// import javax.ws.rs.PathParam;
// import javax.ws.rs.Produces;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.classloading.ApplicationClasses.ApplicationClass;
import play.exceptions.UnexpectedException;
import play.jobs.Job;
import play.jobs.JobsPlugin;
import play.modules.jobs.PlayJobs.JobEntry;
/**
* The Class JobsService.
*/
// @Path("/jobs")
public class PlayJobsService {
/**
* Gets the scheduled jobs.
*
* @return the scheduled jobs
*/
// @GET
// @Path("/list")
// @Produces("application/json")
public PlayJobs getJobs() {
// Get Jobs Plugin
JobsPlugin plugin = Play.plugin(JobsPlugin.class);
if (plugin == null) {
throw new UnexpectedException("Cannot load jobs plugin!");
}
// Get Metrics
int poolSize = plugin.executor.getPoolSize();
int activeCount = plugin.executor.getActiveCount();
long scheduledTaskCount = plugin.executor.getTaskCount();
int queueSize = plugin.executor.getPoolSize();
// Get Scheduled Jobs
List<JobEntry> jobEntries = new ArrayList<JobEntry>();
List<ApplicationClass> classes = Play.classes.all();
if (classes != null) {
// Wrap Pojos
for (Class clazz : Play.classloader.getAllClasses()) {
if ((clazz != null) && Job.class.isAssignableFrom(clazz)) {
jobEntries.add(new JobEntry(clazz));
}
}
}
// Create Data Container
PlayJobs jobs = new PlayJobs(poolSize, activeCount, scheduledTaskCount, queueSize, jobEntries);
Logger.info("Scheduled Jobs: %s", jobs);
// Return Schedule Jobs
return jobs;
}
/**
* Trigger.
*
* @param jobClass
* the job class
*/
// @GET
// @Path("/trigger/{jobClass}/${instances}")
// @Produces("application/json")
public void triggerJob(String jobClass, Integer instances) {
// Jobs Plugin
Play.plugin(JobsPlugin.class);
// Check Job Class
if (StringUtils.isBlank(jobClass)) {
throw new RuntimeException("Invalid Job Class!");
}
// Check Number of Instances
if (instances == null) {
instances = 1;
}
if (instances < 1) {
instances = 1;
}
// Log Debug
Logger.info("Trigger Job - Class: %s, Number of Instances: %s", jobClass, instances);
// Trigger Job(s)
try {
// Define Class
- Class clazz = Class.forName(jobClass);
+ Class clazz = Play.classloader.getClassIgnoreCase(jobClass);
if (clazz == null) {
throw new RuntimeException("Invalid Job Class: " + jobClass);
}
// Define Executor Service
ExecutorService executor = Executors.newFixedThreadPool(instances);
// Loop on number of instances needed
int count = 0;
for (int i = 0; i < instances; i++) {
// Add Count (I don't like to mix with "i" to avoid causing bugs
// when code gets refactored or something that I can't predict)
count = count + 1;
// Create Instance
Object o = clazz.newInstance();
// Check Instance Type
if ((o instanceof Job) == false) {
throw new RuntimeException("Invalid Class Instance: " + o);
}
// Log Debug
Logger.info("Triggering Job: %s", o);
// Fire Job
Job job = (Job) o;
executor.submit((Callable) job);
Logger.info("%s) Triggered Job: %s", count, job);
}
} catch (Throwable t) {
// Job wasn't found
logError(t);
throw new UnexpectedException(String.format("Couldn't trigger job: %s", jobClass));
}
}
}
| true | true | public void triggerJob(String jobClass, Integer instances) {
// Jobs Plugin
Play.plugin(JobsPlugin.class);
// Check Job Class
if (StringUtils.isBlank(jobClass)) {
throw new RuntimeException("Invalid Job Class!");
}
// Check Number of Instances
if (instances == null) {
instances = 1;
}
if (instances < 1) {
instances = 1;
}
// Log Debug
Logger.info("Trigger Job - Class: %s, Number of Instances: %s", jobClass, instances);
// Trigger Job(s)
try {
// Define Class
Class clazz = Class.forName(jobClass);
if (clazz == null) {
throw new RuntimeException("Invalid Job Class: " + jobClass);
}
// Define Executor Service
ExecutorService executor = Executors.newFixedThreadPool(instances);
// Loop on number of instances needed
int count = 0;
for (int i = 0; i < instances; i++) {
// Add Count (I don't like to mix with "i" to avoid causing bugs
// when code gets refactored or something that I can't predict)
count = count + 1;
// Create Instance
Object o = clazz.newInstance();
// Check Instance Type
if ((o instanceof Job) == false) {
throw new RuntimeException("Invalid Class Instance: " + o);
}
// Log Debug
Logger.info("Triggering Job: %s", o);
// Fire Job
Job job = (Job) o;
executor.submit((Callable) job);
Logger.info("%s) Triggered Job: %s", count, job);
}
} catch (Throwable t) {
// Job wasn't found
logError(t);
throw new UnexpectedException(String.format("Couldn't trigger job: %s", jobClass));
}
}
| public void triggerJob(String jobClass, Integer instances) {
// Jobs Plugin
Play.plugin(JobsPlugin.class);
// Check Job Class
if (StringUtils.isBlank(jobClass)) {
throw new RuntimeException("Invalid Job Class!");
}
// Check Number of Instances
if (instances == null) {
instances = 1;
}
if (instances < 1) {
instances = 1;
}
// Log Debug
Logger.info("Trigger Job - Class: %s, Number of Instances: %s", jobClass, instances);
// Trigger Job(s)
try {
// Define Class
Class clazz = Play.classloader.getClassIgnoreCase(jobClass);
if (clazz == null) {
throw new RuntimeException("Invalid Job Class: " + jobClass);
}
// Define Executor Service
ExecutorService executor = Executors.newFixedThreadPool(instances);
// Loop on number of instances needed
int count = 0;
for (int i = 0; i < instances; i++) {
// Add Count (I don't like to mix with "i" to avoid causing bugs
// when code gets refactored or something that I can't predict)
count = count + 1;
// Create Instance
Object o = clazz.newInstance();
// Check Instance Type
if ((o instanceof Job) == false) {
throw new RuntimeException("Invalid Class Instance: " + o);
}
// Log Debug
Logger.info("Triggering Job: %s", o);
// Fire Job
Job job = (Job) o;
executor.submit((Callable) job);
Logger.info("%s) Triggered Job: %s", count, job);
}
} catch (Throwable t) {
// Job wasn't found
logError(t);
throw new UnexpectedException(String.format("Couldn't trigger job: %s", jobClass));
}
}
|
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java
index 13dc3a82..cbb336f9 100644
--- a/src/com/android/camera/Camera.java
+++ b/src/com/android/camera/Camera.java
@@ -1,2532 +1,2532 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2009, Code Aurora Forum. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.AudioManager;
import android.media.CameraProfile;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.preference.CheckBoxPreference;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.camera.gallery.IImage;
import com.android.camera.gallery.IImageList;
import com.android.camera.ui.CameraHeadUpDisplay;
import com.android.camera.ui.GLRootView;
import com.android.camera.ui.HeadUpDisplay;
import com.android.camera.ui.ZoomControllerListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/** The Camera activity which can preview and take pictures. */
public class Camera extends BaseCamera implements View.OnClickListener,
ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
Switcher.OnSwitchListener {
private static final String TAG = "camera";
private static final int CROP_MSG = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int RESTART_PREVIEW = 3;
private static final int CLEAR_SCREEN_DELAY = 4;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5;
private static final int CAMERA_TIMER = 6;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
// The brightness settings used when it is set to automatic in the system.
// The reason why it is set to 0.7 is just because 1.0 is too bright.
private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
private static final int SCREEN_DELAY = 1000;
private static final int FOCUS_BEEP_VOLUME = 100;
private static final int ZOOM_STOPPED = 0;
private static final int ZOOM_START = 1;
private static final int ZOOM_STOPPING = 2;
private int mZoomState = ZOOM_STOPPED;
private boolean mSmoothZoomSupported = false;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private boolean mTimerMode = false;
private int mTargetZoomValue;
private Parameters mInitialParams;
private MyOrientationEventListener mOrientationListener;
// The device orientation in degrees. Default is unknown.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// The orientation compensation for icons and thumbnails.
private int mOrientationCompensation = 0;
private static final int IDLE = 1;
private static final int SNAPSHOT_IN_PROGRESS = 2;
private static final boolean SWITCH_CAMERA = true;
private static final boolean SWITCH_VIDEO = false;
private int mStatus = IDLE;
private static final String sTempCropFilename = "crop-temp";
private ContentProviderClient mMediaProviderClient;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder = null;
private ShutterButton mShutterButton;
private ToneGenerator mFocusToneGenerator;
private GestureDetector mGestureDetector;
private Switcher mSwitcher;
private boolean mStartPreviewFail = false;
private GLRootView mGLRootView;
// mPostCaptureAlert, mLastPictureButton, mThumbController
// are non-null only if isImageCaptureIntent() is true.
private ImageView mLastPictureButton;
private ThumbnailController mThumbController;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
private ImageCapture mImageCapture = null;
private TextView mRecordingTimeView;
private boolean mFirstTimeInitialized;
private static int keypresscount = 0;
private static int keyup = 0;
private boolean mIsImageCaptureIntent;
private boolean mRecordLocation;
private ContentResolver mContentResolver;
private boolean mDidRegister = false;
private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
private LocationManager mLocationManager = null;
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final ZoomListener mZoomListener = new ZoomListener();
// Use the ErrorCallback to capture the crash count
// on the mediaserver
private final ErrorCallback mErrorCallback = new ErrorCallback();
private long mFocusStartTime;
private long mFocusCallbackTime;
private long mCaptureStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private long mShutterdownTime;
private long mShutterupTime;
private int mPicturesRemaining;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
// Add for test
public static boolean mMediaServerDied = false;
private String mSceneMode;
private final Handler mHandler = new MainHandler();
// multiple cameras support
private int mNumberOfCameras;
private int mCameraId;
private SharedPreferences prefs;
private int mImageWidth = 0;
private int mImageHeight = 0;
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RESTART_PREVIEW: {
restartPreview();
if (mJpegPictureCallbackTime != 0) {
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
break;
}
case CLEAR_SCREEN_DELAY: {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
case CAMERA_TIMER: {
updateTimer(msg.arg1);
break;
}
}
}
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
if (mHeadUpDisplay != null) {
mHeadUpDisplay.reloadPreferences();
}
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = getContentResolver()
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Create orientation listenter. This should be done first because it
// takes some time to get first orientation.
mOrientationListener = new MyOrientationEventListener(Camera.this);
mOrientationListener.enable();
// Initialize location sevice.
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mRecordLocation = RecordLocationPreference.get(
mPreferences, getContentResolver());
if (mRecordLocation) startReceivingLocationUpdates();
keepMediaProviderInstance();
checkStorage();
// Initialize last picture button.
mContentResolver = getContentResolver();
if (!mIsImageCaptureIntent) {
findViewById(R.id.camera_switch).setOnClickListener(this);
mLastPictureButton =
(ImageView) findViewById(R.id.review_thumbnail);
mLastPictureButton.setOnClickListener(this);
mThumbController = new ThumbnailController(
getResources(), mLastPictureButton, mContentResolver);
mThumbController.loadData(ImageManager.getLastImageThumbPath());
// Update last image thumbnail.
updateThumbnailButton();
}
// Initialize shutter button.
mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
updateFocusIndicator();
initializeScreenBrightness();
installIntentFilter();
initializeFocusTone();
initializeZoom();
mHeadUpDisplay = new CameraHeadUpDisplay(this);
mHeadUpDisplay.setListener(new MyHeadUpDisplayListener());
initializeHeadUpDisplay();
initializeTouchFocus();
clearFocusState();
resetFocusIndicator();
mFirstTimeInitialized = true;
changeHeadUpDisplayState();
addIdleHandler();
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
public boolean queueIdle() {
ImageManager.ensureOSXCompatibleFolder();
return false;
}
});
}
private void updateThumbnailButton() {
// Update last image if URI is invalid and the storage is ready.
if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
updateLastImage();
}
mThumbController.updateDisplayIfNeeded();
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start orientation listener as soon as possible because it takes
// some time to get first orientation.
mOrientationListener.enable();
// Start location update if needed.
mRecordLocation = RecordLocationPreference.get(
mPreferences, getContentResolver());
if (mRecordLocation) startReceivingLocationUpdates();
installIntentFilter();
initializeFocusTone();
initializeZoom();
changeHeadUpDisplayState();
keepMediaProviderInstance();
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
private void initializeZoom() {
if (!mParameters.isZoomSupported()) return;
mZoomMax = mParameters.getMaxZoom();
mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
mGestureDetector = new GestureDetector(this, new ZoomGestureListener());
mCameraDevice.setZoomChangeListener(mZoomListener);
}
private void onZoomValueChanged(int index) {
if (mSmoothZoomSupported) {
if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
mTargetZoomValue = index;
if (mZoomState == ZOOM_START) {
mZoomState = ZOOM_STOPPING;
mCameraDevice.stopSmoothZoom();
}
} else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
mTargetZoomValue = index;
mCameraDevice.startSmoothZoom(index);
mZoomState = ZOOM_START;
}
} else {
mZoomValue = index;
setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
}
}
private float[] getZoomRatios() {
if(!mParameters.isZoomSupported()) return null;
List<Integer> zoomRatios = mParameters.getZoomRatios();
float result[] = new float[zoomRatios.size()];
for (int i = 0, n = result.length; i < n; ++i) {
result[i] = (float) zoomRatios.get(i) / 100f;
}
return result;
}
private class ZoomGestureListener extends
GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent e) {
// Perform zoom only when preview is started and snapshot is not in
// progress.
if (mPausing || !isCameraIdle() || !mPreviewing
|| mZoomState != ZOOM_STOPPED) {
return false;
}
if (mZoomValue < mZoomMax) {
// Zoom in to the maximum.
mZoomValue = mZoomMax;
} else {
mZoomValue = 0;
}
setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
((CameraHeadUpDisplay)mHeadUpDisplay).setZoomIndex(mZoomValue);
return true;
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
boolean ret = true;
if (!super.dispatchTouchEvent(m)) {
if (mGestureDetector != null) {
ret = mGestureDetector.onTouchEvent(m);
}
if (mFocusGestureDetector != null) {
ret = mFocusGestureDetector.onTouchEvent(m);
}
}
return ret;
}
LocationListener [] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING)) {
checkStorage();
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
}
};
private class LocationListener
implements android.location.LocationListener {
Location mLastLocation;
boolean mValid = false;
String mProvider;
public LocationListener(String provider) {
mProvider = provider;
mLastLocation = new Location(mProvider);
}
public void onLocationChanged(Location newLocation) {
if (newLocation.getLatitude() == 0.0
&& newLocation.getLongitude() == 0.0) {
// Hack to filter out 0.0,0.0 locations
return;
}
// If GPS is available before start camera, we won't get status
// update so update GPS indicator when we receive data.
if (mRecordLocation
&& LocationManager.GPS_PROVIDER.equals(mProvider)) {
if (mHeadUpDisplay != null) {
((CameraHeadUpDisplay)mHeadUpDisplay).setGpsHasSignal(true);
}
}
mLastLocation.set(newLocation);
mValid = true;
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
mValid = false;
}
public void onStatusChanged(
String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE: {
mValid = false;
if (mRecordLocation &&
LocationManager.GPS_PROVIDER.equals(provider)) {
if (mHeadUpDisplay != null) {
((CameraHeadUpDisplay)mHeadUpDisplay).setGpsHasSignal(false);
}
}
break;
}
}
}
public Location current() {
return mValid ? mLastLocation : null;
}
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
clearFocusState();
}
}
private final class PostViewPictureCallback implements PictureCallback {
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
if (mShutterdownTime != 0)
Log.e(TAG,"<PROFILE> Snapshot to Thumb Latency = "
+ (mRawPictureCallbackTime - mShutterdownTime) + " ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPausing) {
return;
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
mHeadUpDisplay.setEnabled(true);
if (mShutterdownTime != 0)
Log.e(TAG,"<PROFILE> Snapshot to Snapshot Latency = "
+ (mJpegPictureCallbackTime - mShutterdownTime) + " ms");
if (!mIsImageCaptureIntent) {
// We want to show the taken picture for a while, so we wait
// for at least 1.2 second before restarting the preview.
long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
if (delay < 0) {
restartPreview();
} else {
mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
}
}
mImageCapture.storeImage(jpegData, camera, mLocation);
// Calculate this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
calculatePicturesRemaining();
if (mPicturesRemaining < 1) {
updateStorageHint(mPicturesRemaining);
}
if (!mHandler.hasMessages(RESTART_PREVIEW)) {
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
mStatus = IDLE;
decrementkeypress();
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
mFocusCallbackTime = System.currentTimeMillis();
mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
Log.e(TAG, "<PROFILE> mAutoFocusTime = " + mAutoFocusTime + "ms");
if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
// Take the picture no matter focus succeeds or fails. No need
// to play the AF sound if we're about to play the shutter
// sound.
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
mImageCapture.onSnap();
} else if (mFocusState == FOCUSING) {
// User is half-pressing the focus key. Play the focus tone.
// Do not take the picture now.
ToneGenerator tg = mFocusToneGenerator;
if (tg != null) {
tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
}
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
} else if (mFocusState == FOCUS_NOT_STARTED) {
// User has released the focus key before focus completes.
// Do nothing.
}
updateFocusIndicator();
}
}
private static final class ErrorCallback
implements android.hardware.Camera.ErrorCallback {
public void onError(int error, android.hardware.Camera camera) {
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
mMediaServerDied = true;
Log.v(TAG, "media server died");
}
}
}
private final class ZoomListener
implements android.hardware.Camera.OnZoomChangeListener {
public void onZoomChange(
int value, boolean stopped, android.hardware.Camera camera) {
Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
mZoomValue = value;
// Keep mParameters up to date. We do not getParameter again in
// takePicture. If we do not do this, wrong zoom value will be set.
mParameters.setZoom(value);
// We only care if the zoom is stopped. mZooming is set to true when
// we start smooth zoom.
if (stopped && mZoomState != ZOOM_STOPPED) {
if (value != mTargetZoomValue) {
mCameraDevice.startSmoothZoom(mTargetZoomValue);
mZoomState = ZOOM_START;
} else {
mZoomState = ZOOM_STOPPED;
}
}
}
}
private class ImageCapture {
private Uri mLastContentUri;
byte[] mCaptureOnlyData;
// Returns the rotation degree in the jpeg header.
private int storeImage(byte[] data, Location loc) {
try {
long dateTaken = System.currentTimeMillis();
String title = createName(dateTaken);
String filename = title + ".jpg";
int[] degree = new int[1];
mLastContentUri = ImageManager.addImage(
mContentResolver,
title,
dateTaken,
loc, // location from gps/network
ImageManager.CAMERA_IMAGE_BUCKET_NAME, filename,
null, data,
degree);
return degree[0];
} catch (Exception ex) {
Log.e(TAG, "Exception while compressing image.", ex);
return 0;
}
}
public void storeImage(final byte[] data,
android.hardware.Camera camera, Location loc) {
if (!mIsImageCaptureIntent) {
int degree = storeImage(data, loc);
sendBroadcast(new Intent(
"com.android.camera.NEW_PICTURE", mLastContentUri));
setLastPictureThumb(data, degree,
mImageCapture.getLastCaptureUri());
mThumbController.updateDisplayIfNeeded();
} else {
mCaptureOnlyData = data;
showPostCaptureAlert();
}
}
/**
* Initiate the capture of an image.
*/
public void initiate() {
if (mCameraDevice == null) {
return;
}
capture();
}
public Uri getLastCaptureUri() {
return mLastContentUri;
}
public byte[] getLastCaptureData() {
return mCaptureOnlyData;
}
private void capture() {
mCaptureOnlyData = null;
// See android.hardware.Camera.Parameters.setRotation for
// documentation.
int rotation = 0;
if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
if (info.facing == CameraInfo.CAMERA_FACING_FRONT &&
info.orientation != 90) {
rotation = (info.orientation - mOrientation + 360) % 360;
} else { // back-facing camera (or acting like it)
rotation = (info.orientation + mOrientation) % 360;
}
}
mParameters.setRotation(rotation);
// Clear previous GPS location from the parameters.
mParameters.removeGpsData();
// We always encode GpsTimeStamp
mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
// Set GPS location.
Location loc = mRecordLocation ? getCurrentLocation() : null;
if (loc != null) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
if (hasLatLon) {
mParameters.setGpsLatitude(lat);
mParameters.setGpsLongitude(lon);
mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
if (loc.hasAltitude()) {
mParameters.setGpsAltitude(loc.getAltitude());
} else {
// for NETWORK_PROVIDER location provider, we may have
// no altitude information, but the driver needs it, so
// we fake one.
mParameters.setGpsAltitude(0);
}
if (loc.getTime() != 0) {
// Location.getTime() is UTC in milliseconds.
// gps-timestamp is UTC in seconds.
long utcTimeSeconds = loc.getTime() / 1000;
mParameters.setGpsTimestamp(utcTimeSeconds);
}
} else {
loc = null;
}
}
mCameraDevice.setParameters(mParameters);
incrementkeypress();
Size pictureSize = mParameters.getPictureSize();
mImageWidth = pictureSize.width;
mImageHeight = pictureSize.height;
mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
mPostViewPictureCallback, new JpegPictureCallback(loc));
mPreviewing = false;
}
public void onSnap() {
// If we are already in the middle of taking a snapshot then ignore.
if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS || !mPreviewing) {
return;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mHeadUpDisplay.setEnabled(false);
mStatus = SNAPSHOT_IN_PROGRESS;
mImageCapture.initiate();
}
private void clearLastData() {
mCaptureOnlyData = null;
}
}
private boolean saveDataToFile(String filePath, byte[] data) {
FileOutputStream f = null;
try {
f = new FileOutputStream(filePath);
f.write(data);
} catch (IOException e) {
return false;
} finally {
MenuHelper.closeSilently(f);
}
return true;
}
private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
if(mThumbController != null && mImageWidth > 0 && mImageHeight > 0){
int miniThumbHeight = mThumbController.getThumbnailHeight();
if(miniThumbHeight > 0){
options.inSampleSize = mImageHeight/miniThumbHeight;
}
}
Bitmap lastPictureThumb =
BitmapFactory.decodeByteArray(data, 0, data.length, options);
lastPictureThumb = Util.rotate(lastPictureThumb, degree);
mThumbController.setData(uri, lastPictureThumb);
}
private String createName(long dateTaken) {
Date date = new Date(dateTaken);
SimpleDateFormat dateFormat = new SimpleDateFormat(
getString(R.string.image_file_name_format));
return dateFormat.format(date);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
prefs = getSharedPreferences("com.android.camera_preferences", 0);
powerShutter(prefs);
setContentView(R.layout.camera);
mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
mRecordingTimeView = (TextView) findViewById(R.id.recording_time);
mPreferences = new ComboPreferences(this);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
mPreferences.setLocalId(this, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
mShutterdownTime = 0;
mShutterupTime = 0;
mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
// we need to reset exposure for the preview
resetExposureCompensation();
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
Thread startPreviewThread = new Thread(new Runnable() {
public void run() {
try {
mStartPreviewFail = false;
startPreview();
} catch (CameraHardwareException e) {
// In eng build, we throw the exception so that test tool
// can detect it and report it
if ("eng".equals(Build.TYPE)) {
throw new RuntimeException(e);
}
mStartPreviewFail = true;
}
}
});
startPreviewThread.start();
// don't set mSurfaceHolder here. We have it set ONLY within
// surfaceChanged / surfaceDestroyed, other parts of the code
// assume that when it is set, the surface is also set.
SurfaceHolder holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mIsImageCaptureIntent = isImageCaptureIntent();
if (mIsImageCaptureIntent) {
setupCaptureParams();
}
LayoutInflater inflater = getLayoutInflater();
ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
if (mIsImageCaptureIntent) {
View controlBar = inflater.inflate(
R.layout.attach_camera_control, rootView);
controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
} else {
inflater.inflate(R.layout.camera_control, rootView);
mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
mSwitcher.setOnSwitchListener(this);
mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
}
// Make sure preview is started.
try {
startPreviewThread.join();
if (mStartPreviewFail) {
showCameraErrorAndFinish();
return;
}
} catch (InterruptedException ex) {
// ignore
}
}
private void changeHeadUpDisplayState() {
// If the camera resumes behind the lock screen, the orientation
// will be portrait. That causes OOM when we try to allocation GPU
// memory for the GLSurfaceView again when the orientation changes. So,
// we delayed initialization of HeadUpDisplay until the orientation
// becomes landscape.
Configuration config = getResources().getConfiguration();
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
&& !mPausing && mFirstTimeInitialized) {
if (mGLRootView == null) attachHeadUpDisplay();
} else if (mGLRootView != null) {
detachHeadUpDisplay();
}
}
private void overrideHudSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
mHeadUpDisplay.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
}
private void updateSceneModeInHud() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideHudSettings(getString(R.string.pref_camera_flashmode_default),
getString(R.string.pref_camera_whitebalance_default),
getString(R.string.pref_camera_focusmode_default));
} else {
overrideHudSettings(null, null, null);
}
}
private void initializeHeadUpDisplay() {
CameraSettings settings = new CameraSettings(this, mInitialParams,
CameraHolder.instance().getCameraInfo(), mCameraId);
boolean zoomSupported = CameraSettings.isZoomSupported(this, mCameraId);
((CameraHeadUpDisplay)mHeadUpDisplay).initialize(this,
settings.getPreferenceGroup(R.xml.camera_preferences),
zoomSupported ? getZoomRatios() : null,
mOrientationCompensation, mParameters);
if (zoomSupported) {
((CameraHeadUpDisplay)mHeadUpDisplay).setZoomListener(new ZoomControllerListener() {
public void onZoomChanged(
int index, float ratio, boolean isMoving) {
onZoomValueChanged(index);
}
});
}
updateSceneModeInHud();
}
private void attachHeadUpDisplay() {
mHeadUpDisplay.setOrientation(mOrientationCompensation);
if (mParameters.isZoomSupported()) {
((CameraHeadUpDisplay)mHeadUpDisplay).setZoomIndex(mZoomValue);
}
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
mGLRootView = new GLRootView(this);
mGLRootView.setContentPane(mHeadUpDisplay);
frame.addView(mGLRootView);
}
private void detachHeadUpDisplay() {
((CameraHeadUpDisplay)mHeadUpDisplay).setGpsHasSignal(false);
mHeadUpDisplay.collapse();
((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView);
mGLRootView = null;
}
public static int roundOrientation(int orientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
private class MyOrientationEventListener
extends OrientationEventListener {
public MyOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == ORIENTATION_UNKNOWN) return;
mOrientation = roundOrientation(orientation);
// When the screen is unlocked, display rotation may change. Always
// calculate the up-to-date orientationCompensation.
int orientationCompensation = mOrientation
+ Util.getDisplayRotation(Camera.this);
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
if (!mIsImageCaptureIntent) {
setOrientationIndicator(mOrientationCompensation);
}
mHeadUpDisplay.setOrientation(mOrientationCompensation);
}
}
}
private void setOrientationIndicator(int degree) {
((RotateImageView) findViewById(
R.id.review_thumbnail)).setDegree(degree);
((RotateImageView) findViewById(
R.id.camera_switch_icon)).setDegree(degree);
((RotateImageView) findViewById(
R.id.video_switch_icon)).setDegree(degree);
}
@Override
public void onStart() {
super.onStart();
if (!mIsImageCaptureIntent) {
mSwitcher.setSwitch(SWITCH_CAMERA);
}
}
@Override
public void onStop() {
super.onStop();
if (mMediaProviderClient != null) {
mMediaProviderClient.release();
mMediaProviderClient = null;
}
}
private void checkStorage() {
calculatePicturesRemaining();
updateStorageHint(mPicturesRemaining);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_retake:
hidePostCaptureAlert();
restartPreview();
break;
case R.id.review_thumbnail:
if (isCameraIdle()) {
viewLastImage();
}
break;
case R.id.btn_done:
doAttach();
break;
case R.id.btn_cancel:
doCancel();
}
}
private Bitmap createCaptureBitmap(byte[] data) {
// This is really stupid...we just want to read the orientation in
// the jpeg header.
String filepath = ImageManager.getTempJpegPath();
int degree = 0;
if (saveDataToFile(filepath, data)) {
degree = ImageManager.getExifOrientation(filepath);
new File(filepath).delete();
}
// Limit to 50k pixels so we can return it in the intent.
Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
bitmap = Util.rotate(bitmap, degree);
return bitmap;
}
private void doAttach() {
if (mPausing) {
return;
}
byte[] data = mImageCapture.getLastCaptureData();
if (mCropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to it's
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
setResult(RESULT_OK);
finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else {
Bitmap bitmap = createCaptureBitmap(data);
setResult(RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = openFileOutput(sTempCropFilename, 0);
tempStream.write(data);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
} catch (IOException ex) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
} finally {
Util.closeSilently(tempStream);
}
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
newExtras.putBoolean("return-data", true);
}
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
startActivityForResult(cropIntent, CROP_MSG);
}
}
private void doCancel() {
setResult(RESULT_CANCELED, new Intent());
finish();
}
private synchronized void incrementkeypress() {
if(keypresscount == 0)
keypresscount++;
}
private synchronized void decrementkeypress() {
if(keypresscount > 0)
keypresscount--;
}
private synchronized int keypressvalue() {
return keypresscount;
}
public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
if (mPausing) {
return;
}
int keydown = keypressvalue();
if(keydown==0 && pressed)
{
keyup = 1;
Log.v(TAG, "the keydown is pressed first time");
mShutterdownTime = System.currentTimeMillis();
}
else if(keyup==1 && !pressed)
{
Log.v(TAG, "the keyup is pressed first time ");
keyup = 0;
}
switch (button.getId()) {
case R.id.shutter_button:
doFocus(pressed);
break;
}
}
public void onShutterButtonClick(ShutterButton button) {
mShutterupTime = System.currentTimeMillis();
if (mPausing) {
return;
}
switch (button.getId()) {
case R.id.shutter_button:
doSnap();
break;
}
}
private OnScreenHint mStorageHint;
private void updateStorageHint(int remaining) {
String noStorageText = null;
if (remaining == MenuHelper.NO_STORAGE_ERROR) {
String state = Environment.getExternalStorageState();
if (state == Environment.MEDIA_CHECKING) {
noStorageText = getString(R.string.preparing_sd);
} else {
noStorageText = getString(R.string.no_storage);
}
} else if (remaining == MenuHelper.CANNOT_STAT_ERROR) {
noStorageText = getString(R.string.access_sd_fail);
} else if (remaining < 1) {
noStorageText = getString(R.string.not_enough_space);
}
if (noStorageText != null) {
if (mStorageHint == null) {
mStorageHint = OnScreenHint.makeText(this, noStorageText);
} else {
mStorageHint.setText(noStorageText);
}
mStorageHint.show();
} else if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
}
private void installIntentFilter() {
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addDataScheme("file");
registerReceiver(mReceiver, intentFilter);
mDidRegister = true;
}
private void initializeFocusTone() {
// Initialize focus tone generator.
try {
mFocusToneGenerator = new ToneGenerator(
AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
} catch (Throwable ex) {
Log.w(TAG, "Exception caught while creating tone generator: ", ex);
mFocusToneGenerator = null;
}
}
private void initializeScreenBrightness() {
Window win = getWindow();
// Overright the brightness settings if it is automatic
int mode = Settings.System.getInt(
getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
win.setAttributes(winParams);
}
}
@Override
protected void onResume() {
super.onResume();
mPausing = false;
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
mImageCapture = new ImageCapture();
// Start the preview if it is not started.
if (!mPreviewing && !mStartPreviewFail) {
resetExposureCompensation();
if (!restartPreview()) return;
}
if (mSurfaceHolder != null) {
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
}
keepScreenOnAwhile();
}
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
changeHeadUpDisplayState();
}
private static ImageManager.DataLocation dataLocation() {
return ImageManager.DataLocation.EXTERNAL;
}
@Override
protected void onPause() {
mPausing = true;
stopPreview();
// Close the camera now because other activities may need to use it.
closeCamera();
resetScreenOn();
changeHeadUpDisplayState();
if (mFirstTimeInitialized) {
mOrientationListener.disable();
if (!mIsImageCaptureIntent) {
mThumbController.storeData(
ImageManager.getLastImageThumbPath());
}
hidePostCaptureAlert();
}
keypresscount = 0;
if (mDidRegister) {
unregisterReceiver(mReceiver);
mDidRegister = false;
}
stopReceivingLocationUpdates();
if (mFocusToneGenerator != null) {
mFocusToneGenerator.release();
mFocusToneGenerator = null;
}
if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mImageCapture.clearLastData();
mImageCapture = null;
// Remove the messages in the event queue.
mHandler.removeMessages(RESTART_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
super.onPause();
}
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CROP_MSG: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
setResult(resultCode, intent);
finish();
File path = getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
}
private void autoFocus() {
// Initiate autofocus only when preview is started and snapshot is not
// in progress.
if (canTakePicture()) {
mHeadUpDisplay.setEnabled(false);
Log.v(TAG, "Start autofocus.");
mFocusStartTime = System.currentTimeMillis();
mFocusState = FOCUSING;
updateFocusIndicator();
mCameraDevice.autoFocus(mAutoFocusCallback);
}
}
private void cancelAutoFocus() {
// User releases half-pressed focus key.
if (mStatus != SNAPSHOT_IN_PROGRESS && (mFocusState == FOCUSING
|| mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) {
Log.v(TAG, "Cancel autofocus.");
mHeadUpDisplay.setEnabled(true);
mCameraDevice.cancelAutoFocus();
}
if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
clearFocusState();
}
}
private void clearFocusState() {
mFocusState = FOCUS_NOT_STARTED;
updateFocusIndicator();
}
private void updateFocusIndicator() {
if (mFocusRectangle == null) return;
if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
mFocusRectangle.showStart();
} else if (mFocusState == FOCUS_SUCCESS) {
mFocusRectangle.showSuccess();
} else if (mFocusState == FOCUS_FAIL) {
mFocusRectangle.showFail();
} else {
mFocusRectangle.clear();
}
}
@Override
public void onBackPressed() {
if (!isCameraIdle()) {
// ignore backs while we're taking a picture
return;
} else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) {
super.onBackPressed();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean searchShutter = prefs.getBoolean("search_shutter_enabled", false);
boolean volUpShutter = prefs.getBoolean("vol_up_shutter_enabled", false);
boolean volDownShutter = prefs.getBoolean("vol_down_shutter_enabled", false);
boolean volZoom = prefs.getBoolean("vol_zoom_enabled", false);
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
doFocus(true);
}
return true;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
doSnap();
}
return true;
case KeyEvent.KEYCODE_SEARCH:
if (searchShutter) {
doShutter(prefs, event);
}
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
if (volUpShutter && doShutter(prefs, event)) {
return true;
}
if (volZoom && !doVolZoom(true)) {
return false;
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (volDownShutter && doShutter(prefs, event)) {
return true;
}
if (volZoom && !doVolZoom(false)) {
return false;
}
return true;
case KeyEvent.KEYCODE_POWER:
if (powerShutter(prefs)){
doFocus(true);
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, doFocus() will be
// called again but it is fine.
if (mHeadUpDisplay.collapse()) return true;
doFocus(true);
if (mShutterButton.isInTouchMode()) {
mShutterButton.requestFocusFromTouch();
} else {
mShutterButton.requestFocus();
}
mShutterButton.setPressed(true);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean doShutter(SharedPreferences prefs, KeyEvent event) {
if (!mFirstTimeInitialized || event.getRepeatCount() != 0) {
return false;
}
boolean longFocus = prefs.getBoolean("long_focus_enabled", false);
boolean preFocus = prefs.getBoolean("pre_focus_enabled", false);
if (preFocus || longFocus) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, doFocus() will be
// called again but it is fine.
if (mHeadUpDisplay.collapse()) return true;
doFocus(true);
} else {
mFocusState = FOCUS_SUCCESS;
}
if (!longFocus) {
doSnap();
} else {
if (mHeadUpDisplay.collapse()) return true;
doFocus(true);
}
return false;
}
private boolean doVolZoom(boolean up) {
if (!mParameters.isZoomSupported()) {
return true;
}
// Perform zoom only when preview is started and snapshot is not in progress.
if (mPausing || !isCameraIdle() || !mPreviewing || mZoomState != ZOOM_STOPPED) {
return false;
}
if (up && mZoomValue < mZoomMax) {
mZoomValue++;
} else if (!up && mZoomValue > 0) {
mZoomValue--;
}
setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
((CameraHeadUpDisplay)mHeadUpDisplay).setZoomIndex(mZoomValue);
return true;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean longFocus = prefs.getBoolean("long_focus_enabled", false);
switch (keyCode) {
case KeyEvent.KEYCODE_SEARCH:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (longFocus) {
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
doSnap();
}
}
return true;
case KeyEvent.KEYCODE_POWER:
if (powerShutter(prefs)){
doSnap();
}
return true;
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
doFocus(false);
}
return true;
}
return super.onKeyUp(keyCode, event);
}
private void updateTimer(int timerSeconds) {
mRecordingTimeView.setText(String.format("%d:%02d", timerSeconds / 60, timerSeconds % 60));
timerSeconds--;
if (timerSeconds < 0) {
autoFocus();
mFocusState = FOCUSING_SNAP_ON_FINISH;
doFocus(true);
} else {
Message timerMsg = Message.obtain();
timerMsg.arg1 = timerSeconds;
timerMsg.what = CAMERA_TIMER;
mHandler.sendMessageDelayed(timerMsg, 1000);
}
}
private void doSnap() {
if (mHeadUpDisplay.collapse()) return;
if (mTimerMode) return;
Log.d(TAG, "doSnap: mFocusState=" + mFocusState + " mFocusMode=" + mFocusMode);
// If the user has half-pressed the shutter and focus is completed, we
// can take the photo right away. If the focus mode is infinity, we can
// also take the photo.
if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
|| mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
|| mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
|| mFocusMode.equals(CameraSettings.FOCUS_MODE_TOUCH)
|| (mFocusState == FOCUS_SUCCESS
|| mFocusState == FOCUS_FAIL)) {
mImageCapture.onSnap();
} else if (mFocusState == FOCUSING) {
// Half pressing the shutter (i.e. the focus button event) will
// already have requested AF for us, so just request capture on
// focus here.
mFocusState = FOCUSING_SNAP_ON_FINISH;
} else if (mFocusState == FOCUS_NOT_STARTED) {
// Focus key down event is dropped for some reasons. Just ignore.
}
}
private void doFocus(boolean pressed) {
if (!mTimerMode && pressed) {
if (mCaptureMode.equals(getResources().getString(
R.string.pref_camera_capturemode_entry_timer))) {
mTimerMode = true;
mShutterButton.setImageDrawable(getResources().getDrawable(
R.drawable.btn_ic_video_record_stop));
mRecordingTimeView.setVisibility(View.VISIBLE);
updateTimer(Integer.valueOf(prefs.getString("timer_duration", "10")));
return;
}
} else if (mTimerMode && pressed) {
mShutterButton.setImageDrawable(getResources().getDrawable(
R.drawable.btn_ic_camera_shutter));
mTimerMode = false;
mHandler.removeMessages(CAMERA_TIMER);
mRecordingTimeView.setVisibility(View.GONE);
return;
} else if (mTimerMode && !pressed) {
return;
}
// Do the focus if the mode is not infinity.
if (mHeadUpDisplay.collapse()) return;
if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
|| mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
|| mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
|| mFocusMode.equals(CameraSettings.FOCUS_MODE_TOUCH))) {
if (pressed) { // Focus key down.
autoFocus();
} else { // Focus key up.
cancelAutoFocus();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Make sure we have a surface in the holder before proceeding.
if (holder.getSurface() == null) {
Log.d(TAG, "holder.getSurface() == null");
return;
}
// We need to save the holder for later use, even when the mCameraDevice
// is null. This could happen if onResume() is invoked after this
// function.
mSurfaceHolder = holder;
// The mCameraDevice will be null if it fails to connect to the camera
// hardware. In this case we will show a dialog and then finish the
// activity, so it's OK to ignore it.
if (mCameraDevice == null) return;
// Sometimes surfaceChanged is called after onPause or before onResume.
// Ignore it.
if (mPausing || isFinishing()) return;
if (mPreviewing && holder.isCreating()) {
// Set preview display if the surface is being created and preview
// was already started. That means preview display was set to null
// and we need to set it now.
setPreviewDisplay(holder);
} else {
// 1. Restart the preview if the size of surface was changed. The
// framework may not support changing preview display on the fly.
// 2. Start the preview now if surface was destroyed and preview
// stopped.
restartPreview();
}
// If first time initialization is not finished, send a message to do
// it later. We want to finish surfaceChanged as soon as possible to let
// user see preview first.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
stopPreview();
mSurfaceHolder = null;
}
private void closeCamera() {
if (mCameraDevice != null) {
CameraHolder.instance().release();
mCameraDevice.setZoomChangeListener(null);
mCameraDevice = null;
mPreviewing = false;
}
}
private void ensureCameraDevice() throws CameraHardwareException {
if (mCameraDevice == null) {
mCameraDevice = CameraHolder.instance().open(mCameraId);
mInitialParams = mCameraDevice.getParameters();
}
}
private void updateLastImage() {
IImageList list = ImageManager.makeImageList(
mContentResolver,
dataLocation(),
ImageManager.INCLUDE_IMAGES,
ImageManager.SORT_ASCENDING,
ImageManager.CAMERA_IMAGE_BUCKET_ID);
int count = list.getCount();
if (count > 0) {
IImage image = list.getImageAt(count - 1);
Uri uri = image.fullSizeImageUri();
mThumbController.setData(uri, image.miniThumbBitmap());
} else {
mThumbController.setData(null, null);
}
list.close();
}
private void showCameraErrorAndFinish() {
Resources ress = getResources();
Util.showFatalErrorAndFinish(Camera.this,
ress.getString(R.string.camera_error_title),
ress.getString(R.string.cannot_connect_camera));
}
private boolean restartPreview() {
try {
startPreview();
} catch (CameraHardwareException e) {
showCameraErrorAndFinish();
return false;
}
return true;
}
private void setPreviewDisplay(SurfaceHolder holder) {
try {
mCameraDevice.setPreviewDisplay(holder);
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("setPreviewDisplay failed", ex);
}
}
private void startPreview() throws CameraHardwareException {
if (mPausing || isFinishing()) return;
ensureCameraDevice();
// If we're previewing already, stop the preview first (this will blank
// the screen).
if (mPreviewing) stopPreview();
setPreviewDisplay(mSurfaceHolder);
Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
setCameraParameters(UPDATE_PARAM_ALL);
CameraSettings.setVideoMode(mParameters, false);
mCameraDevice.setParameters(mParameters);
mCameraDevice.setErrorCallback(mErrorCallback);
try {
Log.v(TAG, "startPreview");
mCameraDevice.startPreview();
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("startPreview failed", ex);
}
mPreviewing = true;
mZoomState = ZOOM_STOPPED;
mStatus = IDLE;
/* Get the correct max zoom value, as this varies with
* preview size/picture resolution
*/
mParameters = mCameraDevice.getParameters();
mZoomMax = mParameters.getMaxZoom();
}
private void stopPreview() {
if (mCameraDevice != null && mPreviewing) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
}
mPreviewing = false;
// If auto focus was in progress, it would have been canceled.
clearFocusState();
}
private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
final double ASPECT_TOLERANCE = 0.05;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
// Because of bugs of overlay and layout, we sometimes will try to
// layout the viewfinder in the portrait orientation and thus get the
// wrong size of mSurfaceView. When we change the preview size, the
// new overlay will be created before the old one closed, which causes
// an exception. For now, just get the screen size
Display display = getWindowManager().getDefaultDisplay();
int targetHeight = Math.min(display.getHeight(), display.getWidth());
if (targetHeight <= 0) {
// We don't know the size of SurefaceView, use screen height
WindowManager windowManager = (WindowManager)
getSystemService(Context.WINDOW_SERVICE);
targetHeight = windowManager.getDefaultDisplay().getHeight();
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
Log.v(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
private void updateCameraParametersInitialize() {
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
private void updateCameraParametersPreference() {
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(this, mParameters);
} else {
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
}
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
PreviewFrameLayout frameLayout =
(PreviewFrameLayout) findViewById(R.id.frame_layout);
frameLayout.setAspectRatio((double) size.width / size.height);
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(
sizes, (double) size.width / size.height);
if (optimalSize != null) {
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get lastest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
}
// Since change scene mode may change supported values,
// Set scene mode first,
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
getString(R.string.pref_camera_scenemode_default));
if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
mCameraDevice.setParameters(mParameters);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
// Set JPEG quality.
String jpegQuality = mPreferences.getString(
CameraSettings.KEY_JPEG_QUALITY,
getString(R.string.pref_camera_jpegquality_default));
mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set ISO parameter.
String iso = mPreferences.getString(
CameraSettings.KEY_ISO,
getString(R.string.pref_camera_iso_default));
if (isSupported(iso,
mParameters.getSupportedIsoValues())) {
mParameters.setISOValue(iso);
}
//Set LensShading
String lensshade = mPreferences.getString(
CameraSettings.KEY_LENSSHADING,
getString(R.string.pref_camera_lensshading_default));
if (isSupported(lensshade,
mParameters.getSupportedLensShadeModes())) {
mParameters.setLensShade(lensshade);
}
// Set auto exposure parameter.
String autoExposure = mPreferences.getString(
CameraSettings.KEY_AUTOEXPOSURE,
getString(R.string.pref_camera_autoexposure_default));
if (isSupported(autoExposure, mParameters.getSupportedAutoexposure())) {
mParameters.setAutoExposure(autoExposure);
}
// Set anti banding parameter.
String antiBanding = mPreferences.getString(
CameraSettings.KEY_ANTIBANDING,
getString(R.string.pref_camera_antibanding_default));
if (isSupported(antiBanding, mParameters.getSupportedAntibanding())) {
mParameters.setAntibanding(antiBanding);
}
// Set exposure compensation
String exposure = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
try {
float value = Float.parseFloat(exposure);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.set("exposure-compensation", exposure);
} else {
Log.w(TAG, "invalid exposure range: " + exposure);
}
} catch (NumberFormatException e) {
Log.w(TAG, "invalid exposure: " + exposure);
}
setCommonParameters();
//Clearing previous GPS data if any
if(mRecordLocation) {
//Reset the values when store location is selected
mParameters.setGpsLatitude(0);
mParameters.setGpsLongitude(0);
mParameters.setGpsAltitude(0);
mParameters.setGpsTimestamp(0);
}
if (mHeadUpDisplay != null) updateSceneModeInHud();
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Do white balance after as scenemode affects it
setWhiteBalance();
// Set focus mode.
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE,
getString(R.string.pref_camera_focusmode_default));
// Set capture mode.
mCaptureMode = mPreferences.getString(
CameraSettings.KEY_CAPTURE_MODE,
- getString(R.string.pref_camera_capturemode_entry_timer));
+ getString(R.string.pref_camera_capturemode_entry_default));
if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
mParameters.setFocusMode(mFocusMode);
} else if (CameraSettings.FOCUS_MODE_TOUCH.equals(mFocusMode)) {
mParameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
} else {
mFocusMode = mParameters.getFocusMode();
if (mFocusMode == null) {
mFocusMode = Parameters.FOCUS_MODE_AUTO;
}
}
clearFocusState();
resetFocusIndicator();
clearTouchFocusAEC();
} else {
mFocusMode = mParameters.getFocusMode();
}
}
// We separate the parameters into several subsets, so we can update only
// the subsets actually need updating. The PREFERENCE set needs extra
// locking because the preference can be changed from GLThread as well.
private void setCameraParameters(int updateSet) {
mParameters = mCameraDevice.getParameters();
if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
updateCameraParametersInitialize();
}
if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
updateCameraParametersZoom();
}
if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
updateCameraParametersPreference();
}
CameraSettings.dumpParameters(mParameters);
try {
mCameraDevice.setParameters(mParameters);
} catch (Exception e) {
// Some phones with dual cameras fail to report the actual parameters
// on the FFC. Filtering is device-specific but would be better.
Log.e(TAG, "Error setting parameters: " + e.getMessage());
}
}
// If the Camera is idle, update the parameters immediately, otherwise
// accumulate them in mUpdateSet and update later.
private void setCameraParametersWhenIdle(int additionalUpdateSet) {
mUpdateSet |= additionalUpdateSet;
if (mCameraDevice == null) {
// We will update all the parameters when we open the device, so
// we don't need to do anything now.
mUpdateSet = 0;
return;
} else if (isCameraIdle()) {
setCameraParameters(mUpdateSet);
mUpdateSet = 0;
} else {
if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
mHandler.sendEmptyMessageDelayed(
SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
}
}
}
private void gotoCameraSettings() {
Intent intent = new Intent(this, AdvancedSettings.class);
startActivity(intent);
}
private void gotoGallery() {
MenuHelper.gotoCameraImageGallery(this);
}
private void viewLastImage() {
if (mThumbController.isUriValid()) {
Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
try {
intent = new Intent(Intent.ACTION_VIEW, mThumbController.getUri());
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "review image fail", e);
}
}
} else {
Log.e(TAG, "Can't view last image.");
}
}
private void startReceivingLocationUpdates() {
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0F,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0F,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
}
}
private void stopReceivingLocationUpdates() {
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private Location getCurrentLocation() {
// go in best to worst order
for (int i = 0; i < mLocationListeners.length; i++) {
Location l = mLocationListeners[i].current();
if (l != null) return l;
}
return null;
}
private boolean isCameraIdle() {
return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
}
private boolean isImageCaptureIntent() {
String action = getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
}
private void setupCaptureParams() {
Bundle myExtras = getIntent().getExtras();
if (myExtras != null) {
mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
mCropValue = myExtras.getString("crop");
}
}
private void showPostCaptureAlert() {
if (mIsImageCaptureIntent) {
findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
int[] pickIds = {R.id.btn_retake, R.id.btn_done};
for (int id : pickIds) {
View button = findViewById(id);
((View) button.getParent()).setVisibility(View.VISIBLE);
}
}
}
private void hidePostCaptureAlert() {
if (mIsImageCaptureIntent) {
findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
int[] pickIds = {R.id.btn_retake, R.id.btn_done};
for (int id : pickIds) {
View button = findViewById(id);
((View) button.getParent()).setVisibility(View.GONE);
}
}
}
private int calculatePicturesRemaining() {
mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
return mPicturesRemaining;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// Only show the menu when camera is idle.
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(isCameraIdle());
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
if (mIsImageCaptureIntent) {
// No options menu for attach mode.
return false;
} else {
addBaseMenuItems(menu);
}
return true;
}
private void addBaseMenuItems(Menu menu) {
MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
public void run() {
switchToVideoMode();
}
});
MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
MenuHelper.POSITION_GOTO_GALLERY,
R.string.camera_gallery_photos_text)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
gotoGallery();
return true;
}
});
gallery.setIcon(android.R.drawable.ic_menu_gallery);
mGalleryItems.add(gallery);
MenuItem mCameraSettings = menu.add(Menu.NONE, Menu.NONE,
MenuHelper.POSITION_CAMERA_SETTINGS,
R.string.advanced_options_label)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
gotoCameraSettings();
return true;
}
});
mCameraSettings.setIcon(android.R.drawable.ic_menu_preferences);
mGalleryItems.add(mCameraSettings);
if (mNumberOfCameras > 1) {
menu.add(Menu.NONE, Menu.NONE,
MenuHelper.POSITION_SWITCH_CAMERA_ID,
R.string.switch_camera_id)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switchCameraId((mCameraId + 1) % mNumberOfCameras);
return true;
}
}).setIcon(android.R.drawable.ic_menu_camera);
}
}
private void switchCameraId(int cameraId) {
if (mPausing || !isCameraIdle()) return;
mCameraId = cameraId;
CameraSettings.writePreferredCameraId(mPreferences, cameraId);
stopPreview();
closeCamera();
// Remove the messages in the event queue.
mHandler.removeMessages(RESTART_PREVIEW);
// Reset variables
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
// Reload the preferences.
mPreferences.setLocalId(this, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
// Restart the preview.
resetExposureCompensation();
if (!restartPreview()) return;
initializeZoom();
// Reload the UI.
if (mFirstTimeInitialized) {
initializeHeadUpDisplay();
}
}
private boolean switchToVideoMode() {
if (isFinishing() || !isCameraIdle()) return false;
MenuHelper.gotoVideoMode(this);
mHandler.removeMessages(FIRST_TIME_INIT);
finish();
return true;
}
public boolean onSwitchChanged(Switcher source, boolean onOff) {
if (onOff == SWITCH_VIDEO) {
return switchToVideoMode();
} else {
return true;
}
}
private void onSharedPreferenceChanged() {
// ignore the events after "onPause()"
if (mPausing) return;
boolean recordLocation;
recordLocation = RecordLocationPreference.get(
mPreferences, getContentResolver());
if (mRecordLocation != recordLocation) {
mRecordLocation = recordLocation;
if (mRecordLocation) {
startReceivingLocationUpdates();
} else {
stopReceivingLocationUpdates();
}
}
int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
if (mCameraId != cameraId) {
switchCameraId(cameraId);
} else {
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
}
}
@Override
public void onUserInteraction() {
super.onUserInteraction();
keepScreenOnAwhile();
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
public void onSharedPreferencesChanged() {
Camera.this.onSharedPreferenceChanged();
}
public void onRestorePreferencesClicked() {
Camera.this.onRestorePreferencesClicked();
}
public void onPopupWindowVisibilityChanged(int visibility) {
}
}
protected void onRestorePreferencesClicked() {
if (mPausing) return;
Runnable runnable = new Runnable() {
public void run() {
mHeadUpDisplay.restorePreferences(mParameters);
}
};
MenuHelper.confirmAction(this,
getString(R.string.confirm_restore_title),
getString(R.string.confirm_restore_message),
runnable);
}
}
/*
* Provide a mapping for Jpeg encoding quality levels
* from String representation to numeric representation.
*/
class JpegEncodingQualityMappings {
private static final String TAG = "JpegEncodingQualityMappings";
private static final int DEFAULT_QUALITY = 85;
private static HashMap<String, Integer> mHashMap =
new HashMap<String, Integer>();
static {
mHashMap.put("normal", CameraProfile.QUALITY_LOW);
mHashMap.put("fine", CameraProfile.QUALITY_MEDIUM);
mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
}
// Retrieve and return the Jpeg encoding quality number
// for the given quality level.
public static int getQualityNumber(String jpegQuality) {
Integer quality = mHashMap.get(jpegQuality);
if (quality == null) {
Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
return DEFAULT_QUALITY;
}
return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
}
}
| true | true | private void updateCameraParametersPreference() {
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(this, mParameters);
} else {
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
}
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
PreviewFrameLayout frameLayout =
(PreviewFrameLayout) findViewById(R.id.frame_layout);
frameLayout.setAspectRatio((double) size.width / size.height);
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(
sizes, (double) size.width / size.height);
if (optimalSize != null) {
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get lastest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
}
// Since change scene mode may change supported values,
// Set scene mode first,
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
getString(R.string.pref_camera_scenemode_default));
if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
mCameraDevice.setParameters(mParameters);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
// Set JPEG quality.
String jpegQuality = mPreferences.getString(
CameraSettings.KEY_JPEG_QUALITY,
getString(R.string.pref_camera_jpegquality_default));
mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set ISO parameter.
String iso = mPreferences.getString(
CameraSettings.KEY_ISO,
getString(R.string.pref_camera_iso_default));
if (isSupported(iso,
mParameters.getSupportedIsoValues())) {
mParameters.setISOValue(iso);
}
//Set LensShading
String lensshade = mPreferences.getString(
CameraSettings.KEY_LENSSHADING,
getString(R.string.pref_camera_lensshading_default));
if (isSupported(lensshade,
mParameters.getSupportedLensShadeModes())) {
mParameters.setLensShade(lensshade);
}
// Set auto exposure parameter.
String autoExposure = mPreferences.getString(
CameraSettings.KEY_AUTOEXPOSURE,
getString(R.string.pref_camera_autoexposure_default));
if (isSupported(autoExposure, mParameters.getSupportedAutoexposure())) {
mParameters.setAutoExposure(autoExposure);
}
// Set anti banding parameter.
String antiBanding = mPreferences.getString(
CameraSettings.KEY_ANTIBANDING,
getString(R.string.pref_camera_antibanding_default));
if (isSupported(antiBanding, mParameters.getSupportedAntibanding())) {
mParameters.setAntibanding(antiBanding);
}
// Set exposure compensation
String exposure = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
try {
float value = Float.parseFloat(exposure);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.set("exposure-compensation", exposure);
} else {
Log.w(TAG, "invalid exposure range: " + exposure);
}
} catch (NumberFormatException e) {
Log.w(TAG, "invalid exposure: " + exposure);
}
setCommonParameters();
//Clearing previous GPS data if any
if(mRecordLocation) {
//Reset the values when store location is selected
mParameters.setGpsLatitude(0);
mParameters.setGpsLongitude(0);
mParameters.setGpsAltitude(0);
mParameters.setGpsTimestamp(0);
}
if (mHeadUpDisplay != null) updateSceneModeInHud();
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Do white balance after as scenemode affects it
setWhiteBalance();
// Set focus mode.
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE,
getString(R.string.pref_camera_focusmode_default));
// Set capture mode.
mCaptureMode = mPreferences.getString(
CameraSettings.KEY_CAPTURE_MODE,
getString(R.string.pref_camera_capturemode_entry_timer));
if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
mParameters.setFocusMode(mFocusMode);
} else if (CameraSettings.FOCUS_MODE_TOUCH.equals(mFocusMode)) {
mParameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
} else {
mFocusMode = mParameters.getFocusMode();
if (mFocusMode == null) {
mFocusMode = Parameters.FOCUS_MODE_AUTO;
}
}
clearFocusState();
resetFocusIndicator();
clearTouchFocusAEC();
} else {
mFocusMode = mParameters.getFocusMode();
}
}
| private void updateCameraParametersPreference() {
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(this, mParameters);
} else {
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
}
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
PreviewFrameLayout frameLayout =
(PreviewFrameLayout) findViewById(R.id.frame_layout);
frameLayout.setAspectRatio((double) size.width / size.height);
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(
sizes, (double) size.width / size.height);
if (optimalSize != null) {
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get lastest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
}
// Since change scene mode may change supported values,
// Set scene mode first,
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
getString(R.string.pref_camera_scenemode_default));
if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
mCameraDevice.setParameters(mParameters);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
// Set JPEG quality.
String jpegQuality = mPreferences.getString(
CameraSettings.KEY_JPEG_QUALITY,
getString(R.string.pref_camera_jpegquality_default));
mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set ISO parameter.
String iso = mPreferences.getString(
CameraSettings.KEY_ISO,
getString(R.string.pref_camera_iso_default));
if (isSupported(iso,
mParameters.getSupportedIsoValues())) {
mParameters.setISOValue(iso);
}
//Set LensShading
String lensshade = mPreferences.getString(
CameraSettings.KEY_LENSSHADING,
getString(R.string.pref_camera_lensshading_default));
if (isSupported(lensshade,
mParameters.getSupportedLensShadeModes())) {
mParameters.setLensShade(lensshade);
}
// Set auto exposure parameter.
String autoExposure = mPreferences.getString(
CameraSettings.KEY_AUTOEXPOSURE,
getString(R.string.pref_camera_autoexposure_default));
if (isSupported(autoExposure, mParameters.getSupportedAutoexposure())) {
mParameters.setAutoExposure(autoExposure);
}
// Set anti banding parameter.
String antiBanding = mPreferences.getString(
CameraSettings.KEY_ANTIBANDING,
getString(R.string.pref_camera_antibanding_default));
if (isSupported(antiBanding, mParameters.getSupportedAntibanding())) {
mParameters.setAntibanding(antiBanding);
}
// Set exposure compensation
String exposure = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
try {
float value = Float.parseFloat(exposure);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.set("exposure-compensation", exposure);
} else {
Log.w(TAG, "invalid exposure range: " + exposure);
}
} catch (NumberFormatException e) {
Log.w(TAG, "invalid exposure: " + exposure);
}
setCommonParameters();
//Clearing previous GPS data if any
if(mRecordLocation) {
//Reset the values when store location is selected
mParameters.setGpsLatitude(0);
mParameters.setGpsLongitude(0);
mParameters.setGpsAltitude(0);
mParameters.setGpsTimestamp(0);
}
if (mHeadUpDisplay != null) updateSceneModeInHud();
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Do white balance after as scenemode affects it
setWhiteBalance();
// Set focus mode.
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE,
getString(R.string.pref_camera_focusmode_default));
// Set capture mode.
mCaptureMode = mPreferences.getString(
CameraSettings.KEY_CAPTURE_MODE,
getString(R.string.pref_camera_capturemode_entry_default));
if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
mParameters.setFocusMode(mFocusMode);
} else if (CameraSettings.FOCUS_MODE_TOUCH.equals(mFocusMode)) {
mParameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
} else {
mFocusMode = mParameters.getFocusMode();
if (mFocusMode == null) {
mFocusMode = Parameters.FOCUS_MODE_AUTO;
}
}
clearFocusState();
resetFocusIndicator();
clearTouchFocusAEC();
} else {
mFocusMode = mParameters.getFocusMode();
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java
index 678a0bef6..c79d54bb6 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java
@@ -1,1813 +1,1812 @@
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Benjamin Muskalla ([email protected]) - Bug 149672 [Patch] Create Patch wizard should remember previous settings
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui.wizards;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.wizard.*;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.team.core.Team;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.diff.IDiff;
import org.eclipse.team.core.diff.IDiffVisitor;
import org.eclipse.team.core.mapping.provider.ResourceDiffTree;
import org.eclipse.team.core.synchronize.SyncInfoSet;
import org.eclipse.team.internal.ccvs.core.CVSException;
import org.eclipse.team.internal.ccvs.core.ICVSFile;
import org.eclipse.team.internal.ccvs.core.client.Command;
import org.eclipse.team.internal.ccvs.core.client.Diff;
import org.eclipse.team.internal.ccvs.core.client.Command.LocalOption;
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
import org.eclipse.team.internal.ccvs.core.syncinfo.ResourceSyncInfo;
import org.eclipse.team.internal.ccvs.ui.*;
import org.eclipse.team.internal.ccvs.ui.IHelpContextIds;
import org.eclipse.team.internal.ccvs.ui.operations.*;
import org.eclipse.team.internal.ccvs.ui.subscriber.CreatePatchWizardParticipant;
import org.eclipse.team.internal.ccvs.ui.subscriber.WorkspaceSynchronizeParticipant;
import org.eclipse.team.internal.core.subscribers.SubscriberSyncInfoCollector;
import org.eclipse.team.internal.ui.*;
import org.eclipse.team.ui.synchronize.*;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.views.navigator.ResourceComparator;
/**
* A wizard for creating a patch file by running the CVS diff command.
*/
public class GenerateDiffFileWizard extends Wizard {
//The initial size of this wizard.
private final static int INITIAL_WIDTH = 300;
private final static int INITIAL_HEIGHT = 350;
public static void run(IWorkbenchPart part, final IResource[] resources, boolean unifiedSelectionEnabled) {
final String title = CVSUIMessages.GenerateCVSDiff_title;
final GenerateDiffFileWizard wizard = new GenerateDiffFileWizard(part,resources, unifiedSelectionEnabled);
wizard.setWindowTitle(title);
WizardDialog dialog = new WizardDialog(part.getSite().getShell(), wizard);
dialog.setMinimumPageSize(INITIAL_WIDTH, INITIAL_HEIGHT);
dialog.open();
}
public static void run(IWorkbenchPart part, final IResource[] resources) {
GenerateDiffFileWizard.run(part,resources,true);
}
/**
* Page to select a patch file. Overriding validatePage was necessary to allow
* entering a file name that already exists.
*/
public class LocationPage extends WizardPage {
/**
* The possible locations to save a patch.
*/
public final static int CLIPBOARD = 1;
public final static int FILESYSTEM = 2;
public final static int WORKSPACE = 3;
/**
* GUI controls for clipboard (cp), filesystem (fs) and workspace (ws).
*/
private Button cpRadio;
private Button fsRadio;
protected Text fsPathText;
private Button fsBrowseButton;
private boolean fsBrowsed = false;
private Button wsRadio;
protected Text wsPathText;
private Button wsBrowseButton;
private boolean wsBrowsed = false;
protected CreatePatchWizardParticipant fParticipant;
private Button chgSelectAll;
private Button chgDeselectAll;
/**
* State information of this page, updated by the listeners.
*/
protected boolean canValidate;
protected boolean pageValid;
protected IContainer wsSelectedContainer;
protected IPath[] foldersToCreate;
protected int selectedLocation;
/**
* The default values store used to initialize the selections.
*/
private final DefaultValuesStore store;
class LocationPageContentProvider extends BaseWorkbenchContentProvider {
//Never show closed projects
boolean showClosedProjects=false;
public Object[] getChildren(Object element) {
if (element instanceof IWorkspace) {
// check if closed projects should be shown
IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects();
if (showClosedProjects)
return allProjects;
ArrayList accessibleProjects = new ArrayList();
for (int i = 0; i < allProjects.length; i++) {
if (allProjects[i].isOpen()) {
accessibleProjects.add(allProjects[i]);
}
}
return accessibleProjects.toArray();
}
return super.getChildren(element);
}
}
class WorkspaceDialog extends TitleAreaDialog {
protected TreeViewer wsTreeViewer;
protected Text wsFilenameText;
protected Image dlgTitleImage;
private boolean modified = false;
public WorkspaceDialog(Shell shell) {
super(shell);
}
protected Control createContents(Composite parent) {
Control control = super.createContents(parent);
setTitle(CVSUIMessages.WorkspacePatchDialogTitle);
setMessage(CVSUIMessages.WorkspacePatchDialogDescription);
//create title image
dlgTitleImage = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_DIFF).createImage();
setTitleImage(dlgTitleImage);
return control;
}
protected Control createDialogArea(Composite parent){
Composite parentComposite = (Composite) super.createDialogArea(parent);
// create a composite with standard margins and spacing
Composite composite = new Composite(parentComposite, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setFont(parentComposite.getFont());
getShell().setText(CVSUIMessages.GenerateDiffFileWizard_9);
wsTreeViewer = new TreeViewer(composite, SWT.BORDER);
final GridData gd= new GridData(SWT.FILL, SWT.FILL, true, true);
gd.widthHint= 550;
gd.heightHint= 250;
wsTreeViewer.getTree().setLayoutData(gd);
wsTreeViewer.setContentProvider(new LocationPageContentProvider());
wsTreeViewer.setComparator(new ResourceComparator(ResourceComparator.NAME));
wsTreeViewer.setLabelProvider(new WorkbenchLabelProvider());
wsTreeViewer.setInput(ResourcesPlugin.getWorkspace());
//Open to whatever is selected in the workspace field
IPath existingWorkspacePath = new Path(wsPathText.getText());
if (existingWorkspacePath != null){
//Ensure that this workspace path is valid
IResource selectedResource = ResourcesPlugin.getWorkspace().getRoot().findMember(existingWorkspacePath);
if (selectedResource != null) {
wsTreeViewer.expandToLevel(selectedResource, 0);
wsTreeViewer.setSelection(new StructuredSelection(selectedResource));
}
}
final Composite group = new Composite(composite, SWT.NONE);
layout = new GridLayout(2, false);
layout.marginWidth = 0;
group.setLayout(layout);
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
final Label label = new Label(group, SWT.NONE);
label.setLayoutData(new GridData());
label.setText(CVSUIMessages.Fi_le_name__9);
wsFilenameText = new Text(group,SWT.BORDER);
wsFilenameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
setupListeners();
return parent;
}
protected Button createButton(Composite parent, int id,
String label, boolean defaultButton) {
Button button = super.createButton(parent, id, label,
defaultButton);
if (id == IDialogConstants.OK_ID) {
button.setEnabled(false);
}
return button;
}
private void validateDialog() {
String fileName = wsFilenameText.getText();
if (fileName.equals("")) { //$NON-NLS-1$
if (modified) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_2);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return;
} else {
setErrorMessage(null);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return;
}
}
// make sure that the filename is valid
if (!(ResourcesPlugin.getWorkspace().validateName(fileName,
IResource.FILE)).isOK() && modified) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_5);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return;
}
// Make sure that a container has been selected
if (getSelectedContainer() == null) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_0);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return;
} else {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IPath fullPath = wsSelectedContainer.getFullPath().append(
fileName);
if (workspace.getRoot().getFolder(fullPath).exists()) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_FolderExists);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return;
}
}
setErrorMessage(null);
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
protected void okPressed() {
IFile file = wsSelectedContainer.getFile(new Path(
wsFilenameText.getText()));
if (file != null)
wsPathText.setText(file.getFullPath().toString());
validatePage();
super.okPressed();
}
private IContainer getSelectedContainer() {
Object obj = ((IStructuredSelection)wsTreeViewer.getSelection()).getFirstElement();
if (obj instanceof IContainer) {
wsSelectedContainer = (IContainer) obj;
} else if (obj instanceof IFile) {
wsSelectedContainer = ((IFile) obj).getParent();
}
return wsSelectedContainer;
}
protected void cancelPressed() {
validatePage();
super.cancelPressed();
}
public boolean close() {
if (dlgTitleImage != null)
dlgTitleImage.dispose();
return super.close();
}
void setupListeners(){
wsTreeViewer.addSelectionChangedListener(
new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection s = (IStructuredSelection)event.getSelection();
Object obj=s.getFirstElement();
if (obj instanceof IContainer)
wsSelectedContainer = (IContainer) obj;
else if (obj instanceof IFile){
IFile tempFile = (IFile) obj;
wsSelectedContainer = tempFile.getParent();
wsFilenameText.setText(tempFile.getName());
}
validateDialog();
}
});
wsTreeViewer.addDoubleClickListener(
new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
ISelection s= event.getSelection();
if (s instanceof IStructuredSelection) {
Object item = ((IStructuredSelection)s).getFirstElement();
if (wsTreeViewer.getExpandedState(item))
wsTreeViewer.collapseToLevel(item, 1);
else
wsTreeViewer.expandToLevel(item, 1);
}
validateDialog();
}
});
wsFilenameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
modified = true;
validateDialog();
}
});
}
}
LocationPage(String pageName, String title, ImageDescriptor image, DefaultValuesStore store) {
super(pageName, title, image);
setPageComplete(false);
this.store= store;
this.canValidate=false;
}
/**
* Allow the user to finish if a valid file has been entered.
*/
protected boolean validatePage() {
if (!canValidate)
return false;
switch (selectedLocation) {
case WORKSPACE:
pageValid= validateWorkspaceLocation();
break;
case FILESYSTEM:
pageValid= validateFilesystemLocation();
break;
case CLIPBOARD:
pageValid= true;
break;
}
if ((resources = getSelectedResources()).length == 0) {
pageValid = false;
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_noChangesSelected);
}
/**
* Avoid draw flicker by clearing error message
* if all is valid.
*/
if (pageValid) {
setMessage(null);
setErrorMessage(null);
}
setPageComplete(pageValid);
return pageValid;
}
/**
* The following conditions must hold for the file system location
* to be valid:
* - the path must be valid and non-empty
* - the path must be absolute
* - the specified file must be of type file
* - the parent must exist (new folders can be created via the browse button)
*/
private boolean validateFilesystemLocation() {
final String pathString= fsPathText.getText().trim();
if (pathString.length() == 0 || !new Path("").isValidPath(pathString)) { //$NON-NLS-1$
if (fsBrowsed)
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_0);
else
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_browseFilesystem);
return false;
}
final File file= new File(pathString);
if (!file.isAbsolute()) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_0);
return false;
}
if (file.isDirectory()) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_2);
return false;
}
if (pathString.endsWith("/") || pathString.endsWith("\\")) { //$NON-NLS-1$//$NON-NLS-2$
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_3);
return false;
}
final File parent= file.getParentFile();
if (!(parent.exists() && parent.isDirectory())) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_3);
return false;
}
return true;
}
/**
* The following conditions must hold for the file system location to be valid:
* - a parent must be selected in the workspace tree view
* - the resource name must be valid
*/
private boolean validateWorkspaceLocation() {
//make sure that the field actually has a filename in it - making
//sure that the user has had a chance to browse the workspace first
if (wsPathText.getText().equals("")){ //$NON-NLS-1$
if (selectedLocation ==WORKSPACE && wsBrowsed)
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_5);
else
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_4);
return false;
}
//Make sure that all the segments but the last one (i.e. project + all
//folders) exist - file doesn't have to exist. It may have happened that
//some folder refactoring has been done since this path was last saved.
//
// The path will always be in format project/{folders}*/file - this
// is controlled by the workspace location dialog and by
// validatePath method when path has been entered manually.
IPath pathToWorkspaceFile = new Path(wsPathText.getText());
IStatus status = ResourcesPlugin.getWorkspace().validatePath(wsPathText.getText(), IResource.FILE);
if (status.isOK()) {
//Trim file name from path
IPath containerPath = pathToWorkspaceFile.removeLastSegments(1);
IResource container =ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
if (container == null) {
if (selectedLocation == WORKSPACE)
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_4);
return false;
} else if (!container.isAccessible()) {
if (selectedLocation == WORKSPACE)
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_ProjectClosed);
return false;
} else {
if (ResourcesPlugin.getWorkspace().getRoot().getFolder(
pathToWorkspaceFile).exists()) {
setErrorMessage(CVSUIMessages.GenerateDiffFileWizard_FolderExists);
return false;
}
}
} else {
setErrorMessage(status.getMessage());
return false;
}
return true;
}
/**
* Answers a full path to a file system file or <code>null</code> if the user
* selected to save the patch in the clipboard.
*/
public File getFile() {
if (pageValid && selectedLocation == FILESYSTEM) {
return new File(fsPathText.getText().trim());
}
if (pageValid && selectedLocation == WORKSPACE) {
final String filename= wsPathText.getText().trim();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
final IFile file= root.getFile(new Path(filename));
return file.getLocation().toFile();
}
return null;
}
/**
* Answers the workspace string entered in the dialog or <code>null</code> if the user
* selected to save the patch in the clipboard or file system.
*/
public String getWorkspaceLocation() {
if (pageValid && selectedLocation == WORKSPACE) {
final String filename= wsPathText.getText().trim();
return filename;
}
return null;
}
/**
* Get the selected workspace resource if the patch is to be saved in the
* workspace, or null otherwise.
*/
public IResource getResource() {
if (pageValid && selectedLocation == WORKSPACE) {
IPath pathToWorkspaceFile = new Path(wsPathText.getText().trim());
//Trim file name from path
IPath containerPath = pathToWorkspaceFile.removeLastSegments(1);
return ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
}
return null;
}
/**
* Allow the user to chose to save the patch to the workspace or outside
* of the workspace.
*/
public void createControl(Composite parent) {
final Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
setControl(composite);
initializeDialogUnits(composite);
// set F1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.PATCH_SELECTION_PAGE);
//Create a location group
setupLocationControls(composite);
initializeDefaultValues();
fParticipant = new CreatePatchWizardParticipant(new ResourceScope(((GenerateDiffFileWizard)this.getWizard()).resources), (GenerateDiffFileWizard) this.getWizard());
try {
getAllOutOfSync();
} catch (CVSException e) {}
final PixelConverter converter= new PixelConverter(parent);
createChangesArea(composite, converter);
createSelectionButtons(composite);
Dialog.applyDialogFont(parent);
/**
* Ensure the page is in a valid state.
*/
/*if (!validatePage()) {
store.storeRadioSelection(CLIPBOARD);
initializeDefaultValues();
validatePage();
}
pageValid= true;*/
validatePage();
updateEnablements();
setupListeners();
}
private void createSelectionButtons(Composite composite) {
final Composite buttonGroup = new Composite(composite,SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
buttonGroup.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END
| GridData.VERTICAL_ALIGN_CENTER);
buttonGroup.setLayoutData(data);
chgSelectAll = createSelectionButton(CVSUIMessages.GenerateDiffFileWizard_SelectAll, buttonGroup);
chgDeselectAll = createSelectionButton(CVSUIMessages.GenerateDiffFileWizard_DeselectAll, buttonGroup);
}
private Button createSelectionButton(String buttonName, Composite buttonGroup) {
Button button = new Button(buttonGroup,SWT.PUSH);
button.setText(buttonName);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
data.widthHint = Math.max(widthHint, minSize.x);
button.setLayoutData(data);
return button;
}
/**
* Setup the controls for the location.
*/
private void setupLocationControls(final Composite parent) {
final Composite composite = new Composite(parent, SWT.NULL);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// clipboard
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan = 3;
cpRadio = new Button(composite, SWT.RADIO);
cpRadio.setText(CVSUIMessages.Save_To_Clipboard_2);
cpRadio.setLayoutData(gd);
// filesystem
fsRadio = new Button(composite, SWT.RADIO);
fsRadio.setText(CVSUIMessages.Save_In_File_System_3);
fsPathText = new Text(composite, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
fsPathText.setLayoutData(gd);
fsBrowseButton = new Button(composite, SWT.PUSH);
fsBrowseButton.setText(CVSUIMessages.Browse____4);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
Point minSize = fsBrowseButton.computeSize(SWT.DEFAULT,
SWT.DEFAULT, true);
data.widthHint = Math.max(widthHint, minSize.x);
fsBrowseButton.setLayoutData(data);
// workspace
wsRadio = new Button(composite, SWT.RADIO);
wsRadio.setText(CVSUIMessages.Save_In_Workspace_7);
wsPathText = new Text(composite, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
wsPathText.setLayoutData(gd);
wsBrowseButton = new Button(composite, SWT.PUSH);
wsBrowseButton.setText(CVSUIMessages.Browse____4);
data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
minSize = fsBrowseButton
.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
data.widthHint = Math.max(widthHint, minSize.x);
wsBrowseButton.setLayoutData(data);
// change the cpRadio layout to be of the same height as other rows' layout
((GridData)cpRadio.getLayoutData()).heightHint = minSize.y;
}
private ParticipantPagePane fPagePane;
private PageBook bottomChild;
private ISynchronizePageConfiguration fConfiguration;
private void createChangesArea(Composite parent, PixelConverter converter) {
int size = fParticipant.getSyncInfoSet().size();
if (size > getFileDisplayThreshold()) {
// Create a page book to allow eventual inclusion of changes
bottomChild = new PageBook(parent, SWT.NONE);
bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, false));
// Create composite for showing the reason for not showing the changes and a button to show them
Composite changeDesc = new Composite(bottomChild, SWT.NONE);
changeDesc.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE));
SWTUtils.createLabel(changeDesc, NLS.bind(CVSUIMessages.CommitWizardCommitPage_1, new String[] { Integer.toString(size), Integer.toString(getFileDisplayThreshold()) }));
Button showChanges = new Button(changeDesc, SWT.PUSH);
showChanges.setText(CVSUIMessages.CommitWizardCommitPage_5);
showChanges.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showChangesPane();
}
});
showChanges.setLayoutData(new GridData());
bottomChild.showPage(changeDesc);
} else {
final Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE));
composite.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true));
createPlaceholder(composite);
Control c = createChangesPage(composite, fParticipant);
c.setLayoutData(SWTUtils.createHVFillGridData());
}
}
protected void showChangesPane() {
Control c = createChangesPage(bottomChild, fParticipant);
bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true));
bottomChild.showPage(c);
Dialog.applyDialogFont(getControl());
((Composite)getControl()).layout();
}
private Control createChangesPage(final Composite composite, WorkspaceSynchronizeParticipant participant) {
fConfiguration= participant.createPageConfiguration();
fPagePane= new ParticipantPagePane(getShell(), true /* modal */, fConfiguration, participant);
Control control = fPagePane.createPartControl(composite);
return control;
}
public void dispose() {
if (fPagePane != null)
fPagePane.dispose();
if (fParticipant != null)
fParticipant.dispose();
super.dispose();
}
private int getFileDisplayThreshold() {
return CVSUIPlugin.getPlugin().getPreferenceStore().getInt(ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD);
}
private void createPlaceholder(final Composite composite) {
final Composite placeholder= new Composite(composite, SWT.NONE);
placeholder.setLayoutData(new GridData(SWT.DEFAULT, convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_SPACING) /3));
}
/**
* Initialize the controls with the saved default values which are
* obtained from the DefaultValuesStore.
*/
private void initializeDefaultValues() {
selectedLocation= store.getLocationSelection();
updateRadioButtons();
/**
* Text fields.
*/
// We need to ensure that we have a valid workspace path - user
//could have altered workspace since last time this was saved
wsPathText.setText(store.getWorkspacePath());
if(!validateWorkspaceLocation()) {
wsPathText.setText(""); //$NON-NLS-1$
//Don't open wizard with an error - instead change selection
//to clipboard
if (selectedLocation == WORKSPACE){
//clear the error message caused by the workspace not having
//any workspace path entered
setErrorMessage(null);
selectedLocation=CLIPBOARD;
updateRadioButtons();
}
}
// Do the same thing for the filesystem field
fsPathText.setText(store.getFilesystemPath());
if (!validateFilesystemLocation()) {
fsPathText.setText(""); //$NON-NLS-1$
if (selectedLocation == FILESYSTEM) {
setErrorMessage(null);
selectedLocation = CLIPBOARD;
updateRadioButtons();
}
}
}
private void updateRadioButtons() {
/**
* Radio buttons
*/
cpRadio.setSelection(selectedLocation == CLIPBOARD);
fsRadio.setSelection(selectedLocation == FILESYSTEM);
wsRadio.setSelection(selectedLocation == WORKSPACE);
}
/**
* Setup all the listeners for the controls.
*/
private void setupListeners() {
cpRadio.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
selectedLocation= CLIPBOARD;
validatePage();
updateEnablements();
}
});
fsRadio.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
selectedLocation= FILESYSTEM;
validatePage();
updateEnablements();
}
});
wsRadio.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
selectedLocation= WORKSPACE;
validatePage();
updateEnablements();
}
});
ModifyListener pathTextModifyListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
validatePage();
}
};
fsPathText.addModifyListener(pathTextModifyListener);
wsPathText.addModifyListener(pathTextModifyListener);
fsBrowseButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
final FileDialog dialog = new FileDialog(getShell(), SWT.PRIMARY_MODAL | SWT.SAVE);
if (pageValid) {
final File file= new File(fsPathText.getText());
dialog.setFilterPath(file.getParent());
}
dialog.setText(CVSUIMessages.Save_Patch_As_5);
dialog.setFileName(CVSUIMessages.patch_txt_6);
final String path = dialog.open();
fsBrowsed = true;
if (path != null) {
fsPathText.setText(new Path(path).toOSString());
}
validatePage();
}
});
wsBrowseButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
final WorkspaceDialog dialog = new WorkspaceDialog(getShell());
wsBrowsed = true;
dialog.open();
validatePage();
}
});
chgSelectAll.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
initCheckedItems();
//Only bother changing isPageComplete state if the current state
//is not enabled
if (!isPageComplete())
setPageComplete(validatePage());
}
});
chgDeselectAll.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
ISynchronizePage page = fConfiguration.getPage();
if (page != null){
Viewer viewer = page.getViewer();
if (viewer instanceof CheckboxTreeViewer) {
CheckboxTreeViewer treeViewer =(CheckboxTreeViewer)viewer;
treeViewer.setCheckedElements(new Object[0]);
}
}
//Only bother changing isPageComplete state if the current state
//is enabled
if (isPageComplete())
setPageComplete(validatePage());
}
});
ISynchronizePage page = fConfiguration.getPage();
if (page != null) {
Viewer viewer = page.getViewer();
if (viewer instanceof CheckboxTreeViewer) {
((CheckboxTreeViewer)viewer).addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
setPageComplete(validatePage());
}
});
}
}
}
protected void initCheckedItems() {
ISynchronizePage page = fConfiguration.getPage();
if (page != null) {
Viewer viewer = page.getViewer();
if (viewer instanceof CheckboxTreeViewer) {
TreeItem[] items=((CheckboxTreeViewer)viewer).getTree().getItems();
for (int i = 0; i < items.length; i++) {
((CheckboxTreeViewer)viewer).setChecked(items[i].getData(), true);
}
}
}
}
protected IResource[] getSelectedResources() {
ISynchronizePage page = fConfiguration.getPage();
if (page != null) {
Viewer viewer = page.getViewer();
if (viewer instanceof CheckboxTreeViewer) {
Object[] elements = ((CheckboxTreeViewer)viewer).getCheckedElements();
IResource[]selectedResources = Utils.getResources(elements);
ArrayList result = new ArrayList();
for (int i = 0; i < selectedResources.length; i++) {
IResource resource = selectedResources[i];
if (fConfiguration.getSyncInfoSet().getSyncInfo(resource) != null) {
result.add(resource);
}
}
return (IResource[]) result.toArray(new IResource[result.size()]);
}
}
return new IResource[0];
}
/**
* Enable and disable controls based on the selected radio button.
*/
public void updateEnablements() {
fsBrowseButton.setEnabled(selectedLocation == FILESYSTEM);
fsPathText.setEnabled(selectedLocation == FILESYSTEM);
if (selectedLocation == FILESYSTEM)
fsBrowsed=false;
wsPathText.setEnabled(selectedLocation == WORKSPACE);
wsBrowseButton.setEnabled(selectedLocation == WORKSPACE);
if (selectedLocation == WORKSPACE)
wsBrowsed=false;
}
public int getSelectedLocation() {
return selectedLocation;
}
private SyncInfoSet getAllOutOfSync() throws CVSException {
final SubscriberSyncInfoCollector syncInfoCollector = fParticipant.getSubscriberSyncInfoCollector();
//WaitForChangesJob waits for the syncInfoCollector to get all the changes
//before checking off the tree items and validating the page
class WaitForChangesJob extends Job{
LocationPage fLocationPage;
public WaitForChangesJob(LocationPage page) {
super(""); //$NON-NLS-1$
fLocationPage=page;
}
public IStatus run(IProgressMonitor monitor) {
monitor.beginTask(CVSUIMessages.CommitWizard_4, IProgressMonitor.UNKNOWN);
syncInfoCollector.waitForCollector(monitor);
Utils.syncExec(new Runnable() {
public void run() {
fLocationPage.initCheckedItems();
fLocationPage.canValidate=true;
fLocationPage.validatePage();
}
}, getControl());
monitor.done();
return Status.OK_STATUS;
}
}
WaitForChangesJob job =new WaitForChangesJob(this);
//Don't need the job in the UI, make it a system job
job.setSystem(true);
job.schedule();
return fParticipant.getSyncInfoSet();
}
public IFile findBinaryFile() {
try {
final IFile[] found = new IFile[1];
fParticipant.getSubscriber().accept(resources, IResource.DEPTH_INFINITE, new IDiffVisitor() {
public boolean visit(IDiff diff) {
if (isBinaryFile(diff))
found[0] = getFile(diff);
return true;
}
});
return found[0];
} catch (CoreException e) {
CVSUIPlugin.log(e);
}
return null;
}
protected boolean isBinaryFile(IDiff diff) {
IFile file = getFile(diff);
if (file != null) {
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file);
try {
byte[] bytes = cvsFile.getSyncBytes();
if (bytes != null) {
return ResourceSyncInfo.getKeywordMode(bytes).toMode().equals(
Command.KSUBST_BINARY.toMode());
}
} catch (CVSException e) {
CVSUIPlugin.log(e);
}
return (Team.getFileContentManager().getType(file) == Team.BINARY);
}
return false;
}
protected IFile getFile(IDiff diff) {
IResource resource = ResourceDiffTree.getResourceFor(diff);
if (resource instanceof IFile) {
IFile file = (IFile) resource;
return file;
}
return null;
}
public void removeBinaryFiles() {
try {
final List nonBinaryFiles = new ArrayList();
fParticipant.getSubscriber().accept(resources, IResource.DEPTH_INFINITE, new IDiffVisitor() {
public boolean visit(IDiff diff) {
if (!isBinaryFile(diff)) {
IFile file = getFile(diff);
if (file != null)
nonBinaryFiles.add(file);
}
return true;
}
});
resources = (IResource[]) nonBinaryFiles
.toArray(new IResource[nonBinaryFiles.size()]);
} catch (CoreException e) {
CVSUIPlugin.log(e);
}
}
}
/**
* Page to select the options for creating the patch.
*/
private class OptionsPage extends WizardPage {
/**
* The possible file format to save a patch.
*/
public final static int FORMAT_UNIFIED = 1;
public final static int FORMAT_CONTEXT = 2;
public final static int FORMAT_STANDARD = 3;
/**
The possible root of the patch
*/
public final static int ROOT_WORKSPACE = 1;
public final static int ROOT_PROJECT = 2;
public final static int ROOT_SELECTION = 3;
private Button unifiedDiffOption;
private Button unified_workspaceRelativeOption; //multi-patch format
private Button unified_projectRelativeOption; //full project path
private Button unified_selectionRelativeOption; //use path of whatever is selected
private Button contextDiffOption;
private Button regularDiffOption;
private final RadioButtonGroup diffTypeRadioGroup = new RadioButtonGroup();
private final RadioButtonGroup unifiedRadioGroup = new RadioButtonGroup();
private boolean patchHasCommonRoot=true;
protected IPath patchRoot=ResourcesPlugin.getWorkspace().getRoot().getFullPath();
private final DefaultValuesStore store;
/**
* Constructor for PatchFileCreationOptionsPage.
*
* @param pageName
* the name of the page
*
* @param title
* the title for this wizard page, or <code>null</code> if
* none
* @param titleImage
* the image descriptor for the title of this wizard page, or
* <code>null</code> if none
* @param store
* the value store where the page stores it's data
*/
protected OptionsPage(String pageName, String title,
ImageDescriptor titleImage, DefaultValuesStore store) {
super(pageName, title, titleImage);
this.store = store;
}
/*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
composite.setLayout(layout);
composite.setLayoutData(new GridData());
setControl(composite);
// set F1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.PATCH_OPTIONS_PAGE);
Group diffTypeGroup = new Group(composite, SWT.NONE);
layout = new GridLayout();
- layout.marginHeight = 0;
diffTypeGroup.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
diffTypeGroup.setLayoutData(data);
diffTypeGroup.setText(CVSUIMessages.Diff_output_format_12);
unifiedDiffOption = new Button(diffTypeGroup, SWT.RADIO);
unifiedDiffOption.setText(CVSUIMessages.Unified__format_required_by_Compare_With_Patch_feature__13);
contextDiffOption = new Button(diffTypeGroup, SWT.RADIO);
contextDiffOption.setText(CVSUIMessages.Context_14);
regularDiffOption = new Button(diffTypeGroup, SWT.RADIO);
regularDiffOption.setText(CVSUIMessages.Standard_15);
diffTypeRadioGroup.add(FORMAT_UNIFIED, unifiedDiffOption);
diffTypeRadioGroup.add(FORMAT_CONTEXT, contextDiffOption);
diffTypeRadioGroup.add(FORMAT_STANDARD, regularDiffOption);
//Unified Format Options
Group unifiedGroup = new Group(composite, SWT.None);
layout = new GridLayout();
unifiedGroup.setLayout(layout);
data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
unifiedGroup.setLayoutData(data);
unifiedGroup.setText(CVSUIMessages.GenerateDiffFileWizard_10);
unified_workspaceRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_workspaceRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_6);
unified_workspaceRelativeOption.setSelection(true);
unified_projectRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_projectRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_7);
unified_selectionRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_selectionRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_8);
unifiedRadioGroup.add(ROOT_WORKSPACE, unified_workspaceRelativeOption);
unifiedRadioGroup.add(ROOT_PROJECT, unified_projectRelativeOption);
unifiedRadioGroup.add(ROOT_SELECTION, unified_selectionRelativeOption);
Dialog.applyDialogFont(parent);
initializeDefaultValues();
//add listeners
unifiedDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(true);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_UNIFIED, false);
}
});
contextDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_CONTEXT, false);
}
});
regularDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_STANDARD, false);
}
});
unified_workspaceRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_WORKSPACE, false);
}
});
unified_projectRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_PROJECT, false);
}
});
unified_selectionRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_SELECTION, false);
}
});
calculatePatchRoot();
updateEnablements();
// update selection
diffTypeRadioGroup.selectEnabledOnly();
unifiedRadioGroup.selectEnabledOnly();
}
public int getFormatSelection() {
return diffTypeRadioGroup.getSelected();
}
public int getRootSelection() {
return unifiedRadioGroup.getSelected();
}
private void initializeDefaultValues() {
// Radio buttons for format
diffTypeRadioGroup.setSelection(store.getFormatSelection(), true);
// Radio buttons for patch root
unifiedRadioGroup.setSelection(store.getRootSelection(), true);
if (store.getFormatSelection() != FORMAT_UNIFIED) {
setEnableUnifiedGroup(false);
}
}
protected void updateEnablements() {
if (!patchHasCommonRoot){
diffTypeRadioGroup.setEnablement(false, new int[] {
FORMAT_CONTEXT, FORMAT_STANDARD }, FORMAT_UNIFIED);
unifiedRadioGroup.setEnablement(false, new int[] {
ROOT_PROJECT, ROOT_SELECTION }, ROOT_WORKSPACE);
}
// temporary until we figure out best way to fix synchronize view
// selection
if (!unifiedSelectionEnabled)
unifiedRadioGroup.setEnablement(false, new int[] {ROOT_SELECTION});
}
private void calculatePatchRoot(){
//check to see if this is a multi select patch, if so disable
IResource[] tempResources = ((GenerateDiffFileWizard)this.getWizard()).resources;
//Guard for quick cancellation to avoid ArrayOutOfBounds (see Bug# 117234)
if (tempResources == null)
return;
if (tempResources.length > 1){
//Check to see is the selected resources are contained by the same parent (climbing
//parent by parent to the project root)
//If so, then allow selection relative patches -> set the relative path to the common
//parent [also allow project relative patches]
//If parents are different projects, allow only multiproject selection
patchHasCommonRoot=true;
int segmentMatch=-1;
IPath path = tempResources[0].getFullPath().removeLastSegments(1);
for (int i = 1; i < tempResources.length; i++) {
int segments=path.matchingFirstSegments(tempResources[i].getFullPath());
//Keep track of the lowest number of matches that were found - the common
//path will be this number
if (segmentMatch == -1 ||
segmentMatch>segments){
segmentMatch=segments;
}
//However, if no segments for any one resource - break out of the loop
if (segments == 0){
patchHasCommonRoot=false;
break;
}
}
if (patchHasCommonRoot){
IPath tempPath = path.uptoSegment(segmentMatch);
/*IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
while (!root.exists(tempPath) &&
!tempPath.isRoot()){
tempPath = tempPath.removeLastSegments(1);
}*/
patchRoot=tempPath;
}
} else {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
//take the file name off the path and use that as the patch root
//patchRoot = tempResources[0].getFullPath().removeLastSegments(1);
IPath fullPath = tempResources[0].getFullPath();
IResource resource = root.findMember(fullPath);
//keep trimming the path until we find something that can be used as the
//patch root
while (resource == null &&
!(resource instanceof IWorkspaceRoot)){
fullPath=fullPath.removeLastSegments(1);
resource=root.findMember(fullPath);
}
patchRoot = resource.getFullPath();
if (resource.getType() == IResource.FILE)
patchRoot =resource.getFullPath().removeLastSegments(1);
}
}
/**
* Return the list of Diff command options configured on this page.
*/
public LocalOption[] getOptions() {
List options = new ArrayList(5);
/* if(includeNewFilesOptions.getSelection()) {
options.add(Diff.INCLUDE_NEWFILES);
}
if(!recurseOption.getSelection()) {
options.add(Command.DO_NOT_RECURSE);
}*/
//Add new files for now
options.add(Diff.INCLUDE_NEWFILES);
if(unifiedDiffOption.getSelection()) {
options.add(Diff.UNIFIED_FORMAT);
} else if(contextDiffOption.getSelection()) {
options.add(Diff.CONTEXT_FORMAT);
}
return (LocalOption[]) options.toArray(new LocalOption[options.size()]);
}
protected void setEnableUnifiedGroup(boolean enabled){
unifiedRadioGroup.setEnablement(enabled, new int[] {
ROOT_WORKSPACE, ROOT_PROJECT, ROOT_SELECTION });
//temporary until we figure out best way to fix synchronize view selection
if (!unifiedSelectionEnabled)
unifiedRadioGroup.setEnablement(false, new int[] {ROOT_SELECTION});
}
}
/**
* Class to retrieve and store the default selected values.
*/
private final class DefaultValuesStore {
private static final String PREF_LAST_SELECTION= "org.eclipse.team.internal.ccvs.ui.wizards.GenerateDiffFileWizard.PatchFileSelectionPage.lastselection"; //$NON-NLS-1$
private static final String PREF_LAST_FS_PATH= "org.eclipse.team.internal.ccvs.ui.wizards.GenerateDiffFileWizard.PatchFileSelectionPage.filesystem.path"; //$NON-NLS-1$
private static final String PREF_LAST_WS_PATH= "org.eclipse.team.internal.ccvs.ui.wizards.GenerateDiffFileWizard.PatchFileSelectionPage.workspace.path"; //$NON-NLS-1$
private static final String PREF_LAST_AO_FORMAT = "org.eclipse.team.internal.ccvs.ui.wizards.GenerateDiffFileWizard.OptionsPage.diff.format"; //$NON-NLS-1$
private static final String PREF_LAST_AO_ROOT = "org.eclipse.team.internal.ccvs.ui.wizards.GenerateDiffFileWizard.OptionsPage.patch.root"; //$NON-NLS-1$
private final IDialogSettings dialogSettings;
public DefaultValuesStore() {
dialogSettings= CVSUIPlugin.getPlugin().getDialogSettings();
}
public int getLocationSelection() {
int value= LocationPage.CLIPBOARD;
try {
value= dialogSettings.getInt(PREF_LAST_SELECTION);
} catch (NumberFormatException e) {
// ignore
}
switch (value) {
case LocationPage.FILESYSTEM:
case LocationPage.WORKSPACE:
case LocationPage.CLIPBOARD:
return value;
default:
return LocationPage.CLIPBOARD;
}
}
public String getFilesystemPath() {
final String path= dialogSettings.get(PREF_LAST_FS_PATH);
return path != null ? path : ""; //$NON-NLS-1$
}
public String getWorkspacePath() {
final String path= dialogSettings.get(PREF_LAST_WS_PATH);
return path != null ? path : ""; //$NON-NLS-1$
}
public int getFormatSelection() {
int value = OptionsPage.FORMAT_UNIFIED;
try {
value = dialogSettings.getInt(PREF_LAST_AO_FORMAT);
} catch (NumberFormatException e) {
}
switch (value) {
case OptionsPage.FORMAT_UNIFIED:
case OptionsPage.FORMAT_CONTEXT:
case OptionsPage.FORMAT_STANDARD:
return value;
default:
return OptionsPage.FORMAT_UNIFIED;
}
}
public int getRootSelection() {
int value = OptionsPage.ROOT_WORKSPACE;
try {
value = dialogSettings.getInt(PREF_LAST_AO_ROOT);
} catch (NumberFormatException e) {
}
switch (value) {
case OptionsPage.ROOT_WORKSPACE:
case OptionsPage.ROOT_PROJECT:
case OptionsPage.ROOT_SELECTION:
return value;
default:
return OptionsPage.ROOT_WORKSPACE;
}
}
public void storeLocationSelection(int defaultSelection) {
dialogSettings.put(PREF_LAST_SELECTION, defaultSelection);
}
public void storeFilesystemPath(String path) {
dialogSettings.put(PREF_LAST_FS_PATH, path);
}
public void storeWorkspacePath(String path) {
dialogSettings.put(PREF_LAST_WS_PATH, path);
}
public void storeOutputFormat(int selection) {
dialogSettings.put(PREF_LAST_AO_FORMAT, selection);
}
public void storePatchRoot(int selection) {
dialogSettings.put(PREF_LAST_AO_ROOT, selection);
}
}
private LocationPage locationPage;
private OptionsPage optionsPage;
protected IResource[] resources;
private final DefaultValuesStore defaultValuesStore;
private final IWorkbenchPart part;
//temporary until we figure out best way to fix synchronize view selection
protected boolean unifiedSelectionEnabled;
public GenerateDiffFileWizard(IWorkbenchPart part, IResource[] resources, boolean unifiedSelectionEnabled) {
super();
this.part = part;
this.resources = resources;
setWindowTitle(CVSUIMessages.GenerateCVSDiff_title);
initializeDefaultPageImageDescriptor();
defaultValuesStore= new DefaultValuesStore();
this.unifiedSelectionEnabled=unifiedSelectionEnabled;
}
public void addPages() {
String pageTitle = CVSUIMessages.GenerateCVSDiff_pageTitle;
String pageDescription = CVSUIMessages.GenerateCVSDiff_pageDescription;
locationPage = new LocationPage(pageTitle, pageTitle, CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_DIFF), defaultValuesStore);
locationPage.setDescription(pageDescription);
addPage(locationPage);
pageTitle = CVSUIMessages.Advanced_options_19;
pageDescription = CVSUIMessages.Configure_the_options_used_for_the_CVS_diff_command_20;
optionsPage = new OptionsPage(pageTitle, pageTitle, CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_DIFF), defaultValuesStore);
optionsPage.setDescription(pageDescription);
addPage(optionsPage);
}
/**
* Declares the wizard banner iamge descriptor
*/
protected void initializeDefaultPageImageDescriptor() {
final String iconPath= "icons/full/"; //$NON-NLS-1$
try {
final URL installURL = CVSUIPlugin.getPlugin().getBundle().getEntry("/"); //$NON-NLS-1$
final URL url = new URL(installURL, iconPath + "wizards/newconnect_wiz.gif"); //$NON-NLS-1$
ImageDescriptor desc = ImageDescriptor.createFromURL(url);
setDefaultPageImageDescriptor(desc);
} catch (MalformedURLException e) {
// Should not happen. Ignore.
}
}
/* (Non-javadoc)
* Method declared on IWizard.
*/
public boolean needsProgressMonitor() {
return true;
}
/**
* Completes processing of the wizard. If this method returns <code>
* true</code>, the wizard will close; otherwise, it will stay active.
*/
public boolean performFinish() {
final int location= locationPage.getSelectedLocation();
final File file= location != LocationPage.CLIPBOARD? locationPage.getFile() : null;
if (!(file == null || validateFile(file))) {
return false;
}
//Is this a multi-patch?
boolean multiPatch=false;
if (optionsPage.unifiedDiffOption.getSelection() && optionsPage.unified_workspaceRelativeOption.getSelection())
multiPatch=true;
//If not a multipatch, patch should use project relative or selection relative paths[default]?
boolean useProjectRelativePaths=false;
if (optionsPage.unifiedDiffOption.getSelection() &&
optionsPage.unified_projectRelativeOption.getSelection())
useProjectRelativePaths=true;
IFile binFile = locationPage.findBinaryFile();
if (binFile != null) {
int result = promptToIncludeBinary(binFile);
if (result == 2)
return false;
if (result == 1)
locationPage.removeBinaryFiles();
}
/**
* Perform diff operation.
*/
try {
if (file != null) {
generateDiffToFile(file,multiPatch,useProjectRelativePaths);
} else {
generateDiffToClipboard(multiPatch,useProjectRelativePaths);
}
} catch (TeamException e) {}
/**
* Refresh workspace if necessary and save default selection.
*/
switch (location) {
case LocationPage.WORKSPACE:
final String workspaceResource= locationPage.getWorkspaceLocation();
if (workspaceResource != null){
defaultValuesStore.storeLocationSelection(LocationPage.WORKSPACE);
defaultValuesStore.storeWorkspacePath(workspaceResource);
/* try {
workspaceResource.getParent().refreshLocal(IResource.DEPTH_ONE, null);
} catch(CoreException e) {
CVSUIPlugin.openError(getShell(), CVSUIMessages.GenerateCVSDiff_error, null, e);
return false;
} */
} else {
//Problem with workspace location, open with clipboard next time
defaultValuesStore.storeLocationSelection(LocationPage.CLIPBOARD);
}
break;
case LocationPage.FILESYSTEM:
defaultValuesStore.storeFilesystemPath(file.getPath());
defaultValuesStore.storeLocationSelection(LocationPage.FILESYSTEM);
break;
case LocationPage.CLIPBOARD:
defaultValuesStore.storeLocationSelection(LocationPage.CLIPBOARD);
break;
default:
return false;
}
/**
* Save default selections of Options Page
*/
defaultValuesStore.storeOutputFormat(optionsPage.getFormatSelection());
defaultValuesStore.storePatchRoot(optionsPage.getRootSelection());
return true;
}
private int promptToIncludeBinary(IFile file) {
MessageDialog dialog = new MessageDialog(getShell(), CVSUIMessages.GenerateDiffFileWizard_11, null, // accept
// the default window icon
NLS.bind(CVSUIMessages.GenerateDiffFileWizard_12, file.getFullPath()), MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 1); // no is the default
return dialog.open();
}
private void generateDiffToClipboard(boolean multiPatch, boolean useProjectRelativePaths) throws TeamException {
DiffOperation diffop = new ClipboardDiffOperation(part,RepositoryProviderOperation.asResourceMappers(resources),optionsPage.getOptions(),multiPatch, useProjectRelativePaths, optionsPage.patchRoot);
try {
diffop.run();
} catch (InvocationTargetException e) {}
catch (InterruptedException e) {}
}
private void generateDiffToFile(File file, boolean multiPatch, boolean useProjectRelativePaths) throws TeamException {
DiffOperation diffop = null;
if (locationPage.selectedLocation == LocationPage.WORKSPACE){
diffop = new WorkspaceFileDiffOperation(part,RepositoryProviderOperation.asResourceMappers(resources),optionsPage.getOptions(),file, multiPatch, useProjectRelativePaths, optionsPage.patchRoot);
}
else {
diffop = new FileDiffOperation(part,RepositoryProviderOperation.asResourceMappers(resources),optionsPage.getOptions(),file, multiPatch, useProjectRelativePaths, optionsPage.patchRoot);
}
try {
diffop.run();
} catch (InvocationTargetException e) {}
catch (InterruptedException e) {}
}
public boolean validateFile(File file) {
if (file == null)
return false;
/**
* Consider file valid if it doesn't exist for now.
*/
if (!file.exists())
return true;
/**
* The file exists.
*/
if (!file.canWrite()) {
final String title= CVSUIMessages.GenerateCVSDiff_1;
final String msg= CVSUIMessages.GenerateCVSDiff_2;
final MessageDialog dialog= new MessageDialog(getShell(), title, null, msg, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, 0);
dialog.open();
return false;
}
final String title = CVSUIMessages.GenerateCVSDiff_overwriteTitle;
final String msg = CVSUIMessages.GenerateCVSDiff_overwriteMsg;
final MessageDialog dialog = new MessageDialog(getShell(), title, null, msg, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
dialog.open();
if (dialog.getReturnCode() != 0)
return false;
return true;
}
public LocationPage getLocationPage() {
return locationPage;
}
/**
* The class maintain proper selection of radio button within the group:
* <ul>
* <li>Only one button can be selected at the time.</li>
* <li>Disabled button can't be selected unless all buttons in the group
* are disabled.</li>
* </ul>
*/
/*private*/ class RadioButtonGroup {
/**
* List of buttons in the group. Both radio groups contain 3 elements.
*/
private List buttons = new ArrayList(3);
/**
* Index of the selected button.
*/
private int selected = 0;
/**
* Add a button to the group. While adding a new button the method
* checks if there is only one button selected in the group.
*
* @param buttonCode
* A button's code (eg. <code>ROOT_WORKSPACE</code>). To get
* an index we need to subtract 1 from it.
* @param button
* A button to add.
*/
public void add(int buttonCode, Button button) {
if (button != null && (button.getStyle() & SWT.RADIO) != 0) {
if (button.getSelection() && !buttons.isEmpty()) {
deselectAll();
selected = buttonCode - 1;
}
buttons.add(buttonCode - 1, button);
}
}
/**
* Returns selected button's code.
*
* @return Selected button's code.
*/
public int getSelected() {
return selected + 1;
}
/**
* Set selection to the given button. When
* <code>selectEnabledOnly</code> flag is true the returned value can
* differ from the parameter when a button we want to set selection to
* is disabled and there are other buttons which are enabled.
*
* @param buttonCode
* A button's code (eg. <code>ROOT_WORKSPACE</code>). To get
* an index we need to subtract 1 from it.
* @return Code of the button to which selection was finally set.
*/
public int setSelection(int buttonCode, boolean selectEnabledOnly) {
deselectAll();
((Button) buttons.get(buttonCode - 1)).setSelection(true);
selected = buttonCode - 1;
if (selectEnabledOnly)
selected = selectEnabledOnly() - 1;
return getSelected();
}
/**
* Make sure that only an enabled radio button is selected.
*
* @return A code of the selected button.
*/
public int selectEnabledOnly() {
deselectAll();
Button selectedButton = (Button) buttons.get(selected);
if (!selectedButton.isEnabled()) {
// if the button is disabled, set selection to an enabled one
for (Iterator iterator = buttons.iterator(); iterator.hasNext();) {
Button b = (Button) iterator.next();
if (b.isEnabled()) {
b.setSelection(true);
selected = buttons.indexOf(b);
return selected + 1;
}
}
// if none found, reset the initial selection
selectedButton.setSelection(true);
} else {
// because selection has been cleared, set it again
selectedButton.setSelection(true);
}
// return selected button's code so the value can be stored
return getSelected();
}
/**
* Enable or disable given buttons.
*
* @param enabled
* Indicates whether to enable or disable the buttons.
* @param buttonsToChange
* Buttons to enable/disable.
* @param defaultSelection
* The button to select if the currently selected button
* becomes disabled.
*/
public void setEnablement(boolean enabled, int[] buttonsToChange,
int defaultSelection) {
// enable (or disable) given buttons
for (int i = 0; i < buttonsToChange.length; i++) {
((Button) this.buttons.get(buttonsToChange[i] - 1))
.setEnabled(enabled);
}
// check whether the selected button is enabled
if (!((Button) this.buttons.get(selected)).isEnabled()) {
if (defaultSelection != -1)
// set the default selection and check if it's enabled
setSelection(defaultSelection, true);
else
// no default selection is given, select any enabled button
selectEnabledOnly();
}
}
/**
* Enable or disable given buttons with no default selection. The selection
* will be set to an enabled button using the <code>selectEnabledOnly</code> method.
*
* @param enabled Indicates whether to enable or disable the buttons.
* @param buttonsToChange Buttons to enable/disable.
*/
public void setEnablement(boolean enabled, int[] buttonsToChange) {
// -1 means that no default selection is given
setEnablement(enabled, buttonsToChange, -1);
}
/**
* Deselect all buttons in the group.
*/
private void deselectAll() {
// clear all selections
for (Iterator iterator = buttons.iterator(); iterator.hasNext();)
((Button) iterator.next()).setSelection(false);
}
}
}
| true | true | public void createControl(Composite parent) {
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
composite.setLayout(layout);
composite.setLayoutData(new GridData());
setControl(composite);
// set F1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.PATCH_OPTIONS_PAGE);
Group diffTypeGroup = new Group(composite, SWT.NONE);
layout = new GridLayout();
layout.marginHeight = 0;
diffTypeGroup.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
diffTypeGroup.setLayoutData(data);
diffTypeGroup.setText(CVSUIMessages.Diff_output_format_12);
unifiedDiffOption = new Button(diffTypeGroup, SWT.RADIO);
unifiedDiffOption.setText(CVSUIMessages.Unified__format_required_by_Compare_With_Patch_feature__13);
contextDiffOption = new Button(diffTypeGroup, SWT.RADIO);
contextDiffOption.setText(CVSUIMessages.Context_14);
regularDiffOption = new Button(diffTypeGroup, SWT.RADIO);
regularDiffOption.setText(CVSUIMessages.Standard_15);
diffTypeRadioGroup.add(FORMAT_UNIFIED, unifiedDiffOption);
diffTypeRadioGroup.add(FORMAT_CONTEXT, contextDiffOption);
diffTypeRadioGroup.add(FORMAT_STANDARD, regularDiffOption);
//Unified Format Options
Group unifiedGroup = new Group(composite, SWT.None);
layout = new GridLayout();
unifiedGroup.setLayout(layout);
data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
unifiedGroup.setLayoutData(data);
unifiedGroup.setText(CVSUIMessages.GenerateDiffFileWizard_10);
unified_workspaceRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_workspaceRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_6);
unified_workspaceRelativeOption.setSelection(true);
unified_projectRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_projectRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_7);
unified_selectionRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_selectionRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_8);
unifiedRadioGroup.add(ROOT_WORKSPACE, unified_workspaceRelativeOption);
unifiedRadioGroup.add(ROOT_PROJECT, unified_projectRelativeOption);
unifiedRadioGroup.add(ROOT_SELECTION, unified_selectionRelativeOption);
Dialog.applyDialogFont(parent);
initializeDefaultValues();
//add listeners
unifiedDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(true);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_UNIFIED, false);
}
});
contextDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_CONTEXT, false);
}
});
regularDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_STANDARD, false);
}
});
unified_workspaceRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_WORKSPACE, false);
}
});
unified_projectRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_PROJECT, false);
}
});
unified_selectionRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_SELECTION, false);
}
});
calculatePatchRoot();
updateEnablements();
// update selection
diffTypeRadioGroup.selectEnabledOnly();
unifiedRadioGroup.selectEnabledOnly();
}
| public void createControl(Composite parent) {
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
composite.setLayout(layout);
composite.setLayoutData(new GridData());
setControl(composite);
// set F1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.PATCH_OPTIONS_PAGE);
Group diffTypeGroup = new Group(composite, SWT.NONE);
layout = new GridLayout();
diffTypeGroup.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
diffTypeGroup.setLayoutData(data);
diffTypeGroup.setText(CVSUIMessages.Diff_output_format_12);
unifiedDiffOption = new Button(diffTypeGroup, SWT.RADIO);
unifiedDiffOption.setText(CVSUIMessages.Unified__format_required_by_Compare_With_Patch_feature__13);
contextDiffOption = new Button(diffTypeGroup, SWT.RADIO);
contextDiffOption.setText(CVSUIMessages.Context_14);
regularDiffOption = new Button(diffTypeGroup, SWT.RADIO);
regularDiffOption.setText(CVSUIMessages.Standard_15);
diffTypeRadioGroup.add(FORMAT_UNIFIED, unifiedDiffOption);
diffTypeRadioGroup.add(FORMAT_CONTEXT, contextDiffOption);
diffTypeRadioGroup.add(FORMAT_STANDARD, regularDiffOption);
//Unified Format Options
Group unifiedGroup = new Group(composite, SWT.None);
layout = new GridLayout();
unifiedGroup.setLayout(layout);
data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
unifiedGroup.setLayoutData(data);
unifiedGroup.setText(CVSUIMessages.GenerateDiffFileWizard_10);
unified_workspaceRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_workspaceRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_6);
unified_workspaceRelativeOption.setSelection(true);
unified_projectRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_projectRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_7);
unified_selectionRelativeOption = new Button(unifiedGroup, SWT.RADIO);
unified_selectionRelativeOption.setText(CVSUIMessages.GenerateDiffFileWizard_8);
unifiedRadioGroup.add(ROOT_WORKSPACE, unified_workspaceRelativeOption);
unifiedRadioGroup.add(ROOT_PROJECT, unified_projectRelativeOption);
unifiedRadioGroup.add(ROOT_SELECTION, unified_selectionRelativeOption);
Dialog.applyDialogFont(parent);
initializeDefaultValues();
//add listeners
unifiedDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(true);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_UNIFIED, false);
}
});
contextDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_CONTEXT, false);
}
});
regularDiffOption.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setEnableUnifiedGroup(false);
updateEnablements();
diffTypeRadioGroup.setSelection(FORMAT_STANDARD, false);
}
});
unified_workspaceRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_WORKSPACE, false);
}
});
unified_projectRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_PROJECT, false);
}
});
unified_selectionRelativeOption
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
unifiedRadioGroup.setSelection(ROOT_SELECTION, false);
}
});
calculatePatchRoot();
updateEnablements();
// update selection
diffTypeRadioGroup.selectEnabledOnly();
unifiedRadioGroup.selectEnabledOnly();
}
|
diff --git a/src/paulscode/android/mupen64plusae/util/AssetExtractor.java b/src/paulscode/android/mupen64plusae/util/AssetExtractor.java
index f295dcdf..a0b23f10 100644
--- a/src/paulscode/android/mupen64plusae/util/AssetExtractor.java
+++ b/src/paulscode/android/mupen64plusae/util/AssetExtractor.java
@@ -1,142 +1,142 @@
/**
* Mupen64PlusAE, an N64 emulator for the Android platform
*
* Copyright (C) 2013 Paul Lamb
*
* This file is part of Mupen64PlusAE.
*
* Mupen64PlusAE is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Mupen64PlusAE 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 for more details.
*
* You should have received a copy of the GNU General Public License along with Mupen64PlusAE. If
* not, see <http://www.gnu.org/licenses/>.
*
* Authors: littleguy77
*
* References:
* http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcard
*/
package paulscode.android.mupen64plusae.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.res.AssetManager;
import android.util.Log;
public class AssetExtractor
{
public interface OnExtractionProgressListener
{
public void onExtractionProgress( String nextFileExtracted );
}
public static boolean extractAssets( AssetManager assetManager, String srcPath, String dstPath,
OnExtractionProgressListener onProgress )
{
boolean result = true;
if( srcPath.startsWith( "/" ) )
srcPath = srcPath.substring( 1 );
String[] srcSubPaths = getAssetList( assetManager, srcPath );
if( srcSubPaths.length > 0 )
{
// srcPath is a directory
// Ensure the parent directories exist
new File( dstPath ).mkdirs();
// Recurse into each subdirectory
for( String srcSubPath : srcSubPaths )
{
String suffix = "/" + srcSubPath;
- extractAssets( assetManager, srcPath + suffix, dstPath + suffix, onProgress );
+ result &= extractAssets( assetManager, srcPath + suffix, dstPath + suffix, onProgress );
}
}
else
{
// srcPath is a file
// Call the progress listener before extracting
if( onProgress != null )
onProgress.onExtractionProgress( dstPath );
// Extract the file
try
{
InputStream in = assetManager.open( srcPath );
OutputStream out = new FileOutputStream( dstPath );
byte[] buffer = new byte[1024];
int read;
while( ( read = in.read( buffer ) ) != -1 )
{
out.write( buffer, 0, read );
}
in.close();
out.flush();
out.close();
}
catch( IOException e )
{
Log.w( "AssetExtractor", "Failed to extract asset file: " + srcPath );
result = false;
}
}
return result;
}
public static int countAssets( AssetManager assetManager, String srcPath )
{
int count = 0;
// TODO: This function takes a surprisingly long time to complete.
if( srcPath.startsWith( "/" ) )
srcPath = srcPath.substring( 1 );
String[] srcSubPaths = getAssetList( assetManager, srcPath );
if( srcSubPaths.length > 0 )
{
// srcPath is a directory
for( String srcSubPath : srcSubPaths )
{
count += countAssets( assetManager, srcPath + "/" + srcSubPath );
}
}
else
{
// srcPath is a file
count++;
}
return count;
}
private static String[] getAssetList( AssetManager assetManager, String srcPath )
{
String[] srcSubPaths = null;
try
{
srcSubPaths = assetManager.list( srcPath );
}
catch( IOException e )
{
Log.w( "AssetExtractor", "Failed to get asset file list." );
}
return srcSubPaths;
}
}
| true | true | public static boolean extractAssets( AssetManager assetManager, String srcPath, String dstPath,
OnExtractionProgressListener onProgress )
{
boolean result = true;
if( srcPath.startsWith( "/" ) )
srcPath = srcPath.substring( 1 );
String[] srcSubPaths = getAssetList( assetManager, srcPath );
if( srcSubPaths.length > 0 )
{
// srcPath is a directory
// Ensure the parent directories exist
new File( dstPath ).mkdirs();
// Recurse into each subdirectory
for( String srcSubPath : srcSubPaths )
{
String suffix = "/" + srcSubPath;
extractAssets( assetManager, srcPath + suffix, dstPath + suffix, onProgress );
}
}
else
{
// srcPath is a file
// Call the progress listener before extracting
if( onProgress != null )
onProgress.onExtractionProgress( dstPath );
// Extract the file
try
{
InputStream in = assetManager.open( srcPath );
OutputStream out = new FileOutputStream( dstPath );
byte[] buffer = new byte[1024];
int read;
while( ( read = in.read( buffer ) ) != -1 )
{
out.write( buffer, 0, read );
}
in.close();
out.flush();
out.close();
}
catch( IOException e )
{
Log.w( "AssetExtractor", "Failed to extract asset file: " + srcPath );
result = false;
}
}
return result;
}
| public static boolean extractAssets( AssetManager assetManager, String srcPath, String dstPath,
OnExtractionProgressListener onProgress )
{
boolean result = true;
if( srcPath.startsWith( "/" ) )
srcPath = srcPath.substring( 1 );
String[] srcSubPaths = getAssetList( assetManager, srcPath );
if( srcSubPaths.length > 0 )
{
// srcPath is a directory
// Ensure the parent directories exist
new File( dstPath ).mkdirs();
// Recurse into each subdirectory
for( String srcSubPath : srcSubPaths )
{
String suffix = "/" + srcSubPath;
result &= extractAssets( assetManager, srcPath + suffix, dstPath + suffix, onProgress );
}
}
else
{
// srcPath is a file
// Call the progress listener before extracting
if( onProgress != null )
onProgress.onExtractionProgress( dstPath );
// Extract the file
try
{
InputStream in = assetManager.open( srcPath );
OutputStream out = new FileOutputStream( dstPath );
byte[] buffer = new byte[1024];
int read;
while( ( read = in.read( buffer ) ) != -1 )
{
out.write( buffer, 0, read );
}
in.close();
out.flush();
out.close();
}
catch( IOException e )
{
Log.w( "AssetExtractor", "Failed to extract asset file: " + srcPath );
result = false;
}
}
return result;
}
|
diff --git a/NetBeansProjects/LoginScreen/src/loginscreen/StartupScreen.java b/NetBeansProjects/LoginScreen/src/loginscreen/StartupScreen.java
index 51658a5..7dfbd56 100644
--- a/NetBeansProjects/LoginScreen/src/loginscreen/StartupScreen.java
+++ b/NetBeansProjects/LoginScreen/src/loginscreen/StartupScreen.java
@@ -1,4128 +1,4123 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package loginscreen;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
/**
*
* @author jroberti
*/
public class StartupScreen extends javax.swing.JFrame {
Mediator mediator;
String loginName;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
/**
* Creates new form StartupScreen
*/
public StartupScreen(Mediator m, String ln, Connection c) {
mediator = m;
loginName = ln;
conn = c;
initComponents();
ArrayList list;
ArrayList<JComboBox> comboGrp1;
//Fillcombo();
// Method calls to fill combo boxes
// list = mediator.fillCombo("157", "201");
// for (int i = 0; i < list.size(); i++) {
// jComboBox1.addItem(list.get(i));
// jComboBox2.addItem(list.get(i));
// }
// comboGrp1 = new ArrayList<JComboBox>(jComboBox7, jComboBox8, jComboBox9, jComboBox10);
// list = mediator.fillCombo("201", "312");
// for (int i = 0; i < list.size(); i++) {
// comboGrp1.get(i).addItem(list.get(i));
// }
}
private void Fillcombo(){
try{
String sql = "select * from courses WHERE course_type = 'CSCI' AND course_num >= 157 AND course_num <= 201";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()){
String cid = rs.getString("course_id");
jComboBox1.addItem(cid);
jComboBox2.addItem(cid);
/*for(int i = 1; i<48; i++){
jComboBox1.addItem(cid);*/
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
try{
String sql2 = "select * from courses WHERE course_type = 'CSCI' AND course_num >= 201 AND course_num <= 312";
pst = conn.prepareStatement(sql2);
rs = pst.executeQuery();
while (rs.next()){
String cid = rs.getString("course_id");
jComboBox7.addItem(cid);
jComboBox8.addItem(cid);
jComboBox9.addItem(cid);
jComboBox10.addItem(cid);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel7 = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel6 = new javax.swing.JPanel();
jPanel13 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jComboBox5 = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox3 = new javax.swing.JComboBox();
jComboBox6 = new javax.swing.JComboBox();
jPanel14 = new javax.swing.JPanel();
jLabel198 = new javax.swing.JLabel();
jPanel27 = new javax.swing.JPanel();
jLabel237 = new javax.swing.JLabel();
jLabel238 = new javax.swing.JLabel();
jComboBox7 = new javax.swing.JComboBox();
jComboBox10 = new javax.swing.JComboBox();
jLabel239 = new javax.swing.JLabel();
jLabel240 = new javax.swing.JLabel();
jComboBox8 = new javax.swing.JComboBox();
jComboBox11 = new javax.swing.JComboBox();
jLabel241 = new javax.swing.JLabel();
jLabel242 = new javax.swing.JLabel();
jComboBox9 = new javax.swing.JComboBox();
jComboBox12 = new javax.swing.JComboBox();
jPanel28 = new javax.swing.JPanel();
jLabel243 = new javax.swing.JLabel();
jPanel53 = new javax.swing.JPanel();
jLabel319 = new javax.swing.JLabel();
jLabel320 = new javax.swing.JLabel();
jComboBox13 = new javax.swing.JComboBox();
jComboBox14 = new javax.swing.JComboBox();
jLabel321 = new javax.swing.JLabel();
jLabel322 = new javax.swing.JLabel();
jComboBox15 = new javax.swing.JComboBox();
jComboBox16 = new javax.swing.JComboBox();
jLabel323 = new javax.swing.JLabel();
jLabel324 = new javax.swing.JLabel();
jComboBox17 = new javax.swing.JComboBox();
jComboBox18 = new javax.swing.JComboBox();
jPanel54 = new javax.swing.JPanel();
jLabel325 = new javax.swing.JLabel();
jPanel72 = new javax.swing.JPanel();
jLabel376 = new javax.swing.JLabel();
jLabel377 = new javax.swing.JLabel();
jComboBox19 = new javax.swing.JComboBox();
jComboBox20 = new javax.swing.JComboBox();
jLabel378 = new javax.swing.JLabel();
jLabel379 = new javax.swing.JLabel();
jComboBox21 = new javax.swing.JComboBox();
jComboBox22 = new javax.swing.JComboBox();
jLabel380 = new javax.swing.JLabel();
jLabel381 = new javax.swing.JLabel();
jComboBox23 = new javax.swing.JComboBox();
jComboBox24 = new javax.swing.JComboBox();
jPanel73 = new javax.swing.JPanel();
jLabel382 = new javax.swing.JLabel();
jPanel74 = new javax.swing.JPanel();
jLabel383 = new javax.swing.JLabel();
jLabel384 = new javax.swing.JLabel();
jComboBox25 = new javax.swing.JComboBox();
jComboBox26 = new javax.swing.JComboBox();
jLabel385 = new javax.swing.JLabel();
jLabel386 = new javax.swing.JLabel();
jComboBox27 = new javax.swing.JComboBox();
jComboBox28 = new javax.swing.JComboBox();
jLabel387 = new javax.swing.JLabel();
jLabel388 = new javax.swing.JLabel();
jComboBox29 = new javax.swing.JComboBox();
jComboBox30 = new javax.swing.JComboBox();
jPanel75 = new javax.swing.JPanel();
jLabel389 = new javax.swing.JLabel();
jPanel76 = new javax.swing.JPanel();
jLabel390 = new javax.swing.JLabel();
jLabel391 = new javax.swing.JLabel();
jComboBox31 = new javax.swing.JComboBox();
jComboBox32 = new javax.swing.JComboBox();
jLabel392 = new javax.swing.JLabel();
jLabel393 = new javax.swing.JLabel();
jComboBox33 = new javax.swing.JComboBox();
jComboBox34 = new javax.swing.JComboBox();
jLabel394 = new javax.swing.JLabel();
jLabel395 = new javax.swing.JLabel();
jComboBox35 = new javax.swing.JComboBox();
jComboBox36 = new javax.swing.JComboBox();
jPanel77 = new javax.swing.JPanel();
jLabel396 = new javax.swing.JLabel();
jPanel78 = new javax.swing.JPanel();
jLabel397 = new javax.swing.JLabel();
jLabel398 = new javax.swing.JLabel();
jComboBox37 = new javax.swing.JComboBox();
jComboBox38 = new javax.swing.JComboBox();
jLabel399 = new javax.swing.JLabel();
jLabel400 = new javax.swing.JLabel();
jComboBox39 = new javax.swing.JComboBox();
jComboBox40 = new javax.swing.JComboBox();
jLabel401 = new javax.swing.JLabel();
jLabel402 = new javax.swing.JLabel();
jComboBox41 = new javax.swing.JComboBox();
jComboBox42 = new javax.swing.JComboBox();
jPanel79 = new javax.swing.JPanel();
jLabel403 = new javax.swing.JLabel();
jPanel80 = new javax.swing.JPanel();
jLabel404 = new javax.swing.JLabel();
jLabel405 = new javax.swing.JLabel();
jComboBox43 = new javax.swing.JComboBox();
jComboBox44 = new javax.swing.JComboBox();
jLabel406 = new javax.swing.JLabel();
jLabel407 = new javax.swing.JLabel();
jComboBox45 = new javax.swing.JComboBox();
jComboBox46 = new javax.swing.JComboBox();
jLabel408 = new javax.swing.JLabel();
jLabel409 = new javax.swing.JLabel();
jComboBox47 = new javax.swing.JComboBox();
jComboBox48 = new javax.swing.JComboBox();
jPanel81 = new javax.swing.JPanel();
jLabel410 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jPanel10 = new javax.swing.JPanel();
jPanel45 = new javax.swing.JPanel();
jLabel294 = new javax.swing.JLabel();
jLabel295 = new javax.swing.JLabel();
jComboBox272 = new javax.swing.JComboBox();
jComboBox273 = new javax.swing.JComboBox();
jLabel296 = new javax.swing.JLabel();
jLabel297 = new javax.swing.JLabel();
jComboBox274 = new javax.swing.JComboBox();
jComboBox275 = new javax.swing.JComboBox();
jLabel298 = new javax.swing.JLabel();
jLabel299 = new javax.swing.JLabel();
jComboBox276 = new javax.swing.JComboBox();
jComboBox277 = new javax.swing.JComboBox();
jPanel46 = new javax.swing.JPanel();
jLabel300 = new javax.swing.JLabel();
jPanel47 = new javax.swing.JPanel();
jLabel301 = new javax.swing.JLabel();
jComboBox278 = new javax.swing.JComboBox();
jLabel302 = new javax.swing.JLabel();
jComboBox279 = new javax.swing.JComboBox();
jLabel303 = new javax.swing.JLabel();
jComboBox280 = new javax.swing.JComboBox();
jPanel48 = new javax.swing.JPanel();
jLabel304 = new javax.swing.JLabel();
jPanel49 = new javax.swing.JPanel();
jLabel305 = new javax.swing.JLabel();
jLabel306 = new javax.swing.JLabel();
jComboBox281 = new javax.swing.JComboBox();
jComboBox282 = new javax.swing.JComboBox();
jLabel307 = new javax.swing.JLabel();
jLabel308 = new javax.swing.JLabel();
jComboBox283 = new javax.swing.JComboBox();
jComboBox284 = new javax.swing.JComboBox();
jLabel309 = new javax.swing.JLabel();
jLabel310 = new javax.swing.JLabel();
jComboBox285 = new javax.swing.JComboBox();
jComboBox286 = new javax.swing.JComboBox();
jPanel50 = new javax.swing.JPanel();
jLabel311 = new javax.swing.JLabel();
jPanel51 = new javax.swing.JPanel();
jLabel312 = new javax.swing.JLabel();
jLabel313 = new javax.swing.JLabel();
jComboBox287 = new javax.swing.JComboBox();
jComboBox288 = new javax.swing.JComboBox();
jLabel314 = new javax.swing.JLabel();
jLabel315 = new javax.swing.JLabel();
jComboBox289 = new javax.swing.JComboBox();
jComboBox290 = new javax.swing.JComboBox();
jLabel316 = new javax.swing.JLabel();
jLabel317 = new javax.swing.JLabel();
jComboBox291 = new javax.swing.JComboBox();
jComboBox292 = new javax.swing.JComboBox();
jPanel52 = new javax.swing.JPanel();
jLabel318 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jPanel12 = new javax.swing.JPanel();
jPanel37 = new javax.swing.JPanel();
jLabel272 = new javax.swing.JLabel();
jLabel273 = new javax.swing.JLabel();
jComboBox254 = new javax.swing.JComboBox();
jComboBox255 = new javax.swing.JComboBox();
jLabel274 = new javax.swing.JLabel();
jLabel275 = new javax.swing.JLabel();
jComboBox256 = new javax.swing.JComboBox();
jComboBox257 = new javax.swing.JComboBox();
jLabel276 = new javax.swing.JLabel();
jLabel277 = new javax.swing.JLabel();
jComboBox258 = new javax.swing.JComboBox();
jComboBox259 = new javax.swing.JComboBox();
jPanel38 = new javax.swing.JPanel();
jLabel278 = new javax.swing.JLabel();
jPanel39 = new javax.swing.JPanel();
jLabel217 = new javax.swing.JLabel();
jComboBox207 = new javax.swing.JComboBox();
jLabel219 = new javax.swing.JLabel();
jComboBox209 = new javax.swing.JComboBox();
jLabel221 = new javax.swing.JLabel();
jComboBox211 = new javax.swing.JComboBox();
jPanel40 = new javax.swing.JPanel();
jLabel279 = new javax.swing.JLabel();
jPanel41 = new javax.swing.JPanel();
jLabel280 = new javax.swing.JLabel();
jLabel281 = new javax.swing.JLabel();
jComboBox260 = new javax.swing.JComboBox();
jComboBox261 = new javax.swing.JComboBox();
jLabel282 = new javax.swing.JLabel();
jLabel283 = new javax.swing.JLabel();
jComboBox262 = new javax.swing.JComboBox();
jComboBox263 = new javax.swing.JComboBox();
jLabel284 = new javax.swing.JLabel();
jLabel285 = new javax.swing.JLabel();
jComboBox264 = new javax.swing.JComboBox();
jComboBox265 = new javax.swing.JComboBox();
jPanel42 = new javax.swing.JPanel();
jLabel286 = new javax.swing.JLabel();
jPanel43 = new javax.swing.JPanel();
jLabel287 = new javax.swing.JLabel();
jLabel288 = new javax.swing.JLabel();
jComboBox266 = new javax.swing.JComboBox();
jComboBox267 = new javax.swing.JComboBox();
jLabel289 = new javax.swing.JLabel();
jLabel290 = new javax.swing.JLabel();
jComboBox268 = new javax.swing.JComboBox();
jComboBox269 = new javax.swing.JComboBox();
jLabel291 = new javax.swing.JLabel();
jLabel292 = new javax.swing.JLabel();
jComboBox270 = new javax.swing.JComboBox();
jComboBox271 = new javax.swing.JComboBox();
jPanel44 = new javax.swing.JPanel();
jLabel293 = new javax.swing.JLabel();
jPanel18 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
jPanel17 = new javax.swing.JPanel();
jPanel55 = new javax.swing.JPanel();
jLabel326 = new javax.swing.JLabel();
jLabel327 = new javax.swing.JLabel();
jComboBox299 = new javax.swing.JComboBox();
jComboBox300 = new javax.swing.JComboBox();
jLabel328 = new javax.swing.JLabel();
jLabel329 = new javax.swing.JLabel();
jComboBox301 = new javax.swing.JComboBox();
jComboBox302 = new javax.swing.JComboBox();
jLabel330 = new javax.swing.JLabel();
jLabel331 = new javax.swing.JLabel();
jComboBox303 = new javax.swing.JComboBox();
jComboBox304 = new javax.swing.JComboBox();
jPanel56 = new javax.swing.JPanel();
jLabel332 = new javax.swing.JLabel();
jPanel57 = new javax.swing.JPanel();
jLabel333 = new javax.swing.JLabel();
jComboBox305 = new javax.swing.JComboBox();
jLabel334 = new javax.swing.JLabel();
jComboBox306 = new javax.swing.JComboBox();
jLabel335 = new javax.swing.JLabel();
jComboBox307 = new javax.swing.JComboBox();
jPanel58 = new javax.swing.JPanel();
jLabel336 = new javax.swing.JLabel();
jPanel59 = new javax.swing.JPanel();
jLabel337 = new javax.swing.JLabel();
jLabel338 = new javax.swing.JLabel();
jComboBox308 = new javax.swing.JComboBox();
jComboBox309 = new javax.swing.JComboBox();
jLabel339 = new javax.swing.JLabel();
jLabel340 = new javax.swing.JLabel();
jComboBox310 = new javax.swing.JComboBox();
jComboBox311 = new javax.swing.JComboBox();
jLabel341 = new javax.swing.JLabel();
jLabel342 = new javax.swing.JLabel();
jComboBox312 = new javax.swing.JComboBox();
jComboBox313 = new javax.swing.JComboBox();
jPanel60 = new javax.swing.JPanel();
jLabel343 = new javax.swing.JLabel();
jPanel61 = new javax.swing.JPanel();
jLabel344 = new javax.swing.JLabel();
jLabel345 = new javax.swing.JLabel();
jComboBox314 = new javax.swing.JComboBox();
jComboBox315 = new javax.swing.JComboBox();
jLabel346 = new javax.swing.JLabel();
jLabel347 = new javax.swing.JLabel();
jComboBox316 = new javax.swing.JComboBox();
jComboBox317 = new javax.swing.JComboBox();
jLabel348 = new javax.swing.JLabel();
jLabel349 = new javax.swing.JLabel();
jComboBox318 = new javax.swing.JComboBox();
jComboBox319 = new javax.swing.JComboBox();
jPanel62 = new javax.swing.JPanel();
jLabel350 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jPanel63 = new javax.swing.JPanel();
jPanel64 = new javax.swing.JPanel();
jLabel351 = new javax.swing.JLabel();
jLabel352 = new javax.swing.JLabel();
jComboBox320 = new javax.swing.JComboBox();
jComboBox321 = new javax.swing.JComboBox();
jLabel353 = new javax.swing.JLabel();
jLabel354 = new javax.swing.JLabel();
jComboBox322 = new javax.swing.JComboBox();
jComboBox323 = new javax.swing.JComboBox();
jLabel355 = new javax.swing.JLabel();
jLabel356 = new javax.swing.JLabel();
jComboBox324 = new javax.swing.JComboBox();
jComboBox325 = new javax.swing.JComboBox();
jPanel65 = new javax.swing.JPanel();
jLabel357 = new javax.swing.JLabel();
jPanel66 = new javax.swing.JPanel();
jLabel358 = new javax.swing.JLabel();
jComboBox326 = new javax.swing.JComboBox();
jLabel359 = new javax.swing.JLabel();
jComboBox327 = new javax.swing.JComboBox();
jLabel360 = new javax.swing.JLabel();
jComboBox328 = new javax.swing.JComboBox();
jPanel67 = new javax.swing.JPanel();
jLabel361 = new javax.swing.JLabel();
jPanel68 = new javax.swing.JPanel();
jLabel362 = new javax.swing.JLabel();
jLabel363 = new javax.swing.JLabel();
jComboBox329 = new javax.swing.JComboBox();
jComboBox330 = new javax.swing.JComboBox();
jLabel364 = new javax.swing.JLabel();
jLabel365 = new javax.swing.JLabel();
jComboBox331 = new javax.swing.JComboBox();
jComboBox332 = new javax.swing.JComboBox();
jLabel366 = new javax.swing.JLabel();
jLabel367 = new javax.swing.JLabel();
jComboBox333 = new javax.swing.JComboBox();
jComboBox334 = new javax.swing.JComboBox();
jPanel69 = new javax.swing.JPanel();
jLabel368 = new javax.swing.JLabel();
jPanel70 = new javax.swing.JPanel();
jLabel369 = new javax.swing.JLabel();
jLabel370 = new javax.swing.JLabel();
jComboBox335 = new javax.swing.JComboBox();
jComboBox336 = new javax.swing.JComboBox();
jLabel371 = new javax.swing.JLabel();
jLabel372 = new javax.swing.JLabel();
jComboBox337 = new javax.swing.JComboBox();
jComboBox338 = new javax.swing.JComboBox();
jLabel373 = new javax.swing.JLabel();
jLabel374 = new javax.swing.JLabel();
jComboBox339 = new javax.swing.JComboBox();
jComboBox340 = new javax.swing.JComboBox();
jPanel71 = new javax.swing.JPanel();
jLabel375 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel196 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel199 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel200 = new javax.swing.JLabel();
jLabel201 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
logoutButton = new javax.swing.JButton();
editAccountButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Courses");
setBackground(new java.awt.Color(255, 255, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jPanel7.setBackground(new java.awt.Color(255, 255, 255));
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel13.setBackground(new java.awt.Color(225, 225, 225));
jPanel13.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel1.setText("Course 1");
jLabel1.setToolTipText("");
jLabel2.setText("Course 2");
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jLabel3.setText("Course 3");
jLabel3.setToolTipText("");
jLabel4.setText("Course 4");
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jLabel5.setText("Course 5");
jLabel9.setText("Course 6");
jPanel14.setBackground(new java.awt.Color(204, 204, 204));
jLabel198.setText(" Fall Semester 1");
jLabel198.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel27.setBackground(new java.awt.Color(225, 225, 225));
jPanel27.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel237.setText("Course 1");
jLabel237.setToolTipText("");
jLabel238.setText("Course 2");
jComboBox7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox7ActionPerformed(evt);
}
});
jLabel239.setText("Course 3");
jLabel239.setToolTipText("");
jLabel240.setText("Course 4");
jComboBox8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox8ActionPerformed(evt);
}
});
jLabel241.setText("Course 5");
jLabel242.setText("Course 6");
jPanel28.setBackground(new java.awt.Color(204, 204, 204));
jLabel243.setText(" Fall Semester 1");
jLabel243.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28);
jPanel28.setLayout(jPanel28Layout);
jPanel28Layout.setHorizontalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel28Layout.createSequentialGroup()
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel28Layout.setVerticalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27);
jPanel27.setLayout(jPanel27Layout);
jPanel27Layout.setHorizontalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel237)
.addComponent(jLabel238))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel239)
.addComponent(jLabel240))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel241)
.addComponent(jLabel242))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel27Layout.setVerticalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel237)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel239)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel241, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel238)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel240)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel242, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel53.setBackground(new java.awt.Color(225, 225, 225));
jPanel53.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel319.setText("Course 1");
jLabel319.setToolTipText("");
jLabel320.setText("Course 2");
jComboBox13.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox13ActionPerformed(evt);
}
});
jComboBox14.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel321.setText("Course 3");
jLabel321.setToolTipText("");
jLabel322.setText("Course 4");
jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox15ActionPerformed(evt);
}
});
jComboBox16.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel323.setText("Course 5");
jLabel324.setText("Course 6");
jComboBox17.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox18.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel54.setBackground(new java.awt.Color(204, 204, 204));
jPanel54.setForeground(new java.awt.Color(255, 255, 255));
jLabel325.setText(" Fall Semester 1");
jLabel325.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel54Layout = new javax.swing.GroupLayout(jPanel54);
jPanel54.setLayout(jPanel54Layout);
jPanel54Layout.setHorizontalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel54Layout.createSequentialGroup()
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel54Layout.setVerticalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel53Layout = new javax.swing.GroupLayout(jPanel53);
jPanel53.setLayout(jPanel53Layout);
jPanel53Layout.setHorizontalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel319)
.addComponent(jLabel320))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel321)
.addComponent(jLabel322))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel323)
.addComponent(jLabel324))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(12, Short.MAX_VALUE))
);
jPanel53Layout.setVerticalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel319)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel321)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel323, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel320)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel322)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel324, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel72.setBackground(new java.awt.Color(225, 225, 225));
jPanel72.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel376.setText("Course 1");
jLabel376.setToolTipText("");
jLabel377.setText("Course 2");
jComboBox19.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox19ActionPerformed(evt);
}
});
jComboBox20.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel378.setText("Course 3");
jLabel378.setToolTipText("");
jLabel379.setText("Course 4");
jComboBox21.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox21.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox21ActionPerformed(evt);
}
});
jComboBox22.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel380.setText("Course 5");
jLabel381.setText("Course 6");
jComboBox23.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox24.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel73.setBackground(new java.awt.Color(204, 204, 204));
jLabel382.setText(" Fall Semester 1");
jLabel382.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel73Layout = new javax.swing.GroupLayout(jPanel73);
jPanel73.setLayout(jPanel73Layout);
jPanel73Layout.setHorizontalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel73Layout.createSequentialGroup()
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel73Layout.setVerticalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel72Layout = new javax.swing.GroupLayout(jPanel72);
jPanel72.setLayout(jPanel72Layout);
jPanel72Layout.setHorizontalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel376)
.addComponent(jLabel377))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel378)
.addComponent(jLabel379))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel380)
.addComponent(jLabel381))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel72Layout.setVerticalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel376)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel378)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel380, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel377)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel379)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel381, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel74.setBackground(new java.awt.Color(225, 225, 225));
jPanel74.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel383.setText("Course 1");
jLabel383.setToolTipText("");
jLabel384.setText("Course 2");
jComboBox25.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox25.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox25ActionPerformed(evt);
}
});
jComboBox26.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel385.setText("Course 3");
jLabel385.setToolTipText("");
jLabel386.setText("Course 4");
jComboBox27.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox27.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox27ActionPerformed(evt);
}
});
jComboBox28.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel387.setText("Course 5");
jLabel388.setText("Course 6");
jComboBox29.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox30.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel75.setBackground(new java.awt.Color(204, 204, 204));
jPanel75.setForeground(new java.awt.Color(255, 255, 255));
jLabel389.setText(" Fall Semester 1");
jLabel389.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel75Layout = new javax.swing.GroupLayout(jPanel75);
jPanel75.setLayout(jPanel75Layout);
jPanel75Layout.setHorizontalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel75Layout.createSequentialGroup()
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel75Layout.setVerticalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel74Layout = new javax.swing.GroupLayout(jPanel74);
jPanel74.setLayout(jPanel74Layout);
jPanel74Layout.setHorizontalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel383)
.addComponent(jLabel384))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel385)
.addComponent(jLabel386))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel387)
.addComponent(jLabel388))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel74Layout.setVerticalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel383)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel385)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel387, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel384)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel386)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel388, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel76.setBackground(new java.awt.Color(225, 225, 225));
jPanel76.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel390.setText("Course 1");
jLabel390.setToolTipText("");
jLabel391.setText("Course 2");
jComboBox31.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox31.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox31ActionPerformed(evt);
}
});
jComboBox32.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel392.setText("Course 3");
jLabel392.setToolTipText("");
jLabel393.setText("Course 4");
jComboBox33.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox33.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox33ActionPerformed(evt);
}
});
jComboBox34.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel394.setText("Course 5");
jLabel395.setText("Course 6");
jComboBox35.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox36.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel77.setBackground(new java.awt.Color(204, 204, 204));
jPanel77.setForeground(new java.awt.Color(255, 255, 255));
jLabel396.setText(" Fall Semester 1");
jLabel396.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel77Layout = new javax.swing.GroupLayout(jPanel77);
jPanel77.setLayout(jPanel77Layout);
jPanel77Layout.setHorizontalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel77Layout.createSequentialGroup()
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel77Layout.setVerticalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel76Layout = new javax.swing.GroupLayout(jPanel76);
jPanel76.setLayout(jPanel76Layout);
jPanel76Layout.setHorizontalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel390)
.addComponent(jLabel391))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel392)
.addComponent(jLabel393))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel394)
.addComponent(jLabel395))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel76Layout.setVerticalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel390)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel392)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel394, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel391)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel393)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel395, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel78.setBackground(new java.awt.Color(225, 225, 225));
jPanel78.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel397.setText("Course 1");
jLabel397.setToolTipText("");
jLabel398.setText("Course 2");
jComboBox37.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox37.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox37ActionPerformed(evt);
}
});
jComboBox38.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel399.setText("Course 3");
jLabel399.setToolTipText("");
jLabel400.setText("Course 4");
jComboBox39.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox39.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox39ActionPerformed(evt);
}
});
jComboBox40.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel401.setText("Course 5");
jLabel402.setText("Course 6");
jComboBox41.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox42.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel79.setBackground(new java.awt.Color(204, 204, 204));
jPanel79.setForeground(new java.awt.Color(255, 255, 255));
jLabel403.setText(" Fall Semester 1");
jLabel403.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel79Layout = new javax.swing.GroupLayout(jPanel79);
jPanel79.setLayout(jPanel79Layout);
jPanel79Layout.setHorizontalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel79Layout.createSequentialGroup()
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel79Layout.setVerticalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel78Layout = new javax.swing.GroupLayout(jPanel78);
jPanel78.setLayout(jPanel78Layout);
jPanel78Layout.setHorizontalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel397)
.addComponent(jLabel398))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel399)
.addComponent(jLabel400))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel401)
.addComponent(jLabel402))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel78Layout.setVerticalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel397)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel399)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel401, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel398)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel400)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel402, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel80.setBackground(new java.awt.Color(225, 225, 225));
jPanel80.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel404.setText("Course 1");
jLabel404.setToolTipText("");
jLabel405.setText("Course 2");
jComboBox43.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox43.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox43ActionPerformed(evt);
}
});
jComboBox44.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel406.setText("Course 3");
jLabel406.setToolTipText("");
jLabel407.setText("Course 4");
jComboBox45.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox45.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox45ActionPerformed(evt);
}
});
jComboBox46.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel408.setText("Course 5");
jLabel409.setText("Course 6");
jComboBox47.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox48.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel81.setBackground(new java.awt.Color(204, 204, 204));
jPanel81.setForeground(new java.awt.Color(255, 255, 255));
jLabel410.setText(" Fall Semester 1");
jLabel410.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel81Layout = new javax.swing.GroupLayout(jPanel81);
jPanel81.setLayout(jPanel81Layout);
jPanel81Layout.setHorizontalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel81Layout.createSequentialGroup()
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel81Layout.setVerticalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel80Layout = new javax.swing.GroupLayout(jPanel80);
jPanel80.setLayout(jPanel80Layout);
jPanel80Layout.setHorizontalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel404)
.addComponent(jLabel405))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel406)
.addComponent(jLabel407))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel408)
.addComponent(jLabel409))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel80Layout.setVerticalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel404)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel406)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel408, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel405)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel407)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel409, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE))
);
jScrollPane1.setViewportView(jPanel6);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Computer Science", jPanel1);
jPanel10.setBackground(new java.awt.Color(255, 255, 255));
jPanel45.setBackground(new java.awt.Color(225, 225, 225));
jPanel45.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel294.setText("Course 1");
jLabel294.setToolTipText("");
jLabel295.setText("Course 2");
jComboBox272.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox272.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox272ActionPerformed(evt);
}
});
jComboBox273.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel296.setText("Course 3");
jLabel296.setToolTipText("");
jLabel297.setText("Course 4");
jComboBox274.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox274.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox274ActionPerformed(evt);
}
});
jComboBox275.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel298.setText("Course 5");
jLabel299.setText("Course 6");
jComboBox276.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox277.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel46.setBackground(new java.awt.Color(204, 204, 204));
jLabel300.setText(" Spring Semester 2");
jLabel300.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel46Layout = new javax.swing.GroupLayout(jPanel46);
jPanel46.setLayout(jPanel46Layout);
jPanel46Layout.setHorizontalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel46Layout.createSequentialGroup()
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel46Layout.setVerticalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel45Layout = new javax.swing.GroupLayout(jPanel45);
jPanel45.setLayout(jPanel45Layout);
jPanel45Layout.setHorizontalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel294)
.addComponent(jLabel295))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel296)
.addComponent(jLabel297))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel298)
.addComponent(jLabel299))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel45Layout.setVerticalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel294)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel296)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel298, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel295)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel297)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel299, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel47.setBackground(new java.awt.Color(225, 225, 225));
jPanel47.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel301.setText("Course 1");
jLabel301.setToolTipText("");
jComboBox278.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox278.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox278ActionPerformed(evt);
}
});
jLabel302.setText("Course 2");
jLabel302.setToolTipText("");
jComboBox279.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox279.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox279ActionPerformed(evt);
}
});
jLabel303.setText("Course 3");
jComboBox280.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel48.setBackground(new java.awt.Color(204, 204, 204));
jLabel304.setText(" Summer Semester 2.5");
jLabel304.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel48Layout = new javax.swing.GroupLayout(jPanel48);
jPanel48.setLayout(jPanel48Layout);
jPanel48Layout.setHorizontalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel48Layout.createSequentialGroup()
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel48Layout.setVerticalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel47Layout = new javax.swing.GroupLayout(jPanel47);
jPanel47.setLayout(jPanel47Layout);
jPanel47Layout.setHorizontalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addComponent(jLabel301)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel302)
.addGap(18, 18, 18)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel303)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel47Layout.setVerticalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel301)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel302)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel303, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel49.setBackground(new java.awt.Color(225, 225, 225));
jPanel49.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel305.setText("Course 1");
jLabel305.setToolTipText("");
jLabel306.setText("Course 2");
jComboBox281.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox281.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox281ActionPerformed(evt);
}
});
jComboBox282.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel307.setText("Course 3");
jLabel307.setToolTipText("");
jLabel308.setText("Course 4");
jComboBox283.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox283.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox283ActionPerformed(evt);
}
});
jComboBox284.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel309.setText("Course 5");
jLabel310.setText("Course 6");
jComboBox285.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox286.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel50.setBackground(new java.awt.Color(204, 204, 204));
jPanel50.setForeground(new java.awt.Color(255, 255, 255));
jLabel311.setText(" Fall Semester 1");
jLabel311.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel50Layout = new javax.swing.GroupLayout(jPanel50);
jPanel50.setLayout(jPanel50Layout);
jPanel50Layout.setHorizontalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel50Layout.createSequentialGroup()
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel50Layout.setVerticalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel49Layout = new javax.swing.GroupLayout(jPanel49);
jPanel49.setLayout(jPanel49Layout);
jPanel49Layout.setHorizontalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel305)
.addComponent(jLabel306))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel307)
.addComponent(jLabel308))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel309)
.addComponent(jLabel310))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel49Layout.setVerticalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel305)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel307)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel309, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel306)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel308)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel310, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel51.setBackground(new java.awt.Color(225, 225, 225));
jPanel51.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel312.setText("Course 1");
jLabel312.setToolTipText("");
jLabel313.setText("Course 2");
jComboBox287.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox287.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox287ActionPerformed(evt);
}
});
jComboBox288.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel314.setText("Course 3");
jLabel314.setToolTipText("");
jLabel315.setText("Course 4");
jComboBox289.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox289.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox289ActionPerformed(evt);
}
});
jComboBox290.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel316.setText("Course 5");
jLabel317.setText("Course 6");
jComboBox291.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox292.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel52.setBackground(new java.awt.Color(204, 204, 204));
jPanel52.setForeground(new java.awt.Color(255, 255, 255));
jLabel318.setText(" Fall Semester 3");
jLabel318.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel52Layout = new javax.swing.GroupLayout(jPanel52);
jPanel52.setLayout(jPanel52Layout);
jPanel52Layout.setHorizontalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel52Layout.createSequentialGroup()
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel52Layout.setVerticalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel51Layout = new javax.swing.GroupLayout(jPanel51);
jPanel51.setLayout(jPanel51Layout);
jPanel51Layout.setHorizontalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel312)
.addComponent(jLabel313))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel314)
.addComponent(jLabel315))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel316)
.addComponent(jLabel317))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel51Layout.setVerticalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel312)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel314)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel316, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel313)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel315)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel317, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(67, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane3.setViewportView(jPanel10);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Science ", jPanel4);
jPanel12.setBackground(new java.awt.Color(255, 255, 255));
jPanel37.setBackground(new java.awt.Color(225, 225, 225));
jPanel37.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel272.setText("Course 1");
jLabel272.setToolTipText("");
jLabel273.setText("Course 2");
jComboBox254.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox254.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox254ActionPerformed(evt);
}
});
jComboBox255.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel274.setText("Course 3");
jLabel274.setToolTipText("");
jLabel275.setText("Course 4");
jComboBox256.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox256.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox256ActionPerformed(evt);
}
});
jComboBox257.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel276.setText("Course 5");
jLabel277.setText("Course 6");
jComboBox258.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox259.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel38.setBackground(new java.awt.Color(204, 204, 204));
jLabel278.setText(" Spring Semester 2");
jLabel278.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel38Layout = new javax.swing.GroupLayout(jPanel38);
jPanel38.setLayout(jPanel38Layout);
jPanel38Layout.setHorizontalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel38Layout.createSequentialGroup()
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel38Layout.setVerticalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel37Layout = new javax.swing.GroupLayout(jPanel37);
jPanel37.setLayout(jPanel37Layout);
jPanel37Layout.setHorizontalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel272)
.addComponent(jLabel273))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel274)
.addComponent(jLabel275))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel276)
.addComponent(jLabel277))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel37Layout.setVerticalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel272)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel274)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel276, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel273)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel275)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel277, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel39.setBackground(new java.awt.Color(225, 225, 225));
jPanel39.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel217.setText("Course 1");
jLabel217.setToolTipText("");
jComboBox207.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox207.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox207ActionPerformed(evt);
}
});
jLabel219.setText("Course 2");
jLabel219.setToolTipText("");
jComboBox209.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox209.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox209ActionPerformed(evt);
}
});
jLabel221.setText("Course 3");
jComboBox211.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel40.setBackground(new java.awt.Color(204, 204, 204));
jLabel279.setText(" Summer Semester 2.5");
jLabel279.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel40Layout = new javax.swing.GroupLayout(jPanel40);
jPanel40.setLayout(jPanel40Layout);
jPanel40Layout.setHorizontalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel40Layout.createSequentialGroup()
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel40Layout.setVerticalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel39Layout = new javax.swing.GroupLayout(jPanel39);
jPanel39.setLayout(jPanel39Layout);
jPanel39Layout.setHorizontalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addComponent(jLabel217)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel219)
.addGap(18, 18, 18)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel221)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel39Layout.setVerticalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel217)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel219)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel221, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel41.setBackground(new java.awt.Color(225, 225, 225));
jPanel41.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel280.setText("Course 1");
jLabel280.setToolTipText("");
jLabel281.setText("Course 2");
jComboBox260.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox260.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox260ActionPerformed(evt);
}
});
jComboBox261.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel282.setText("Course 3");
jLabel282.setToolTipText("");
jLabel283.setText("Course 4");
jComboBox262.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox262.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox262ActionPerformed(evt);
}
});
jComboBox263.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel284.setText("Course 5");
jLabel285.setText("Course 6");
jComboBox264.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox265.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel42.setBackground(new java.awt.Color(204, 204, 204));
jPanel42.setForeground(new java.awt.Color(255, 255, 255));
jLabel286.setText(" Fall Semester 1");
jLabel286.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel42Layout = new javax.swing.GroupLayout(jPanel42);
jPanel42.setLayout(jPanel42Layout);
jPanel42Layout.setHorizontalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel42Layout.createSequentialGroup()
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel42Layout.setVerticalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel41Layout = new javax.swing.GroupLayout(jPanel41);
jPanel41.setLayout(jPanel41Layout);
jPanel41Layout.setHorizontalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel280)
.addComponent(jLabel281))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel282)
.addComponent(jLabel283))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel284)
.addComponent(jLabel285))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel41Layout.setVerticalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel280)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel282)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel284, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel281)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel283)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel285, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel43.setBackground(new java.awt.Color(225, 225, 225));
jPanel43.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel287.setText("Course 1");
jLabel287.setToolTipText("");
jLabel288.setText("Course 2");
jComboBox266.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox266.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox266ActionPerformed(evt);
}
});
jComboBox267.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel289.setText("Course 3");
jLabel289.setToolTipText("");
jLabel290.setText("Course 4");
jComboBox268.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox268.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox268ActionPerformed(evt);
}
});
jComboBox269.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel291.setText("Course 5");
jLabel292.setText("Course 6");
jComboBox270.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox271.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel44.setBackground(new java.awt.Color(204, 204, 204));
jPanel44.setForeground(new java.awt.Color(255, 255, 255));
jLabel293.setText(" Fall Semester 3");
jLabel293.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel44Layout = new javax.swing.GroupLayout(jPanel44);
jPanel44.setLayout(jPanel44Layout);
jPanel44Layout.setHorizontalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel44Layout.createSequentialGroup()
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel44Layout.setVerticalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel43Layout = new javax.swing.GroupLayout(jPanel43);
jPanel43.setLayout(jPanel43Layout);
jPanel43Layout.setHorizontalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel287)
.addComponent(jLabel288))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel289)
.addComponent(jLabel290))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel291)
.addComponent(jLabel292))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel43Layout.setVerticalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel287)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel289)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel291, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel288)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel290)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel292, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(331, Short.MAX_VALUE))
);
jScrollPane4.setViewportView(jPanel12);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Core ", jPanel2);
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jPanel55.setBackground(new java.awt.Color(225, 225, 225));
jPanel55.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel326.setText("Course 1");
jLabel326.setToolTipText("");
jLabel327.setText("Course 2");
jComboBox299.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox299.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox299ActionPerformed(evt);
}
});
jComboBox300.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel328.setText("Course 3");
jLabel328.setToolTipText("");
jLabel329.setText("Course 4");
jComboBox301.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox301.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox301ActionPerformed(evt);
}
});
jComboBox302.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel330.setText("Course 5");
jLabel331.setText("Course 6");
jComboBox303.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox304.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel56.setBackground(new java.awt.Color(204, 204, 204));
jLabel332.setText(" Spring Semester 2");
jLabel332.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel56Layout = new javax.swing.GroupLayout(jPanel56);
jPanel56.setLayout(jPanel56Layout);
jPanel56Layout.setHorizontalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel56Layout.createSequentialGroup()
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel56Layout.setVerticalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel55Layout = new javax.swing.GroupLayout(jPanel55);
jPanel55.setLayout(jPanel55Layout);
jPanel55Layout.setHorizontalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel326)
.addComponent(jLabel327))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel328)
.addComponent(jLabel329))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel330)
.addComponent(jLabel331))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel55Layout.setVerticalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel326)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel328)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel330, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel327)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel329)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel331, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel57.setBackground(new java.awt.Color(225, 225, 225));
jPanel57.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel333.setText("Course 1");
jLabel333.setToolTipText("");
jComboBox305.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox305.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox305ActionPerformed(evt);
}
});
jLabel334.setText("Course 2");
jLabel334.setToolTipText("");
jComboBox306.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox306.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox306ActionPerformed(evt);
}
});
jLabel335.setText("Course 3");
jComboBox307.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel58.setBackground(new java.awt.Color(204, 204, 204));
jLabel336.setText(" Summer Semester 2.5");
jLabel336.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel58Layout = new javax.swing.GroupLayout(jPanel58);
jPanel58.setLayout(jPanel58Layout);
jPanel58Layout.setHorizontalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel58Layout.createSequentialGroup()
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel58Layout.setVerticalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel57Layout = new javax.swing.GroupLayout(jPanel57);
jPanel57.setLayout(jPanel57Layout);
jPanel57Layout.setHorizontalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addComponent(jLabel333)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel334)
.addGap(18, 18, 18)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel335)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel57Layout.setVerticalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel333)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel334)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel335, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel59.setBackground(new java.awt.Color(225, 225, 225));
jPanel59.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel337.setText("Course 1");
jLabel337.setToolTipText("");
jLabel338.setText("Course 2");
jComboBox308.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox308.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox308ActionPerformed(evt);
}
});
jComboBox309.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel339.setText("Course 3");
jLabel339.setToolTipText("");
jLabel340.setText("Course 4");
jComboBox310.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox310.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox310ActionPerformed(evt);
}
});
jComboBox311.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel341.setText("Course 5");
jLabel342.setText("Course 6");
jComboBox312.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox313.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel60.setBackground(new java.awt.Color(204, 204, 204));
jPanel60.setForeground(new java.awt.Color(255, 255, 255));
jLabel343.setText(" Fall Semester 1");
jLabel343.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel60Layout = new javax.swing.GroupLayout(jPanel60);
jPanel60.setLayout(jPanel60Layout);
jPanel60Layout.setHorizontalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel60Layout.createSequentialGroup()
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel60Layout.setVerticalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel59Layout = new javax.swing.GroupLayout(jPanel59);
jPanel59.setLayout(jPanel59Layout);
jPanel59Layout.setHorizontalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel337)
.addComponent(jLabel338))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel339)
.addComponent(jLabel340))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel341)
.addComponent(jLabel342))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel59Layout.setVerticalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel337)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel339)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel341, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel338)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel340)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel342, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel61.setBackground(new java.awt.Color(225, 225, 225));
jPanel61.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel344.setText("Course 1");
jLabel344.setToolTipText("");
jLabel345.setText("Course 2");
jComboBox314.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox314.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox314ActionPerformed(evt);
}
});
jComboBox315.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel346.setText("Course 3");
jLabel346.setToolTipText("");
jLabel347.setText("Course 4");
jComboBox316.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox316.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox316ActionPerformed(evt);
}
});
jComboBox317.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel348.setText("Course 5");
jLabel349.setText("Course 6");
jComboBox318.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox319.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel62.setBackground(new java.awt.Color(204, 204, 204));
jPanel62.setForeground(new java.awt.Color(255, 255, 255));
jLabel350.setText(" Fall Semester 3");
jLabel350.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel62Layout = new javax.swing.GroupLayout(jPanel62);
jPanel62.setLayout(jPanel62Layout);
jPanel62Layout.setHorizontalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel62Layout.createSequentialGroup()
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel62Layout.setVerticalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel61Layout = new javax.swing.GroupLayout(jPanel61);
jPanel61.setLayout(jPanel61Layout);
jPanel61Layout.setHorizontalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel344)
.addComponent(jLabel345))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel346)
.addComponent(jLabel347))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel348)
.addComponent(jLabel349))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel61Layout.setVerticalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel344)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel346)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel348, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel345)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel347)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel349, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane5.setViewportView(jPanel17);
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Electives ", jPanel18);
jPanel63.setBackground(new java.awt.Color(255, 255, 255));
jPanel64.setBackground(new java.awt.Color(225, 225, 225));
jPanel64.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel351.setText("Course 1");
jLabel351.setToolTipText("");
jLabel352.setText("Course 2");
jComboBox320.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox320.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox320ActionPerformed(evt);
}
});
jComboBox321.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel353.setText("Course 3");
jLabel353.setToolTipText("");
jLabel354.setText("Course 4");
jComboBox322.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox322.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox322ActionPerformed(evt);
}
});
jComboBox323.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel355.setText("Course 5");
jLabel356.setText("Course 6");
jComboBox324.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox325.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel65.setBackground(new java.awt.Color(204, 204, 204));
jLabel357.setText(" Spring Semester 2");
jLabel357.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel65Layout = new javax.swing.GroupLayout(jPanel65);
jPanel65.setLayout(jPanel65Layout);
jPanel65Layout.setHorizontalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel65Layout.createSequentialGroup()
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel65Layout.setVerticalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel64Layout = new javax.swing.GroupLayout(jPanel64);
jPanel64.setLayout(jPanel64Layout);
jPanel64Layout.setHorizontalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel351)
.addComponent(jLabel352))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel353)
.addComponent(jLabel354))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel355)
.addComponent(jLabel356))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel64Layout.setVerticalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel351)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel353)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel355, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel352)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel354)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel356, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel66.setBackground(new java.awt.Color(225, 225, 225));
jPanel66.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel358.setText("Course 1");
jLabel358.setToolTipText("");
jComboBox326.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox326.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox326ActionPerformed(evt);
}
});
jLabel359.setText("Course 2");
jLabel359.setToolTipText("");
jComboBox327.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox327.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox327ActionPerformed(evt);
}
});
jLabel360.setText("Course 3");
jComboBox328.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel67.setBackground(new java.awt.Color(204, 204, 204));
jLabel361.setText(" Summer Semester 2.5");
jLabel361.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel67Layout = new javax.swing.GroupLayout(jPanel67);
jPanel67.setLayout(jPanel67Layout);
jPanel67Layout.setHorizontalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel67Layout.createSequentialGroup()
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel67Layout.setVerticalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel66Layout = new javax.swing.GroupLayout(jPanel66);
jPanel66.setLayout(jPanel66Layout);
jPanel66Layout.setHorizontalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addComponent(jLabel358)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel359)
.addGap(18, 18, 18)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel360)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel66Layout.setVerticalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel358)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel359)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel360, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel68.setBackground(new java.awt.Color(225, 225, 225));
jPanel68.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel362.setText("Course 1");
jLabel362.setToolTipText("");
jLabel363.setText("Course 2");
jComboBox329.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox329.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox329ActionPerformed(evt);
}
});
jComboBox330.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel364.setText("Course 3");
jLabel364.setToolTipText("");
jLabel365.setText("Course 4");
jComboBox331.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox331.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox331ActionPerformed(evt);
}
});
jComboBox332.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel366.setText("Course 5");
jLabel367.setText("Course 6");
jComboBox333.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox334.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel69.setBackground(new java.awt.Color(204, 204, 204));
jPanel69.setForeground(new java.awt.Color(255, 255, 255));
jLabel368.setText(" Fall Semester 1");
jLabel368.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel69Layout = new javax.swing.GroupLayout(jPanel69);
jPanel69.setLayout(jPanel69Layout);
jPanel69Layout.setHorizontalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel69Layout.createSequentialGroup()
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel69Layout.setVerticalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel68Layout = new javax.swing.GroupLayout(jPanel68);
jPanel68.setLayout(jPanel68Layout);
jPanel68Layout.setHorizontalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel362)
.addComponent(jLabel363))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel364)
.addComponent(jLabel365))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel366)
.addComponent(jLabel367))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel68Layout.setVerticalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel362)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel364)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel366, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel363)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel365)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel367, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel70.setBackground(new java.awt.Color(225, 225, 225));
jPanel70.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel369.setText("Course 1");
jLabel369.setToolTipText("");
jLabel370.setText("Course 2");
jComboBox335.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox335.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox335ActionPerformed(evt);
}
});
jComboBox336.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel371.setText("Course 3");
jLabel371.setToolTipText("");
jLabel372.setText("Course 4");
jComboBox337.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox337.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox337ActionPerformed(evt);
}
});
jComboBox338.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel373.setText("Course 5");
jLabel374.setText("Course 6");
jComboBox339.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox340.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel71.setBackground(new java.awt.Color(204, 204, 204));
jPanel71.setForeground(new java.awt.Color(255, 255, 255));
jLabel375.setText(" Fall Semester 3");
jLabel375.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel71Layout = new javax.swing.GroupLayout(jPanel71);
jPanel71.setLayout(jPanel71Layout);
jPanel71Layout.setHorizontalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel71Layout.createSequentialGroup()
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel71Layout.setVerticalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel70Layout = new javax.swing.GroupLayout(jPanel70);
jPanel70.setLayout(jPanel70Layout);
jPanel70Layout.setHorizontalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel369)
.addComponent(jLabel370))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel371)
.addComponent(jLabel372))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel373)
.addComponent(jLabel374))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel70Layout.setVerticalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel369)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel371)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel373, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel370)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel372)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel374, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel63Layout = new javax.swing.GroupLayout(jPanel63);
jPanel63.setLayout(jPanel63Layout);
jPanel63Layout.setHorizontalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel63Layout.setVerticalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane2.setViewportView(jPanel63);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Math ", jPanel3);
jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setToolTipText("");
jLabel16.setToolTipText("");
jPanel15.setBackground(new java.awt.Color(83, 13, 47));
jPanel15.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel196.setForeground(new java.awt.Color(255, 255, 255));
jLabel196.setText("Student Name: ");
jTextField1.setText("CSCI");
jLabel199.setForeground(new java.awt.Color(255, 255, 255));
jLabel199.setText("Student Major:");
jTextField2.setText("Davey Jones");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jLabel200.setForeground(new java.awt.Color(255, 255, 255));
jLabel200.setText("Total Hours:");
jLabel201.setForeground(new java.awt.Color(255, 255, 255));
jLabel201.setText("Graduation Date:");
jTextField3.setText("110");
jTextField4.setText("May 2013");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel196, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jLabel199)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88)
.addComponent(jLabel200)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(94, 94, 94)
.addComponent(jLabel201)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel196, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel199, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel200, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel201, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/ZRICBanner.jpg"))); // NOI18N
jPanel5.setBackground(new java.awt.Color(83, 13, 47));
logoutButton.setForeground(new java.awt.Color(255, 255, 255));
logoutButton.setText("Logout");
logoutButton.setBorder(null);
logoutButton.setContentAreaFilled(false);
logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutButtonMouseClicked(evt);
}
});
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Settings");
editAccountButton.setBorder(null);
editAccountButton.setBorderPainted(false);
editAccountButton.setContentAreaFilled(false);
editAccountButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
editAccountButtonMouseClicked(evt);
}
});
- editAccountButton.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- editAccountButtonActionPerformed(evt);
- }
- });
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(editAccountButton)
.addGap(18, 18, 18)
.addComponent(logoutButton)
.addGap(54, 54, 54))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(0, 2, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(logoutButton)
.addComponent(editAccountButton))
.addGap(0, 4, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addGap(304, 304, 304)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel10))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel16))
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 941, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jLabel16)
.addGap(0, 0, 0)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel6))
.addGap(0, 0, 0)
.addComponent(jLabel10)
.addGap(0, 0, 0)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
);
jTabbedPane1.getAccessibleContext().setAccessibleName("History");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jComboBox268ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox268ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox268ActionPerformed
private void jComboBox266ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox266ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox266ActionPerformed
private void jComboBox262ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox262ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox262ActionPerformed
private void jComboBox260ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox260ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox260ActionPerformed
private void jComboBox209ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox209ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox209ActionPerformed
private void jComboBox207ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox207ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox207ActionPerformed
private void jComboBox256ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox256ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox256ActionPerformed
private void jComboBox254ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox254ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox254ActionPerformed
private void jComboBox289ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox289ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox289ActionPerformed
private void jComboBox287ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox287ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox287ActionPerformed
private void jComboBox283ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox283ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox283ActionPerformed
private void jComboBox281ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox281ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox281ActionPerformed
private void jComboBox279ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox279ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox279ActionPerformed
private void jComboBox278ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox278ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox278ActionPerformed
private void jComboBox274ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox274ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox274ActionPerformed
private void jComboBox272ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox272ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox272ActionPerformed
private void jComboBox8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox8ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox8ActionPerformed
private void jComboBox7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox7ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox7ActionPerformed
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox2ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
// conn = Mediator.ConnectDb();
// Fillcombo();
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jComboBox299ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox299ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox299ActionPerformed
private void jComboBox301ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox301ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox301ActionPerformed
private void jComboBox305ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox305ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox305ActionPerformed
private void jComboBox306ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox306ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox306ActionPerformed
private void jComboBox308ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox308ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox308ActionPerformed
private void jComboBox310ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox310ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox310ActionPerformed
private void jComboBox314ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox314ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox314ActionPerformed
private void jComboBox316ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox316ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox316ActionPerformed
private void jComboBox320ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox320ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox320ActionPerformed
private void jComboBox322ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox322ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox322ActionPerformed
private void jComboBox326ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox326ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox326ActionPerformed
private void jComboBox327ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox327ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox327ActionPerformed
private void jComboBox329ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox329ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox329ActionPerformed
private void jComboBox331ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox331ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox331ActionPerformed
private void jComboBox335ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox335ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox335ActionPerformed
private void jComboBox337ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox337ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox337ActionPerformed
private void jComboBox13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox13ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox13ActionPerformed
private void jComboBox15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox15ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox15ActionPerformed
private void jComboBox19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox19ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox19ActionPerformed
private void jComboBox21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox21ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox21ActionPerformed
private void jComboBox25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox25ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox25ActionPerformed
private void jComboBox27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox27ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox27ActionPerformed
private void jComboBox31ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox31ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox31ActionPerformed
private void jComboBox33ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox33ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox33ActionPerformed
private void jComboBox37ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox37ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox37ActionPerformed
private void jComboBox39ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox39ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox39ActionPerformed
private void jComboBox43ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox43ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox43ActionPerformed
private void jComboBox45ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox45ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox45ActionPerformed
private void logoutButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutButtonMouseClicked
mediator.logout(conn);
}//GEN-LAST:event_logoutButtonMouseClicked
private void editAccountButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editAccountButtonMouseClicked
mediator.createEditScreen();
}//GEN-LAST:event_editAccountButtonMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
//new StartupScreen().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton editAccountButton;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox10;
private javax.swing.JComboBox jComboBox11;
private javax.swing.JComboBox jComboBox12;
private javax.swing.JComboBox jComboBox13;
private javax.swing.JComboBox jComboBox14;
private javax.swing.JComboBox jComboBox15;
private javax.swing.JComboBox jComboBox16;
private javax.swing.JComboBox jComboBox17;
private javax.swing.JComboBox jComboBox18;
private javax.swing.JComboBox jComboBox19;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JComboBox jComboBox20;
private javax.swing.JComboBox jComboBox207;
private javax.swing.JComboBox jComboBox209;
private javax.swing.JComboBox jComboBox21;
private javax.swing.JComboBox jComboBox211;
private javax.swing.JComboBox jComboBox22;
private javax.swing.JComboBox jComboBox23;
private javax.swing.JComboBox jComboBox24;
private javax.swing.JComboBox jComboBox25;
private javax.swing.JComboBox jComboBox254;
private javax.swing.JComboBox jComboBox255;
private javax.swing.JComboBox jComboBox256;
private javax.swing.JComboBox jComboBox257;
private javax.swing.JComboBox jComboBox258;
private javax.swing.JComboBox jComboBox259;
private javax.swing.JComboBox jComboBox26;
private javax.swing.JComboBox jComboBox260;
private javax.swing.JComboBox jComboBox261;
private javax.swing.JComboBox jComboBox262;
private javax.swing.JComboBox jComboBox263;
private javax.swing.JComboBox jComboBox264;
private javax.swing.JComboBox jComboBox265;
private javax.swing.JComboBox jComboBox266;
private javax.swing.JComboBox jComboBox267;
private javax.swing.JComboBox jComboBox268;
private javax.swing.JComboBox jComboBox269;
private javax.swing.JComboBox jComboBox27;
private javax.swing.JComboBox jComboBox270;
private javax.swing.JComboBox jComboBox271;
private javax.swing.JComboBox jComboBox272;
private javax.swing.JComboBox jComboBox273;
private javax.swing.JComboBox jComboBox274;
private javax.swing.JComboBox jComboBox275;
private javax.swing.JComboBox jComboBox276;
private javax.swing.JComboBox jComboBox277;
private javax.swing.JComboBox jComboBox278;
private javax.swing.JComboBox jComboBox279;
private javax.swing.JComboBox jComboBox28;
private javax.swing.JComboBox jComboBox280;
private javax.swing.JComboBox jComboBox281;
private javax.swing.JComboBox jComboBox282;
private javax.swing.JComboBox jComboBox283;
private javax.swing.JComboBox jComboBox284;
private javax.swing.JComboBox jComboBox285;
private javax.swing.JComboBox jComboBox286;
private javax.swing.JComboBox jComboBox287;
private javax.swing.JComboBox jComboBox288;
private javax.swing.JComboBox jComboBox289;
private javax.swing.JComboBox jComboBox29;
private javax.swing.JComboBox jComboBox290;
private javax.swing.JComboBox jComboBox291;
private javax.swing.JComboBox jComboBox292;
private javax.swing.JComboBox jComboBox299;
private javax.swing.JComboBox jComboBox3;
private javax.swing.JComboBox jComboBox30;
private javax.swing.JComboBox jComboBox300;
private javax.swing.JComboBox jComboBox301;
private javax.swing.JComboBox jComboBox302;
private javax.swing.JComboBox jComboBox303;
private javax.swing.JComboBox jComboBox304;
private javax.swing.JComboBox jComboBox305;
private javax.swing.JComboBox jComboBox306;
private javax.swing.JComboBox jComboBox307;
private javax.swing.JComboBox jComboBox308;
private javax.swing.JComboBox jComboBox309;
private javax.swing.JComboBox jComboBox31;
private javax.swing.JComboBox jComboBox310;
private javax.swing.JComboBox jComboBox311;
private javax.swing.JComboBox jComboBox312;
private javax.swing.JComboBox jComboBox313;
private javax.swing.JComboBox jComboBox314;
private javax.swing.JComboBox jComboBox315;
private javax.swing.JComboBox jComboBox316;
private javax.swing.JComboBox jComboBox317;
private javax.swing.JComboBox jComboBox318;
private javax.swing.JComboBox jComboBox319;
private javax.swing.JComboBox jComboBox32;
private javax.swing.JComboBox jComboBox320;
private javax.swing.JComboBox jComboBox321;
private javax.swing.JComboBox jComboBox322;
private javax.swing.JComboBox jComboBox323;
private javax.swing.JComboBox jComboBox324;
private javax.swing.JComboBox jComboBox325;
private javax.swing.JComboBox jComboBox326;
private javax.swing.JComboBox jComboBox327;
private javax.swing.JComboBox jComboBox328;
private javax.swing.JComboBox jComboBox329;
private javax.swing.JComboBox jComboBox33;
private javax.swing.JComboBox jComboBox330;
private javax.swing.JComboBox jComboBox331;
private javax.swing.JComboBox jComboBox332;
private javax.swing.JComboBox jComboBox333;
private javax.swing.JComboBox jComboBox334;
private javax.swing.JComboBox jComboBox335;
private javax.swing.JComboBox jComboBox336;
private javax.swing.JComboBox jComboBox337;
private javax.swing.JComboBox jComboBox338;
private javax.swing.JComboBox jComboBox339;
private javax.swing.JComboBox jComboBox34;
private javax.swing.JComboBox jComboBox340;
private javax.swing.JComboBox jComboBox35;
private javax.swing.JComboBox jComboBox36;
private javax.swing.JComboBox jComboBox37;
private javax.swing.JComboBox jComboBox38;
private javax.swing.JComboBox jComboBox39;
private javax.swing.JComboBox jComboBox4;
private javax.swing.JComboBox jComboBox40;
private javax.swing.JComboBox jComboBox41;
private javax.swing.JComboBox jComboBox42;
private javax.swing.JComboBox jComboBox43;
private javax.swing.JComboBox jComboBox44;
private javax.swing.JComboBox jComboBox45;
private javax.swing.JComboBox jComboBox46;
private javax.swing.JComboBox jComboBox47;
private javax.swing.JComboBox jComboBox48;
private javax.swing.JComboBox jComboBox5;
private javax.swing.JComboBox jComboBox6;
private javax.swing.JComboBox jComboBox7;
private javax.swing.JComboBox jComboBox8;
private javax.swing.JComboBox jComboBox9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel196;
private javax.swing.JLabel jLabel198;
private javax.swing.JLabel jLabel199;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel200;
private javax.swing.JLabel jLabel201;
private javax.swing.JLabel jLabel217;
private javax.swing.JLabel jLabel219;
private javax.swing.JLabel jLabel221;
private javax.swing.JLabel jLabel237;
private javax.swing.JLabel jLabel238;
private javax.swing.JLabel jLabel239;
private javax.swing.JLabel jLabel240;
private javax.swing.JLabel jLabel241;
private javax.swing.JLabel jLabel242;
private javax.swing.JLabel jLabel243;
private javax.swing.JLabel jLabel272;
private javax.swing.JLabel jLabel273;
private javax.swing.JLabel jLabel274;
private javax.swing.JLabel jLabel275;
private javax.swing.JLabel jLabel276;
private javax.swing.JLabel jLabel277;
private javax.swing.JLabel jLabel278;
private javax.swing.JLabel jLabel279;
private javax.swing.JLabel jLabel280;
private javax.swing.JLabel jLabel281;
private javax.swing.JLabel jLabel282;
private javax.swing.JLabel jLabel283;
private javax.swing.JLabel jLabel284;
private javax.swing.JLabel jLabel285;
private javax.swing.JLabel jLabel286;
private javax.swing.JLabel jLabel287;
private javax.swing.JLabel jLabel288;
private javax.swing.JLabel jLabel289;
private javax.swing.JLabel jLabel290;
private javax.swing.JLabel jLabel291;
private javax.swing.JLabel jLabel292;
private javax.swing.JLabel jLabel293;
private javax.swing.JLabel jLabel294;
private javax.swing.JLabel jLabel295;
private javax.swing.JLabel jLabel296;
private javax.swing.JLabel jLabel297;
private javax.swing.JLabel jLabel298;
private javax.swing.JLabel jLabel299;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel300;
private javax.swing.JLabel jLabel301;
private javax.swing.JLabel jLabel302;
private javax.swing.JLabel jLabel303;
private javax.swing.JLabel jLabel304;
private javax.swing.JLabel jLabel305;
private javax.swing.JLabel jLabel306;
private javax.swing.JLabel jLabel307;
private javax.swing.JLabel jLabel308;
private javax.swing.JLabel jLabel309;
private javax.swing.JLabel jLabel310;
private javax.swing.JLabel jLabel311;
private javax.swing.JLabel jLabel312;
private javax.swing.JLabel jLabel313;
private javax.swing.JLabel jLabel314;
private javax.swing.JLabel jLabel315;
private javax.swing.JLabel jLabel316;
private javax.swing.JLabel jLabel317;
private javax.swing.JLabel jLabel318;
private javax.swing.JLabel jLabel319;
private javax.swing.JLabel jLabel320;
private javax.swing.JLabel jLabel321;
private javax.swing.JLabel jLabel322;
private javax.swing.JLabel jLabel323;
private javax.swing.JLabel jLabel324;
private javax.swing.JLabel jLabel325;
private javax.swing.JLabel jLabel326;
private javax.swing.JLabel jLabel327;
private javax.swing.JLabel jLabel328;
private javax.swing.JLabel jLabel329;
private javax.swing.JLabel jLabel330;
private javax.swing.JLabel jLabel331;
private javax.swing.JLabel jLabel332;
private javax.swing.JLabel jLabel333;
private javax.swing.JLabel jLabel334;
private javax.swing.JLabel jLabel335;
private javax.swing.JLabel jLabel336;
private javax.swing.JLabel jLabel337;
private javax.swing.JLabel jLabel338;
private javax.swing.JLabel jLabel339;
private javax.swing.JLabel jLabel340;
private javax.swing.JLabel jLabel341;
private javax.swing.JLabel jLabel342;
private javax.swing.JLabel jLabel343;
private javax.swing.JLabel jLabel344;
private javax.swing.JLabel jLabel345;
private javax.swing.JLabel jLabel346;
private javax.swing.JLabel jLabel347;
private javax.swing.JLabel jLabel348;
private javax.swing.JLabel jLabel349;
private javax.swing.JLabel jLabel350;
private javax.swing.JLabel jLabel351;
private javax.swing.JLabel jLabel352;
private javax.swing.JLabel jLabel353;
private javax.swing.JLabel jLabel354;
private javax.swing.JLabel jLabel355;
private javax.swing.JLabel jLabel356;
private javax.swing.JLabel jLabel357;
private javax.swing.JLabel jLabel358;
private javax.swing.JLabel jLabel359;
private javax.swing.JLabel jLabel360;
private javax.swing.JLabel jLabel361;
private javax.swing.JLabel jLabel362;
private javax.swing.JLabel jLabel363;
private javax.swing.JLabel jLabel364;
private javax.swing.JLabel jLabel365;
private javax.swing.JLabel jLabel366;
private javax.swing.JLabel jLabel367;
private javax.swing.JLabel jLabel368;
private javax.swing.JLabel jLabel369;
private javax.swing.JLabel jLabel370;
private javax.swing.JLabel jLabel371;
private javax.swing.JLabel jLabel372;
private javax.swing.JLabel jLabel373;
private javax.swing.JLabel jLabel374;
private javax.swing.JLabel jLabel375;
private javax.swing.JLabel jLabel376;
private javax.swing.JLabel jLabel377;
private javax.swing.JLabel jLabel378;
private javax.swing.JLabel jLabel379;
private javax.swing.JLabel jLabel380;
private javax.swing.JLabel jLabel381;
private javax.swing.JLabel jLabel382;
private javax.swing.JLabel jLabel383;
private javax.swing.JLabel jLabel384;
private javax.swing.JLabel jLabel385;
private javax.swing.JLabel jLabel386;
private javax.swing.JLabel jLabel387;
private javax.swing.JLabel jLabel388;
private javax.swing.JLabel jLabel389;
private javax.swing.JLabel jLabel390;
private javax.swing.JLabel jLabel391;
private javax.swing.JLabel jLabel392;
private javax.swing.JLabel jLabel393;
private javax.swing.JLabel jLabel394;
private javax.swing.JLabel jLabel395;
private javax.swing.JLabel jLabel396;
private javax.swing.JLabel jLabel397;
private javax.swing.JLabel jLabel398;
private javax.swing.JLabel jLabel399;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel400;
private javax.swing.JLabel jLabel401;
private javax.swing.JLabel jLabel402;
private javax.swing.JLabel jLabel403;
private javax.swing.JLabel jLabel404;
private javax.swing.JLabel jLabel405;
private javax.swing.JLabel jLabel406;
private javax.swing.JLabel jLabel407;
private javax.swing.JLabel jLabel408;
private javax.swing.JLabel jLabel409;
private javax.swing.JLabel jLabel410;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel27;
private javax.swing.JPanel jPanel28;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel37;
private javax.swing.JPanel jPanel38;
private javax.swing.JPanel jPanel39;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel40;
private javax.swing.JPanel jPanel41;
private javax.swing.JPanel jPanel42;
private javax.swing.JPanel jPanel43;
private javax.swing.JPanel jPanel44;
private javax.swing.JPanel jPanel45;
private javax.swing.JPanel jPanel46;
private javax.swing.JPanel jPanel47;
private javax.swing.JPanel jPanel48;
private javax.swing.JPanel jPanel49;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel50;
private javax.swing.JPanel jPanel51;
private javax.swing.JPanel jPanel52;
private javax.swing.JPanel jPanel53;
private javax.swing.JPanel jPanel54;
private javax.swing.JPanel jPanel55;
private javax.swing.JPanel jPanel56;
private javax.swing.JPanel jPanel57;
private javax.swing.JPanel jPanel58;
private javax.swing.JPanel jPanel59;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel60;
private javax.swing.JPanel jPanel61;
private javax.swing.JPanel jPanel62;
private javax.swing.JPanel jPanel63;
private javax.swing.JPanel jPanel64;
private javax.swing.JPanel jPanel65;
private javax.swing.JPanel jPanel66;
private javax.swing.JPanel jPanel67;
private javax.swing.JPanel jPanel68;
private javax.swing.JPanel jPanel69;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel70;
private javax.swing.JPanel jPanel71;
private javax.swing.JPanel jPanel72;
private javax.swing.JPanel jPanel73;
private javax.swing.JPanel jPanel74;
private javax.swing.JPanel jPanel75;
private javax.swing.JPanel jPanel76;
private javax.swing.JPanel jPanel77;
private javax.swing.JPanel jPanel78;
private javax.swing.JPanel jPanel79;
private javax.swing.JPanel jPanel80;
private javax.swing.JPanel jPanel81;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JButton logoutButton;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jPanel7 = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel6 = new javax.swing.JPanel();
jPanel13 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jComboBox5 = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox3 = new javax.swing.JComboBox();
jComboBox6 = new javax.swing.JComboBox();
jPanel14 = new javax.swing.JPanel();
jLabel198 = new javax.swing.JLabel();
jPanel27 = new javax.swing.JPanel();
jLabel237 = new javax.swing.JLabel();
jLabel238 = new javax.swing.JLabel();
jComboBox7 = new javax.swing.JComboBox();
jComboBox10 = new javax.swing.JComboBox();
jLabel239 = new javax.swing.JLabel();
jLabel240 = new javax.swing.JLabel();
jComboBox8 = new javax.swing.JComboBox();
jComboBox11 = new javax.swing.JComboBox();
jLabel241 = new javax.swing.JLabel();
jLabel242 = new javax.swing.JLabel();
jComboBox9 = new javax.swing.JComboBox();
jComboBox12 = new javax.swing.JComboBox();
jPanel28 = new javax.swing.JPanel();
jLabel243 = new javax.swing.JLabel();
jPanel53 = new javax.swing.JPanel();
jLabel319 = new javax.swing.JLabel();
jLabel320 = new javax.swing.JLabel();
jComboBox13 = new javax.swing.JComboBox();
jComboBox14 = new javax.swing.JComboBox();
jLabel321 = new javax.swing.JLabel();
jLabel322 = new javax.swing.JLabel();
jComboBox15 = new javax.swing.JComboBox();
jComboBox16 = new javax.swing.JComboBox();
jLabel323 = new javax.swing.JLabel();
jLabel324 = new javax.swing.JLabel();
jComboBox17 = new javax.swing.JComboBox();
jComboBox18 = new javax.swing.JComboBox();
jPanel54 = new javax.swing.JPanel();
jLabel325 = new javax.swing.JLabel();
jPanel72 = new javax.swing.JPanel();
jLabel376 = new javax.swing.JLabel();
jLabel377 = new javax.swing.JLabel();
jComboBox19 = new javax.swing.JComboBox();
jComboBox20 = new javax.swing.JComboBox();
jLabel378 = new javax.swing.JLabel();
jLabel379 = new javax.swing.JLabel();
jComboBox21 = new javax.swing.JComboBox();
jComboBox22 = new javax.swing.JComboBox();
jLabel380 = new javax.swing.JLabel();
jLabel381 = new javax.swing.JLabel();
jComboBox23 = new javax.swing.JComboBox();
jComboBox24 = new javax.swing.JComboBox();
jPanel73 = new javax.swing.JPanel();
jLabel382 = new javax.swing.JLabel();
jPanel74 = new javax.swing.JPanel();
jLabel383 = new javax.swing.JLabel();
jLabel384 = new javax.swing.JLabel();
jComboBox25 = new javax.swing.JComboBox();
jComboBox26 = new javax.swing.JComboBox();
jLabel385 = new javax.swing.JLabel();
jLabel386 = new javax.swing.JLabel();
jComboBox27 = new javax.swing.JComboBox();
jComboBox28 = new javax.swing.JComboBox();
jLabel387 = new javax.swing.JLabel();
jLabel388 = new javax.swing.JLabel();
jComboBox29 = new javax.swing.JComboBox();
jComboBox30 = new javax.swing.JComboBox();
jPanel75 = new javax.swing.JPanel();
jLabel389 = new javax.swing.JLabel();
jPanel76 = new javax.swing.JPanel();
jLabel390 = new javax.swing.JLabel();
jLabel391 = new javax.swing.JLabel();
jComboBox31 = new javax.swing.JComboBox();
jComboBox32 = new javax.swing.JComboBox();
jLabel392 = new javax.swing.JLabel();
jLabel393 = new javax.swing.JLabel();
jComboBox33 = new javax.swing.JComboBox();
jComboBox34 = new javax.swing.JComboBox();
jLabel394 = new javax.swing.JLabel();
jLabel395 = new javax.swing.JLabel();
jComboBox35 = new javax.swing.JComboBox();
jComboBox36 = new javax.swing.JComboBox();
jPanel77 = new javax.swing.JPanel();
jLabel396 = new javax.swing.JLabel();
jPanel78 = new javax.swing.JPanel();
jLabel397 = new javax.swing.JLabel();
jLabel398 = new javax.swing.JLabel();
jComboBox37 = new javax.swing.JComboBox();
jComboBox38 = new javax.swing.JComboBox();
jLabel399 = new javax.swing.JLabel();
jLabel400 = new javax.swing.JLabel();
jComboBox39 = new javax.swing.JComboBox();
jComboBox40 = new javax.swing.JComboBox();
jLabel401 = new javax.swing.JLabel();
jLabel402 = new javax.swing.JLabel();
jComboBox41 = new javax.swing.JComboBox();
jComboBox42 = new javax.swing.JComboBox();
jPanel79 = new javax.swing.JPanel();
jLabel403 = new javax.swing.JLabel();
jPanel80 = new javax.swing.JPanel();
jLabel404 = new javax.swing.JLabel();
jLabel405 = new javax.swing.JLabel();
jComboBox43 = new javax.swing.JComboBox();
jComboBox44 = new javax.swing.JComboBox();
jLabel406 = new javax.swing.JLabel();
jLabel407 = new javax.swing.JLabel();
jComboBox45 = new javax.swing.JComboBox();
jComboBox46 = new javax.swing.JComboBox();
jLabel408 = new javax.swing.JLabel();
jLabel409 = new javax.swing.JLabel();
jComboBox47 = new javax.swing.JComboBox();
jComboBox48 = new javax.swing.JComboBox();
jPanel81 = new javax.swing.JPanel();
jLabel410 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jPanel10 = new javax.swing.JPanel();
jPanel45 = new javax.swing.JPanel();
jLabel294 = new javax.swing.JLabel();
jLabel295 = new javax.swing.JLabel();
jComboBox272 = new javax.swing.JComboBox();
jComboBox273 = new javax.swing.JComboBox();
jLabel296 = new javax.swing.JLabel();
jLabel297 = new javax.swing.JLabel();
jComboBox274 = new javax.swing.JComboBox();
jComboBox275 = new javax.swing.JComboBox();
jLabel298 = new javax.swing.JLabel();
jLabel299 = new javax.swing.JLabel();
jComboBox276 = new javax.swing.JComboBox();
jComboBox277 = new javax.swing.JComboBox();
jPanel46 = new javax.swing.JPanel();
jLabel300 = new javax.swing.JLabel();
jPanel47 = new javax.swing.JPanel();
jLabel301 = new javax.swing.JLabel();
jComboBox278 = new javax.swing.JComboBox();
jLabel302 = new javax.swing.JLabel();
jComboBox279 = new javax.swing.JComboBox();
jLabel303 = new javax.swing.JLabel();
jComboBox280 = new javax.swing.JComboBox();
jPanel48 = new javax.swing.JPanel();
jLabel304 = new javax.swing.JLabel();
jPanel49 = new javax.swing.JPanel();
jLabel305 = new javax.swing.JLabel();
jLabel306 = new javax.swing.JLabel();
jComboBox281 = new javax.swing.JComboBox();
jComboBox282 = new javax.swing.JComboBox();
jLabel307 = new javax.swing.JLabel();
jLabel308 = new javax.swing.JLabel();
jComboBox283 = new javax.swing.JComboBox();
jComboBox284 = new javax.swing.JComboBox();
jLabel309 = new javax.swing.JLabel();
jLabel310 = new javax.swing.JLabel();
jComboBox285 = new javax.swing.JComboBox();
jComboBox286 = new javax.swing.JComboBox();
jPanel50 = new javax.swing.JPanel();
jLabel311 = new javax.swing.JLabel();
jPanel51 = new javax.swing.JPanel();
jLabel312 = new javax.swing.JLabel();
jLabel313 = new javax.swing.JLabel();
jComboBox287 = new javax.swing.JComboBox();
jComboBox288 = new javax.swing.JComboBox();
jLabel314 = new javax.swing.JLabel();
jLabel315 = new javax.swing.JLabel();
jComboBox289 = new javax.swing.JComboBox();
jComboBox290 = new javax.swing.JComboBox();
jLabel316 = new javax.swing.JLabel();
jLabel317 = new javax.swing.JLabel();
jComboBox291 = new javax.swing.JComboBox();
jComboBox292 = new javax.swing.JComboBox();
jPanel52 = new javax.swing.JPanel();
jLabel318 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jPanel12 = new javax.swing.JPanel();
jPanel37 = new javax.swing.JPanel();
jLabel272 = new javax.swing.JLabel();
jLabel273 = new javax.swing.JLabel();
jComboBox254 = new javax.swing.JComboBox();
jComboBox255 = new javax.swing.JComboBox();
jLabel274 = new javax.swing.JLabel();
jLabel275 = new javax.swing.JLabel();
jComboBox256 = new javax.swing.JComboBox();
jComboBox257 = new javax.swing.JComboBox();
jLabel276 = new javax.swing.JLabel();
jLabel277 = new javax.swing.JLabel();
jComboBox258 = new javax.swing.JComboBox();
jComboBox259 = new javax.swing.JComboBox();
jPanel38 = new javax.swing.JPanel();
jLabel278 = new javax.swing.JLabel();
jPanel39 = new javax.swing.JPanel();
jLabel217 = new javax.swing.JLabel();
jComboBox207 = new javax.swing.JComboBox();
jLabel219 = new javax.swing.JLabel();
jComboBox209 = new javax.swing.JComboBox();
jLabel221 = new javax.swing.JLabel();
jComboBox211 = new javax.swing.JComboBox();
jPanel40 = new javax.swing.JPanel();
jLabel279 = new javax.swing.JLabel();
jPanel41 = new javax.swing.JPanel();
jLabel280 = new javax.swing.JLabel();
jLabel281 = new javax.swing.JLabel();
jComboBox260 = new javax.swing.JComboBox();
jComboBox261 = new javax.swing.JComboBox();
jLabel282 = new javax.swing.JLabel();
jLabel283 = new javax.swing.JLabel();
jComboBox262 = new javax.swing.JComboBox();
jComboBox263 = new javax.swing.JComboBox();
jLabel284 = new javax.swing.JLabel();
jLabel285 = new javax.swing.JLabel();
jComboBox264 = new javax.swing.JComboBox();
jComboBox265 = new javax.swing.JComboBox();
jPanel42 = new javax.swing.JPanel();
jLabel286 = new javax.swing.JLabel();
jPanel43 = new javax.swing.JPanel();
jLabel287 = new javax.swing.JLabel();
jLabel288 = new javax.swing.JLabel();
jComboBox266 = new javax.swing.JComboBox();
jComboBox267 = new javax.swing.JComboBox();
jLabel289 = new javax.swing.JLabel();
jLabel290 = new javax.swing.JLabel();
jComboBox268 = new javax.swing.JComboBox();
jComboBox269 = new javax.swing.JComboBox();
jLabel291 = new javax.swing.JLabel();
jLabel292 = new javax.swing.JLabel();
jComboBox270 = new javax.swing.JComboBox();
jComboBox271 = new javax.swing.JComboBox();
jPanel44 = new javax.swing.JPanel();
jLabel293 = new javax.swing.JLabel();
jPanel18 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
jPanel17 = new javax.swing.JPanel();
jPanel55 = new javax.swing.JPanel();
jLabel326 = new javax.swing.JLabel();
jLabel327 = new javax.swing.JLabel();
jComboBox299 = new javax.swing.JComboBox();
jComboBox300 = new javax.swing.JComboBox();
jLabel328 = new javax.swing.JLabel();
jLabel329 = new javax.swing.JLabel();
jComboBox301 = new javax.swing.JComboBox();
jComboBox302 = new javax.swing.JComboBox();
jLabel330 = new javax.swing.JLabel();
jLabel331 = new javax.swing.JLabel();
jComboBox303 = new javax.swing.JComboBox();
jComboBox304 = new javax.swing.JComboBox();
jPanel56 = new javax.swing.JPanel();
jLabel332 = new javax.swing.JLabel();
jPanel57 = new javax.swing.JPanel();
jLabel333 = new javax.swing.JLabel();
jComboBox305 = new javax.swing.JComboBox();
jLabel334 = new javax.swing.JLabel();
jComboBox306 = new javax.swing.JComboBox();
jLabel335 = new javax.swing.JLabel();
jComboBox307 = new javax.swing.JComboBox();
jPanel58 = new javax.swing.JPanel();
jLabel336 = new javax.swing.JLabel();
jPanel59 = new javax.swing.JPanel();
jLabel337 = new javax.swing.JLabel();
jLabel338 = new javax.swing.JLabel();
jComboBox308 = new javax.swing.JComboBox();
jComboBox309 = new javax.swing.JComboBox();
jLabel339 = new javax.swing.JLabel();
jLabel340 = new javax.swing.JLabel();
jComboBox310 = new javax.swing.JComboBox();
jComboBox311 = new javax.swing.JComboBox();
jLabel341 = new javax.swing.JLabel();
jLabel342 = new javax.swing.JLabel();
jComboBox312 = new javax.swing.JComboBox();
jComboBox313 = new javax.swing.JComboBox();
jPanel60 = new javax.swing.JPanel();
jLabel343 = new javax.swing.JLabel();
jPanel61 = new javax.swing.JPanel();
jLabel344 = new javax.swing.JLabel();
jLabel345 = new javax.swing.JLabel();
jComboBox314 = new javax.swing.JComboBox();
jComboBox315 = new javax.swing.JComboBox();
jLabel346 = new javax.swing.JLabel();
jLabel347 = new javax.swing.JLabel();
jComboBox316 = new javax.swing.JComboBox();
jComboBox317 = new javax.swing.JComboBox();
jLabel348 = new javax.swing.JLabel();
jLabel349 = new javax.swing.JLabel();
jComboBox318 = new javax.swing.JComboBox();
jComboBox319 = new javax.swing.JComboBox();
jPanel62 = new javax.swing.JPanel();
jLabel350 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jPanel63 = new javax.swing.JPanel();
jPanel64 = new javax.swing.JPanel();
jLabel351 = new javax.swing.JLabel();
jLabel352 = new javax.swing.JLabel();
jComboBox320 = new javax.swing.JComboBox();
jComboBox321 = new javax.swing.JComboBox();
jLabel353 = new javax.swing.JLabel();
jLabel354 = new javax.swing.JLabel();
jComboBox322 = new javax.swing.JComboBox();
jComboBox323 = new javax.swing.JComboBox();
jLabel355 = new javax.swing.JLabel();
jLabel356 = new javax.swing.JLabel();
jComboBox324 = new javax.swing.JComboBox();
jComboBox325 = new javax.swing.JComboBox();
jPanel65 = new javax.swing.JPanel();
jLabel357 = new javax.swing.JLabel();
jPanel66 = new javax.swing.JPanel();
jLabel358 = new javax.swing.JLabel();
jComboBox326 = new javax.swing.JComboBox();
jLabel359 = new javax.swing.JLabel();
jComboBox327 = new javax.swing.JComboBox();
jLabel360 = new javax.swing.JLabel();
jComboBox328 = new javax.swing.JComboBox();
jPanel67 = new javax.swing.JPanel();
jLabel361 = new javax.swing.JLabel();
jPanel68 = new javax.swing.JPanel();
jLabel362 = new javax.swing.JLabel();
jLabel363 = new javax.swing.JLabel();
jComboBox329 = new javax.swing.JComboBox();
jComboBox330 = new javax.swing.JComboBox();
jLabel364 = new javax.swing.JLabel();
jLabel365 = new javax.swing.JLabel();
jComboBox331 = new javax.swing.JComboBox();
jComboBox332 = new javax.swing.JComboBox();
jLabel366 = new javax.swing.JLabel();
jLabel367 = new javax.swing.JLabel();
jComboBox333 = new javax.swing.JComboBox();
jComboBox334 = new javax.swing.JComboBox();
jPanel69 = new javax.swing.JPanel();
jLabel368 = new javax.swing.JLabel();
jPanel70 = new javax.swing.JPanel();
jLabel369 = new javax.swing.JLabel();
jLabel370 = new javax.swing.JLabel();
jComboBox335 = new javax.swing.JComboBox();
jComboBox336 = new javax.swing.JComboBox();
jLabel371 = new javax.swing.JLabel();
jLabel372 = new javax.swing.JLabel();
jComboBox337 = new javax.swing.JComboBox();
jComboBox338 = new javax.swing.JComboBox();
jLabel373 = new javax.swing.JLabel();
jLabel374 = new javax.swing.JLabel();
jComboBox339 = new javax.swing.JComboBox();
jComboBox340 = new javax.swing.JComboBox();
jPanel71 = new javax.swing.JPanel();
jLabel375 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel196 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel199 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel200 = new javax.swing.JLabel();
jLabel201 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
logoutButton = new javax.swing.JButton();
editAccountButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Courses");
setBackground(new java.awt.Color(255, 255, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jPanel7.setBackground(new java.awt.Color(255, 255, 255));
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel13.setBackground(new java.awt.Color(225, 225, 225));
jPanel13.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel1.setText("Course 1");
jLabel1.setToolTipText("");
jLabel2.setText("Course 2");
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jLabel3.setText("Course 3");
jLabel3.setToolTipText("");
jLabel4.setText("Course 4");
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jLabel5.setText("Course 5");
jLabel9.setText("Course 6");
jPanel14.setBackground(new java.awt.Color(204, 204, 204));
jLabel198.setText(" Fall Semester 1");
jLabel198.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel27.setBackground(new java.awt.Color(225, 225, 225));
jPanel27.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel237.setText("Course 1");
jLabel237.setToolTipText("");
jLabel238.setText("Course 2");
jComboBox7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox7ActionPerformed(evt);
}
});
jLabel239.setText("Course 3");
jLabel239.setToolTipText("");
jLabel240.setText("Course 4");
jComboBox8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox8ActionPerformed(evt);
}
});
jLabel241.setText("Course 5");
jLabel242.setText("Course 6");
jPanel28.setBackground(new java.awt.Color(204, 204, 204));
jLabel243.setText(" Fall Semester 1");
jLabel243.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28);
jPanel28.setLayout(jPanel28Layout);
jPanel28Layout.setHorizontalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel28Layout.createSequentialGroup()
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel28Layout.setVerticalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27);
jPanel27.setLayout(jPanel27Layout);
jPanel27Layout.setHorizontalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel237)
.addComponent(jLabel238))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel239)
.addComponent(jLabel240))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel241)
.addComponent(jLabel242))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel27Layout.setVerticalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel237)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel239)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel241, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel238)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel240)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel242, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel53.setBackground(new java.awt.Color(225, 225, 225));
jPanel53.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel319.setText("Course 1");
jLabel319.setToolTipText("");
jLabel320.setText("Course 2");
jComboBox13.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox13ActionPerformed(evt);
}
});
jComboBox14.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel321.setText("Course 3");
jLabel321.setToolTipText("");
jLabel322.setText("Course 4");
jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox15ActionPerformed(evt);
}
});
jComboBox16.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel323.setText("Course 5");
jLabel324.setText("Course 6");
jComboBox17.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox18.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel54.setBackground(new java.awt.Color(204, 204, 204));
jPanel54.setForeground(new java.awt.Color(255, 255, 255));
jLabel325.setText(" Fall Semester 1");
jLabel325.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel54Layout = new javax.swing.GroupLayout(jPanel54);
jPanel54.setLayout(jPanel54Layout);
jPanel54Layout.setHorizontalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel54Layout.createSequentialGroup()
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel54Layout.setVerticalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel53Layout = new javax.swing.GroupLayout(jPanel53);
jPanel53.setLayout(jPanel53Layout);
jPanel53Layout.setHorizontalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel319)
.addComponent(jLabel320))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel321)
.addComponent(jLabel322))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel323)
.addComponent(jLabel324))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(12, Short.MAX_VALUE))
);
jPanel53Layout.setVerticalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel319)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel321)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel323, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel320)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel322)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel324, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel72.setBackground(new java.awt.Color(225, 225, 225));
jPanel72.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel376.setText("Course 1");
jLabel376.setToolTipText("");
jLabel377.setText("Course 2");
jComboBox19.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox19ActionPerformed(evt);
}
});
jComboBox20.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel378.setText("Course 3");
jLabel378.setToolTipText("");
jLabel379.setText("Course 4");
jComboBox21.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox21.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox21ActionPerformed(evt);
}
});
jComboBox22.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel380.setText("Course 5");
jLabel381.setText("Course 6");
jComboBox23.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox24.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel73.setBackground(new java.awt.Color(204, 204, 204));
jLabel382.setText(" Fall Semester 1");
jLabel382.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel73Layout = new javax.swing.GroupLayout(jPanel73);
jPanel73.setLayout(jPanel73Layout);
jPanel73Layout.setHorizontalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel73Layout.createSequentialGroup()
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel73Layout.setVerticalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel72Layout = new javax.swing.GroupLayout(jPanel72);
jPanel72.setLayout(jPanel72Layout);
jPanel72Layout.setHorizontalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel376)
.addComponent(jLabel377))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel378)
.addComponent(jLabel379))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel380)
.addComponent(jLabel381))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel72Layout.setVerticalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel376)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel378)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel380, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel377)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel379)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel381, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel74.setBackground(new java.awt.Color(225, 225, 225));
jPanel74.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel383.setText("Course 1");
jLabel383.setToolTipText("");
jLabel384.setText("Course 2");
jComboBox25.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox25.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox25ActionPerformed(evt);
}
});
jComboBox26.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel385.setText("Course 3");
jLabel385.setToolTipText("");
jLabel386.setText("Course 4");
jComboBox27.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox27.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox27ActionPerformed(evt);
}
});
jComboBox28.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel387.setText("Course 5");
jLabel388.setText("Course 6");
jComboBox29.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox30.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel75.setBackground(new java.awt.Color(204, 204, 204));
jPanel75.setForeground(new java.awt.Color(255, 255, 255));
jLabel389.setText(" Fall Semester 1");
jLabel389.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel75Layout = new javax.swing.GroupLayout(jPanel75);
jPanel75.setLayout(jPanel75Layout);
jPanel75Layout.setHorizontalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel75Layout.createSequentialGroup()
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel75Layout.setVerticalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel74Layout = new javax.swing.GroupLayout(jPanel74);
jPanel74.setLayout(jPanel74Layout);
jPanel74Layout.setHorizontalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel383)
.addComponent(jLabel384))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel385)
.addComponent(jLabel386))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel387)
.addComponent(jLabel388))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel74Layout.setVerticalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel383)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel385)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel387, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel384)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel386)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel388, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel76.setBackground(new java.awt.Color(225, 225, 225));
jPanel76.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel390.setText("Course 1");
jLabel390.setToolTipText("");
jLabel391.setText("Course 2");
jComboBox31.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox31.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox31ActionPerformed(evt);
}
});
jComboBox32.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel392.setText("Course 3");
jLabel392.setToolTipText("");
jLabel393.setText("Course 4");
jComboBox33.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox33.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox33ActionPerformed(evt);
}
});
jComboBox34.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel394.setText("Course 5");
jLabel395.setText("Course 6");
jComboBox35.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox36.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel77.setBackground(new java.awt.Color(204, 204, 204));
jPanel77.setForeground(new java.awt.Color(255, 255, 255));
jLabel396.setText(" Fall Semester 1");
jLabel396.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel77Layout = new javax.swing.GroupLayout(jPanel77);
jPanel77.setLayout(jPanel77Layout);
jPanel77Layout.setHorizontalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel77Layout.createSequentialGroup()
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel77Layout.setVerticalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel76Layout = new javax.swing.GroupLayout(jPanel76);
jPanel76.setLayout(jPanel76Layout);
jPanel76Layout.setHorizontalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel390)
.addComponent(jLabel391))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel392)
.addComponent(jLabel393))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel394)
.addComponent(jLabel395))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel76Layout.setVerticalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel390)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel392)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel394, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel391)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel393)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel395, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel78.setBackground(new java.awt.Color(225, 225, 225));
jPanel78.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel397.setText("Course 1");
jLabel397.setToolTipText("");
jLabel398.setText("Course 2");
jComboBox37.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox37.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox37ActionPerformed(evt);
}
});
jComboBox38.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel399.setText("Course 3");
jLabel399.setToolTipText("");
jLabel400.setText("Course 4");
jComboBox39.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox39.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox39ActionPerformed(evt);
}
});
jComboBox40.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel401.setText("Course 5");
jLabel402.setText("Course 6");
jComboBox41.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox42.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel79.setBackground(new java.awt.Color(204, 204, 204));
jPanel79.setForeground(new java.awt.Color(255, 255, 255));
jLabel403.setText(" Fall Semester 1");
jLabel403.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel79Layout = new javax.swing.GroupLayout(jPanel79);
jPanel79.setLayout(jPanel79Layout);
jPanel79Layout.setHorizontalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel79Layout.createSequentialGroup()
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel79Layout.setVerticalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel78Layout = new javax.swing.GroupLayout(jPanel78);
jPanel78.setLayout(jPanel78Layout);
jPanel78Layout.setHorizontalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel397)
.addComponent(jLabel398))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel399)
.addComponent(jLabel400))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel401)
.addComponent(jLabel402))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel78Layout.setVerticalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel397)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel399)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel401, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel398)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel400)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel402, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel80.setBackground(new java.awt.Color(225, 225, 225));
jPanel80.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel404.setText("Course 1");
jLabel404.setToolTipText("");
jLabel405.setText("Course 2");
jComboBox43.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox43.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox43ActionPerformed(evt);
}
});
jComboBox44.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel406.setText("Course 3");
jLabel406.setToolTipText("");
jLabel407.setText("Course 4");
jComboBox45.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox45.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox45ActionPerformed(evt);
}
});
jComboBox46.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel408.setText("Course 5");
jLabel409.setText("Course 6");
jComboBox47.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox48.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel81.setBackground(new java.awt.Color(204, 204, 204));
jPanel81.setForeground(new java.awt.Color(255, 255, 255));
jLabel410.setText(" Fall Semester 1");
jLabel410.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel81Layout = new javax.swing.GroupLayout(jPanel81);
jPanel81.setLayout(jPanel81Layout);
jPanel81Layout.setHorizontalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel81Layout.createSequentialGroup()
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel81Layout.setVerticalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel80Layout = new javax.swing.GroupLayout(jPanel80);
jPanel80.setLayout(jPanel80Layout);
jPanel80Layout.setHorizontalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel404)
.addComponent(jLabel405))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel406)
.addComponent(jLabel407))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel408)
.addComponent(jLabel409))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel80Layout.setVerticalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel404)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel406)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel408, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel405)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel407)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel409, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE))
);
jScrollPane1.setViewportView(jPanel6);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Computer Science", jPanel1);
jPanel10.setBackground(new java.awt.Color(255, 255, 255));
jPanel45.setBackground(new java.awt.Color(225, 225, 225));
jPanel45.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel294.setText("Course 1");
jLabel294.setToolTipText("");
jLabel295.setText("Course 2");
jComboBox272.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox272.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox272ActionPerformed(evt);
}
});
jComboBox273.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel296.setText("Course 3");
jLabel296.setToolTipText("");
jLabel297.setText("Course 4");
jComboBox274.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox274.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox274ActionPerformed(evt);
}
});
jComboBox275.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel298.setText("Course 5");
jLabel299.setText("Course 6");
jComboBox276.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox277.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel46.setBackground(new java.awt.Color(204, 204, 204));
jLabel300.setText(" Spring Semester 2");
jLabel300.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel46Layout = new javax.swing.GroupLayout(jPanel46);
jPanel46.setLayout(jPanel46Layout);
jPanel46Layout.setHorizontalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel46Layout.createSequentialGroup()
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel46Layout.setVerticalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel45Layout = new javax.swing.GroupLayout(jPanel45);
jPanel45.setLayout(jPanel45Layout);
jPanel45Layout.setHorizontalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel294)
.addComponent(jLabel295))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel296)
.addComponent(jLabel297))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel298)
.addComponent(jLabel299))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel45Layout.setVerticalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel294)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel296)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel298, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel295)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel297)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel299, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel47.setBackground(new java.awt.Color(225, 225, 225));
jPanel47.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel301.setText("Course 1");
jLabel301.setToolTipText("");
jComboBox278.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox278.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox278ActionPerformed(evt);
}
});
jLabel302.setText("Course 2");
jLabel302.setToolTipText("");
jComboBox279.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox279.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox279ActionPerformed(evt);
}
});
jLabel303.setText("Course 3");
jComboBox280.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel48.setBackground(new java.awt.Color(204, 204, 204));
jLabel304.setText(" Summer Semester 2.5");
jLabel304.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel48Layout = new javax.swing.GroupLayout(jPanel48);
jPanel48.setLayout(jPanel48Layout);
jPanel48Layout.setHorizontalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel48Layout.createSequentialGroup()
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel48Layout.setVerticalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel47Layout = new javax.swing.GroupLayout(jPanel47);
jPanel47.setLayout(jPanel47Layout);
jPanel47Layout.setHorizontalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addComponent(jLabel301)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel302)
.addGap(18, 18, 18)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel303)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel47Layout.setVerticalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel301)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel302)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel303, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel49.setBackground(new java.awt.Color(225, 225, 225));
jPanel49.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel305.setText("Course 1");
jLabel305.setToolTipText("");
jLabel306.setText("Course 2");
jComboBox281.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox281.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox281ActionPerformed(evt);
}
});
jComboBox282.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel307.setText("Course 3");
jLabel307.setToolTipText("");
jLabel308.setText("Course 4");
jComboBox283.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox283.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox283ActionPerformed(evt);
}
});
jComboBox284.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel309.setText("Course 5");
jLabel310.setText("Course 6");
jComboBox285.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox286.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel50.setBackground(new java.awt.Color(204, 204, 204));
jPanel50.setForeground(new java.awt.Color(255, 255, 255));
jLabel311.setText(" Fall Semester 1");
jLabel311.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel50Layout = new javax.swing.GroupLayout(jPanel50);
jPanel50.setLayout(jPanel50Layout);
jPanel50Layout.setHorizontalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel50Layout.createSequentialGroup()
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel50Layout.setVerticalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel49Layout = new javax.swing.GroupLayout(jPanel49);
jPanel49.setLayout(jPanel49Layout);
jPanel49Layout.setHorizontalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel305)
.addComponent(jLabel306))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel307)
.addComponent(jLabel308))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel309)
.addComponent(jLabel310))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel49Layout.setVerticalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel305)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel307)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel309, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel306)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel308)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel310, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel51.setBackground(new java.awt.Color(225, 225, 225));
jPanel51.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel312.setText("Course 1");
jLabel312.setToolTipText("");
jLabel313.setText("Course 2");
jComboBox287.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox287.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox287ActionPerformed(evt);
}
});
jComboBox288.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel314.setText("Course 3");
jLabel314.setToolTipText("");
jLabel315.setText("Course 4");
jComboBox289.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox289.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox289ActionPerformed(evt);
}
});
jComboBox290.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel316.setText("Course 5");
jLabel317.setText("Course 6");
jComboBox291.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox292.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel52.setBackground(new java.awt.Color(204, 204, 204));
jPanel52.setForeground(new java.awt.Color(255, 255, 255));
jLabel318.setText(" Fall Semester 3");
jLabel318.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel52Layout = new javax.swing.GroupLayout(jPanel52);
jPanel52.setLayout(jPanel52Layout);
jPanel52Layout.setHorizontalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel52Layout.createSequentialGroup()
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel52Layout.setVerticalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel51Layout = new javax.swing.GroupLayout(jPanel51);
jPanel51.setLayout(jPanel51Layout);
jPanel51Layout.setHorizontalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel312)
.addComponent(jLabel313))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel314)
.addComponent(jLabel315))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel316)
.addComponent(jLabel317))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel51Layout.setVerticalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel312)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel314)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel316, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel313)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel315)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel317, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(67, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane3.setViewportView(jPanel10);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Science ", jPanel4);
jPanel12.setBackground(new java.awt.Color(255, 255, 255));
jPanel37.setBackground(new java.awt.Color(225, 225, 225));
jPanel37.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel272.setText("Course 1");
jLabel272.setToolTipText("");
jLabel273.setText("Course 2");
jComboBox254.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox254.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox254ActionPerformed(evt);
}
});
jComboBox255.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel274.setText("Course 3");
jLabel274.setToolTipText("");
jLabel275.setText("Course 4");
jComboBox256.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox256.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox256ActionPerformed(evt);
}
});
jComboBox257.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel276.setText("Course 5");
jLabel277.setText("Course 6");
jComboBox258.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox259.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel38.setBackground(new java.awt.Color(204, 204, 204));
jLabel278.setText(" Spring Semester 2");
jLabel278.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel38Layout = new javax.swing.GroupLayout(jPanel38);
jPanel38.setLayout(jPanel38Layout);
jPanel38Layout.setHorizontalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel38Layout.createSequentialGroup()
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel38Layout.setVerticalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel37Layout = new javax.swing.GroupLayout(jPanel37);
jPanel37.setLayout(jPanel37Layout);
jPanel37Layout.setHorizontalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel272)
.addComponent(jLabel273))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel274)
.addComponent(jLabel275))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel276)
.addComponent(jLabel277))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel37Layout.setVerticalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel272)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel274)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel276, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel273)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel275)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel277, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel39.setBackground(new java.awt.Color(225, 225, 225));
jPanel39.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel217.setText("Course 1");
jLabel217.setToolTipText("");
jComboBox207.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox207.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox207ActionPerformed(evt);
}
});
jLabel219.setText("Course 2");
jLabel219.setToolTipText("");
jComboBox209.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox209.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox209ActionPerformed(evt);
}
});
jLabel221.setText("Course 3");
jComboBox211.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel40.setBackground(new java.awt.Color(204, 204, 204));
jLabel279.setText(" Summer Semester 2.5");
jLabel279.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel40Layout = new javax.swing.GroupLayout(jPanel40);
jPanel40.setLayout(jPanel40Layout);
jPanel40Layout.setHorizontalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel40Layout.createSequentialGroup()
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel40Layout.setVerticalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel39Layout = new javax.swing.GroupLayout(jPanel39);
jPanel39.setLayout(jPanel39Layout);
jPanel39Layout.setHorizontalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addComponent(jLabel217)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel219)
.addGap(18, 18, 18)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel221)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel39Layout.setVerticalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel217)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel219)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel221, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel41.setBackground(new java.awt.Color(225, 225, 225));
jPanel41.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel280.setText("Course 1");
jLabel280.setToolTipText("");
jLabel281.setText("Course 2");
jComboBox260.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox260.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox260ActionPerformed(evt);
}
});
jComboBox261.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel282.setText("Course 3");
jLabel282.setToolTipText("");
jLabel283.setText("Course 4");
jComboBox262.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox262.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox262ActionPerformed(evt);
}
});
jComboBox263.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel284.setText("Course 5");
jLabel285.setText("Course 6");
jComboBox264.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox265.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel42.setBackground(new java.awt.Color(204, 204, 204));
jPanel42.setForeground(new java.awt.Color(255, 255, 255));
jLabel286.setText(" Fall Semester 1");
jLabel286.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel42Layout = new javax.swing.GroupLayout(jPanel42);
jPanel42.setLayout(jPanel42Layout);
jPanel42Layout.setHorizontalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel42Layout.createSequentialGroup()
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel42Layout.setVerticalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel41Layout = new javax.swing.GroupLayout(jPanel41);
jPanel41.setLayout(jPanel41Layout);
jPanel41Layout.setHorizontalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel280)
.addComponent(jLabel281))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel282)
.addComponent(jLabel283))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel284)
.addComponent(jLabel285))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel41Layout.setVerticalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel280)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel282)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel284, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel281)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel283)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel285, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel43.setBackground(new java.awt.Color(225, 225, 225));
jPanel43.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel287.setText("Course 1");
jLabel287.setToolTipText("");
jLabel288.setText("Course 2");
jComboBox266.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox266.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox266ActionPerformed(evt);
}
});
jComboBox267.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel289.setText("Course 3");
jLabel289.setToolTipText("");
jLabel290.setText("Course 4");
jComboBox268.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox268.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox268ActionPerformed(evt);
}
});
jComboBox269.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel291.setText("Course 5");
jLabel292.setText("Course 6");
jComboBox270.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox271.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel44.setBackground(new java.awt.Color(204, 204, 204));
jPanel44.setForeground(new java.awt.Color(255, 255, 255));
jLabel293.setText(" Fall Semester 3");
jLabel293.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel44Layout = new javax.swing.GroupLayout(jPanel44);
jPanel44.setLayout(jPanel44Layout);
jPanel44Layout.setHorizontalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel44Layout.createSequentialGroup()
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel44Layout.setVerticalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel43Layout = new javax.swing.GroupLayout(jPanel43);
jPanel43.setLayout(jPanel43Layout);
jPanel43Layout.setHorizontalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel287)
.addComponent(jLabel288))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel289)
.addComponent(jLabel290))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel291)
.addComponent(jLabel292))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel43Layout.setVerticalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel287)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel289)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel291, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel288)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel290)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel292, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(331, Short.MAX_VALUE))
);
jScrollPane4.setViewportView(jPanel12);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Core ", jPanel2);
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jPanel55.setBackground(new java.awt.Color(225, 225, 225));
jPanel55.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel326.setText("Course 1");
jLabel326.setToolTipText("");
jLabel327.setText("Course 2");
jComboBox299.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox299.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox299ActionPerformed(evt);
}
});
jComboBox300.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel328.setText("Course 3");
jLabel328.setToolTipText("");
jLabel329.setText("Course 4");
jComboBox301.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox301.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox301ActionPerformed(evt);
}
});
jComboBox302.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel330.setText("Course 5");
jLabel331.setText("Course 6");
jComboBox303.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox304.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel56.setBackground(new java.awt.Color(204, 204, 204));
jLabel332.setText(" Spring Semester 2");
jLabel332.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel56Layout = new javax.swing.GroupLayout(jPanel56);
jPanel56.setLayout(jPanel56Layout);
jPanel56Layout.setHorizontalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel56Layout.createSequentialGroup()
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel56Layout.setVerticalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel55Layout = new javax.swing.GroupLayout(jPanel55);
jPanel55.setLayout(jPanel55Layout);
jPanel55Layout.setHorizontalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel326)
.addComponent(jLabel327))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel328)
.addComponent(jLabel329))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel330)
.addComponent(jLabel331))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel55Layout.setVerticalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel326)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel328)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel330, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel327)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel329)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel331, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel57.setBackground(new java.awt.Color(225, 225, 225));
jPanel57.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel333.setText("Course 1");
jLabel333.setToolTipText("");
jComboBox305.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox305.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox305ActionPerformed(evt);
}
});
jLabel334.setText("Course 2");
jLabel334.setToolTipText("");
jComboBox306.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox306.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox306ActionPerformed(evt);
}
});
jLabel335.setText("Course 3");
jComboBox307.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel58.setBackground(new java.awt.Color(204, 204, 204));
jLabel336.setText(" Summer Semester 2.5");
jLabel336.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel58Layout = new javax.swing.GroupLayout(jPanel58);
jPanel58.setLayout(jPanel58Layout);
jPanel58Layout.setHorizontalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel58Layout.createSequentialGroup()
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel58Layout.setVerticalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel57Layout = new javax.swing.GroupLayout(jPanel57);
jPanel57.setLayout(jPanel57Layout);
jPanel57Layout.setHorizontalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addComponent(jLabel333)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel334)
.addGap(18, 18, 18)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel335)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel57Layout.setVerticalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel333)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel334)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel335, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel59.setBackground(new java.awt.Color(225, 225, 225));
jPanel59.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel337.setText("Course 1");
jLabel337.setToolTipText("");
jLabel338.setText("Course 2");
jComboBox308.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox308.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox308ActionPerformed(evt);
}
});
jComboBox309.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel339.setText("Course 3");
jLabel339.setToolTipText("");
jLabel340.setText("Course 4");
jComboBox310.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox310.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox310ActionPerformed(evt);
}
});
jComboBox311.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel341.setText("Course 5");
jLabel342.setText("Course 6");
jComboBox312.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox313.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel60.setBackground(new java.awt.Color(204, 204, 204));
jPanel60.setForeground(new java.awt.Color(255, 255, 255));
jLabel343.setText(" Fall Semester 1");
jLabel343.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel60Layout = new javax.swing.GroupLayout(jPanel60);
jPanel60.setLayout(jPanel60Layout);
jPanel60Layout.setHorizontalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel60Layout.createSequentialGroup()
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel60Layout.setVerticalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel59Layout = new javax.swing.GroupLayout(jPanel59);
jPanel59.setLayout(jPanel59Layout);
jPanel59Layout.setHorizontalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel337)
.addComponent(jLabel338))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel339)
.addComponent(jLabel340))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel341)
.addComponent(jLabel342))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel59Layout.setVerticalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel337)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel339)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel341, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel338)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel340)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel342, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel61.setBackground(new java.awt.Color(225, 225, 225));
jPanel61.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel344.setText("Course 1");
jLabel344.setToolTipText("");
jLabel345.setText("Course 2");
jComboBox314.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox314.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox314ActionPerformed(evt);
}
});
jComboBox315.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel346.setText("Course 3");
jLabel346.setToolTipText("");
jLabel347.setText("Course 4");
jComboBox316.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox316.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox316ActionPerformed(evt);
}
});
jComboBox317.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel348.setText("Course 5");
jLabel349.setText("Course 6");
jComboBox318.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox319.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel62.setBackground(new java.awt.Color(204, 204, 204));
jPanel62.setForeground(new java.awt.Color(255, 255, 255));
jLabel350.setText(" Fall Semester 3");
jLabel350.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel62Layout = new javax.swing.GroupLayout(jPanel62);
jPanel62.setLayout(jPanel62Layout);
jPanel62Layout.setHorizontalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel62Layout.createSequentialGroup()
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel62Layout.setVerticalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel61Layout = new javax.swing.GroupLayout(jPanel61);
jPanel61.setLayout(jPanel61Layout);
jPanel61Layout.setHorizontalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel344)
.addComponent(jLabel345))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel346)
.addComponent(jLabel347))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel348)
.addComponent(jLabel349))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel61Layout.setVerticalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel344)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel346)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel348, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel345)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel347)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel349, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane5.setViewportView(jPanel17);
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Electives ", jPanel18);
jPanel63.setBackground(new java.awt.Color(255, 255, 255));
jPanel64.setBackground(new java.awt.Color(225, 225, 225));
jPanel64.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel351.setText("Course 1");
jLabel351.setToolTipText("");
jLabel352.setText("Course 2");
jComboBox320.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox320.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox320ActionPerformed(evt);
}
});
jComboBox321.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel353.setText("Course 3");
jLabel353.setToolTipText("");
jLabel354.setText("Course 4");
jComboBox322.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox322.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox322ActionPerformed(evt);
}
});
jComboBox323.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel355.setText("Course 5");
jLabel356.setText("Course 6");
jComboBox324.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox325.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel65.setBackground(new java.awt.Color(204, 204, 204));
jLabel357.setText(" Spring Semester 2");
jLabel357.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel65Layout = new javax.swing.GroupLayout(jPanel65);
jPanel65.setLayout(jPanel65Layout);
jPanel65Layout.setHorizontalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel65Layout.createSequentialGroup()
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel65Layout.setVerticalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel64Layout = new javax.swing.GroupLayout(jPanel64);
jPanel64.setLayout(jPanel64Layout);
jPanel64Layout.setHorizontalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel351)
.addComponent(jLabel352))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel353)
.addComponent(jLabel354))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel355)
.addComponent(jLabel356))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel64Layout.setVerticalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel351)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel353)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel355, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel352)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel354)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel356, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel66.setBackground(new java.awt.Color(225, 225, 225));
jPanel66.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel358.setText("Course 1");
jLabel358.setToolTipText("");
jComboBox326.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox326.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox326ActionPerformed(evt);
}
});
jLabel359.setText("Course 2");
jLabel359.setToolTipText("");
jComboBox327.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox327.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox327ActionPerformed(evt);
}
});
jLabel360.setText("Course 3");
jComboBox328.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel67.setBackground(new java.awt.Color(204, 204, 204));
jLabel361.setText(" Summer Semester 2.5");
jLabel361.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel67Layout = new javax.swing.GroupLayout(jPanel67);
jPanel67.setLayout(jPanel67Layout);
jPanel67Layout.setHorizontalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel67Layout.createSequentialGroup()
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel67Layout.setVerticalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel66Layout = new javax.swing.GroupLayout(jPanel66);
jPanel66.setLayout(jPanel66Layout);
jPanel66Layout.setHorizontalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addComponent(jLabel358)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel359)
.addGap(18, 18, 18)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel360)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel66Layout.setVerticalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel358)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel359)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel360, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel68.setBackground(new java.awt.Color(225, 225, 225));
jPanel68.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel362.setText("Course 1");
jLabel362.setToolTipText("");
jLabel363.setText("Course 2");
jComboBox329.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox329.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox329ActionPerformed(evt);
}
});
jComboBox330.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel364.setText("Course 3");
jLabel364.setToolTipText("");
jLabel365.setText("Course 4");
jComboBox331.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox331.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox331ActionPerformed(evt);
}
});
jComboBox332.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel366.setText("Course 5");
jLabel367.setText("Course 6");
jComboBox333.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox334.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel69.setBackground(new java.awt.Color(204, 204, 204));
jPanel69.setForeground(new java.awt.Color(255, 255, 255));
jLabel368.setText(" Fall Semester 1");
jLabel368.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel69Layout = new javax.swing.GroupLayout(jPanel69);
jPanel69.setLayout(jPanel69Layout);
jPanel69Layout.setHorizontalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel69Layout.createSequentialGroup()
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel69Layout.setVerticalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel68Layout = new javax.swing.GroupLayout(jPanel68);
jPanel68.setLayout(jPanel68Layout);
jPanel68Layout.setHorizontalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel362)
.addComponent(jLabel363))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel364)
.addComponent(jLabel365))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel366)
.addComponent(jLabel367))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel68Layout.setVerticalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel362)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel364)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel366, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel363)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel365)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel367, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel70.setBackground(new java.awt.Color(225, 225, 225));
jPanel70.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel369.setText("Course 1");
jLabel369.setToolTipText("");
jLabel370.setText("Course 2");
jComboBox335.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox335.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox335ActionPerformed(evt);
}
});
jComboBox336.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel371.setText("Course 3");
jLabel371.setToolTipText("");
jLabel372.setText("Course 4");
jComboBox337.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox337.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox337ActionPerformed(evt);
}
});
jComboBox338.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel373.setText("Course 5");
jLabel374.setText("Course 6");
jComboBox339.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox340.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel71.setBackground(new java.awt.Color(204, 204, 204));
jPanel71.setForeground(new java.awt.Color(255, 255, 255));
jLabel375.setText(" Fall Semester 3");
jLabel375.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel71Layout = new javax.swing.GroupLayout(jPanel71);
jPanel71.setLayout(jPanel71Layout);
jPanel71Layout.setHorizontalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel71Layout.createSequentialGroup()
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel71Layout.setVerticalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel70Layout = new javax.swing.GroupLayout(jPanel70);
jPanel70.setLayout(jPanel70Layout);
jPanel70Layout.setHorizontalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel369)
.addComponent(jLabel370))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel371)
.addComponent(jLabel372))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel373)
.addComponent(jLabel374))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel70Layout.setVerticalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel369)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel371)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel373, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel370)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel372)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel374, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel63Layout = new javax.swing.GroupLayout(jPanel63);
jPanel63.setLayout(jPanel63Layout);
jPanel63Layout.setHorizontalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel63Layout.setVerticalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane2.setViewportView(jPanel63);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Math ", jPanel3);
jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setToolTipText("");
jLabel16.setToolTipText("");
jPanel15.setBackground(new java.awt.Color(83, 13, 47));
jPanel15.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel196.setForeground(new java.awt.Color(255, 255, 255));
jLabel196.setText("Student Name: ");
jTextField1.setText("CSCI");
jLabel199.setForeground(new java.awt.Color(255, 255, 255));
jLabel199.setText("Student Major:");
jTextField2.setText("Davey Jones");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jLabel200.setForeground(new java.awt.Color(255, 255, 255));
jLabel200.setText("Total Hours:");
jLabel201.setForeground(new java.awt.Color(255, 255, 255));
jLabel201.setText("Graduation Date:");
jTextField3.setText("110");
jTextField4.setText("May 2013");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel196, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jLabel199)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88)
.addComponent(jLabel200)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(94, 94, 94)
.addComponent(jLabel201)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel196, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel199, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel200, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel201, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/ZRICBanner.jpg"))); // NOI18N
jPanel5.setBackground(new java.awt.Color(83, 13, 47));
logoutButton.setForeground(new java.awt.Color(255, 255, 255));
logoutButton.setText("Logout");
logoutButton.setBorder(null);
logoutButton.setContentAreaFilled(false);
logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutButtonMouseClicked(evt);
}
});
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Settings");
editAccountButton.setBorder(null);
editAccountButton.setBorderPainted(false);
editAccountButton.setContentAreaFilled(false);
editAccountButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
editAccountButtonMouseClicked(evt);
}
});
editAccountButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editAccountButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(editAccountButton)
.addGap(18, 18, 18)
.addComponent(logoutButton)
.addGap(54, 54, 54))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(0, 2, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(logoutButton)
.addComponent(editAccountButton))
.addGap(0, 4, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addGap(304, 304, 304)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel10))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel16))
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 941, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jLabel16)
.addGap(0, 0, 0)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel6))
.addGap(0, 0, 0)
.addComponent(jLabel10)
.addGap(0, 0, 0)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
);
jTabbedPane1.getAccessibleContext().setAccessibleName("History");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jPanel7 = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel6 = new javax.swing.JPanel();
jPanel13 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jComboBox5 = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox3 = new javax.swing.JComboBox();
jComboBox6 = new javax.swing.JComboBox();
jPanel14 = new javax.swing.JPanel();
jLabel198 = new javax.swing.JLabel();
jPanel27 = new javax.swing.JPanel();
jLabel237 = new javax.swing.JLabel();
jLabel238 = new javax.swing.JLabel();
jComboBox7 = new javax.swing.JComboBox();
jComboBox10 = new javax.swing.JComboBox();
jLabel239 = new javax.swing.JLabel();
jLabel240 = new javax.swing.JLabel();
jComboBox8 = new javax.swing.JComboBox();
jComboBox11 = new javax.swing.JComboBox();
jLabel241 = new javax.swing.JLabel();
jLabel242 = new javax.swing.JLabel();
jComboBox9 = new javax.swing.JComboBox();
jComboBox12 = new javax.swing.JComboBox();
jPanel28 = new javax.swing.JPanel();
jLabel243 = new javax.swing.JLabel();
jPanel53 = new javax.swing.JPanel();
jLabel319 = new javax.swing.JLabel();
jLabel320 = new javax.swing.JLabel();
jComboBox13 = new javax.swing.JComboBox();
jComboBox14 = new javax.swing.JComboBox();
jLabel321 = new javax.swing.JLabel();
jLabel322 = new javax.swing.JLabel();
jComboBox15 = new javax.swing.JComboBox();
jComboBox16 = new javax.swing.JComboBox();
jLabel323 = new javax.swing.JLabel();
jLabel324 = new javax.swing.JLabel();
jComboBox17 = new javax.swing.JComboBox();
jComboBox18 = new javax.swing.JComboBox();
jPanel54 = new javax.swing.JPanel();
jLabel325 = new javax.swing.JLabel();
jPanel72 = new javax.swing.JPanel();
jLabel376 = new javax.swing.JLabel();
jLabel377 = new javax.swing.JLabel();
jComboBox19 = new javax.swing.JComboBox();
jComboBox20 = new javax.swing.JComboBox();
jLabel378 = new javax.swing.JLabel();
jLabel379 = new javax.swing.JLabel();
jComboBox21 = new javax.swing.JComboBox();
jComboBox22 = new javax.swing.JComboBox();
jLabel380 = new javax.swing.JLabel();
jLabel381 = new javax.swing.JLabel();
jComboBox23 = new javax.swing.JComboBox();
jComboBox24 = new javax.swing.JComboBox();
jPanel73 = new javax.swing.JPanel();
jLabel382 = new javax.swing.JLabel();
jPanel74 = new javax.swing.JPanel();
jLabel383 = new javax.swing.JLabel();
jLabel384 = new javax.swing.JLabel();
jComboBox25 = new javax.swing.JComboBox();
jComboBox26 = new javax.swing.JComboBox();
jLabel385 = new javax.swing.JLabel();
jLabel386 = new javax.swing.JLabel();
jComboBox27 = new javax.swing.JComboBox();
jComboBox28 = new javax.swing.JComboBox();
jLabel387 = new javax.swing.JLabel();
jLabel388 = new javax.swing.JLabel();
jComboBox29 = new javax.swing.JComboBox();
jComboBox30 = new javax.swing.JComboBox();
jPanel75 = new javax.swing.JPanel();
jLabel389 = new javax.swing.JLabel();
jPanel76 = new javax.swing.JPanel();
jLabel390 = new javax.swing.JLabel();
jLabel391 = new javax.swing.JLabel();
jComboBox31 = new javax.swing.JComboBox();
jComboBox32 = new javax.swing.JComboBox();
jLabel392 = new javax.swing.JLabel();
jLabel393 = new javax.swing.JLabel();
jComboBox33 = new javax.swing.JComboBox();
jComboBox34 = new javax.swing.JComboBox();
jLabel394 = new javax.swing.JLabel();
jLabel395 = new javax.swing.JLabel();
jComboBox35 = new javax.swing.JComboBox();
jComboBox36 = new javax.swing.JComboBox();
jPanel77 = new javax.swing.JPanel();
jLabel396 = new javax.swing.JLabel();
jPanel78 = new javax.swing.JPanel();
jLabel397 = new javax.swing.JLabel();
jLabel398 = new javax.swing.JLabel();
jComboBox37 = new javax.swing.JComboBox();
jComboBox38 = new javax.swing.JComboBox();
jLabel399 = new javax.swing.JLabel();
jLabel400 = new javax.swing.JLabel();
jComboBox39 = new javax.swing.JComboBox();
jComboBox40 = new javax.swing.JComboBox();
jLabel401 = new javax.swing.JLabel();
jLabel402 = new javax.swing.JLabel();
jComboBox41 = new javax.swing.JComboBox();
jComboBox42 = new javax.swing.JComboBox();
jPanel79 = new javax.swing.JPanel();
jLabel403 = new javax.swing.JLabel();
jPanel80 = new javax.swing.JPanel();
jLabel404 = new javax.swing.JLabel();
jLabel405 = new javax.swing.JLabel();
jComboBox43 = new javax.swing.JComboBox();
jComboBox44 = new javax.swing.JComboBox();
jLabel406 = new javax.swing.JLabel();
jLabel407 = new javax.swing.JLabel();
jComboBox45 = new javax.swing.JComboBox();
jComboBox46 = new javax.swing.JComboBox();
jLabel408 = new javax.swing.JLabel();
jLabel409 = new javax.swing.JLabel();
jComboBox47 = new javax.swing.JComboBox();
jComboBox48 = new javax.swing.JComboBox();
jPanel81 = new javax.swing.JPanel();
jLabel410 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jPanel10 = new javax.swing.JPanel();
jPanel45 = new javax.swing.JPanel();
jLabel294 = new javax.swing.JLabel();
jLabel295 = new javax.swing.JLabel();
jComboBox272 = new javax.swing.JComboBox();
jComboBox273 = new javax.swing.JComboBox();
jLabel296 = new javax.swing.JLabel();
jLabel297 = new javax.swing.JLabel();
jComboBox274 = new javax.swing.JComboBox();
jComboBox275 = new javax.swing.JComboBox();
jLabel298 = new javax.swing.JLabel();
jLabel299 = new javax.swing.JLabel();
jComboBox276 = new javax.swing.JComboBox();
jComboBox277 = new javax.swing.JComboBox();
jPanel46 = new javax.swing.JPanel();
jLabel300 = new javax.swing.JLabel();
jPanel47 = new javax.swing.JPanel();
jLabel301 = new javax.swing.JLabel();
jComboBox278 = new javax.swing.JComboBox();
jLabel302 = new javax.swing.JLabel();
jComboBox279 = new javax.swing.JComboBox();
jLabel303 = new javax.swing.JLabel();
jComboBox280 = new javax.swing.JComboBox();
jPanel48 = new javax.swing.JPanel();
jLabel304 = new javax.swing.JLabel();
jPanel49 = new javax.swing.JPanel();
jLabel305 = new javax.swing.JLabel();
jLabel306 = new javax.swing.JLabel();
jComboBox281 = new javax.swing.JComboBox();
jComboBox282 = new javax.swing.JComboBox();
jLabel307 = new javax.swing.JLabel();
jLabel308 = new javax.swing.JLabel();
jComboBox283 = new javax.swing.JComboBox();
jComboBox284 = new javax.swing.JComboBox();
jLabel309 = new javax.swing.JLabel();
jLabel310 = new javax.swing.JLabel();
jComboBox285 = new javax.swing.JComboBox();
jComboBox286 = new javax.swing.JComboBox();
jPanel50 = new javax.swing.JPanel();
jLabel311 = new javax.swing.JLabel();
jPanel51 = new javax.swing.JPanel();
jLabel312 = new javax.swing.JLabel();
jLabel313 = new javax.swing.JLabel();
jComboBox287 = new javax.swing.JComboBox();
jComboBox288 = new javax.swing.JComboBox();
jLabel314 = new javax.swing.JLabel();
jLabel315 = new javax.swing.JLabel();
jComboBox289 = new javax.swing.JComboBox();
jComboBox290 = new javax.swing.JComboBox();
jLabel316 = new javax.swing.JLabel();
jLabel317 = new javax.swing.JLabel();
jComboBox291 = new javax.swing.JComboBox();
jComboBox292 = new javax.swing.JComboBox();
jPanel52 = new javax.swing.JPanel();
jLabel318 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jPanel12 = new javax.swing.JPanel();
jPanel37 = new javax.swing.JPanel();
jLabel272 = new javax.swing.JLabel();
jLabel273 = new javax.swing.JLabel();
jComboBox254 = new javax.swing.JComboBox();
jComboBox255 = new javax.swing.JComboBox();
jLabel274 = new javax.swing.JLabel();
jLabel275 = new javax.swing.JLabel();
jComboBox256 = new javax.swing.JComboBox();
jComboBox257 = new javax.swing.JComboBox();
jLabel276 = new javax.swing.JLabel();
jLabel277 = new javax.swing.JLabel();
jComboBox258 = new javax.swing.JComboBox();
jComboBox259 = new javax.swing.JComboBox();
jPanel38 = new javax.swing.JPanel();
jLabel278 = new javax.swing.JLabel();
jPanel39 = new javax.swing.JPanel();
jLabel217 = new javax.swing.JLabel();
jComboBox207 = new javax.swing.JComboBox();
jLabel219 = new javax.swing.JLabel();
jComboBox209 = new javax.swing.JComboBox();
jLabel221 = new javax.swing.JLabel();
jComboBox211 = new javax.swing.JComboBox();
jPanel40 = new javax.swing.JPanel();
jLabel279 = new javax.swing.JLabel();
jPanel41 = new javax.swing.JPanel();
jLabel280 = new javax.swing.JLabel();
jLabel281 = new javax.swing.JLabel();
jComboBox260 = new javax.swing.JComboBox();
jComboBox261 = new javax.swing.JComboBox();
jLabel282 = new javax.swing.JLabel();
jLabel283 = new javax.swing.JLabel();
jComboBox262 = new javax.swing.JComboBox();
jComboBox263 = new javax.swing.JComboBox();
jLabel284 = new javax.swing.JLabel();
jLabel285 = new javax.swing.JLabel();
jComboBox264 = new javax.swing.JComboBox();
jComboBox265 = new javax.swing.JComboBox();
jPanel42 = new javax.swing.JPanel();
jLabel286 = new javax.swing.JLabel();
jPanel43 = new javax.swing.JPanel();
jLabel287 = new javax.swing.JLabel();
jLabel288 = new javax.swing.JLabel();
jComboBox266 = new javax.swing.JComboBox();
jComboBox267 = new javax.swing.JComboBox();
jLabel289 = new javax.swing.JLabel();
jLabel290 = new javax.swing.JLabel();
jComboBox268 = new javax.swing.JComboBox();
jComboBox269 = new javax.swing.JComboBox();
jLabel291 = new javax.swing.JLabel();
jLabel292 = new javax.swing.JLabel();
jComboBox270 = new javax.swing.JComboBox();
jComboBox271 = new javax.swing.JComboBox();
jPanel44 = new javax.swing.JPanel();
jLabel293 = new javax.swing.JLabel();
jPanel18 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
jPanel17 = new javax.swing.JPanel();
jPanel55 = new javax.swing.JPanel();
jLabel326 = new javax.swing.JLabel();
jLabel327 = new javax.swing.JLabel();
jComboBox299 = new javax.swing.JComboBox();
jComboBox300 = new javax.swing.JComboBox();
jLabel328 = new javax.swing.JLabel();
jLabel329 = new javax.swing.JLabel();
jComboBox301 = new javax.swing.JComboBox();
jComboBox302 = new javax.swing.JComboBox();
jLabel330 = new javax.swing.JLabel();
jLabel331 = new javax.swing.JLabel();
jComboBox303 = new javax.swing.JComboBox();
jComboBox304 = new javax.swing.JComboBox();
jPanel56 = new javax.swing.JPanel();
jLabel332 = new javax.swing.JLabel();
jPanel57 = new javax.swing.JPanel();
jLabel333 = new javax.swing.JLabel();
jComboBox305 = new javax.swing.JComboBox();
jLabel334 = new javax.swing.JLabel();
jComboBox306 = new javax.swing.JComboBox();
jLabel335 = new javax.swing.JLabel();
jComboBox307 = new javax.swing.JComboBox();
jPanel58 = new javax.swing.JPanel();
jLabel336 = new javax.swing.JLabel();
jPanel59 = new javax.swing.JPanel();
jLabel337 = new javax.swing.JLabel();
jLabel338 = new javax.swing.JLabel();
jComboBox308 = new javax.swing.JComboBox();
jComboBox309 = new javax.swing.JComboBox();
jLabel339 = new javax.swing.JLabel();
jLabel340 = new javax.swing.JLabel();
jComboBox310 = new javax.swing.JComboBox();
jComboBox311 = new javax.swing.JComboBox();
jLabel341 = new javax.swing.JLabel();
jLabel342 = new javax.swing.JLabel();
jComboBox312 = new javax.swing.JComboBox();
jComboBox313 = new javax.swing.JComboBox();
jPanel60 = new javax.swing.JPanel();
jLabel343 = new javax.swing.JLabel();
jPanel61 = new javax.swing.JPanel();
jLabel344 = new javax.swing.JLabel();
jLabel345 = new javax.swing.JLabel();
jComboBox314 = new javax.swing.JComboBox();
jComboBox315 = new javax.swing.JComboBox();
jLabel346 = new javax.swing.JLabel();
jLabel347 = new javax.swing.JLabel();
jComboBox316 = new javax.swing.JComboBox();
jComboBox317 = new javax.swing.JComboBox();
jLabel348 = new javax.swing.JLabel();
jLabel349 = new javax.swing.JLabel();
jComboBox318 = new javax.swing.JComboBox();
jComboBox319 = new javax.swing.JComboBox();
jPanel62 = new javax.swing.JPanel();
jLabel350 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jPanel63 = new javax.swing.JPanel();
jPanel64 = new javax.swing.JPanel();
jLabel351 = new javax.swing.JLabel();
jLabel352 = new javax.swing.JLabel();
jComboBox320 = new javax.swing.JComboBox();
jComboBox321 = new javax.swing.JComboBox();
jLabel353 = new javax.swing.JLabel();
jLabel354 = new javax.swing.JLabel();
jComboBox322 = new javax.swing.JComboBox();
jComboBox323 = new javax.swing.JComboBox();
jLabel355 = new javax.swing.JLabel();
jLabel356 = new javax.swing.JLabel();
jComboBox324 = new javax.swing.JComboBox();
jComboBox325 = new javax.swing.JComboBox();
jPanel65 = new javax.swing.JPanel();
jLabel357 = new javax.swing.JLabel();
jPanel66 = new javax.swing.JPanel();
jLabel358 = new javax.swing.JLabel();
jComboBox326 = new javax.swing.JComboBox();
jLabel359 = new javax.swing.JLabel();
jComboBox327 = new javax.swing.JComboBox();
jLabel360 = new javax.swing.JLabel();
jComboBox328 = new javax.swing.JComboBox();
jPanel67 = new javax.swing.JPanel();
jLabel361 = new javax.swing.JLabel();
jPanel68 = new javax.swing.JPanel();
jLabel362 = new javax.swing.JLabel();
jLabel363 = new javax.swing.JLabel();
jComboBox329 = new javax.swing.JComboBox();
jComboBox330 = new javax.swing.JComboBox();
jLabel364 = new javax.swing.JLabel();
jLabel365 = new javax.swing.JLabel();
jComboBox331 = new javax.swing.JComboBox();
jComboBox332 = new javax.swing.JComboBox();
jLabel366 = new javax.swing.JLabel();
jLabel367 = new javax.swing.JLabel();
jComboBox333 = new javax.swing.JComboBox();
jComboBox334 = new javax.swing.JComboBox();
jPanel69 = new javax.swing.JPanel();
jLabel368 = new javax.swing.JLabel();
jPanel70 = new javax.swing.JPanel();
jLabel369 = new javax.swing.JLabel();
jLabel370 = new javax.swing.JLabel();
jComboBox335 = new javax.swing.JComboBox();
jComboBox336 = new javax.swing.JComboBox();
jLabel371 = new javax.swing.JLabel();
jLabel372 = new javax.swing.JLabel();
jComboBox337 = new javax.swing.JComboBox();
jComboBox338 = new javax.swing.JComboBox();
jLabel373 = new javax.swing.JLabel();
jLabel374 = new javax.swing.JLabel();
jComboBox339 = new javax.swing.JComboBox();
jComboBox340 = new javax.swing.JComboBox();
jPanel71 = new javax.swing.JPanel();
jLabel375 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel196 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel199 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel200 = new javax.swing.JLabel();
jLabel201 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
logoutButton = new javax.swing.JButton();
editAccountButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Courses");
setBackground(new java.awt.Color(255, 255, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jPanel7.setBackground(new java.awt.Color(255, 255, 255));
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel13.setBackground(new java.awt.Color(225, 225, 225));
jPanel13.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel1.setText("Course 1");
jLabel1.setToolTipText("");
jLabel2.setText("Course 2");
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jLabel3.setText("Course 3");
jLabel3.setToolTipText("");
jLabel4.setText("Course 4");
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jLabel5.setText("Course 5");
jLabel9.setText("Course 6");
jPanel14.setBackground(new java.awt.Color(204, 204, 204));
jLabel198.setText(" Fall Semester 1");
jLabel198.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel198, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel27.setBackground(new java.awt.Color(225, 225, 225));
jPanel27.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel237.setText("Course 1");
jLabel237.setToolTipText("");
jLabel238.setText("Course 2");
jComboBox7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox7ActionPerformed(evt);
}
});
jLabel239.setText("Course 3");
jLabel239.setToolTipText("");
jLabel240.setText("Course 4");
jComboBox8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox8ActionPerformed(evt);
}
});
jLabel241.setText("Course 5");
jLabel242.setText("Course 6");
jPanel28.setBackground(new java.awt.Color(204, 204, 204));
jLabel243.setText(" Fall Semester 1");
jLabel243.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28);
jPanel28.setLayout(jPanel28Layout);
jPanel28Layout.setHorizontalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel28Layout.createSequentialGroup()
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel28Layout.setVerticalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel243, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27);
jPanel27.setLayout(jPanel27Layout);
jPanel27Layout.setHorizontalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel237)
.addComponent(jLabel238))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel239)
.addComponent(jLabel240))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel241)
.addComponent(jLabel242))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel27Layout.setVerticalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel237)
.addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel239)
.addComponent(jComboBox8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel241, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel238)
.addComponent(jComboBox10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel240)
.addComponent(jComboBox11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel242, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel53.setBackground(new java.awt.Color(225, 225, 225));
jPanel53.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel319.setText("Course 1");
jLabel319.setToolTipText("");
jLabel320.setText("Course 2");
jComboBox13.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox13ActionPerformed(evt);
}
});
jComboBox14.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel321.setText("Course 3");
jLabel321.setToolTipText("");
jLabel322.setText("Course 4");
jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox15ActionPerformed(evt);
}
});
jComboBox16.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel323.setText("Course 5");
jLabel324.setText("Course 6");
jComboBox17.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox18.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel54.setBackground(new java.awt.Color(204, 204, 204));
jPanel54.setForeground(new java.awt.Color(255, 255, 255));
jLabel325.setText(" Fall Semester 1");
jLabel325.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel54Layout = new javax.swing.GroupLayout(jPanel54);
jPanel54.setLayout(jPanel54Layout);
jPanel54Layout.setHorizontalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel54Layout.createSequentialGroup()
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel54Layout.setVerticalGroup(
jPanel54Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel325, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel53Layout = new javax.swing.GroupLayout(jPanel53);
jPanel53.setLayout(jPanel53Layout);
jPanel53Layout.setHorizontalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel53Layout.createSequentialGroup()
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel319)
.addComponent(jLabel320))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel321)
.addComponent(jLabel322))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel323)
.addComponent(jLabel324))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(12, Short.MAX_VALUE))
);
jPanel53Layout.setVerticalGroup(
jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel53Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel54, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel319)
.addComponent(jComboBox13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel321)
.addComponent(jComboBox15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel323, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel53Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel320)
.addComponent(jComboBox14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel322)
.addComponent(jComboBox16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel324, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel72.setBackground(new java.awt.Color(225, 225, 225));
jPanel72.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel376.setText("Course 1");
jLabel376.setToolTipText("");
jLabel377.setText("Course 2");
jComboBox19.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox19ActionPerformed(evt);
}
});
jComboBox20.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel378.setText("Course 3");
jLabel378.setToolTipText("");
jLabel379.setText("Course 4");
jComboBox21.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox21.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox21ActionPerformed(evt);
}
});
jComboBox22.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel380.setText("Course 5");
jLabel381.setText("Course 6");
jComboBox23.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox24.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel73.setBackground(new java.awt.Color(204, 204, 204));
jLabel382.setText(" Fall Semester 1");
jLabel382.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel73Layout = new javax.swing.GroupLayout(jPanel73);
jPanel73.setLayout(jPanel73Layout);
jPanel73Layout.setHorizontalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel73Layout.createSequentialGroup()
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel73Layout.setVerticalGroup(
jPanel73Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel382, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel72Layout = new javax.swing.GroupLayout(jPanel72);
jPanel72.setLayout(jPanel72Layout);
jPanel72Layout.setHorizontalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel72Layout.createSequentialGroup()
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel376)
.addComponent(jLabel377))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel378)
.addComponent(jLabel379))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel380)
.addComponent(jLabel381))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel72Layout.setVerticalGroup(
jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel72Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel73, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel376)
.addComponent(jComboBox19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel378)
.addComponent(jComboBox21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel380, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel72Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel377)
.addComponent(jComboBox20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel379)
.addComponent(jComboBox22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel381, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel74.setBackground(new java.awt.Color(225, 225, 225));
jPanel74.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel383.setText("Course 1");
jLabel383.setToolTipText("");
jLabel384.setText("Course 2");
jComboBox25.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox25.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox25ActionPerformed(evt);
}
});
jComboBox26.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel385.setText("Course 3");
jLabel385.setToolTipText("");
jLabel386.setText("Course 4");
jComboBox27.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox27.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox27ActionPerformed(evt);
}
});
jComboBox28.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel387.setText("Course 5");
jLabel388.setText("Course 6");
jComboBox29.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox30.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel75.setBackground(new java.awt.Color(204, 204, 204));
jPanel75.setForeground(new java.awt.Color(255, 255, 255));
jLabel389.setText(" Fall Semester 1");
jLabel389.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel75Layout = new javax.swing.GroupLayout(jPanel75);
jPanel75.setLayout(jPanel75Layout);
jPanel75Layout.setHorizontalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel75Layout.createSequentialGroup()
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel75Layout.setVerticalGroup(
jPanel75Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel389, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel74Layout = new javax.swing.GroupLayout(jPanel74);
jPanel74.setLayout(jPanel74Layout);
jPanel74Layout.setHorizontalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel74Layout.createSequentialGroup()
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel383)
.addComponent(jLabel384))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel385)
.addComponent(jLabel386))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel387)
.addComponent(jLabel388))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel74Layout.setVerticalGroup(
jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel74Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel75, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel383)
.addComponent(jComboBox25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel385)
.addComponent(jComboBox27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel387, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox29, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel74Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel384)
.addComponent(jComboBox26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel386)
.addComponent(jComboBox28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel388, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel76.setBackground(new java.awt.Color(225, 225, 225));
jPanel76.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel390.setText("Course 1");
jLabel390.setToolTipText("");
jLabel391.setText("Course 2");
jComboBox31.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox31.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox31ActionPerformed(evt);
}
});
jComboBox32.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel392.setText("Course 3");
jLabel392.setToolTipText("");
jLabel393.setText("Course 4");
jComboBox33.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox33.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox33ActionPerformed(evt);
}
});
jComboBox34.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel394.setText("Course 5");
jLabel395.setText("Course 6");
jComboBox35.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox36.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel77.setBackground(new java.awt.Color(204, 204, 204));
jPanel77.setForeground(new java.awt.Color(255, 255, 255));
jLabel396.setText(" Fall Semester 1");
jLabel396.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel77Layout = new javax.swing.GroupLayout(jPanel77);
jPanel77.setLayout(jPanel77Layout);
jPanel77Layout.setHorizontalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel77Layout.createSequentialGroup()
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel77Layout.setVerticalGroup(
jPanel77Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel396, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel76Layout = new javax.swing.GroupLayout(jPanel76);
jPanel76.setLayout(jPanel76Layout);
jPanel76Layout.setHorizontalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel76Layout.createSequentialGroup()
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel390)
.addComponent(jLabel391))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel392)
.addComponent(jLabel393))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel394)
.addComponent(jLabel395))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel76Layout.setVerticalGroup(
jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel76Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel77, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel390)
.addComponent(jComboBox31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel392)
.addComponent(jComboBox33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel394, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox35, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel76Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel391)
.addComponent(jComboBox32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel393)
.addComponent(jComboBox34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel395, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel78.setBackground(new java.awt.Color(225, 225, 225));
jPanel78.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel397.setText("Course 1");
jLabel397.setToolTipText("");
jLabel398.setText("Course 2");
jComboBox37.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox37.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox37ActionPerformed(evt);
}
});
jComboBox38.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel399.setText("Course 3");
jLabel399.setToolTipText("");
jLabel400.setText("Course 4");
jComboBox39.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox39.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox39ActionPerformed(evt);
}
});
jComboBox40.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel401.setText("Course 5");
jLabel402.setText("Course 6");
jComboBox41.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox42.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel79.setBackground(new java.awt.Color(204, 204, 204));
jPanel79.setForeground(new java.awt.Color(255, 255, 255));
jLabel403.setText(" Fall Semester 1");
jLabel403.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel79Layout = new javax.swing.GroupLayout(jPanel79);
jPanel79.setLayout(jPanel79Layout);
jPanel79Layout.setHorizontalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel79Layout.createSequentialGroup()
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel79Layout.setVerticalGroup(
jPanel79Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel403, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel78Layout = new javax.swing.GroupLayout(jPanel78);
jPanel78.setLayout(jPanel78Layout);
jPanel78Layout.setHorizontalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel78Layout.createSequentialGroup()
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel397)
.addComponent(jLabel398))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel399)
.addComponent(jLabel400))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel401)
.addComponent(jLabel402))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel78Layout.setVerticalGroup(
jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel78Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel79, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel397)
.addComponent(jComboBox37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel399)
.addComponent(jComboBox39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel401, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel78Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel398)
.addComponent(jComboBox38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel400)
.addComponent(jComboBox40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel402, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel80.setBackground(new java.awt.Color(225, 225, 225));
jPanel80.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel404.setText("Course 1");
jLabel404.setToolTipText("");
jLabel405.setText("Course 2");
jComboBox43.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox43.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox43ActionPerformed(evt);
}
});
jComboBox44.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel406.setText("Course 3");
jLabel406.setToolTipText("");
jLabel407.setText("Course 4");
jComboBox45.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox45.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox45ActionPerformed(evt);
}
});
jComboBox46.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel408.setText("Course 5");
jLabel409.setText("Course 6");
jComboBox47.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox48.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel81.setBackground(new java.awt.Color(204, 204, 204));
jPanel81.setForeground(new java.awt.Color(255, 255, 255));
jLabel410.setText(" Fall Semester 1");
jLabel410.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel81Layout = new javax.swing.GroupLayout(jPanel81);
jPanel81.setLayout(jPanel81Layout);
jPanel81Layout.setHorizontalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel81Layout.createSequentialGroup()
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel81Layout.setVerticalGroup(
jPanel81Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel410, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel80Layout = new javax.swing.GroupLayout(jPanel80);
jPanel80.setLayout(jPanel80Layout);
jPanel80Layout.setHorizontalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel80Layout.createSequentialGroup()
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel404)
.addComponent(jLabel405))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel406)
.addComponent(jLabel407))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel408)
.addComponent(jLabel409))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel80Layout.setVerticalGroup(
jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel80Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel81, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel404)
.addComponent(jComboBox43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel406)
.addComponent(jComboBox45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel408, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel80Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel405)
.addComponent(jComboBox44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel407)
.addComponent(jComboBox46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel409, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel53, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel72, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel74, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel76, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel78, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel80, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE))
);
jScrollPane1.setViewportView(jPanel6);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Computer Science", jPanel1);
jPanel10.setBackground(new java.awt.Color(255, 255, 255));
jPanel45.setBackground(new java.awt.Color(225, 225, 225));
jPanel45.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel294.setText("Course 1");
jLabel294.setToolTipText("");
jLabel295.setText("Course 2");
jComboBox272.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox272.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox272ActionPerformed(evt);
}
});
jComboBox273.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel296.setText("Course 3");
jLabel296.setToolTipText("");
jLabel297.setText("Course 4");
jComboBox274.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox274.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox274ActionPerformed(evt);
}
});
jComboBox275.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel298.setText("Course 5");
jLabel299.setText("Course 6");
jComboBox276.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox277.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel46.setBackground(new java.awt.Color(204, 204, 204));
jLabel300.setText(" Spring Semester 2");
jLabel300.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel46Layout = new javax.swing.GroupLayout(jPanel46);
jPanel46.setLayout(jPanel46Layout);
jPanel46Layout.setHorizontalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel46Layout.createSequentialGroup()
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel46Layout.setVerticalGroup(
jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel300, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel45Layout = new javax.swing.GroupLayout(jPanel45);
jPanel45.setLayout(jPanel45Layout);
jPanel45Layout.setHorizontalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel45Layout.createSequentialGroup()
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel294)
.addComponent(jLabel295))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel296)
.addComponent(jLabel297))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel298)
.addComponent(jLabel299))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel45Layout.setVerticalGroup(
jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel45Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel294)
.addComponent(jComboBox272, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel296)
.addComponent(jComboBox274, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel298, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox276, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel295)
.addComponent(jComboBox273, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel297)
.addComponent(jComboBox275, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel299, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox277, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel47.setBackground(new java.awt.Color(225, 225, 225));
jPanel47.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel301.setText("Course 1");
jLabel301.setToolTipText("");
jComboBox278.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox278.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox278ActionPerformed(evt);
}
});
jLabel302.setText("Course 2");
jLabel302.setToolTipText("");
jComboBox279.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox279.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox279ActionPerformed(evt);
}
});
jLabel303.setText("Course 3");
jComboBox280.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel48.setBackground(new java.awt.Color(204, 204, 204));
jLabel304.setText(" Summer Semester 2.5");
jLabel304.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel48Layout = new javax.swing.GroupLayout(jPanel48);
jPanel48.setLayout(jPanel48Layout);
jPanel48Layout.setHorizontalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel48Layout.createSequentialGroup()
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel48Layout.setVerticalGroup(
jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel304, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel47Layout = new javax.swing.GroupLayout(jPanel47);
jPanel47.setLayout(jPanel47Layout);
jPanel47Layout.setHorizontalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel47Layout.createSequentialGroup()
.addComponent(jLabel301)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel302)
.addGap(18, 18, 18)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel303)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel47Layout.setVerticalGroup(
jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel47Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel301)
.addComponent(jComboBox278, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel302)
.addComponent(jComboBox279, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel303, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox280, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel49.setBackground(new java.awt.Color(225, 225, 225));
jPanel49.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel305.setText("Course 1");
jLabel305.setToolTipText("");
jLabel306.setText("Course 2");
jComboBox281.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox281.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox281ActionPerformed(evt);
}
});
jComboBox282.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel307.setText("Course 3");
jLabel307.setToolTipText("");
jLabel308.setText("Course 4");
jComboBox283.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox283.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox283ActionPerformed(evt);
}
});
jComboBox284.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel309.setText("Course 5");
jLabel310.setText("Course 6");
jComboBox285.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox286.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel50.setBackground(new java.awt.Color(204, 204, 204));
jPanel50.setForeground(new java.awt.Color(255, 255, 255));
jLabel311.setText(" Fall Semester 1");
jLabel311.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel50Layout = new javax.swing.GroupLayout(jPanel50);
jPanel50.setLayout(jPanel50Layout);
jPanel50Layout.setHorizontalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel50Layout.createSequentialGroup()
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel50Layout.setVerticalGroup(
jPanel50Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel311, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel49Layout = new javax.swing.GroupLayout(jPanel49);
jPanel49.setLayout(jPanel49Layout);
jPanel49Layout.setHorizontalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel49Layout.createSequentialGroup()
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel305)
.addComponent(jLabel306))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel307)
.addComponent(jLabel308))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel309)
.addComponent(jLabel310))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel49Layout.setVerticalGroup(
jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel49Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel50, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel305)
.addComponent(jComboBox281, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel307)
.addComponent(jComboBox283, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel309, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox285, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel306)
.addComponent(jComboBox282, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel308)
.addComponent(jComboBox284, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel310, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox286, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel51.setBackground(new java.awt.Color(225, 225, 225));
jPanel51.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel312.setText("Course 1");
jLabel312.setToolTipText("");
jLabel313.setText("Course 2");
jComboBox287.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox287.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox287ActionPerformed(evt);
}
});
jComboBox288.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel314.setText("Course 3");
jLabel314.setToolTipText("");
jLabel315.setText("Course 4");
jComboBox289.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox289.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox289ActionPerformed(evt);
}
});
jComboBox290.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel316.setText("Course 5");
jLabel317.setText("Course 6");
jComboBox291.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox292.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel52.setBackground(new java.awt.Color(204, 204, 204));
jPanel52.setForeground(new java.awt.Color(255, 255, 255));
jLabel318.setText(" Fall Semester 3");
jLabel318.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel52Layout = new javax.swing.GroupLayout(jPanel52);
jPanel52.setLayout(jPanel52Layout);
jPanel52Layout.setHorizontalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel52Layout.createSequentialGroup()
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel52Layout.setVerticalGroup(
jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel318, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel51Layout = new javax.swing.GroupLayout(jPanel51);
jPanel51.setLayout(jPanel51Layout);
jPanel51Layout.setHorizontalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel51Layout.createSequentialGroup()
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel312)
.addComponent(jLabel313))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel314)
.addComponent(jLabel315))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel316)
.addComponent(jLabel317))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel51Layout.setVerticalGroup(
jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel51Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel52, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel312)
.addComponent(jComboBox287, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel314)
.addComponent(jComboBox289, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel316, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox291, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel313)
.addComponent(jComboBox288, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel315)
.addComponent(jComboBox290, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel317, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox292, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(67, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel49, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel51, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane3.setViewportView(jPanel10);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Science ", jPanel4);
jPanel12.setBackground(new java.awt.Color(255, 255, 255));
jPanel37.setBackground(new java.awt.Color(225, 225, 225));
jPanel37.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel272.setText("Course 1");
jLabel272.setToolTipText("");
jLabel273.setText("Course 2");
jComboBox254.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox254.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox254ActionPerformed(evt);
}
});
jComboBox255.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel274.setText("Course 3");
jLabel274.setToolTipText("");
jLabel275.setText("Course 4");
jComboBox256.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox256.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox256ActionPerformed(evt);
}
});
jComboBox257.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel276.setText("Course 5");
jLabel277.setText("Course 6");
jComboBox258.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox259.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel38.setBackground(new java.awt.Color(204, 204, 204));
jLabel278.setText(" Spring Semester 2");
jLabel278.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel38Layout = new javax.swing.GroupLayout(jPanel38);
jPanel38.setLayout(jPanel38Layout);
jPanel38Layout.setHorizontalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel38Layout.createSequentialGroup()
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel38Layout.setVerticalGroup(
jPanel38Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel278, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel37Layout = new javax.swing.GroupLayout(jPanel37);
jPanel37.setLayout(jPanel37Layout);
jPanel37Layout.setHorizontalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel37Layout.createSequentialGroup()
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel272)
.addComponent(jLabel273))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel274)
.addComponent(jLabel275))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel276)
.addComponent(jLabel277))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel37Layout.setVerticalGroup(
jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel37Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel38, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel272)
.addComponent(jComboBox254, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel274)
.addComponent(jComboBox256, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel276, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox258, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel37Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel273)
.addComponent(jComboBox255, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel275)
.addComponent(jComboBox257, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel277, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox259, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel39.setBackground(new java.awt.Color(225, 225, 225));
jPanel39.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel217.setText("Course 1");
jLabel217.setToolTipText("");
jComboBox207.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox207.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox207ActionPerformed(evt);
}
});
jLabel219.setText("Course 2");
jLabel219.setToolTipText("");
jComboBox209.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox209.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox209ActionPerformed(evt);
}
});
jLabel221.setText("Course 3");
jComboBox211.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel40.setBackground(new java.awt.Color(204, 204, 204));
jLabel279.setText(" Summer Semester 2.5");
jLabel279.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel40Layout = new javax.swing.GroupLayout(jPanel40);
jPanel40.setLayout(jPanel40Layout);
jPanel40Layout.setHorizontalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel40Layout.createSequentialGroup()
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel40Layout.setVerticalGroup(
jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel279, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel39Layout = new javax.swing.GroupLayout(jPanel39);
jPanel39.setLayout(jPanel39Layout);
jPanel39Layout.setHorizontalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel39Layout.createSequentialGroup()
.addComponent(jLabel217)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel219)
.addGap(18, 18, 18)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel221)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel39Layout.setVerticalGroup(
jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel39Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel40, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel39Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel217)
.addComponent(jComboBox207, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel219)
.addComponent(jComboBox209, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel221, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox211, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel41.setBackground(new java.awt.Color(225, 225, 225));
jPanel41.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel280.setText("Course 1");
jLabel280.setToolTipText("");
jLabel281.setText("Course 2");
jComboBox260.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox260.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox260ActionPerformed(evt);
}
});
jComboBox261.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel282.setText("Course 3");
jLabel282.setToolTipText("");
jLabel283.setText("Course 4");
jComboBox262.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox262.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox262ActionPerformed(evt);
}
});
jComboBox263.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel284.setText("Course 5");
jLabel285.setText("Course 6");
jComboBox264.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox265.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel42.setBackground(new java.awt.Color(204, 204, 204));
jPanel42.setForeground(new java.awt.Color(255, 255, 255));
jLabel286.setText(" Fall Semester 1");
jLabel286.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel42Layout = new javax.swing.GroupLayout(jPanel42);
jPanel42.setLayout(jPanel42Layout);
jPanel42Layout.setHorizontalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel42Layout.createSequentialGroup()
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel42Layout.setVerticalGroup(
jPanel42Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel286, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel41Layout = new javax.swing.GroupLayout(jPanel41);
jPanel41.setLayout(jPanel41Layout);
jPanel41Layout.setHorizontalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel41Layout.createSequentialGroup()
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel280)
.addComponent(jLabel281))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel282)
.addComponent(jLabel283))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel284)
.addComponent(jLabel285))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel41Layout.setVerticalGroup(
jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel41Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel42, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel280)
.addComponent(jComboBox260, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel282)
.addComponent(jComboBox262, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel284, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox264, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel41Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel281)
.addComponent(jComboBox261, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel283)
.addComponent(jComboBox263, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel285, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox265, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel43.setBackground(new java.awt.Color(225, 225, 225));
jPanel43.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel287.setText("Course 1");
jLabel287.setToolTipText("");
jLabel288.setText("Course 2");
jComboBox266.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox266.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox266ActionPerformed(evt);
}
});
jComboBox267.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel289.setText("Course 3");
jLabel289.setToolTipText("");
jLabel290.setText("Course 4");
jComboBox268.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox268.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox268ActionPerformed(evt);
}
});
jComboBox269.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel291.setText("Course 5");
jLabel292.setText("Course 6");
jComboBox270.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox271.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel44.setBackground(new java.awt.Color(204, 204, 204));
jPanel44.setForeground(new java.awt.Color(255, 255, 255));
jLabel293.setText(" Fall Semester 3");
jLabel293.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel44Layout = new javax.swing.GroupLayout(jPanel44);
jPanel44.setLayout(jPanel44Layout);
jPanel44Layout.setHorizontalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel44Layout.createSequentialGroup()
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel44Layout.setVerticalGroup(
jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel293, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel43Layout = new javax.swing.GroupLayout(jPanel43);
jPanel43.setLayout(jPanel43Layout);
jPanel43Layout.setHorizontalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel43Layout.createSequentialGroup()
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel287)
.addComponent(jLabel288))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel289)
.addComponent(jLabel290))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel291)
.addComponent(jLabel292))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel43Layout.setVerticalGroup(
jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel43Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel287)
.addComponent(jComboBox266, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel289)
.addComponent(jComboBox268, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel291, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox270, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel43Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel288)
.addComponent(jComboBox267, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel290)
.addComponent(jComboBox269, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel292, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox271, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel39, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel43, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(331, Short.MAX_VALUE))
);
jScrollPane4.setViewportView(jPanel12);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Core ", jPanel2);
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jPanel55.setBackground(new java.awt.Color(225, 225, 225));
jPanel55.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel326.setText("Course 1");
jLabel326.setToolTipText("");
jLabel327.setText("Course 2");
jComboBox299.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox299.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox299ActionPerformed(evt);
}
});
jComboBox300.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel328.setText("Course 3");
jLabel328.setToolTipText("");
jLabel329.setText("Course 4");
jComboBox301.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox301.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox301ActionPerformed(evt);
}
});
jComboBox302.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel330.setText("Course 5");
jLabel331.setText("Course 6");
jComboBox303.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox304.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel56.setBackground(new java.awt.Color(204, 204, 204));
jLabel332.setText(" Spring Semester 2");
jLabel332.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel56Layout = new javax.swing.GroupLayout(jPanel56);
jPanel56.setLayout(jPanel56Layout);
jPanel56Layout.setHorizontalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel56Layout.createSequentialGroup()
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel56Layout.setVerticalGroup(
jPanel56Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel332, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel55Layout = new javax.swing.GroupLayout(jPanel55);
jPanel55.setLayout(jPanel55Layout);
jPanel55Layout.setHorizontalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel55Layout.createSequentialGroup()
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel326)
.addComponent(jLabel327))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel328)
.addComponent(jLabel329))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel330)
.addComponent(jLabel331))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel55Layout.setVerticalGroup(
jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel55Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel56, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel326)
.addComponent(jComboBox299, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel328)
.addComponent(jComboBox301, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel330, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox303, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel55Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel327)
.addComponent(jComboBox300, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel329)
.addComponent(jComboBox302, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel331, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox304, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel57.setBackground(new java.awt.Color(225, 225, 225));
jPanel57.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel333.setText("Course 1");
jLabel333.setToolTipText("");
jComboBox305.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox305.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox305ActionPerformed(evt);
}
});
jLabel334.setText("Course 2");
jLabel334.setToolTipText("");
jComboBox306.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox306.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox306ActionPerformed(evt);
}
});
jLabel335.setText("Course 3");
jComboBox307.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel58.setBackground(new java.awt.Color(204, 204, 204));
jLabel336.setText(" Summer Semester 2.5");
jLabel336.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel58Layout = new javax.swing.GroupLayout(jPanel58);
jPanel58.setLayout(jPanel58Layout);
jPanel58Layout.setHorizontalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel58Layout.createSequentialGroup()
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel58Layout.setVerticalGroup(
jPanel58Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel336, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel57Layout = new javax.swing.GroupLayout(jPanel57);
jPanel57.setLayout(jPanel57Layout);
jPanel57Layout.setHorizontalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel57Layout.createSequentialGroup()
.addComponent(jLabel333)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel334)
.addGap(18, 18, 18)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel335)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel57Layout.setVerticalGroup(
jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel57Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel57Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel333)
.addComponent(jComboBox305, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel334)
.addComponent(jComboBox306, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel335, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox307, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel59.setBackground(new java.awt.Color(225, 225, 225));
jPanel59.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel337.setText("Course 1");
jLabel337.setToolTipText("");
jLabel338.setText("Course 2");
jComboBox308.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox308.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox308ActionPerformed(evt);
}
});
jComboBox309.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel339.setText("Course 3");
jLabel339.setToolTipText("");
jLabel340.setText("Course 4");
jComboBox310.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox310.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox310ActionPerformed(evt);
}
});
jComboBox311.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel341.setText("Course 5");
jLabel342.setText("Course 6");
jComboBox312.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox313.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel60.setBackground(new java.awt.Color(204, 204, 204));
jPanel60.setForeground(new java.awt.Color(255, 255, 255));
jLabel343.setText(" Fall Semester 1");
jLabel343.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel60Layout = new javax.swing.GroupLayout(jPanel60);
jPanel60.setLayout(jPanel60Layout);
jPanel60Layout.setHorizontalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel60Layout.createSequentialGroup()
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel60Layout.setVerticalGroup(
jPanel60Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel343, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel59Layout = new javax.swing.GroupLayout(jPanel59);
jPanel59.setLayout(jPanel59Layout);
jPanel59Layout.setHorizontalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel59Layout.createSequentialGroup()
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel337)
.addComponent(jLabel338))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel339)
.addComponent(jLabel340))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel341)
.addComponent(jLabel342))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel59Layout.setVerticalGroup(
jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel59Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel337)
.addComponent(jComboBox308, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel339)
.addComponent(jComboBox310, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel341, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox312, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel59Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel338)
.addComponent(jComboBox309, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel340)
.addComponent(jComboBox311, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel342, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox313, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel61.setBackground(new java.awt.Color(225, 225, 225));
jPanel61.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel344.setText("Course 1");
jLabel344.setToolTipText("");
jLabel345.setText("Course 2");
jComboBox314.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox314.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox314ActionPerformed(evt);
}
});
jComboBox315.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel346.setText("Course 3");
jLabel346.setToolTipText("");
jLabel347.setText("Course 4");
jComboBox316.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox316.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox316ActionPerformed(evt);
}
});
jComboBox317.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel348.setText("Course 5");
jLabel349.setText("Course 6");
jComboBox318.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox319.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel62.setBackground(new java.awt.Color(204, 204, 204));
jPanel62.setForeground(new java.awt.Color(255, 255, 255));
jLabel350.setText(" Fall Semester 3");
jLabel350.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel62Layout = new javax.swing.GroupLayout(jPanel62);
jPanel62.setLayout(jPanel62Layout);
jPanel62Layout.setHorizontalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel62Layout.createSequentialGroup()
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel62Layout.setVerticalGroup(
jPanel62Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel350, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel61Layout = new javax.swing.GroupLayout(jPanel61);
jPanel61.setLayout(jPanel61Layout);
jPanel61Layout.setHorizontalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel61Layout.createSequentialGroup()
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel344)
.addComponent(jLabel345))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel346)
.addComponent(jLabel347))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel348)
.addComponent(jLabel349))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel61Layout.setVerticalGroup(
jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel61Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel344)
.addComponent(jComboBox314, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel346)
.addComponent(jComboBox316, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel348, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox318, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel61Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel345)
.addComponent(jComboBox315, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel347)
.addComponent(jComboBox317, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel349, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox319, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel55, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel57, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane5.setViewportView(jPanel17);
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Electives ", jPanel18);
jPanel63.setBackground(new java.awt.Color(255, 255, 255));
jPanel64.setBackground(new java.awt.Color(225, 225, 225));
jPanel64.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel351.setText("Course 1");
jLabel351.setToolTipText("");
jLabel352.setText("Course 2");
jComboBox320.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox320.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox320ActionPerformed(evt);
}
});
jComboBox321.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel353.setText("Course 3");
jLabel353.setToolTipText("");
jLabel354.setText("Course 4");
jComboBox322.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox322.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox322ActionPerformed(evt);
}
});
jComboBox323.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel355.setText("Course 5");
jLabel356.setText("Course 6");
jComboBox324.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox325.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel65.setBackground(new java.awt.Color(204, 204, 204));
jLabel357.setText(" Spring Semester 2");
jLabel357.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel65Layout = new javax.swing.GroupLayout(jPanel65);
jPanel65.setLayout(jPanel65Layout);
jPanel65Layout.setHorizontalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel65Layout.createSequentialGroup()
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel65Layout.setVerticalGroup(
jPanel65Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel357, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel64Layout = new javax.swing.GroupLayout(jPanel64);
jPanel64.setLayout(jPanel64Layout);
jPanel64Layout.setHorizontalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel64Layout.createSequentialGroup()
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel351)
.addComponent(jLabel352))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel353)
.addComponent(jLabel354))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel355)
.addComponent(jLabel356))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel64Layout.setVerticalGroup(
jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel64Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel351)
.addComponent(jComboBox320, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel353)
.addComponent(jComboBox322, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel355, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox324, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel64Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel352)
.addComponent(jComboBox321, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel354)
.addComponent(jComboBox323, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel356, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox325, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel66.setBackground(new java.awt.Color(225, 225, 225));
jPanel66.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel358.setText("Course 1");
jLabel358.setToolTipText("");
jComboBox326.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox326.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox326ActionPerformed(evt);
}
});
jLabel359.setText("Course 2");
jLabel359.setToolTipText("");
jComboBox327.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox327.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox327ActionPerformed(evt);
}
});
jLabel360.setText("Course 3");
jComboBox328.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel67.setBackground(new java.awt.Color(204, 204, 204));
jLabel361.setText(" Summer Semester 2.5");
jLabel361.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel67Layout = new javax.swing.GroupLayout(jPanel67);
jPanel67.setLayout(jPanel67Layout);
jPanel67Layout.setHorizontalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel67Layout.createSequentialGroup()
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel67Layout.setVerticalGroup(
jPanel67Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel361, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel66Layout = new javax.swing.GroupLayout(jPanel66);
jPanel66.setLayout(jPanel66Layout);
jPanel66Layout.setHorizontalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel66Layout.createSequentialGroup()
.addComponent(jLabel358)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel359)
.addGap(18, 18, 18)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel360)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel66Layout.setVerticalGroup(
jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel66Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel66Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel358)
.addComponent(jComboBox326, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel359)
.addComponent(jComboBox327, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel360, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox328, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel68.setBackground(new java.awt.Color(225, 225, 225));
jPanel68.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel362.setText("Course 1");
jLabel362.setToolTipText("");
jLabel363.setText("Course 2");
jComboBox329.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox329.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox329ActionPerformed(evt);
}
});
jComboBox330.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel364.setText("Course 3");
jLabel364.setToolTipText("");
jLabel365.setText("Course 4");
jComboBox331.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox331.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox331ActionPerformed(evt);
}
});
jComboBox332.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel366.setText("Course 5");
jLabel367.setText("Course 6");
jComboBox333.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox334.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel69.setBackground(new java.awt.Color(204, 204, 204));
jPanel69.setForeground(new java.awt.Color(255, 255, 255));
jLabel368.setText(" Fall Semester 1");
jLabel368.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel69Layout = new javax.swing.GroupLayout(jPanel69);
jPanel69.setLayout(jPanel69Layout);
jPanel69Layout.setHorizontalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel69Layout.createSequentialGroup()
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel69Layout.setVerticalGroup(
jPanel69Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel368, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel68Layout = new javax.swing.GroupLayout(jPanel68);
jPanel68.setLayout(jPanel68Layout);
jPanel68Layout.setHorizontalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel68Layout.createSequentialGroup()
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel362)
.addComponent(jLabel363))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel364)
.addComponent(jLabel365))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel366)
.addComponent(jLabel367))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel68Layout.setVerticalGroup(
jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel68Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel362)
.addComponent(jComboBox329, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel364)
.addComponent(jComboBox331, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel366, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox333, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel68Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel363)
.addComponent(jComboBox330, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel365)
.addComponent(jComboBox332, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel367, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox334, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
jPanel70.setBackground(new java.awt.Color(225, 225, 225));
jPanel70.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel369.setText("Course 1");
jLabel369.setToolTipText("");
jLabel370.setText("Course 2");
jComboBox335.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox335.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox335ActionPerformed(evt);
}
});
jComboBox336.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel371.setText("Course 3");
jLabel371.setToolTipText("");
jLabel372.setText("Course 4");
jComboBox337.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox337.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox337ActionPerformed(evt);
}
});
jComboBox338.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel373.setText("Course 5");
jLabel374.setText("Course 6");
jComboBox339.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox340.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jPanel71.setBackground(new java.awt.Color(204, 204, 204));
jPanel71.setForeground(new java.awt.Color(255, 255, 255));
jLabel375.setText(" Fall Semester 3");
jLabel375.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel71Layout = new javax.swing.GroupLayout(jPanel71);
jPanel71.setLayout(jPanel71Layout);
jPanel71Layout.setHorizontalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel71Layout.createSequentialGroup()
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE)
.addContainerGap())
);
jPanel71Layout.setVerticalGroup(
jPanel71Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel375, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel70Layout = new javax.swing.GroupLayout(jPanel70);
jPanel70.setLayout(jPanel70Layout);
jPanel70Layout.setHorizontalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel70Layout.createSequentialGroup()
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel369)
.addComponent(jLabel370))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel371)
.addComponent(jLabel372))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel373)
.addComponent(jLabel374))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel70Layout.setVerticalGroup(
jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel70Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel369)
.addComponent(jComboBox335, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel371)
.addComponent(jComboBox337, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel373, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox339, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel70Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel370)
.addComponent(jComboBox336, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel372)
.addComponent(jComboBox338, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel374, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox340, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24))
);
javax.swing.GroupLayout jPanel63Layout = new javax.swing.GroupLayout(jPanel63);
jPanel63.setLayout(jPanel63Layout);
jPanel63Layout.setHorizontalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel63Layout.setVerticalGroup(
jPanel63Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel63Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(452, Short.MAX_VALUE))
);
jScrollPane2.setViewportView(jPanel63);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
);
jTabbedPane1.addTab(" Math ", jPanel3);
jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setToolTipText("");
jLabel16.setToolTipText("");
jPanel15.setBackground(new java.awt.Color(83, 13, 47));
jPanel15.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel196.setForeground(new java.awt.Color(255, 255, 255));
jLabel196.setText("Student Name: ");
jTextField1.setText("CSCI");
jLabel199.setForeground(new java.awt.Color(255, 255, 255));
jLabel199.setText("Student Major:");
jTextField2.setText("Davey Jones");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jLabel200.setForeground(new java.awt.Color(255, 255, 255));
jLabel200.setText("Total Hours:");
jLabel201.setForeground(new java.awt.Color(255, 255, 255));
jLabel201.setText("Graduation Date:");
jTextField3.setText("110");
jTextField4.setText("May 2013");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel196, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jLabel199)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88)
.addComponent(jLabel200)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(94, 94, 94)
.addComponent(jLabel201)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel196, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel199, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel200, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel201, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/ZRICBanner.jpg"))); // NOI18N
jPanel5.setBackground(new java.awt.Color(83, 13, 47));
logoutButton.setForeground(new java.awt.Color(255, 255, 255));
logoutButton.setText("Logout");
logoutButton.setBorder(null);
logoutButton.setContentAreaFilled(false);
logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutButtonMouseClicked(evt);
}
});
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Settings");
editAccountButton.setBorder(null);
editAccountButton.setBorderPainted(false);
editAccountButton.setContentAreaFilled(false);
editAccountButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
editAccountButtonMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(editAccountButton)
.addGap(18, 18, 18)
.addComponent(logoutButton)
.addGap(54, 54, 54))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(0, 2, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(logoutButton)
.addComponent(editAccountButton))
.addGap(0, 4, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addGap(304, 304, 304)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel10))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel16))
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 941, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jLabel16)
.addGap(0, 0, 0)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel6))
.addGap(0, 0, 0)
.addComponent(jLabel10)
.addGap(0, 0, 0)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
);
jTabbedPane1.getAccessibleContext().setAccessibleName("History");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/org/infoscoop/request/OAuthAuthenticator.java b/src/main/java/org/infoscoop/request/OAuthAuthenticator.java
index 2cd9e312..9d7e878d 100644
--- a/src/main/java/org/infoscoop/request/OAuthAuthenticator.java
+++ b/src/main/java/org/infoscoop/request/OAuthAuthenticator.java
@@ -1,206 +1,206 @@
/* infoScoop OpenSource
* Copyright (C) 2010 Beacon IT Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0-standalone.html>.
*/
package org.infoscoop.request;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import net.oauth.OAuthServiceProvider;
import net.oauth.client.OAuthClient;
import net.oauth.client.httpclient3.HttpClient3;
import net.oauth.signature.RSA_SHA1;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.RedirectException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.infoscoop.dao.OAuthCertificateDAO;
import org.infoscoop.dao.OAuthConsumerDAO;
import org.infoscoop.dao.model.OAuthCertificate;
import org.infoscoop.dao.model.OAuthConsumerProp;
import org.infoscoop.request.ProxyRequest.OAuthConfig;
public class OAuthAuthenticator implements Authenticator {
public static final OAuthClient CLIENT = new OAuthClient(new HttpClient3());
private static String AUTH_CALLBACK_URL = "oauthcallback";
private static Log log = LogFactory.getLog(OAuthAuthenticator.class);
private static Map<String, OAuthConsumer> consumers = new HashMap<String, OAuthConsumer>();
public OAuthAuthenticator(){
}
public static OAuthConsumer getConsumer(String gadgetUrl, String serviceName) {
return consumers.get(gadgetUrl + "\t" + serviceName);
}
public void doAuthentication(HttpClient client, ProxyRequest request,
HttpMethod method, String uid, String pwd)
throws ProxyAuthenticationException {
ProxyRequest.OAuthConfig oauthConfig = request.getOauthConfig();
try {
OAuthConsumer consumer = newConsumer(oauthConfig.serviceName,oauthConfig);
OAuthAccessor accessor = newAccessor(consumer, oauthConfig);
if (accessor.accessToken == null) {
getRequestToken(request, accessor);
}
Collection<Map.Entry<String, String>> parms = request.getFilterParameters().entrySet();
OAuthMessage message = new OAuthMessage("GET", request.getTargetURL(), parms);
message.addRequiredParameters(accessor);
String authHeader = message.getAuthorizationHeader(null);
request.putRequestHeader("Authorization", authHeader);
// Find the non-OAuth parameters:
} catch (MalformedURLException e) {
throw new ProxyAuthenticationException(e);
}catch (URISyntaxException e) {
throw new ProxyAuthenticationException(e);
} catch (OAuthException e) {
throw new ProxyAuthenticationException(e);
} catch (IOException e) {
throw new ProxyAuthenticationException(e);
}
}
public int getCredentialType() {
// TODO Auto-generated method stub
return 3;
}
protected OAuthConsumer newConsumer(String name, ProxyRequest.OAuthConfig oauthConfig) throws ProxyAuthenticationException{
OAuthServiceProvider serviceProvider =
new OAuthServiceProvider(
oauthConfig.requestTokenURL,
oauthConfig.userAuthorizationURL,
oauthConfig.accessTokenURL);
OAuthConsumerProp consumerProp = OAuthConsumerDAO.newInstance()
.getConsumer(oauthConfig.getGadgetUrl(), name);
OAuthCertificate certificate = OAuthCertificateDAO.newInstance().get();
String consumerKey;
String consumerSecret;
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
consumerKey = certificate.getConsumerKey();
- consumerSecret = "infoScoop";//TODO:
+ consumerSecret = null;
}else{
consumerKey = consumerProp.getConsumerKey();
consumerSecret = consumerProp.getConsumerSecret();
}
OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, serviceProvider);
consumer.setProperty("name", name);
if (consumerProp.getSignatureMethod() != null)
consumer.setProperty("oauth_signature_method", consumerProp
.getSignatureMethod());
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
if (certificate == null)
throw new ProxyAuthenticationException(
"a container's certificate is not set.");
//consumer.setProperty("oauth_signature_method", "RSA-SHA1");
try {
String privateKey = new String(certificate.getPrivateKey(), "UTF-8");
consumer.setProperty(RSA_SHA1.PRIVATE_KEY, privateKey);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
consumers.put(consumerProp.getGadgetUrl() + "\t" + name, consumer);
return consumer;
}
/**
* Construct an accessor from cookies. The resulting accessor won't
* necessarily have any tokens.
*/
private static OAuthAccessor newAccessor(OAuthConsumer consumer, OAuthConfig oauthConfig)
throws OAuthException {
OAuthAccessor accessor = new OAuthAccessor(consumer);
accessor.requestToken = oauthConfig.requestToken;
accessor.accessToken = oauthConfig.accessToken;
accessor.tokenSecret = oauthConfig.tokenSecret;
return accessor;
}
/**
* Get from oauth example CookieConsumer.
* @throws IOException
* @throws URISyntaxException
* @throws ProxyAuthenticationException
*
* @throws RedirectException
* to obtain authorization
*/
private static void getRequestToken(ProxyRequest request, OAuthAccessor accessor)
throws OAuthException, IOException, URISyntaxException, ProxyAuthenticationException
{
final String consumerName = (String) accessor.consumer.getProperty("name");
final String callbackURL = getCallbackURL(request, consumerName);
List<OAuth.Parameter> parameters = OAuth.newList(OAuth.OAUTH_CALLBACK, callbackURL);
// Google needs to know what you intend to do with the access token:
Object scope = accessor.consumer.getProperty("request.scope");
if (scope != null) {
parameters.add(new OAuth.Parameter("scope", scope.toString()));
}
OAuthMessage response = CLIENT.getRequestTokenResponse(accessor, null, parameters);
request.putResponseHeader(consumerName + ".requesttoken", accessor.requestToken);
request.putResponseHeader(consumerName + ".tokensecret", accessor.tokenSecret);
String authorizationURL = accessor.consumer.serviceProvider.userAuthorizationURL;
authorizationURL = OAuth.addParameters(authorizationURL //
, OAuth.OAUTH_TOKEN, accessor.requestToken);
if (response.getParameter(OAuth.OAUTH_CALLBACK_CONFIRMED) == null) {
authorizationURL = OAuth.addParameters(authorizationURL //
, OAuth.OAUTH_CALLBACK, callbackURL);
}
request.putResponseHeader("oauthApprovalUrl", authorizationURL);
throw new ProxyAuthenticationException("Redirect to authorization url.");
}
private static String getCallbackURL(ProxyRequest request,
String consumerName) throws IOException {
String gadgetUrl = request.getOauthConfig().getGadgetUrl();
String hostPrefix = request.getOauthConfig().getHostPrefix();
URL base = new URL(hostPrefix + "/" + AUTH_CALLBACK_URL
+ "?__GADGET_URL__=" + gadgetUrl);
return OAuth.addParameters(base.toExternalForm() //
, "consumer", consumerName //
);
}
}
| true | true | protected OAuthConsumer newConsumer(String name, ProxyRequest.OAuthConfig oauthConfig) throws ProxyAuthenticationException{
OAuthServiceProvider serviceProvider =
new OAuthServiceProvider(
oauthConfig.requestTokenURL,
oauthConfig.userAuthorizationURL,
oauthConfig.accessTokenURL);
OAuthConsumerProp consumerProp = OAuthConsumerDAO.newInstance()
.getConsumer(oauthConfig.getGadgetUrl(), name);
OAuthCertificate certificate = OAuthCertificateDAO.newInstance().get();
String consumerKey;
String consumerSecret;
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
consumerKey = certificate.getConsumerKey();
consumerSecret = "infoScoop";//TODO:
}else{
consumerKey = consumerProp.getConsumerKey();
consumerSecret = consumerProp.getConsumerSecret();
}
OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, serviceProvider);
consumer.setProperty("name", name);
if (consumerProp.getSignatureMethod() != null)
consumer.setProperty("oauth_signature_method", consumerProp
.getSignatureMethod());
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
if (certificate == null)
throw new ProxyAuthenticationException(
"a container's certificate is not set.");
//consumer.setProperty("oauth_signature_method", "RSA-SHA1");
try {
String privateKey = new String(certificate.getPrivateKey(), "UTF-8");
consumer.setProperty(RSA_SHA1.PRIVATE_KEY, privateKey);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
consumers.put(consumerProp.getGadgetUrl() + "\t" + name, consumer);
return consumer;
}
| protected OAuthConsumer newConsumer(String name, ProxyRequest.OAuthConfig oauthConfig) throws ProxyAuthenticationException{
OAuthServiceProvider serviceProvider =
new OAuthServiceProvider(
oauthConfig.requestTokenURL,
oauthConfig.userAuthorizationURL,
oauthConfig.accessTokenURL);
OAuthConsumerProp consumerProp = OAuthConsumerDAO.newInstance()
.getConsumer(oauthConfig.getGadgetUrl(), name);
OAuthCertificate certificate = OAuthCertificateDAO.newInstance().get();
String consumerKey;
String consumerSecret;
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
consumerKey = certificate.getConsumerKey();
consumerSecret = null;
}else{
consumerKey = consumerProp.getConsumerKey();
consumerSecret = consumerProp.getConsumerSecret();
}
OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, serviceProvider);
consumer.setProperty("name", name);
if (consumerProp.getSignatureMethod() != null)
consumer.setProperty("oauth_signature_method", consumerProp
.getSignatureMethod());
if("RSA-SHA1".equals(consumerProp.getSignatureMethod())){
if (certificate == null)
throw new ProxyAuthenticationException(
"a container's certificate is not set.");
//consumer.setProperty("oauth_signature_method", "RSA-SHA1");
try {
String privateKey = new String(certificate.getPrivateKey(), "UTF-8");
consumer.setProperty(RSA_SHA1.PRIVATE_KEY, privateKey);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
consumers.put(consumerProp.getGadgetUrl() + "\t" + name, consumer);
return consumer;
}
|
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java
index 49f8df867..cd0aeaf59 100644
--- a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java
+++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java
@@ -1,421 +1,422 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* Default implementation of {@link org.eclipse.jface.text.IInformationControl}.
* <p>
* Displays textual information in a {@link org.eclipse.swt.custom.StyledText}
* widget. Before displaying, the information set to this information control is
* processed by an <code>IInformationPresenter</code>.
*
* @since 2.0
*/
public class DefaultInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension3, DisposeListener {
/**
* An information presenter determines the style presentation
* of information displayed in the default information control.
* The interface can be implemented by clients.
*/
public interface IInformationPresenter {
/**
* Updates the given presentation of the given information and
* thereby may manipulate the information to be displayed. The manipulation
* could be the extraction of textual encoded style information etc. Returns the
* manipulated information.
*
* @param display the display of the information control
* @param hoverInfo the information to be presented
* @param presentation the presentation to be updated
* @param maxWidth the maximal width in pixels
* @param maxHeight the maximal height in pixels
*
* @return the manipulated information
*/
String updatePresentation(Display display, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight);
}
/** Border thickness in pixels. */
private static final int BORDER= 1;
/** The control's shell */
private Shell fShell;
/** The control's text widget */
private StyledText fText;
/** The information presenter */
private IInformationPresenter fPresenter;
/** A cached text presentation */
private TextPresentation fPresentation= new TextPresentation();
/** The control width constraint */
private int fMaxWidth= -1;
/** The control height constraint */
private int fMaxHeight= -1;
/**
* The font of the optional status text label.
*
* @since 3.0
*/
private Font fStatusTextFont;
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param shellStyle the additional styles for the shell
* @param style the additional styles for the styled text widget
* @param presenter the presenter to be used
*/
public DefaultInformationControl(Shell parent, int shellStyle, int style, IInformationPresenter presenter) {
this(parent, shellStyle, style, presenter, null);
}
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param shellStyle the additional styles for the shell
* @param style the additional styles for the styled text widget
* @param presenter the presenter to be used
* @param statusFieldText the text to be used in the optional status field
* or <code>null</code> if the status field should be hidden
* @since 3.0
*/
public DefaultInformationControl(Shell parent, int shellStyle, int style, IInformationPresenter presenter, String statusFieldText) {
GridLayout layout;
GridData gd;
fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
Display display= fShell.getDisplay();
fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
Composite composite= fShell;
layout= new GridLayout(1, false);
int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
layout.marginHeight= border;
layout.marginWidth= border;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
if (statusFieldText != null) {
composite= new Composite(composite, SWT.NONE);
layout= new GridLayout(1, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
+ layout.verticalSpacing= 1;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
// Text field
fText= new StyledText(composite, SWT.MULTI | SWT.READ_ONLY | style);
gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
fText.setLayoutData(gd);
fText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
fText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
fText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == 0x1B) // ESC
fShell.dispose();
}
public void keyReleased(KeyEvent e) {}
});
fPresenter= presenter;
// Status field
if (statusFieldText != null) {
// Horizontal separator line
Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Status field label
Label statusField= new Label(composite, SWT.RIGHT);
statusField.setText(statusFieldText);
Font font= statusField.getFont();
FontData[] fontDatas= font.getFontData();
for (int i= 0; i < fontDatas.length; i++)
fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
fStatusTextFont= new Font(statusField.getDisplay(), fontDatas);
statusField.setFont(fStatusTextFont);
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
statusField.setLayoutData(gd);
statusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
statusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
addDisposeListener(this);
}
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param style the additional styles for the styled text widget
* @param presenter the presenter to be used
*/
public DefaultInformationControl(Shell parent,int style, IInformationPresenter presenter) {
this(parent, SWT.NO_TRIM, style, presenter);
}
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param style the additional styles for the styled text widget
* @param presenter the presenter to be used
* @param statusFieldText the text to be used in the optional status field
* or <code>null</code> if the status field should be hidden
* @since 3.0
*/
public DefaultInformationControl(Shell parent,int style, IInformationPresenter presenter, String statusFieldText) {
this(parent, SWT.NO_TRIM, style, presenter, statusFieldText);
}
/**
* Creates a default information control with the given shell as parent.
* No information presenter is used to process the information
* to be displayed. No additional styles are applied to the styled text widget.
*
* @param parent the parent shell
*/
public DefaultInformationControl(Shell parent) {
this(parent, SWT.NONE, null);
}
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed.
* No additional styles are applied to the styled text widget.
*
* @param parent the parent shell
* @param presenter the presenter to be used
*/
public DefaultInformationControl(Shell parent, IInformationPresenter presenter) {
this(parent, SWT.NONE, presenter);
}
/*
* @see IInformationControl#setInformation(String)
*/
public void setInformation(String content) {
if (fPresenter == null) {
fText.setText(content);
} else {
fPresentation.clear();
content= fPresenter.updatePresentation(fShell.getDisplay(), content, fPresentation, fMaxWidth, fMaxHeight);
if (content != null) {
fText.setText(content);
TextPresentation.applyTextPresentation(fPresentation, fText);
} else {
fText.setText(""); //$NON-NLS-1$
}
}
}
/*
* @see IInformationControl#setVisible(boolean)
*/
public void setVisible(boolean visible) {
fShell.setVisible(visible);
}
/*
* @see IInformationControl#dispose()
*/
public void dispose() {
if (fShell != null && !fShell.isDisposed())
fShell.dispose();
else
widgetDisposed(null);
}
/*
* @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
* @since 3.0
*/
public void widgetDisposed(DisposeEvent event) {
if (fStatusTextFont != null && !fStatusTextFont.isDisposed())
fStatusTextFont.dispose();
fShell= null;
fText= null;
fStatusTextFont= null;
}
/*
* @see IInformationControl#setSize(int, int)
*/
public void setSize(int width, int height) {
fShell.setSize(width, height);
}
/*
* @see IInformationControl#setLocation(Point)
*/
public void setLocation(Point location) {
Rectangle trim= fShell.computeTrim(0, 0, 0, 0);
Point textLocation= fText.getLocation();
location.x += trim.x - textLocation.x;
location.y += trim.y - textLocation.y;
fShell.setLocation(location);
}
/*
* @see IInformationControl#setSizeConstraints(int, int)
*/
public void setSizeConstraints(int maxWidth, int maxHeight) {
fMaxWidth= maxWidth;
fMaxHeight= maxHeight;
}
/*
* @see IInformationControl#computeSizeHint()
*/
public Point computeSizeHint() {
return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension3#computeTrim()
* @since 3.0
*/
public Rectangle computeTrim() {
return fShell.computeTrim(0, 0, 0, 0);
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension3#getBounds()
* @since 3.0
*/
public Rectangle getBounds() {
return fShell.getBounds();
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension3#restoresLocation()
* @since 3.0
*/
public boolean restoresLocation() {
return false;
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension3#restoresSize()
* @since 3.0
*/
public boolean restoresSize() {
return false;
}
/*
* @see IInformationControl#addDisposeListener(DisposeListener)
*/
public void addDisposeListener(DisposeListener listener) {
fShell.addDisposeListener(listener);
}
/*
* @see IInformationControl#removeDisposeListener(DisposeListener)
*/
public void removeDisposeListener(DisposeListener listener) {
fShell.removeDisposeListener(listener);
}
/*
* @see IInformationControl#setForegroundColor(Color)
*/
public void setForegroundColor(Color foreground) {
fText.setForeground(foreground);
}
/*
* @see IInformationControl#setBackgroundColor(Color)
*/
public void setBackgroundColor(Color background) {
fText.setBackground(background);
}
/*
* @see IInformationControl#isFocusControl()
*/
public boolean isFocusControl() {
return fText.isFocusControl();
}
/*
* @see IInformationControl#setFocus()
*/
public void setFocus() {
fShell.forceFocus();
fText.setFocus();
}
/*
* @see IInformationControl#addFocusListener(FocusListener)
*/
public void addFocusListener(FocusListener listener) {
fText.addFocusListener(listener);
}
/*
* @see IInformationControl#removeFocusListener(FocusListener)
*/
public void removeFocusListener(FocusListener listener) {
fText.removeFocusListener(listener);
}
/*
* @see IInformationControlExtension#hasContents()
*/
public boolean hasContents() {
return fText.getCharCount() > 0;
}
}
| true | true | public DefaultInformationControl(Shell parent, int shellStyle, int style, IInformationPresenter presenter, String statusFieldText) {
GridLayout layout;
GridData gd;
fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
Display display= fShell.getDisplay();
fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
Composite composite= fShell;
layout= new GridLayout(1, false);
int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
layout.marginHeight= border;
layout.marginWidth= border;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
if (statusFieldText != null) {
composite= new Composite(composite, SWT.NONE);
layout= new GridLayout(1, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
// Text field
fText= new StyledText(composite, SWT.MULTI | SWT.READ_ONLY | style);
gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
fText.setLayoutData(gd);
fText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
fText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
fText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == 0x1B) // ESC
fShell.dispose();
}
public void keyReleased(KeyEvent e) {}
});
fPresenter= presenter;
// Status field
if (statusFieldText != null) {
// Horizontal separator line
Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Status field label
Label statusField= new Label(composite, SWT.RIGHT);
statusField.setText(statusFieldText);
Font font= statusField.getFont();
FontData[] fontDatas= font.getFontData();
for (int i= 0; i < fontDatas.length; i++)
fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
fStatusTextFont= new Font(statusField.getDisplay(), fontDatas);
statusField.setFont(fStatusTextFont);
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
statusField.setLayoutData(gd);
statusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
statusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
addDisposeListener(this);
}
| public DefaultInformationControl(Shell parent, int shellStyle, int style, IInformationPresenter presenter, String statusFieldText) {
GridLayout layout;
GridData gd;
fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
Display display= fShell.getDisplay();
fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
Composite composite= fShell;
layout= new GridLayout(1, false);
int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
layout.marginHeight= border;
layout.marginWidth= border;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
if (statusFieldText != null) {
composite= new Composite(composite, SWT.NONE);
layout= new GridLayout(1, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.verticalSpacing= 1;
composite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
// Text field
fText= new StyledText(composite, SWT.MULTI | SWT.READ_ONLY | style);
gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
fText.setLayoutData(gd);
fText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
fText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
fText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == 0x1B) // ESC
fShell.dispose();
}
public void keyReleased(KeyEvent e) {}
});
fPresenter= presenter;
// Status field
if (statusFieldText != null) {
// Horizontal separator line
Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Status field label
Label statusField= new Label(composite, SWT.RIGHT);
statusField.setText(statusFieldText);
Font font= statusField.getFont();
FontData[] fontDatas= font.getFontData();
for (int i= 0; i < fontDatas.length; i++)
fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
fStatusTextFont= new Font(statusField.getDisplay(), fontDatas);
statusField.setFont(fStatusTextFont);
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
statusField.setLayoutData(gd);
statusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
statusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
addDisposeListener(this);
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/DataTransferManager.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/DataTransferManager.java
index b34fcdb10..beb1daa0f 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/DataTransferManager.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/DataTransferManager.java
@@ -1,901 +1,902 @@
package de.fu_berlin.inf.dpp.net.internal;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.dnd.TransferData;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;
import org.jivesoftware.smackx.packet.Jingle;
import org.jivesoftware.smackx.socks5bytestream.Socks5ByteStreamManager;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.annotations.Component;
import de.fu_berlin.inf.dpp.exceptions.LocalCancellationException;
import de.fu_berlin.inf.dpp.exceptions.SarosCancellationException;
import de.fu_berlin.inf.dpp.net.ITransferModeListener;
import de.fu_berlin.inf.dpp.net.IncomingTransferObject;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.net.IncomingTransferObject.IncomingTransferObjectExtensionProvider;
import de.fu_berlin.inf.dpp.net.business.ActivitiesHandler;
import de.fu_berlin.inf.dpp.net.business.DispatchThreadContext;
import de.fu_berlin.inf.dpp.net.internal.TransferDescription.FileTransferType;
import de.fu_berlin.inf.dpp.net.jingle.IJingleFileTransferListener;
import de.fu_berlin.inf.dpp.net.jingle.JingleFileTransferManager;
import de.fu_berlin.inf.dpp.net.jingle.JingleSessionException;
import de.fu_berlin.inf.dpp.net.jingle.JingleFileTransferManager.JingleConnectionState;
import de.fu_berlin.inf.dpp.observables.InvitationProcessObservable;
import de.fu_berlin.inf.dpp.observables.JingleFileTransferManagerObservable;
import de.fu_berlin.inf.dpp.observables.SessionIDObservable;
import de.fu_berlin.inf.dpp.preferences.PreferenceConstants;
import de.fu_berlin.inf.dpp.preferences.PreferenceUtils;
import de.fu_berlin.inf.dpp.project.ConnectionSessionListener;
import de.fu_berlin.inf.dpp.util.CausedIOException;
import de.fu_berlin.inf.dpp.util.Util;
/**
* This class is responsible for handling all transfers of binary data
*/
@Component(module = "net")
public class DataTransferManager implements ConnectionSessionListener {
protected Map<JID, List<TransferDescription>> incomingTransfers = new HashMap<JID, List<TransferDescription>>();
protected Map<JID, NetTransferMode> incomingTransferModes = Collections
.synchronizedMap(new HashMap<JID, NetTransferMode>());
protected Map<JID, NetTransferMode> outgoingTransferModes = Collections
.synchronizedMap(new HashMap<JID, NetTransferMode>());
protected TransferModeDispatch transferModeDispatch = new TransferModeDispatch();
/**
* TransferModeListener which keeps track of the last type of transfer mode
* *started* in both incoming and outgoing directions.
*/
protected ITransferModeListener trackingTransferModeListener = new ITransferModeListener() {
public void clear() {
incomingTransferModes.clear();
outgoingTransferModes.clear();
}
public void transferFinished(JID jid, NetTransferMode newMode,
boolean incoming, long size, long transmissionMillisecs) {
if (incoming) {
incomingTransferModes.put(jid, newMode);
} else {
outgoingTransferModes.put(jid, newMode);
}
}
};
protected boolean forceFileTransferByChat;
protected IPropertyChangeListener propertyListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(
PreferenceConstants.FORCE_FILETRANSFER_BY_CHAT)) {
Object value = event.getNewValue();
// make sure the cast will work
if (value instanceof Boolean) {
forceFileTransferByChat = ((Boolean) value).booleanValue();
// add/remove Jingle XMPP feature
if (connection != null) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (forceFileTransferByChat) {
sdm.removeFeature(Jingle.NAMESPACE);
} else {
if (!sdm.includesFeature(Jingle.NAMESPACE))
sdm.addFeature(Jingle.NAMESPACE);
}
}
} else {
log.warn("Preference value FORCE_FILETRANSFER_BY_CHAT"
+ " is supposed to be a boolean, but it unexpectedly"
+ " changed to a different type!");
}
}
}
};
protected IJingleFileTransferListener jingleListener = new JingleTransferListener();
protected FileTransferManager fileTransferManager;
protected ConcurrentLinkedQueue<TransferData> fileTransferQueue;
protected Thread startingJingleThread;
protected XMPPConnection connection;
@Inject
protected DiscoveryManager discoveryManager;
@Inject
protected InvitationProcessObservable invitationProcesses;
@Inject
protected JingleFileTransferManagerObservable jingleManager;
@Inject
protected XMPPReceiver receiver;
@Inject
protected ActivitiesHandler activitiesHandler;
@Inject
protected InvitationProcessObservable invitationProcess;
@Inject
protected ActivitiesExtensionProvider activitiesProvider;
@Inject
protected PreferenceUtils preferenceUtils;
@Inject
protected DispatchThreadContext dispatchThreadContext;
@Inject
protected IncomingTransferObjectExtensionProvider incomingExtProv;
protected Saros saros;
protected SessionIDObservable sessionID;
public DataTransferManager(Saros saros, SessionIDObservable sessionID,
PreferenceUtils prefUtils) {
this.sessionID = sessionID;
this.saros = saros;
this.forceFileTransferByChat = prefUtils.forceFileTranserByChat();
/*
* register a property change listeners to keep forceFileTransferByChat
* up-to-date
*/
saros.getPreferenceStore().addPropertyChangeListener(propertyListener);
transferModeDispatch.add(trackingTransferModeListener);
}
public JingleFileTransferManager getJingleManager() {
try {
if (startingJingleThread == null)
return null;
startingJingleThread.join();
} catch (InterruptedException e) {
log.error("Code not designed to be interruptable", e);
Thread.currentThread().interrupt();
return null;
}
return jingleManager.getValue();
}
/**
* JingleTransferListener receives from all JingleFileTransferSessions
* {@link IncomingTransferObject}
*/
protected final class JingleTransferListener implements
IJingleFileTransferListener {
/**
* It changes to the Thread context of XMPPChatTransmiter before calling
* XMPPReceiver's processPacket.
*/
public void incomingData(final IncomingTransferObject transferObject) {
addIncomingTransferObject(transferObject);
}
}
/**
* Adds an incoming transfer.
*
* @param transferObjectDescription
* An IncomingTransferObject that has the TransferDescription as
* content to provide information of the incoming transfer to
* upper layers.
*/
protected void addIncomingTransferObject(
final IncomingTransferObject transferObjectDescription) {
final TransferDescription description = transferObjectDescription
.getTransferDescription();
final IncomingTransferObject transferObjectData = new IncomingTransferObject() {
/**
* Accepts a transfer and returns the incoming data.
*/
public byte[] accept(final SubMonitor progress)
throws SarosCancellationException, IOException {
addIncomingFileTransfer(description);
try {
// TODO Put size in TransferDescription, so we can
// display it here
if (description.type == FileTransferType.ACTIVITY_TRANSFER
|| description.type == FileTransferType.STREAM_DATA
|| description.type == FileTransferType.STREAM_META) {
if (log.isTraceEnabled()) {
log.trace("[" + getTransferMode().toString()
+ "] Starting incoming data transfer: "
+ description.toString());
}
} else {
log.debug("[" + getTransferMode().toString()
+ "] Starting incoming data transfer: "
+ description.toString());
}
long startTime = System.nanoTime();
byte[] content = transferObjectDescription.accept(progress);
long duration = Math.max(0, System.nanoTime() - startTime) / 1000000;
if (description.type == FileTransferType.ACTIVITY_TRANSFER
|| description.type == FileTransferType.STREAM_DATA
|| description.type == FileTransferType.STREAM_META) {
if (log.isTraceEnabled()) {
log.trace("[" + getTransferMode().toString()
+ "] Finished incoming data transfer: "
+ description.toString() + ", size: "
+ Util.throughput(content.length, duration));
}
} else {
log.debug("[" + getTransferMode().toString()
+ "] Finished incoming data transfer: "
+ description.toString() + ", size: "
+ Util.throughput(content.length, duration));
}
transferModeDispatch.transferFinished(description
.getSender(), getTransferMode(), true, content.length,
duration);
return content;
} finally {
removeIncomingFileTransfer(description);
}
}
public TransferDescription getTransferDescription() {
return description;
}
/**
* Rejects the incoming transfer data.
*/
public void reject() throws IOException {
transferObjectDescription.reject();
}
public NetTransferMode getTransferMode() {
return transferObjectDescription.getTransferMode();
}
};
// ask upper layer to accept
dispatchThreadContext.executeAsDispatch(new Runnable() {
public void run() {
receiver.processIncomingTransferObject(description,
transferObjectData);
}
});
}
protected class XMPPFileTransferListener implements FileTransferListener {
public void fileTransferRequest(final FileTransferRequest request) {
final TransferDescription transferDescription;
try {
transferDescription = TransferDescription.fromBase64(request
.getDescription());
} catch (IOException e) {
log.error("Incoming File Transfer via IBB failed: ", e);
+ request.reject(); // Reject (no way to tell remote user why)
return;
}
final IncomingTransferObject transferObject = new IncomingTransferObject() {
/**
* @throws SarosCancellationException
* It will be thrown if the user (locally or
* remotely) has canceled the transfer.
*
* @throws IOException
* It will be thrown if the stream negotiation, the
* read from InputStream or the inflation failed
* during I/O operations or Timeout.
*/
public byte[] accept(SubMonitor monitor)
throws SarosCancellationException, IOException {
monitor.beginTask("Receive via IBB", 10000);
// TODO how to handle files larger than the max size of a
// byte array
IncomingFileTransfer accept = request.accept();
monitor.worked(100);
byte[] content;
InputStream in = null;
try {
if (monitor.isCanceled())
throw new LocalCancellationException();
in = accept.recieveFile();
monitor.worked(100);
content = Util.toByteArray(in, request.getFileSize(),
monitor.newChild(8000));
IOUtils.closeQuietly(in);
// File is meant to be empty
if (transferDescription.emptyFile) {
content = new byte[0];
}
if (transferDescription.compressInDataTransferManager())
content = Util.inflate(content, monitor
.newChild(1500));
} catch (LocalCancellationException e) {
log.info("Local monitor was cancelled.");
throw e;
} catch (IOException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
log.error("Incoming File Transfer via IBB failed: ", e);
throw e;
} catch (XMPPException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
Throwable tmp = e.getWrappedThrowable();
Exception cause = (tmp != null) ? (Exception) tmp : e;
if (cause instanceof InterruptedException) {
log.warn("Interrupted on IBB stream negotiation.");
} else if (e.getCause() instanceof TimeoutException) {
log
.warn("Timeout while waiting for incoming File ransfer via IBB.");
} else if (cause instanceof ExecutionException) {
// unwrap
Throwable t = cause.getCause();
if (t != null)
log.warn(t.getMessage(), t);
}
throw new IOException(
"Failed to negotiate Stream via IBB.");
}
monitor.worked(100);
monitor.done();
return content;
}
public TransferDescription getTransferDescription() {
return transferDescription;
}
public void reject() throws IOException {
request.reject();
}
public NetTransferMode getTransferMode() {
return NetTransferMode.IBB;
}
};
addIncomingTransferObject(transferObject);
}
}
private static final Logger log = Logger
.getLogger(DataTransferManager.class);
public interface Transmitter {
public String getName();
/**
* Should return true if this transmitter can send data to the given
* JID.
*/
public boolean isSuitable(JID jid);
/**
* If this call returns the data has been send successfully, otherwise
* an IOException is thrown with the reason why the transfer failed.
*
* @param data
* The data to be sent.
* @throws IOException
* if the send failed
* @throws SarosCancellationException
* It will be thrown if the user (locally or remotely) has
* canceled the transfer.
* @blocking Send the given data as a blocking operation.
*/
public NetTransferMode send(TransferDescription data, byte[] content,
SubMonitor callback) throws IOException, SarosCancellationException;
}
protected Transmitter xmppFileTransfer = new Transmitter() {
public NetTransferMode send(TransferDescription data, byte[] content,
SubMonitor progress) throws IOException, LocalCancellationException {
final long startTime = System.nanoTime();
log.debug("[IBB] Sending to " + data.getRecipient() + ": "
+ data.toString() + ", size: "
+ Util.formatByte(content.length));
OutgoingFileTransfer transfer = fileTransferManager
.createOutgoingFileTransfer(data.getRecipient().toString());
progress.setWorkRemaining(110);
progress.subTask("Negotiating file transfer");
if (content.length == 0) {
content = new byte[] { 0 };
data.setEmptyFile(true);
}
// The file path is irrelevant
transfer.sendStream(new ByteArrayInputStream(content),
"Filename managed by Description", content.length, data
.toBase64());
progress.worked(10);
int worked = 0;
InterruptedException interrupted = null;
progress.subTask("Sending data");
while (!transfer.isDone()) {
if (progress.isCanceled()) {
transfer.cancel();
throw new LocalCancellationException();
}
int newProgress = (int) ((100.0 * transfer.getAmountWritten()) / Math
.max(1, content.length));
log.trace("Progress " + newProgress + "%");
if (worked < newProgress) {
progress.worked(newProgress - worked);
worked = newProgress;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
interrupted = e;
}
}
if (interrupted != null) {
log.error("Code not designed to be interruptable", interrupted);
Thread.currentThread().interrupt();
}
if (transfer.getStatus() == Status.error) {
throw new IOException("XMPPError in IBB-FileTransfer: "
+ transfer.getError() + " caused by: "
+ transfer.getException());
}
if (transfer.getStatus() != Status.complete) {
throw new IOException("Error in IBB-FileTransfer wrong state: "
+ transfer.getStatus());
}
long duration = Math.max(0, System.nanoTime() - startTime) / 1000000;
log.debug("[IBB] Finished sending to " + data.getRecipient() + ": "
+ data.toString() + ", "
+ Util.throughput(content.length, duration));
return NetTransferMode.IBB;
}
public boolean isSuitable(JID jid) {
return true;
}
public String getName() {
return "IBB";
}
};
protected Transmitter jingle = new Transmitter() {
public NetTransferMode send(TransferDescription data, byte[] content,
SubMonitor progress) throws SarosCancellationException, IOException {
try {
JingleFileTransferManager jftm = getJingleManager();
if (jftm == null)
throw new IOException("Jingle is disabled");
return jftm.send(data, content, progress);
} catch (JingleSessionException e) {
throw new CausedIOException(e);
}
}
public boolean isSuitable(JID jid) {
if (preferenceUtils.forceFileTranserByChat())
return false;
if (!discoveryManager.isJingleSupported(jid))
return false;
JingleFileTransferManager jftm = getJingleManager();
if (jftm == null)
return false;
JingleConnectionState state = jftm.getState(jid);
// If null, then we have never tried to connect
if (state == null)
return true;
// Only use Jingle, if not in ERROR
return state != JingleConnectionState.ERROR;
}
public String getName() {
return "Jingle";
}
};
/**
* Dispatch to Transmitter.
*
* @throws SarosCancellationException
* It will be thrown if the local or remote user has canceled
* the transfer.
* @throws IOException
* If a technical problem occurred.
*/
public void sendData(TransferDescription transferData, byte[] input,
SubMonitor progress) throws IOException, SarosCancellationException {
// TODO Buffer correctly when not connected....
// this.fileTransferQueue.offer(transfer);
// sendNextFile();
Transmitter[] transmitters;
if (forceFileTransferByChat) {
transmitters = new Transmitter[] { xmppFileTransfer };
} else {
transmitters = new Transmitter[] { jingle, xmppFileTransfer };
}
progress.beginTask("Sending Data", 100);
if (transferData.compressInDataTransferManager()) {
input = Util.deflate(input, progress.newChild(15));
}
SubMonitor transferProgress = progress.newChild(85);
try {
// Try all transmitters
for (Transmitter transmitter : transmitters) {
if (sendData(transmitter, transferData, input, transferProgress)) {
// Successfully sent!
transferProgress.done();
return;
}
}
// No transmitter worked! :-(
throw new IOException(Util.prefix(transferData.recipient)
+ "Exhausted all options " + Arrays.toString(transmitters)
+ " to send " + transferData);
} finally {
progress.done();
}
}
/**
* Tries to send the given data using the given transmitter returning true
* if the transfer was successfully completed, false otherwise.
*
* @throws SarosCancellationException
* It will be thrown if the local user or remote user has
* canceled the transfer.
*/
protected boolean sendData(Transmitter transmitter,
TransferDescription transferData, byte[] content, SubMonitor progress)
throws SarosCancellationException {
if (!transmitter.isSuitable(transferData.recipient))
return false;
try {
long startTime = System.nanoTime();
NetTransferMode mode = transmitter.send(transferData, content,
progress);
long duration = Math.max(0, System.nanoTime() - startTime) / 1000000;
transferModeDispatch.transferFinished(transferData.recipient, mode,
false, content.length, duration);
return true;
} catch (SarosCancellationException e) {
throw e; // Rethrow to circumvent the Exception catch below
} catch (CausedIOException e) {
log.error(Util.prefix(transferData.recipient) + "Failed to send "
+ transferData + " with " + transmitter.getName() + ":", e
.getCause());
} catch (Exception e) {
log.error(Util.prefix(transferData.recipient) + "Failed to send "
+ transferData + " with " + transmitter.getName() + ":", e);
// Try other transport methods
}
return false;
}
public static class TransferModeDispatch implements ITransferModeListener {
protected List<ITransferModeListener> listeners = new ArrayList<ITransferModeListener>();
public synchronized void add(ITransferModeListener listener) {
listeners.add(listener);
}
public synchronized void remove(ITransferModeListener listener) {
listeners.remove(listener);
}
public synchronized void clear() {
for (ITransferModeListener listener : listeners) {
listener.clear();
}
}
public synchronized void transferFinished(JID jid,
NetTransferMode newMode, boolean incoming, long size,
long transmissionMillisecs) {
for (ITransferModeListener listener : listeners) {
listener.transferFinished(jid, newMode, incoming, size,
transmissionMillisecs);
}
}
}
public void awaitJingleManager(JID jid) {
if (discoveryManager.isJingleSupported(jid)) {
getJingleManager();
}
}
public void prepareConnection(final XMPPConnection connection) {
// Create Containers
this.connection = connection;
this.fileTransferQueue = new ConcurrentLinkedQueue<TransferData>();
this.jingleManager.setValue(null);
Socks5ByteStreamManager socks5ByteStreamManager = Socks5ByteStreamManager
.getByteStreamManager(connection);
socks5ByteStreamManager.setTargetResponseTimeout(7000);
this.fileTransferManager = new FileTransferManager(connection);
this.fileTransferManager
.addFileTransferListener(new XMPPFileTransferListener());
if (!preferenceUtils.forceFileTranserByChat()) {
// Start Jingle Manager asynchronous
this.startingJingleThread = new Thread(new Runnable() {
/**
* @review runSafe OK
*/
public void run() {
try {
jingleManager
.setValue(new JingleFileTransferManager(saros,
connection, jingleListener, incomingExtProv));
log.debug("Jingle Manager started");
} catch (Exception e) {
if (saros.isConnected())
log.error("Jingle Manager could not be started", e);
else
log.debug("Jingle Manager could not be started,"
+ " because Saros was disconnected from"
+ " XMPP server.");
jingleManager.setValue(null);
}
}
});
this.startingJingleThread.start();
}
}
public enum NetTransferMode {
UNKNOWN("???", false), IBB("IBB", false), JINGLETCP("Jingle/TCP", true), JINGLEUDP(
"Jingle/UDP", true), HANDMADE("Chat", false);
String name;
boolean p2p;
NetTransferMode(String name, boolean p2p) {
this.name = name;
this.p2p = p2p;
}
@Override
public String toString() {
return name;
}
public boolean isP2P() {
return p2p;
}
}
/**
* @return the last TransferMode used when receiving a file from the given
* user or UNKNOWN if no file was received since the last
* connection-reset.
*/
public NetTransferMode getIncomingTransferMode(JID jid) {
NetTransferMode result = incomingTransferModes.get(jid);
if (result == null) {
return NetTransferMode.UNKNOWN;
} else {
return result;
}
}
/**
* @return the last TransferMode that was used to send a file to the given
* user or null if no file has been sent since the last
* connection-reset.
*/
public NetTransferMode getOutgoingTransferMode(JID jid) {
NetTransferMode result = outgoingTransferModes.get(jid);
if (result == null) {
return NetTransferMode.UNKNOWN;
} else {
return result;
}
}
public void disposeConnection() {
fileTransferQueue.clear();
transferModeDispatch.clear();
connection = null;
// If Jingle is still starting, wait for it...
if (startingJingleThread != null) {
try {
startingJingleThread.join();
} catch (InterruptedException e) {
log.error("Code not designed to be interruptable", e);
Thread.currentThread().interrupt();
return;
}
}
// Terminate all Jingle connections and notify everybody who used this
// JingleFileTransferManager
if (jingleManager.getValue() != null) {
jingleManager.getValue().terminateAllJingleSessions();
jingleManager.setValue(null);
}
fileTransferManager = null;
startingJingleThread = null;
}
public void startConnection() {
// TODO The data transfer manager does not support caching yet
}
public void stopConnection() {
// TODO The data transfer manager does not support caching yet
}
/**
* ------------------------------------------------------------------------
* Support for monitoring ongoing transfers
* ------------------------------------------------------------------------
*/
/**
* Returns just whether there is currently a file transfer being received
* from the given user.
*/
public boolean isReceiving(JID from) {
return getIncomingTransfers(from).size() > 0;
}
/**
* Returns a live copy of the file-transfers currently being received
*/
public List<TransferDescription> getIncomingTransfers(JID from) {
synchronized (incomingTransfers) {
List<TransferDescription> transfers = incomingTransfers.get(from);
if (transfers == null) {
transfers = new ArrayList<TransferDescription>();
incomingTransfers.put(from, transfers);
}
return transfers;
}
}
protected void removeIncomingFileTransfer(
TransferDescription transferDescription) {
synchronized (incomingTransfers) {
JID from = transferDescription.sender;
List<TransferDescription> transfers = getIncomingTransfers(from);
if (!transfers.remove(transferDescription)) {
log
.warn("Removing incoming transfer description that was never added!:"
+ transferDescription);
}
}
}
protected void addIncomingFileTransfer(
TransferDescription transferDescription) {
synchronized (incomingTransfers) {
JID from = transferDescription.sender;
List<TransferDescription> transfers = getIncomingTransfers(from);
transfers.add(transferDescription);
}
}
public TransferModeDispatch getTransferModeDispatch() {
return transferModeDispatch;
}
}
| true | true | public void fileTransferRequest(final FileTransferRequest request) {
final TransferDescription transferDescription;
try {
transferDescription = TransferDescription.fromBase64(request
.getDescription());
} catch (IOException e) {
log.error("Incoming File Transfer via IBB failed: ", e);
return;
}
final IncomingTransferObject transferObject = new IncomingTransferObject() {
/**
* @throws SarosCancellationException
* It will be thrown if the user (locally or
* remotely) has canceled the transfer.
*
* @throws IOException
* It will be thrown if the stream negotiation, the
* read from InputStream or the inflation failed
* during I/O operations or Timeout.
*/
public byte[] accept(SubMonitor monitor)
throws SarosCancellationException, IOException {
monitor.beginTask("Receive via IBB", 10000);
// TODO how to handle files larger than the max size of a
// byte array
IncomingFileTransfer accept = request.accept();
monitor.worked(100);
byte[] content;
InputStream in = null;
try {
if (monitor.isCanceled())
throw new LocalCancellationException();
in = accept.recieveFile();
monitor.worked(100);
content = Util.toByteArray(in, request.getFileSize(),
monitor.newChild(8000));
IOUtils.closeQuietly(in);
// File is meant to be empty
if (transferDescription.emptyFile) {
content = new byte[0];
}
if (transferDescription.compressInDataTransferManager())
content = Util.inflate(content, monitor
.newChild(1500));
} catch (LocalCancellationException e) {
log.info("Local monitor was cancelled.");
throw e;
} catch (IOException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
log.error("Incoming File Transfer via IBB failed: ", e);
throw e;
} catch (XMPPException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
Throwable tmp = e.getWrappedThrowable();
Exception cause = (tmp != null) ? (Exception) tmp : e;
if (cause instanceof InterruptedException) {
log.warn("Interrupted on IBB stream negotiation.");
} else if (e.getCause() instanceof TimeoutException) {
log
.warn("Timeout while waiting for incoming File ransfer via IBB.");
} else if (cause instanceof ExecutionException) {
// unwrap
Throwable t = cause.getCause();
if (t != null)
log.warn(t.getMessage(), t);
}
throw new IOException(
"Failed to negotiate Stream via IBB.");
}
monitor.worked(100);
monitor.done();
return content;
}
public TransferDescription getTransferDescription() {
return transferDescription;
}
public void reject() throws IOException {
request.reject();
}
public NetTransferMode getTransferMode() {
return NetTransferMode.IBB;
}
};
addIncomingTransferObject(transferObject);
}
| public void fileTransferRequest(final FileTransferRequest request) {
final TransferDescription transferDescription;
try {
transferDescription = TransferDescription.fromBase64(request
.getDescription());
} catch (IOException e) {
log.error("Incoming File Transfer via IBB failed: ", e);
request.reject(); // Reject (no way to tell remote user why)
return;
}
final IncomingTransferObject transferObject = new IncomingTransferObject() {
/**
* @throws SarosCancellationException
* It will be thrown if the user (locally or
* remotely) has canceled the transfer.
*
* @throws IOException
* It will be thrown if the stream negotiation, the
* read from InputStream or the inflation failed
* during I/O operations or Timeout.
*/
public byte[] accept(SubMonitor monitor)
throws SarosCancellationException, IOException {
monitor.beginTask("Receive via IBB", 10000);
// TODO how to handle files larger than the max size of a
// byte array
IncomingFileTransfer accept = request.accept();
monitor.worked(100);
byte[] content;
InputStream in = null;
try {
if (monitor.isCanceled())
throw new LocalCancellationException();
in = accept.recieveFile();
monitor.worked(100);
content = Util.toByteArray(in, request.getFileSize(),
monitor.newChild(8000));
IOUtils.closeQuietly(in);
// File is meant to be empty
if (transferDescription.emptyFile) {
content = new byte[0];
}
if (transferDescription.compressInDataTransferManager())
content = Util.inflate(content, monitor
.newChild(1500));
} catch (LocalCancellationException e) {
log.info("Local monitor was cancelled.");
throw e;
} catch (IOException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
log.error("Incoming File Transfer via IBB failed: ", e);
throw e;
} catch (XMPPException e) {
if (monitor.isCanceled())
throw new LocalCancellationException();
Throwable tmp = e.getWrappedThrowable();
Exception cause = (tmp != null) ? (Exception) tmp : e;
if (cause instanceof InterruptedException) {
log.warn("Interrupted on IBB stream negotiation.");
} else if (e.getCause() instanceof TimeoutException) {
log
.warn("Timeout while waiting for incoming File ransfer via IBB.");
} else if (cause instanceof ExecutionException) {
// unwrap
Throwable t = cause.getCause();
if (t != null)
log.warn(t.getMessage(), t);
}
throw new IOException(
"Failed to negotiate Stream via IBB.");
}
monitor.worked(100);
monitor.done();
return content;
}
public TransferDescription getTransferDescription() {
return transferDescription;
}
public void reject() throws IOException {
request.reject();
}
public NetTransferMode getTransferMode() {
return NetTransferMode.IBB;
}
};
addIncomingTransferObject(transferObject);
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
index b6d5938c..602eaec7 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
@@ -1,191 +1,192 @@
package uk.ac.ebi.fgpt.sampletab.sra;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.dom4j.DocumentException;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.fgpt.sampletab.utils.ConanUtils;
import uk.ac.ebi.fgpt.sampletab.utils.FileRecursiveIterable;
import uk.ac.ebi.fgpt.sampletab.utils.SampleTabUtils;
public class ENASRACron {
@Option(name = "--help", aliases = { "-h" }, usage = "display help")
private boolean help;
@Argument(required=true, index=0, metaVar="OUTPUT", usage = "output directory")
private String outputDirName;
@Option(name = "--threads", aliases = { "-t" }, usage = "number of additional threads")
private int threads = 0;
@Option(name = "--no-conan", usage = "do not trigger conan loads?")
private boolean noconan = false;
private Logger log = LoggerFactory.getLogger(getClass());
private ENASRACron() {
}
public static void main(String[] args) {
new ENASRACron().doMain(args);
}
public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) {
//TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
- File sampletabpre = new File(SampleTabUtils.getSubmissionDirFile(submissionID), "sampletab.pre.txt");
+ File sampletabpre = new File(outdir.toString(), SampleTabUtils.getSubmissionDirFile(submissionID).toString());
+ sampletabpre = new File(sampletabpre, "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
}
| true | true | public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) {
//TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
File sampletabpre = new File(SampleTabUtils.getSubmissionDirFile(submissionID), "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
| public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) {
//TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
File sampletabpre = new File(outdir.toString(), SampleTabUtils.getSubmissionDirFile(submissionID).toString());
sampletabpre = new File(sampletabpre, "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
|
diff --git a/lib/src/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java b/lib/src/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
index 398a4bd..ca07bbc 100644
--- a/lib/src/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
+++ b/lib/src/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
@@ -1,549 +1,549 @@
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Qbittorrent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.FilePart;
import com.android.internalcopy.http.multipart.MultipartEntity;
import com.android.internalcopy.http.multipart.Part;
/**
* The daemon adapter for the qBittorrent torrent client.
*
* @author erickok
*
*/
public class QbittorrentAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "qBittorrent daemon";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
private int version = -1;
public QbittorrentAdapter(DaemonSettings settings) {
this.settings = settings;
}
private void ensureVersion() throws DaemonException {
if (version > 0)
return;
// We still need to retrieve the version number from the server
// Do this by getting the web interface about page and trying to parse the version number
// Format is something like 'qBittorrent v2.9.7 (Web UI)'
String about = makeRequest("/about.html");
String aboutStartText = "qBittorrent v";
String aboutEndText = " (Web UI)";
int aboutStart = about.indexOf(aboutStartText);
int aboutEnd = about.indexOf(aboutEndText);
if (aboutStart >= 0 && aboutEnd > aboutStart) {
// String found: now parse a version like 2.9.7 as a number like 20907 (allowing 10 places for each .)
String[] parts = about.substring(aboutStart + aboutStartText.length(), aboutEnd).split("\\.");
if (parts.length > 0) {
version = Integer.parseInt(parts[0]) * 100 * 100;
if (parts.length > 1) {
version += Integer.parseInt(parts[1]) * 100;
if (parts.length > 2) {
version += Integer.parseInt(parts[2]);
return;
}
}
}
}
// Unable to establish version number; assume an old version by setting it to version 1
version = 10000;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
ensureVersion();
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
- JSONArray result = new JSONArray(makeRequest(version > 30000? "/json/torrents": "/json/events"));
+ JSONArray result = new JSONArray(makeRequest(version >= 30000? "/json/torrents": "/json/events"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result),null);
case GetTorrentDetails:
// Request tracker and error details for a specific teacher
String mhash = ((GetTorrentDetailsTask)task).getTargetTorrent().getUniqueID();
JSONArray messages = new JSONArray(makeRequest("/json/propertiesTrackers/" + mhash));
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(messages));
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
JSONArray files = new JSONArray(makeRequest("/json/propertiesFiles/" + fhash));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeUploadRequest("/command/upload", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", url));
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a magnet link by URL
String magnet = ((AddByMagnetUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", magnet));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest((removeTask.includingData()? "/command/deletePerm": "/command/delete"), new BasicNameValuePair("hashes", removeTask.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeRequest("/command/pauseall");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeRequest("/command/resumeall");
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
// Update the priorities to a set of files
SetFilePriorityTask setPrio = (SetFilePriorityTask) task;
String newPrio = "0";
if (setPrio.getNewPriority() == Priority.Low) {
newPrio = "1";
} else if (setPrio.getNewPriority() == Priority.Normal) {
newPrio = "2";
} else if (setPrio.getNewPriority() == Priority.High) {
newPrio = "7";
}
// We have to make a separate request per file, it seems
for (TorrentFile file : setPrio.getForFiles()) {
makeRequest("/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("id", file.getKey()), new BasicNameValuePair("priority", newPrio));
}
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// TODO: This doesn't seem to work yet
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
int dl = (ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue());
int ul = (ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue());
// First get the preferences
JSONObject prefs = new JSONObject(makeRequest("/json/preferences"));
prefs.put("dl_limit", dl);
prefs.put("up_limit", ul);
makeRequest("/command/setPreferences", new BasicNameValuePair("json", URLEncoder.encode(prefs.toString(), HTTP.UTF_8)));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (UnsupportedEncodingException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
}
}
private String makeRequest(String path, NameValuePair... params) throws DaemonException {
try {
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (NameValuePair param : params) {
nvps.add(param);
}
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
return makeWebRequest(path, httppost);
} catch (UnsupportedEncodingException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private String makeUploadRequest(String path, String file) throws DaemonException {
try {
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
File upload = new File(URI.create(file));
Part[] parts = { new FilePart("torrentfile", upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
return makeWebRequest(path, httppost);
} catch (FileNotFoundException e) {
throw new DaemonException(ExceptionType.FileAccessError, e.toString());
}
}
private String makeWebRequest(String path, HttpPost httppost) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Execute
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
//TLog.d(LOG_NAME, "Success: " + (result.length() > 300? result.substring(0, 300) + "... (" + result.length() + " chars)": result));
// Return raw result
return result;
}
DLog.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all qBittorrent requests.
* @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
/*httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
for (Header header : request.getAllHeaders()) {
TLog.d(LOG_NAME, "Request: " + header.getName() + ": " + header.getValue());
}
}
});*/
}
/**
* Build the URL of the web UI request from the user settings
* @return The URL to request
*/
private String buildWebUIUrl(String path) {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + path;
}
private TorrentDetails parseJsonTorrentDetails(JSONArray messages) throws JSONException {
ArrayList<String> trackers = new ArrayList<String>();
ArrayList<String> errors = new ArrayList<String>();
// Parse response
if (messages.length() > 0) {
for (int i = 0; i < messages.length(); i++) {
JSONObject tor = messages.getJSONObject(i);
trackers.add(tor.getString("url"));
String msg = tor.getString("msg");
if (msg != null && !msg.equals(""))
errors.add(msg);
}
}
// Return the list
return new TorrentDetails(trackers, errors);
}
private ArrayList<Torrent> parseJsonTorrents(JSONArray response) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
for (int i = 0; i < response.length(); i++) {
JSONObject tor = response.getJSONObject(i);
int leechers = parseLeech(tor.getString("num_leechs"));
int seeders = parseSeeds(tor.getString("num_seeds"));
int known = parseKnown(tor.getString("num_leechs"), tor.getString("num_seeds"));
long size = parseSize(tor.getString("size"));
double ratio = parseRatio(tor.getString("ratio"));
double progress = tor.getDouble("progress");
int dlspeed = parseSpeed(tor.getString("dlspeed"));
// Add the parsed torrent to the list
torrents.add(new Torrent(
(long)i,
tor.getString("hash"),
tor.getString("name"),
parseStatus(tor.getString("state")),
null,
dlspeed,
parseSpeed(tor.getString("upspeed")),
leechers,
leechers + seeders,
known,
known,
(int) ((size - (size * progress)) / dlspeed),
(long)(size * progress),
(long)(size * ratio),
size,
(float)progress,
0f,
null,
null,
null));
}
// Return the list
return torrents;
}
private double parseRatio(String string) {
// Ratio is given in "1.5" string format
try {
return Double.parseDouble(string);
} catch (Exception e) {
return 0D;
}
}
private long parseSize(String string) {
// Sizes are given in "703.3 MiB" string format
// Returns size in B-based long
String[] parts = string.split(" ");
if (parts[1].equals("GiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L * 1024L * 1024L);
} else if (parts[1].equals("MiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L * 1024L);
} else if (parts[1].equals("KiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L);
}
return (long) (Double.parseDouble(parts[0]));
}
private int parseKnown(String leechs, String seeds) {
// Peers are given in the "num_leechs":"91 (449)","num_seeds":"6 (27)" strings
// Or sometimes just "num_leechs":"91","num_seeds":"6" strings
// Peers known are in the last () bit of the leechers and seeders
int leechers = 0;
if (leechs.indexOf("(") < 0) {
leechers = Integer.parseInt(leechs);
} else {
leechers = Integer.parseInt(leechs.substring(leechs.indexOf("(") + 1, leechs.indexOf(")")));
}
int seeders = 0;
if (seeds.indexOf("(") < 0) {
seeders = Integer.parseInt(seeds);
} else {
seeders = Integer.parseInt(seeds.substring(seeds.indexOf("(") + 1, seeds.indexOf(")")));
}
return leechers + seeders;
}
private int parseSeeds(String seeds) {
// Seeds are in the first part of the "num_seeds":"6 (27)" string
// In some situations it it just a "6" string
if (seeds.indexOf(" ") < 0) {
return Integer.parseInt(seeds);
}
return Integer.parseInt(seeds.substring(0, seeds.indexOf(" ")));
}
private int parseLeech(String leechs) {
// Leechers are in the first part of the "num_leechs":"91 (449)" string
// In some situations it it just a "0" string
if (leechs.indexOf(" ") < 0) {
return Integer.parseInt(leechs);
}
return Integer.parseInt(leechs.substring(0, leechs.indexOf(" ")));
}
private int parseSpeed(String speed) {
// Speeds are in "21.9 KiB/s" string format
// Returns speed in B/s-based integer
String[] parts = speed.split(" ");
if (parts[1].equals("GiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024 * 1024 * 1024);
} else if (parts[1].equals("MiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024 * 1024);
} else if (parts[1].equals("KiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024);
}
return (int) (Double.parseDouble(parts[0]));
}
private TorrentStatus parseStatus(String state) {
// Status is given as a descriptive string
if (state.equals("downloading")) {
return TorrentStatus.Downloading;
} else if (state.equals("uploading")) {
return TorrentStatus.Seeding;
} else if (state.equals("pausedDL")) {
return TorrentStatus.Paused;
} else if (state.equals("pausedUL")) {
return TorrentStatus.Paused;
} else if (state.equals("stalledUP")) {
return TorrentStatus.Seeding;
} else if (state.equals("stalledDL")) {
return TorrentStatus.Downloading;
} else if (state.equals("checkingUP")) {
return TorrentStatus.Checking;
} else if (state.equals("checkingDL")) {
return TorrentStatus.Checking;
} else if (state.equals("queuedDL")) {
return TorrentStatus.Queued;
} else if (state.equals("queuedUL")) {
return TorrentStatus.Queued;
}
return TorrentStatus.Unknown;
}
private ArrayList<TorrentFile> parseJsonFiles(JSONArray response) throws JSONException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
for (int i = 0; i < response.length(); i++) {
JSONObject file = response.getJSONObject(i);
long size = parseSize(file.getString("size"));
torrentfiles.add(new TorrentFile(
"" + i,
file.getString("name"),
null,
null,
size,
(long) (size * file.getDouble("progress")),
parsePriority(file.getInt("priority"))));
}
// Return the list
return torrentfiles;
}
private Priority parsePriority(int priority) {
// Priority is an integer
// Actually 1 = Normal, 2 = High, 7 = Maximum, but adjust this to Transdroid values
if (priority == 0) {
return Priority.Off;
} else if (priority == 1) {
return Priority.Low;
} else if (priority == 2) {
return Priority.Normal;
}
return Priority.High;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| true | true | public DaemonTaskResult executeTask(DaemonTask task) {
try {
ensureVersion();
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONArray result = new JSONArray(makeRequest(version > 30000? "/json/torrents": "/json/events"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result),null);
case GetTorrentDetails:
// Request tracker and error details for a specific teacher
String mhash = ((GetTorrentDetailsTask)task).getTargetTorrent().getUniqueID();
JSONArray messages = new JSONArray(makeRequest("/json/propertiesTrackers/" + mhash));
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(messages));
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
JSONArray files = new JSONArray(makeRequest("/json/propertiesFiles/" + fhash));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeUploadRequest("/command/upload", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", url));
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a magnet link by URL
String magnet = ((AddByMagnetUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", magnet));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest((removeTask.includingData()? "/command/deletePerm": "/command/delete"), new BasicNameValuePair("hashes", removeTask.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeRequest("/command/pauseall");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeRequest("/command/resumeall");
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
// Update the priorities to a set of files
SetFilePriorityTask setPrio = (SetFilePriorityTask) task;
String newPrio = "0";
if (setPrio.getNewPriority() == Priority.Low) {
newPrio = "1";
} else if (setPrio.getNewPriority() == Priority.Normal) {
newPrio = "2";
} else if (setPrio.getNewPriority() == Priority.High) {
newPrio = "7";
}
// We have to make a separate request per file, it seems
for (TorrentFile file : setPrio.getForFiles()) {
makeRequest("/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("id", file.getKey()), new BasicNameValuePair("priority", newPrio));
}
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// TODO: This doesn't seem to work yet
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
int dl = (ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue());
int ul = (ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue());
// First get the preferences
JSONObject prefs = new JSONObject(makeRequest("/json/preferences"));
prefs.put("dl_limit", dl);
prefs.put("up_limit", ul);
makeRequest("/command/setPreferences", new BasicNameValuePair("json", URLEncoder.encode(prefs.toString(), HTTP.UTF_8)));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (UnsupportedEncodingException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
}
}
| public DaemonTaskResult executeTask(DaemonTask task) {
try {
ensureVersion();
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONArray result = new JSONArray(makeRequest(version >= 30000? "/json/torrents": "/json/events"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result),null);
case GetTorrentDetails:
// Request tracker and error details for a specific teacher
String mhash = ((GetTorrentDetailsTask)task).getTargetTorrent().getUniqueID();
JSONArray messages = new JSONArray(makeRequest("/json/propertiesTrackers/" + mhash));
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(messages));
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
JSONArray files = new JSONArray(makeRequest("/json/propertiesFiles/" + fhash));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeUploadRequest("/command/upload", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", url));
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a magnet link by URL
String magnet = ((AddByMagnetUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", magnet));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest((removeTask.includingData()? "/command/deletePerm": "/command/delete"), new BasicNameValuePair("hashes", removeTask.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeRequest("/command/pauseall");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeRequest("/command/resumeall");
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
// Update the priorities to a set of files
SetFilePriorityTask setPrio = (SetFilePriorityTask) task;
String newPrio = "0";
if (setPrio.getNewPriority() == Priority.Low) {
newPrio = "1";
} else if (setPrio.getNewPriority() == Priority.Normal) {
newPrio = "2";
} else if (setPrio.getNewPriority() == Priority.High) {
newPrio = "7";
}
// We have to make a separate request per file, it seems
for (TorrentFile file : setPrio.getForFiles()) {
makeRequest("/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("id", file.getKey()), new BasicNameValuePair("priority", newPrio));
}
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// TODO: This doesn't seem to work yet
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
int dl = (ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue());
int ul = (ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue());
// First get the preferences
JSONObject prefs = new JSONObject(makeRequest("/json/preferences"));
prefs.put("dl_limit", dl);
prefs.put("up_limit", ul);
makeRequest("/command/setPreferences", new BasicNameValuePair("json", URLEncoder.encode(prefs.toString(), HTTP.UTF_8)));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (UnsupportedEncodingException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
}
}
|
diff --git a/src/main/java/org/atlasapi/tracking/BuzzMessageQueueProbe.java b/src/main/java/org/atlasapi/tracking/BuzzMessageQueueProbe.java
index be3607a02..e7365919b 100644
--- a/src/main/java/org/atlasapi/tracking/BuzzMessageQueueProbe.java
+++ b/src/main/java/org/atlasapi/tracking/BuzzMessageQueueProbe.java
@@ -1,28 +1,28 @@
package org.atlasapi.tracking;
import org.atlasapi.tracking.twitter.QueueingTweetProcessor;
import com.metabroadcast.common.webapp.health.HealthProbe;
import com.metabroadcast.common.webapp.health.ProbeResult;
public class BuzzMessageQueueProbe implements HealthProbe {
private final QueueingTweetProcessor queue;
public BuzzMessageQueueProbe(QueueingTweetProcessor queue) {
this.queue = queue;
}
@Override
public ProbeResult probe() {
ProbeResult result = new ProbeResult(title());
result.addInfo("queue size", queue.queueSize() + " messages");
- result.addInfo("active threads", queue.queueSize() + " threads");
+ result.addInfo("active threads", queue.activeThreads() + " threads");
return result;
}
@Override
public String title() {
return "Tweet queue";
}
}
| true | true | public ProbeResult probe() {
ProbeResult result = new ProbeResult(title());
result.addInfo("queue size", queue.queueSize() + " messages");
result.addInfo("active threads", queue.queueSize() + " threads");
return result;
}
| public ProbeResult probe() {
ProbeResult result = new ProbeResult(title());
result.addInfo("queue size", queue.queueSize() + " messages");
result.addInfo("active threads", queue.activeThreads() + " threads");
return result;
}
|
diff --git a/xtend.website.generator/xtend-gen/generator/xtend/Index.java b/xtend.website.generator/xtend-gen/generator/xtend/Index.java
index 2660b9048..d9d4d0f43 100644
--- a/xtend.website.generator/xtend-gen/generator/xtend/Index.java
+++ b/xtend.website.generator/xtend-gen/generator/xtend/Index.java
@@ -1,535 +1,535 @@
package generator.xtend;
import generator.xtend.AbstractXtendWebsite;
import org.eclipse.xtend2.lib.StringConcatenation;
@SuppressWarnings("all")
public class Index extends AbstractXtendWebsite {
public String path() {
return "index.html";
}
protected boolean isPrettyPrint() {
return true;
}
public CharSequence contents() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("<!--Container-->");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"header_wrapper\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\"> ");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"flexslider image-slider\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span5 slide\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<h2>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("It\'s just Java");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</h2>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<p>Xtend is a little language that compiles ");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("into idiomatic Java source code. ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("You can use any existing Java library seamlessly ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("from Xtend (and vice-versa). The compiled output is readable ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("and pretty-printed, and tends to run as fast or faster than the equivalent");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("handwritten Java code.</p>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<a href=\"download.html\" class=\"btn_download\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<a href=\"documentation.html\" class=\"btn_documentation\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span6\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<div class=\"introduction\">");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"#\"><img src=\"images/title-screenshot.png\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("alt=\"Xtend Screencast\" style=\"margin:40pt;\"/></a> ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"http://vimeo.com/31248257\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("data-rel=\"prettyPhoto\" title=\"Introduction\" class=\"zoom zoom_icon\"></a>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"intro\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<h1>What is Xtend?</h1>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is a statically-typed programming language which <strong>compiles to comprehensible Java source code</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>It is designed to work great with existing Java APIs and idioms, yet introduces new features to modernize Java applications.");
_builder.newLine();
_builder.append("\t\t");
_builder.append("It\'s <strong>faster than Groovy</strong>, <strong>simpler than Scala</strong> and incorporates all <strong>benefits of Java</strong> such as <strong>great tool support</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is implemented on top of <a href=\"http://xtext.org\" style=\" color : white; \">Xtext</a></p>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"features\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"row\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span12\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br /> <br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<h1>6 Good Reasons to use Xtend</h1>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("<p>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("Xtend removes all the unnecessary syntactical noise: No semicolons, ");
_builder_1.newLine();
_builder_1.append("\t");
- _builder_1.append("no empty parenthesis, good default visibility.<br/><br/>");
+ _builder_1.append("no empty parentheses, good default visibility.<br/><br/>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("<strong>Whitespace can be so beautiful!</strong>");
_builder_1.newLine();
_builder_1.append("</p>");
_builder_1.newLine();
CharSequence _entry = this.entry("Less Noise", _builder_1.toString(),
"images/icon-noise.png",
"http://vimeo.com/12824833");
_builder.append(_entry, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_2 = new StringConcatenation();
_builder_2.append("<p>");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Learn how to enhance existing Java APIs through <a href=\"documentation.html#extensionMethods\">extension methods</a> and <a href=\"documentation.html#lambdas\">lambda expressions</a>.");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Make use of <a href=\"documentation.html#operators\">operators</a> where you always wanted and <a href=\"documentation.html#switchExpression\">get rid of lengthy instanceof / casting orgies</a> in");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("your existing code.");
_builder_2.newLine();
_builder_2.append("</p>");
_builder_2.newLine();
CharSequence _entry_1 = this.entry("More Power", _builder_2.toString(),
"images/icon-expressive.png",
"http://vimeo.com/12824833");
_builder.append(_entry_1, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_3 = new StringConcatenation();
_builder_3.append("<p>");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("Unlike <strong>all</strong> other JVM-languages, Xtend resembles Java\'s type system without any compromises");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("or cheap short-cuts. This guarantees that <strong>you won\'t run into any interoperability caveats</strong>. Integration with Java");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("works as expected in both directions and the generated code runs as fast as or faster than hand-written Java.");
_builder_3.newLine();
_builder_3.append("</p>");
_builder_3.newLine();
CharSequence _entry_2 = this.entry("100% Java Compatible", _builder_3.toString(),
"images/icon_interop.png",
"http://vimeo.com/12824833");
_builder.append(_entry_2, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_4 = new StringConcatenation();
_builder_4.append("<p>");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("Static typing is not only important for early error detection but even more so for top-notch IDE support.");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("To ensure a great and holistic user experience, the IDE and the language has been designed side by side. And of course");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("the tools integrate tightly with Eclipse\'s existing Java IDE.");
_builder_4.newLine();
_builder_4.append("</p>");
_builder_4.newLine();
CharSequence _entry_3 = this.entry("Better Tooling", _builder_4.toString(),
"images/icon-tools.png",
"http://vimeo.com/12824833");
_builder.append(_entry_3, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_5 = new StringConcatenation();
_builder_5.append("<p>");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Xtend leverages existing Java concepts and adds modern language features on top.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Unlike other JVM-Languages like Scala, Xtend doesn\'t add a whole new type system because this");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("would cause interoperability issues and make the language harder to learn for Java developers.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("If you know Java you already know most of Xtend. ");
_builder_5.newLine();
_builder_5.append("</p>");
_builder_5.newLine();
CharSequence _entry_4 = this.entry("Easy to Learn", _builder_5.toString(),
"images/icon_simple.png",
"http://vimeo.com/12824833");
_builder.append(_entry_4, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_6 = new StringConcatenation();
_builder_6.append("<p>");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("Xtend not only resembles the type system to ensure 100% interoperability, it also generates comprehensible Java source code.");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("This not only allows to run the code on platforms such as GWT, which doesn\'t understand bytecode, but also lets you see how certain language");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("constructs are translated to idiomatic Java source code.");
_builder_6.newLine();
_builder_6.append("</p>");
_builder_6.newLine();
CharSequence _entry_5 = this.entry("Still Java", _builder_6.toString(),
"images/icon-java.png",
"http://vimeo.com/12824833");
_builder.append(_entry_5, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
return _builder;
}
public CharSequence comparison() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("<div id=\"comparison\">");
_builder.newLine();
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"span12\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<br/> <br/>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<h1 align=\"center\">Code Comparison</h1>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<br/>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("<table class=\"span12 table table-striped\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<thead>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<tr>");
_builder.newLine();
_builder.append("\t\t\t ");
_builder.append("<th style=\"width:20%;\"></th>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<th style=\"width:40%;\">");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<h2 style=\"text-align:center;\">Xtend</h2>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("</th>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<th style=\"width:40%;\">");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<h2 style=\"text-align:center;\">Java</h2>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("</th>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</tr>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("</thead>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<tbody>");
_builder.newLine();
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("myStrings.filter[ length > 5 ]");
_builder_1.newLine();
StringConcatenation _builder_2 = new StringConcatenation();
_builder_2.append("Iterables.filter(myStrings, new Predicate<String>() {");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("public boolean apply(String it) {");
_builder_2.newLine();
_builder_2.append("\t\t");
_builder_2.append("return it.length() > 5;");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("}");
_builder_2.newLine();
_builder_2.append("});");
_builder_2.newLine();
CharSequence _compare = this.compare("Google Guava", _builder_1.toString(), _builder_2.toString());
_builder.append(_compare, "");
_builder.newLineIfNotEmpty();
StringConcatenation _builder_3 = new StringConcatenation();
_builder_3.append("myStrings.filter[ length > 5 ]");
_builder_3.newLine();
StringConcatenation _builder_4 = new StringConcatenation();
_builder_4.append("Iterables.filter(myStrings, new Predicate<String>() {");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("public boolean apply(String it) {");
_builder_4.newLine();
_builder_4.append("\t\t");
_builder_4.append("return it.length() > 5;");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("}");
_builder_4.newLine();
_builder_4.append("}");
_builder_4.newLine();
CharSequence _compare_1 = this.compare("Java FX", _builder_3.toString(), _builder_4.toString());
_builder.append(_compare_1, "");
_builder.newLineIfNotEmpty();
StringConcatenation _builder_5 = new StringConcatenation();
_builder_5.append("myStrings.filter[ length > 5 ]");
_builder_5.newLine();
StringConcatenation _builder_6 = new StringConcatenation();
_builder_6.append("Iterables.filter(myStrings, new Predicate<String>() {");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("public boolean apply(String it) {");
_builder_6.newLine();
_builder_6.append("\t\t");
_builder_6.append("return it.length() > 5;");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("}");
_builder_6.newLine();
_builder_6.append("}");
_builder_6.newLine();
CharSequence _compare_2 = this.compare("Android", _builder_5.toString(), _builder_6.toString());
_builder.append(_compare_2, "");
_builder.newLineIfNotEmpty();
StringConcatenation _builder_7 = new StringConcatenation();
_builder_7.append("myStrings.filter[ length > 5 ]");
_builder_7.newLine();
StringConcatenation _builder_8 = new StringConcatenation();
_builder_8.append("Iterables.filter(myStrings, new Predicate<String>() {");
_builder_8.newLine();
_builder_8.append("\t");
_builder_8.append("public boolean apply(String it) {");
_builder_8.newLine();
_builder_8.append("\t\t");
_builder_8.append("return it.length() > 5;");
_builder_8.newLine();
_builder_8.append("\t");
_builder_8.append("}");
_builder_8.newLine();
_builder_8.append("}");
_builder_8.newLine();
CharSequence _compare_3 = this.compare("GWT", _builder_7.toString(), _builder_8.toString());
_builder.append(_compare_3, "");
_builder.newLineIfNotEmpty();
StringConcatenation _builder_9 = new StringConcatenation();
_builder_9.append("myStrings.filter[ length > 5 ]");
_builder_9.newLine();
StringConcatenation _builder_10 = new StringConcatenation();
_builder_10.append("Iterables.filter(myStrings, new Predicate<String>() {");
_builder_10.newLine();
_builder_10.append("\t");
_builder_10.append("public boolean apply(String it) {");
_builder_10.newLine();
_builder_10.append("\t\t");
_builder_10.append("return it.length() > 5;");
_builder_10.newLine();
_builder_10.append("\t");
_builder_10.append("}");
_builder_10.newLine();
_builder_10.append("});");
_builder_10.newLine();
CharSequence _compare_4 = this.compare("Java EE", _builder_9.toString(), _builder_10.toString());
_builder.append(_compare_4, "");
_builder.newLineIfNotEmpty();
_builder.append("\t");
_builder.append("</tbody>");
_builder.newLine();
_builder.append("\t");
_builder.append("</table>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
return _builder;
}
public CharSequence compare(final String framework, final String xtendCode, final String javaCode) {
StringConcatenation _builder = new StringConcatenation();
_builder.newLine();
_builder.append("\t");
_builder.append("<tr>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<td><h2>");
_builder.append(framework, " ");
_builder.append("</h2></td>");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
_builder.append("<td class=\"code\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<pre class=\"prettyprint lang-Xtend\" >");
_builder.newLine();
String _trim = xtendCode.trim();
_builder.append(_trim, "");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
_builder.append("</pre>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("</td>");
_builder.newLine();
_builder.append("\t \t");
_builder.append("<td class=\"code\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<pre class=\"prettyprint lang-Java\" >");
_builder.newLine();
String _trim_1 = javaCode.trim();
_builder.append(_trim_1, "");
_builder.append("</pre>");
_builder.newLineIfNotEmpty();
_builder.append("\t \t");
_builder.append("</td>");
_builder.newLine();
_builder.append("\t");
_builder.append("</tr>");
_builder.newLine();
return _builder;
}
public CharSequence entry(final String title, final String description, final String imgSrc, final String imgRef) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("<div class=\"span6 float\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"thumb\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<img class=\"screenshot\"");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("src=\"");
_builder.append(imgSrc, " ");
_builder.append("\" alt=\"Image\" />");
_builder.newLineIfNotEmpty();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("<h4>");
_builder.append(title, " ");
_builder.append("</h4>");
_builder.newLineIfNotEmpty();
_builder.append("\t");
_builder.append(description, " ");
_builder.newLineIfNotEmpty();
_builder.append("</div>");
_builder.newLine();
return _builder;
}
}
| true | true | public CharSequence contents() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("<!--Container-->");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"header_wrapper\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\"> ");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"flexslider image-slider\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span5 slide\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<h2>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("It\'s just Java");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</h2>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<p>Xtend is a little language that compiles ");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("into idiomatic Java source code. ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("You can use any existing Java library seamlessly ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("from Xtend (and vice-versa). The compiled output is readable ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("and pretty-printed, and tends to run as fast or faster than the equivalent");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("handwritten Java code.</p>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<a href=\"download.html\" class=\"btn_download\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<a href=\"documentation.html\" class=\"btn_documentation\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span6\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<div class=\"introduction\">");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"#\"><img src=\"images/title-screenshot.png\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("alt=\"Xtend Screencast\" style=\"margin:40pt;\"/></a> ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"http://vimeo.com/31248257\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("data-rel=\"prettyPhoto\" title=\"Introduction\" class=\"zoom zoom_icon\"></a>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"intro\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<h1>What is Xtend?</h1>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is a statically-typed programming language which <strong>compiles to comprehensible Java source code</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>It is designed to work great with existing Java APIs and idioms, yet introduces new features to modernize Java applications.");
_builder.newLine();
_builder.append("\t\t");
_builder.append("It\'s <strong>faster than Groovy</strong>, <strong>simpler than Scala</strong> and incorporates all <strong>benefits of Java</strong> such as <strong>great tool support</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is implemented on top of <a href=\"http://xtext.org\" style=\" color : white; \">Xtext</a></p>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"features\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"row\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span12\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br /> <br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<h1>6 Good Reasons to use Xtend</h1>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("<p>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("Xtend removes all the unnecessary syntactical noise: No semicolons, ");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("no empty parenthesis, good default visibility.<br/><br/>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("<strong>Whitespace can be so beautiful!</strong>");
_builder_1.newLine();
_builder_1.append("</p>");
_builder_1.newLine();
CharSequence _entry = this.entry("Less Noise", _builder_1.toString(),
"images/icon-noise.png",
"http://vimeo.com/12824833");
_builder.append(_entry, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_2 = new StringConcatenation();
_builder_2.append("<p>");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Learn how to enhance existing Java APIs through <a href=\"documentation.html#extensionMethods\">extension methods</a> and <a href=\"documentation.html#lambdas\">lambda expressions</a>.");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Make use of <a href=\"documentation.html#operators\">operators</a> where you always wanted and <a href=\"documentation.html#switchExpression\">get rid of lengthy instanceof / casting orgies</a> in");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("your existing code.");
_builder_2.newLine();
_builder_2.append("</p>");
_builder_2.newLine();
CharSequence _entry_1 = this.entry("More Power", _builder_2.toString(),
"images/icon-expressive.png",
"http://vimeo.com/12824833");
_builder.append(_entry_1, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_3 = new StringConcatenation();
_builder_3.append("<p>");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("Unlike <strong>all</strong> other JVM-languages, Xtend resembles Java\'s type system without any compromises");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("or cheap short-cuts. This guarantees that <strong>you won\'t run into any interoperability caveats</strong>. Integration with Java");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("works as expected in both directions and the generated code runs as fast as or faster than hand-written Java.");
_builder_3.newLine();
_builder_3.append("</p>");
_builder_3.newLine();
CharSequence _entry_2 = this.entry("100% Java Compatible", _builder_3.toString(),
"images/icon_interop.png",
"http://vimeo.com/12824833");
_builder.append(_entry_2, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_4 = new StringConcatenation();
_builder_4.append("<p>");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("Static typing is not only important for early error detection but even more so for top-notch IDE support.");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("To ensure a great and holistic user experience, the IDE and the language has been designed side by side. And of course");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("the tools integrate tightly with Eclipse\'s existing Java IDE.");
_builder_4.newLine();
_builder_4.append("</p>");
_builder_4.newLine();
CharSequence _entry_3 = this.entry("Better Tooling", _builder_4.toString(),
"images/icon-tools.png",
"http://vimeo.com/12824833");
_builder.append(_entry_3, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_5 = new StringConcatenation();
_builder_5.append("<p>");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Xtend leverages existing Java concepts and adds modern language features on top.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Unlike other JVM-Languages like Scala, Xtend doesn\'t add a whole new type system because this");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("would cause interoperability issues and make the language harder to learn for Java developers.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("If you know Java you already know most of Xtend. ");
_builder_5.newLine();
_builder_5.append("</p>");
_builder_5.newLine();
CharSequence _entry_4 = this.entry("Easy to Learn", _builder_5.toString(),
"images/icon_simple.png",
"http://vimeo.com/12824833");
_builder.append(_entry_4, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_6 = new StringConcatenation();
_builder_6.append("<p>");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("Xtend not only resembles the type system to ensure 100% interoperability, it also generates comprehensible Java source code.");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("This not only allows to run the code on platforms such as GWT, which doesn\'t understand bytecode, but also lets you see how certain language");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("constructs are translated to idiomatic Java source code.");
_builder_6.newLine();
_builder_6.append("</p>");
_builder_6.newLine();
CharSequence _entry_5 = this.entry("Still Java", _builder_6.toString(),
"images/icon-java.png",
"http://vimeo.com/12824833");
_builder.append(_entry_5, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
return _builder;
}
| public CharSequence contents() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("<!--Container-->");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"header_wrapper\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\"> ");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"flexslider image-slider\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span5 slide\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<h2>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("It\'s just Java");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</h2>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<p>Xtend is a little language that compiles ");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("into idiomatic Java source code. ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("You can use any existing Java library seamlessly ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("from Xtend (and vice-versa). The compiled output is readable ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("and pretty-printed, and tends to run as fast or faster than the equivalent");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("handwritten Java code.</p>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<a href=\"download.html\" class=\"btn_download\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<a href=\"documentation.html\" class=\"btn_documentation\"></a>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span6\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<div class=\"introduction\">");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"#\"><img src=\"images/title-screenshot.png\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("alt=\"Xtend Screencast\" style=\"margin:40pt;\"/></a> ");
_builder.newLine();
_builder.append("\t\t\t\t\t");
_builder.append("<a href=\"http://vimeo.com/31248257\"");
_builder.newLine();
_builder.append("\t\t\t\t\t\t");
_builder.append("data-rel=\"prettyPhoto\" title=\"Introduction\" class=\"zoom zoom_icon\"></a>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"intro\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<h1>What is Xtend?</h1>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is a statically-typed programming language which <strong>compiles to comprehensible Java source code</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>It is designed to work great with existing Java APIs and idioms, yet introduces new features to modernize Java applications.");
_builder.newLine();
_builder.append("\t\t");
_builder.append("It\'s <strong>faster than Groovy</strong>, <strong>simpler than Scala</strong> and incorporates all <strong>benefits of Java</strong> such as <strong>great tool support</strong>.</p>");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<p>Xtend is implemented on top of <a href=\"http://xtext.org\" style=\" color : white; \">Xtext</a></p>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
_builder.newLine();
_builder.append("<div id=\"features\">");
_builder.newLine();
_builder.append("\t");
_builder.append("<div class=\"container\">");
_builder.newLine();
_builder.append("\t\t");
_builder.append("<div class=\"row\">");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("<div class=\"span12\">");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br /> <br />");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<h1>6 Good Reasons to use Xtend</h1>");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("<br />");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t\t\t");
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("<p>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("Xtend removes all the unnecessary syntactical noise: No semicolons, ");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("no empty parentheses, good default visibility.<br/><br/>");
_builder_1.newLine();
_builder_1.append("\t");
_builder_1.append("<strong>Whitespace can be so beautiful!</strong>");
_builder_1.newLine();
_builder_1.append("</p>");
_builder_1.newLine();
CharSequence _entry = this.entry("Less Noise", _builder_1.toString(),
"images/icon-noise.png",
"http://vimeo.com/12824833");
_builder.append(_entry, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_2 = new StringConcatenation();
_builder_2.append("<p>");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Learn how to enhance existing Java APIs through <a href=\"documentation.html#extensionMethods\">extension methods</a> and <a href=\"documentation.html#lambdas\">lambda expressions</a>.");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("Make use of <a href=\"documentation.html#operators\">operators</a> where you always wanted and <a href=\"documentation.html#switchExpression\">get rid of lengthy instanceof / casting orgies</a> in");
_builder_2.newLine();
_builder_2.append("\t");
_builder_2.append("your existing code.");
_builder_2.newLine();
_builder_2.append("</p>");
_builder_2.newLine();
CharSequence _entry_1 = this.entry("More Power", _builder_2.toString(),
"images/icon-expressive.png",
"http://vimeo.com/12824833");
_builder.append(_entry_1, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_3 = new StringConcatenation();
_builder_3.append("<p>");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("Unlike <strong>all</strong> other JVM-languages, Xtend resembles Java\'s type system without any compromises");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("or cheap short-cuts. This guarantees that <strong>you won\'t run into any interoperability caveats</strong>. Integration with Java");
_builder_3.newLine();
_builder_3.append("\t");
_builder_3.append("works as expected in both directions and the generated code runs as fast as or faster than hand-written Java.");
_builder_3.newLine();
_builder_3.append("</p>");
_builder_3.newLine();
CharSequence _entry_2 = this.entry("100% Java Compatible", _builder_3.toString(),
"images/icon_interop.png",
"http://vimeo.com/12824833");
_builder.append(_entry_2, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_4 = new StringConcatenation();
_builder_4.append("<p>");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("Static typing is not only important for early error detection but even more so for top-notch IDE support.");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("To ensure a great and holistic user experience, the IDE and the language has been designed side by side. And of course");
_builder_4.newLine();
_builder_4.append("\t");
_builder_4.append("the tools integrate tightly with Eclipse\'s existing Java IDE.");
_builder_4.newLine();
_builder_4.append("</p>");
_builder_4.newLine();
CharSequence _entry_3 = this.entry("Better Tooling", _builder_4.toString(),
"images/icon-tools.png",
"http://vimeo.com/12824833");
_builder.append(_entry_3, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_5 = new StringConcatenation();
_builder_5.append("<p>");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Xtend leverages existing Java concepts and adds modern language features on top.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("Unlike other JVM-Languages like Scala, Xtend doesn\'t add a whole new type system because this");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("would cause interoperability issues and make the language harder to learn for Java developers.");
_builder_5.newLine();
_builder_5.append("\t");
_builder_5.append("If you know Java you already know most of Xtend. ");
_builder_5.newLine();
_builder_5.append("</p>");
_builder_5.newLine();
CharSequence _entry_4 = this.entry("Easy to Learn", _builder_5.toString(),
"images/icon_simple.png",
"http://vimeo.com/12824833");
_builder.append(_entry_4, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
StringConcatenation _builder_6 = new StringConcatenation();
_builder_6.append("<p>");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("Xtend not only resembles the type system to ensure 100% interoperability, it also generates comprehensible Java source code.");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("This not only allows to run the code on platforms such as GWT, which doesn\'t understand bytecode, but also lets you see how certain language");
_builder_6.newLine();
_builder_6.append("\t");
_builder_6.append("constructs are translated to idiomatic Java source code.");
_builder_6.newLine();
_builder_6.append("</p>");
_builder_6.newLine();
CharSequence _entry_5 = this.entry("Still Java", _builder_6.toString(),
"images/icon-java.png",
"http://vimeo.com/12824833");
_builder.append(_entry_5, " ");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("\t");
_builder.append("</div>");
_builder.newLine();
_builder.append("</div>");
_builder.newLine();
return _builder;
}
|
diff --git a/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/TwinAssociation.java b/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/TwinAssociation.java
index 4a4cdb2cc..f9dc6a39b 100644
--- a/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/TwinAssociation.java
+++ b/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/TwinAssociation.java
@@ -1,227 +1,228 @@
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.tests.crossdatastore.imdb;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.metadata.model.KunderaMetadata;
import com.impetus.kundera.metadata.model.MetamodelImpl;
import com.impetus.kundera.tests.crossdatastore.imdb.entities.Actor;
import com.impetus.kundera.tests.crossdatastore.imdb.entities.Movie;
/**
* The Class TwinAssociation.
*
* @author vivek.mishra
*/
public abstract class TwinAssociation extends AssociationBase
{
/** The combinations. */
protected static List<Map<Class, String>> combinations = new ArrayList<Map<Class, String>>();
/** the log used by this class. */
private static Logger log = LoggerFactory.getLogger(TwinAssociation.class);
/**
* Inits the.
*
* @param classes
* the classes
* @param persistenceUnits
* the persistence units
*/
public static void init(List<Class> classes, String... persistenceUnits) throws Exception
{
KunderaMetadata.INSTANCE.setApplicationMetadata(null);
combinations = null;
combinations = new ArrayList<Map<Class, String>>();
// list of PUS with class.
Map<Class, String> puClazzMapper = null;
for (String pu : persistenceUnits)
{
for (String p : persistenceUnits)
{
puClazzMapper = new HashMap<Class, String>();
puClazzMapper.put(classes.get(0), pu);
for (Class c : classes.subList(1, classes.size()))
{
puClazzMapper.put(c, p);
}
combinations.add(puClazzMapper);
}
}
}
/**
* Try operation.
*
* @param ALL_PUs_UNDER_TEST
*/
protected void tryOperation(String[] ALL_PUs_UNDER_TEST)
{
try
{
Metamodel metaModel = null;
for (int i = 0; i < ALL_PUs_UNDER_TEST.length; i++)
{
metaModel = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(ALL_PUs_UNDER_TEST[i]);
for (int i1 = 0; i1 < ALL_PUs_UNDER_TEST.length; i1++)
{
if (i != i1)
{
Map<Class<?>, EntityType<?>> original = getManagedTypes((MetamodelImpl) metaModel);
Metamodel m = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(
ALL_PUs_UNDER_TEST[i1]);
Map<Class<?>, EntityType<?>> copy = getManagedTypes((MetamodelImpl) m);
if (original != null && copy != null)
{
original.putAll(copy);
}
}
}
}
for (Map<Class, String> c : combinations)
{
Set<String> allPus = new HashSet<String>(c.values());
if (allPus.size() == 1)
{
continue;
}
else
{
String puForActor = c.get(Actor.class);
String puForMovie = c.get(Movie.class);
if (!puForActor.equals("imdbNeo4J") || puForMovie.equals("imdbNeo4J"))
{
continue;
}
}
switchPersistenceUnits(c);
// CRUD
insert();
find();
// Queries
findAllActors();
findActorByID();
findActorByName();
findActorByIDAndNamePositive();
findActorByIDAndNameNegative();
findActorWithMatchingName();
findActorWithinGivenIdRange();
findSelectedFields();
update();
remove();
tearDownInternal(ALL_PUs_UNDER_TEST);
}
}
catch (Exception e)
{
log.error("Error while switching persistence units",e);
Assert.fail("Failure caused by:" + e);
+ throw new RuntimeException(e);
}
}
/** Insert person with address */
protected abstract void insert();
/** Find person by ID */
protected abstract void find();
/** Update Person */
protected abstract void update();
/** Remove Person */
protected abstract void remove();
protected abstract void findAllActors();
protected abstract void findActorByID();
protected abstract void findActorByName();
protected abstract void findActorByIDAndNamePositive();
protected abstract void findActorByIDAndNameNegative();
protected abstract void findActorWithMatchingName();
protected abstract void findActorWithinGivenIdRange();
protected abstract void findSelectedFields();
private Map<Class<?>, EntityType<?>> getManagedTypes(MetamodelImpl metaModel)
{
try
{
Field managedTypesFields = null;
if (metaModel != null)
managedTypesFields = metaModel.getClass().getDeclaredField("entityTypes");
if (managedTypesFields != null && !managedTypesFields.isAccessible())
{
managedTypesFields.setAccessible(true);
return ((Map<Class<?>, EntityType<?>>) managedTypesFields.get(metaModel));
}
}
catch (SecurityException e)
{
Assert.fail(e.getMessage());
}
catch (NoSuchFieldException e)
{
Assert.fail(e.getMessage());
}
catch (IllegalArgumentException e)
{
Assert.fail(e.getMessage());
}
catch (IllegalAccessException e)
{
Assert.fail(e.getMessage());
}
return null;
}
}
| true | true | protected void tryOperation(String[] ALL_PUs_UNDER_TEST)
{
try
{
Metamodel metaModel = null;
for (int i = 0; i < ALL_PUs_UNDER_TEST.length; i++)
{
metaModel = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(ALL_PUs_UNDER_TEST[i]);
for (int i1 = 0; i1 < ALL_PUs_UNDER_TEST.length; i1++)
{
if (i != i1)
{
Map<Class<?>, EntityType<?>> original = getManagedTypes((MetamodelImpl) metaModel);
Metamodel m = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(
ALL_PUs_UNDER_TEST[i1]);
Map<Class<?>, EntityType<?>> copy = getManagedTypes((MetamodelImpl) m);
if (original != null && copy != null)
{
original.putAll(copy);
}
}
}
}
for (Map<Class, String> c : combinations)
{
Set<String> allPus = new HashSet<String>(c.values());
if (allPus.size() == 1)
{
continue;
}
else
{
String puForActor = c.get(Actor.class);
String puForMovie = c.get(Movie.class);
if (!puForActor.equals("imdbNeo4J") || puForMovie.equals("imdbNeo4J"))
{
continue;
}
}
switchPersistenceUnits(c);
// CRUD
insert();
find();
// Queries
findAllActors();
findActorByID();
findActorByName();
findActorByIDAndNamePositive();
findActorByIDAndNameNegative();
findActorWithMatchingName();
findActorWithinGivenIdRange();
findSelectedFields();
update();
remove();
tearDownInternal(ALL_PUs_UNDER_TEST);
}
}
catch (Exception e)
{
log.error("Error while switching persistence units",e);
Assert.fail("Failure caused by:" + e);
}
}
| protected void tryOperation(String[] ALL_PUs_UNDER_TEST)
{
try
{
Metamodel metaModel = null;
for (int i = 0; i < ALL_PUs_UNDER_TEST.length; i++)
{
metaModel = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(ALL_PUs_UNDER_TEST[i]);
for (int i1 = 0; i1 < ALL_PUs_UNDER_TEST.length; i1++)
{
if (i != i1)
{
Map<Class<?>, EntityType<?>> original = getManagedTypes((MetamodelImpl) metaModel);
Metamodel m = KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(
ALL_PUs_UNDER_TEST[i1]);
Map<Class<?>, EntityType<?>> copy = getManagedTypes((MetamodelImpl) m);
if (original != null && copy != null)
{
original.putAll(copy);
}
}
}
}
for (Map<Class, String> c : combinations)
{
Set<String> allPus = new HashSet<String>(c.values());
if (allPus.size() == 1)
{
continue;
}
else
{
String puForActor = c.get(Actor.class);
String puForMovie = c.get(Movie.class);
if (!puForActor.equals("imdbNeo4J") || puForMovie.equals("imdbNeo4J"))
{
continue;
}
}
switchPersistenceUnits(c);
// CRUD
insert();
find();
// Queries
findAllActors();
findActorByID();
findActorByName();
findActorByIDAndNamePositive();
findActorByIDAndNameNegative();
findActorWithMatchingName();
findActorWithinGivenIdRange();
findSelectedFields();
update();
remove();
tearDownInternal(ALL_PUs_UNDER_TEST);
}
}
catch (Exception e)
{
log.error("Error while switching persistence units",e);
Assert.fail("Failure caused by:" + e);
throw new RuntimeException(e);
}
}
|
diff --git a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java
index bd6187db..0fe98d47 100644
--- a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java
+++ b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java
@@ -1,165 +1,165 @@
package cz.vity.freerapid.plugins.services.rapidshare;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.DownloadState;
import cz.vity.freerapid.plugins.webclient.HttpFileDownloader;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Ladislav Vitasek
*/
class RapidShareRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(RapidShareRunner.class.getName());
public void runCheck(HttpFileDownloader downloader) throws Exception {
super.runCheck(downloader);
final GetMethod getMethod = client.getGetMethod(fileURL);
if (makeRequest(getMethod)) {
Matcher matcher = Pattern.compile("form id=\"ff\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
matcher = Pattern.compile("class=\"klappbox\">((\\s|.)*?)</div>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
final String error = matcher.group(1);
if (error.contains("illegal content") || error.contains("file has been removed") || error.contains("has removed") || error.contains("file is neither allocated to") || error.contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
if (error.contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("<b>RapidShare error:</b><br>" + error);
}
if (client.getContentAsString().contains("has removed file"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The uploader has removed this file from the server.");
if (client.getContentAsString().contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The file could not be found. Please check the download link.");
if (client.getContentAsString().contains("illegal content"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Illegal content. File was removed.");
if (client.getContentAsString().contains("file has been removed"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Due to a violation of our terms of use, the file has been removed from the server.");
if (client.getContentAsString().contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>To download this file, the uploader either needs to transfer this file into his/her Collector's Account, or upload the file again. The file can later be moved to a Collector's Account. The uploader just needs to click the delete link of the file to get further information.");
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service");
}
//| 5277 KB</font>
matcher = Pattern.compile("\\| (.*?) KB</font>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find())
httpFile.setFileSize(new Integer(matcher.group(1).replaceAll(" ", "")) * 1024);
} else
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
public void run(HttpFileDownloader downloader) throws Exception {
super.run(downloader);
final GetMethod getMethod = client.getGetMethod(fileURL);
if (makeRequest(getMethod)) {
Matcher matcher = Pattern.compile("form id=\"ff\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
matcher = Pattern.compile("class=\"klappbox\">((\\s|.)*?)</div>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
final String error = matcher.group(1);
if (error.contains("illegal content") || error.contains("file has been removed") || error.contains("has removed") || error.contains("file is neither allocated to") || error.contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
if (error.contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("<b>RapidShare error:</b><br>" + error);
}
if (client.getContentAsString().contains("has removed file"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The uploader has removed this file from the server.");
if (client.getContentAsString().contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The file could not be found. Please check the download link.");
if (client.getContentAsString().contains("illegal content"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Illegal content. File was removed.");
if (client.getContentAsString().contains("file has been removed"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Due to a violation of our terms of use, the file has been removed from the server.");
if (client.getContentAsString().contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>To download this file, the uploader either needs to transfer this file into his/her Collector's Account, or upload the file again. The file can later be moved to a Collector's Account. The uploader just needs to click the delete link of the file to get further information.");
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service");
}
String s = matcher.group(1);
//| 5277 KB</font>
matcher = Pattern.compile("\\| (.*?) KB</font>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find())
httpFile.setFileSize(new Integer(matcher.group(1).replaceAll(" ", "")) * 1024);
logger.info("Found File URL - " + s);
client.setReferer(fileURL);
final PostMethod postMethod = client.getPostMethod(s);
postMethod.addParameter("dl.start", "Free");
- if (makeRequest(getMethod)) {
+ if (makeRequest(postMethod)) {
matcher = Pattern.compile("var c=([0-9]+);", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
checkProblems();
logger.warning(client.getContentAsString());
throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content");
}
s = matcher.group(1);
int seconds = new Integer(s);
matcher = Pattern.compile("form name=\"dlf\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
s = matcher.group(1);
logger.info("Download URL: " + s);
downloader.sleep(seconds + 1);
if (downloader.isTerminated())
throw new InterruptedException();
httpFile.setState(DownloadState.GETTING);
final PostMethod method = client.getPostMethod(s);
method.addParameter("mirror", "on");
try {
final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile);
if (inputStream != null) {
downloader.saveToFile(inputStream);
} else {
checkProblems();
throw new IOException("File input stream is empty.");
}
} finally {
method.abort();//really important lines!!!!!
method.releaseConnection();
}
} else {
checkProblems();
logger.info(client.getContentAsString());
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
}
} else
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
private void checkProblems() throws ServiceConnectionProblemException, YouHaveToWaitException {
Matcher matcher;//Your IP address XXXXXX is already downloading a file. Please wait until the download is completed.
final String contentAsString = client.getContentAsString();
if (contentAsString.contains("You have reached the")) {
matcher = Pattern.compile("try again in about ([0-9]+) minute", Pattern.MULTILINE).matcher(contentAsString);
if (matcher.find()) {
throw new YouHaveToWaitException("You have reached the download-limit for free-users.", Integer.parseInt(matcher.group(1)) * 60 + 10);
}
throw new ServiceConnectionProblemException("<b>RapidShare error:</b><br>You have reached the download-limit for free-users.");
}
matcher = Pattern.compile("IP address (.*?) is already", Pattern.MULTILINE).matcher(contentAsString);
if (matcher.find()) {
final String ip = matcher.group(1);
throw new ServiceConnectionProblemException(String.format("<b>RapidShare error:</b><br>Your IP address %s is already downloading a file. <br>Please wait until the download is completed.", ip));
}
if (contentAsString.contains("Currently a lot of users")) {
matcher = Pattern.compile("Please try again in ([0-9]+) minute", Pattern.MULTILINE).matcher(contentAsString);
if (matcher.find()) {
throw new YouHaveToWaitException("Currently a lot of users are downloading files.", Integer.parseInt(matcher.group(1)) * 60 + 20);
}
throw new ServiceConnectionProblemException("<b>RapidShare error:</b><br>Currently a lot of users are downloading files.");
}
}
}
| true | true | public void run(HttpFileDownloader downloader) throws Exception {
super.run(downloader);
final GetMethod getMethod = client.getGetMethod(fileURL);
if (makeRequest(getMethod)) {
Matcher matcher = Pattern.compile("form id=\"ff\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
matcher = Pattern.compile("class=\"klappbox\">((\\s|.)*?)</div>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
final String error = matcher.group(1);
if (error.contains("illegal content") || error.contains("file has been removed") || error.contains("has removed") || error.contains("file is neither allocated to") || error.contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
if (error.contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("<b>RapidShare error:</b><br>" + error);
}
if (client.getContentAsString().contains("has removed file"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The uploader has removed this file from the server.");
if (client.getContentAsString().contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The file could not be found. Please check the download link.");
if (client.getContentAsString().contains("illegal content"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Illegal content. File was removed.");
if (client.getContentAsString().contains("file has been removed"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Due to a violation of our terms of use, the file has been removed from the server.");
if (client.getContentAsString().contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>To download this file, the uploader either needs to transfer this file into his/her Collector's Account, or upload the file again. The file can later be moved to a Collector's Account. The uploader just needs to click the delete link of the file to get further information.");
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service");
}
String s = matcher.group(1);
//| 5277 KB</font>
matcher = Pattern.compile("\\| (.*?) KB</font>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find())
httpFile.setFileSize(new Integer(matcher.group(1).replaceAll(" ", "")) * 1024);
logger.info("Found File URL - " + s);
client.setReferer(fileURL);
final PostMethod postMethod = client.getPostMethod(s);
postMethod.addParameter("dl.start", "Free");
if (makeRequest(getMethod)) {
matcher = Pattern.compile("var c=([0-9]+);", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
checkProblems();
logger.warning(client.getContentAsString());
throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content");
}
s = matcher.group(1);
int seconds = new Integer(s);
matcher = Pattern.compile("form name=\"dlf\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
s = matcher.group(1);
logger.info("Download URL: " + s);
downloader.sleep(seconds + 1);
if (downloader.isTerminated())
throw new InterruptedException();
httpFile.setState(DownloadState.GETTING);
final PostMethod method = client.getPostMethod(s);
method.addParameter("mirror", "on");
try {
final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile);
if (inputStream != null) {
downloader.saveToFile(inputStream);
} else {
checkProblems();
throw new IOException("File input stream is empty.");
}
} finally {
method.abort();//really important lines!!!!!
method.releaseConnection();
}
} else {
checkProblems();
logger.info(client.getContentAsString());
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
}
} else
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
| public void run(HttpFileDownloader downloader) throws Exception {
super.run(downloader);
final GetMethod getMethod = client.getGetMethod(fileURL);
if (makeRequest(getMethod)) {
Matcher matcher = Pattern.compile("form id=\"ff\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
matcher = Pattern.compile("class=\"klappbox\">((\\s|.)*?)</div>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
final String error = matcher.group(1);
if (error.contains("illegal content") || error.contains("file has been removed") || error.contains("has removed") || error.contains("file is neither allocated to") || error.contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
if (error.contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>" + error);
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("<b>RapidShare error:</b><br>" + error);
}
if (client.getContentAsString().contains("has removed file"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The uploader has removed this file from the server.");
if (client.getContentAsString().contains("file could not be found"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>The file could not be found. Please check the download link.");
if (client.getContentAsString().contains("illegal content"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Illegal content. File was removed.");
if (client.getContentAsString().contains("file has been removed"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>Due to a violation of our terms of use, the file has been removed from the server.");
if (client.getContentAsString().contains("limit is reached"))
throw new URLNotAvailableAnymoreException("<b>RapidShare error:</b><br>To download this file, the uploader either needs to transfer this file into his/her Collector's Account, or upload the file again. The file can later be moved to a Collector's Account. The uploader just needs to click the delete link of the file to get further information.");
logger.warning(client.getContentAsString());
throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service");
}
String s = matcher.group(1);
//| 5277 KB</font>
matcher = Pattern.compile("\\| (.*?) KB</font>", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find())
httpFile.setFileSize(new Integer(matcher.group(1).replaceAll(" ", "")) * 1024);
logger.info("Found File URL - " + s);
client.setReferer(fileURL);
final PostMethod postMethod = client.getPostMethod(s);
postMethod.addParameter("dl.start", "Free");
if (makeRequest(postMethod)) {
matcher = Pattern.compile("var c=([0-9]+);", Pattern.MULTILINE).matcher(client.getContentAsString());
if (!matcher.find()) {
checkProblems();
logger.warning(client.getContentAsString());
throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content");
}
s = matcher.group(1);
int seconds = new Integer(s);
matcher = Pattern.compile("form name=\"dlf\" action=\"([^\"]*)\"", Pattern.MULTILINE).matcher(client.getContentAsString());
if (matcher.find()) {
s = matcher.group(1);
logger.info("Download URL: " + s);
downloader.sleep(seconds + 1);
if (downloader.isTerminated())
throw new InterruptedException();
httpFile.setState(DownloadState.GETTING);
final PostMethod method = client.getPostMethod(s);
method.addParameter("mirror", "on");
try {
final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile);
if (inputStream != null) {
downloader.saveToFile(inputStream);
} else {
checkProblems();
throw new IOException("File input stream is empty.");
}
} finally {
method.abort();//really important lines!!!!!
method.releaseConnection();
}
} else {
checkProblems();
logger.info(client.getContentAsString());
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
}
} else
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
|
diff --git a/rdb/src/main/java/org/apache/tuscany/das/rdb/impl/ConnectionImpl.java b/rdb/src/main/java/org/apache/tuscany/das/rdb/impl/ConnectionImpl.java
index 2434179..5ee4650 100644
--- a/rdb/src/main/java/org/apache/tuscany/das/rdb/impl/ConnectionImpl.java
+++ b/rdb/src/main/java/org/apache/tuscany/das/rdb/impl/ConnectionImpl.java
@@ -1,154 +1,154 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tuscany.das.rdb.impl;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
public class ConnectionImpl {
private final Logger logger = Logger.getLogger(ConnectionImpl.class);
private Connection connection;
private boolean managingTransaction = true;
private String generatedKeysSupported = null;
public ConnectionImpl(Connection connection) {
this.connection = connection;
try {
if (connection.getAutoCommit()) {
throw new RuntimeException("AutoCommit must be off");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Connection getJDBCConnection() {
return connection;
}
public String getGeneratedKeysSupported() {
return this.generatedKeysSupported;
}
public void setGeneratedKeysSupported(String useGetGeneratedKeys){
this.generatedKeysSupported = useGetGeneratedKeys;
}
public boolean isGeneratedKeysSupported() {
try{
if(this.generatedKeysSupported == null){
DatabaseMetaData dbmsMetadata = this.connection.getMetaData();
boolean supportsGetGeneratedKeys = dbmsMetadata.supportsGetGeneratedKeys();
if(supportsGetGeneratedKeys){
this.generatedKeysSupported = "true";
}
//currently DERBY partially supports this feature and thus returns FALSE,
//this hardcoding is needed as the partial support is enough for DAS
//we can remove this later, when DERBY change the behaviour of it's "supportsGetGeneratedKeys"
else if(dbmsMetadata.getDatabaseProductName().indexOf("Derby") > 0){
this.generatedKeysSupported = "true";
}
else{
this.generatedKeysSupported = "false";
}
}
}catch(Exception e){//can be from supportsGetGeneratedKeys or due to absense of supportsGetGeneratedKeys
if (this.logger.isDebugEnabled()) {
this.logger.debug("exception setiing useGetGeneratedKeys false");
}
this.generatedKeysSupported = "false";
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("returning useGetGeneratedKeys():"+ this.generatedKeysSupported);
}
- return Boolean.parseBoolean(this.generatedKeysSupported);
+ return Boolean.valueOf(this.generatedKeysSupported).booleanValue();
}
public void cleanUp() {
try {
if (managingTransaction) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Committing Transaction");
}
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void errorCleanUp() {
try {
if (managingTransaction) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Rolling back Transaction");
}
connection.rollback();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement prepareStatement(String queryString, String[] returnKeys) throws SQLException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Preparing Statement: " + queryString);
this.logger.debug("Boolean value for use gen key: " + this.generatedKeysSupported);
}
if (isGeneratedKeysSupported()) {
return connection.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS);
} else if (returnKeys.length > 0) {
return connection.prepareStatement(queryString, returnKeys);
}
return connection.prepareStatement(queryString);
}
public PreparedStatement preparePagedStatement(String queryString) throws SQLException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Preparing Statement: " + queryString);
}
return connection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
public void setManageTransactions(boolean manageTransactions) {
managingTransaction = manageTransactions;
}
public CallableStatement prepareCall(String queryString) throws SQLException {
return connection.prepareCall(queryString);
}
}
| true | true | public boolean isGeneratedKeysSupported() {
try{
if(this.generatedKeysSupported == null){
DatabaseMetaData dbmsMetadata = this.connection.getMetaData();
boolean supportsGetGeneratedKeys = dbmsMetadata.supportsGetGeneratedKeys();
if(supportsGetGeneratedKeys){
this.generatedKeysSupported = "true";
}
//currently DERBY partially supports this feature and thus returns FALSE,
//this hardcoding is needed as the partial support is enough for DAS
//we can remove this later, when DERBY change the behaviour of it's "supportsGetGeneratedKeys"
else if(dbmsMetadata.getDatabaseProductName().indexOf("Derby") > 0){
this.generatedKeysSupported = "true";
}
else{
this.generatedKeysSupported = "false";
}
}
}catch(Exception e){//can be from supportsGetGeneratedKeys or due to absense of supportsGetGeneratedKeys
if (this.logger.isDebugEnabled()) {
this.logger.debug("exception setiing useGetGeneratedKeys false");
}
this.generatedKeysSupported = "false";
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("returning useGetGeneratedKeys():"+ this.generatedKeysSupported);
}
return Boolean.parseBoolean(this.generatedKeysSupported);
}
| public boolean isGeneratedKeysSupported() {
try{
if(this.generatedKeysSupported == null){
DatabaseMetaData dbmsMetadata = this.connection.getMetaData();
boolean supportsGetGeneratedKeys = dbmsMetadata.supportsGetGeneratedKeys();
if(supportsGetGeneratedKeys){
this.generatedKeysSupported = "true";
}
//currently DERBY partially supports this feature and thus returns FALSE,
//this hardcoding is needed as the partial support is enough for DAS
//we can remove this later, when DERBY change the behaviour of it's "supportsGetGeneratedKeys"
else if(dbmsMetadata.getDatabaseProductName().indexOf("Derby") > 0){
this.generatedKeysSupported = "true";
}
else{
this.generatedKeysSupported = "false";
}
}
}catch(Exception e){//can be from supportsGetGeneratedKeys or due to absense of supportsGetGeneratedKeys
if (this.logger.isDebugEnabled()) {
this.logger.debug("exception setiing useGetGeneratedKeys false");
}
this.generatedKeysSupported = "false";
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("returning useGetGeneratedKeys():"+ this.generatedKeysSupported);
}
return Boolean.valueOf(this.generatedKeysSupported).booleanValue();
}
|
diff --git a/shivas-server/src/main/java/org/shivas/server/core/fights/frames/Frame.java b/shivas-server/src/main/java/org/shivas/server/core/fights/frames/Frame.java
index 04fdc5a..f876c9a 100644
--- a/shivas-server/src/main/java/org/shivas/server/core/fights/frames/Frame.java
+++ b/shivas-server/src/main/java/org/shivas/server/core/fights/frames/Frame.java
@@ -1,76 +1,78 @@
package org.shivas.server.core.fights.frames;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import org.joda.time.Duration;
import org.shivas.server.core.fights.Fight;
import org.shivas.server.core.fights.FightException;
import org.shivas.server.core.fights.FightTurn;
import org.shivas.server.core.fights.Fighter;
/**
* Created with IntelliJ IDEA.
* User: Blackrush
* Date: 22/10/12
* Time: 19:32
*/
public abstract class Frame {
private final SettableFuture<Frame> endFuture = SettableFuture.create();
private Frame next;
protected final FightTurn turn;
protected final Fighter fighter;
protected final Fight fight;
protected Frame(FightTurn turn) {
this.turn = turn;
this.fighter = this.turn.getFighter();
this.fight = this.fighter.getFight();
}
/**
* @return frame's end future or next's if there is one
*/
public final ListenableFuture<Frame> getEndFuture() {
return next != null ? next.getEndFuture() : endFuture;
}
public final void setNext(Frame next) {
if (next == this) return; // avoids stack overflow
if (this.next != null) {
this.next.setNext(next);
} else {
this.next = next;
}
}
public final void blockNext() {
this.next = null;
}
public abstract void begin() throws FightException;
protected abstract void doEnd();
protected void end() {
endFuture.set(this);
doEnd();
if (next != null) {
try {
next.begin();
} catch (FightException e) {
fight.exceptionThrowed(e);
}
+ } else {
+ fight.eraseCurrentFrame();
}
}
protected void scheduleEnd(Duration duration) {
fight.schedule(duration, new Runnable() {
public void run() {
end();
}
});
}
}
| true | true | protected void end() {
endFuture.set(this);
doEnd();
if (next != null) {
try {
next.begin();
} catch (FightException e) {
fight.exceptionThrowed(e);
}
}
}
| protected void end() {
endFuture.set(this);
doEnd();
if (next != null) {
try {
next.begin();
} catch (FightException e) {
fight.exceptionThrowed(e);
}
} else {
fight.eraseCurrentFrame();
}
}
|
diff --git a/src/main/java/hudson/plugins/clearcase/action/UcmSnapshotCheckoutAction.java b/src/main/java/hudson/plugins/clearcase/action/UcmSnapshotCheckoutAction.java
index b7905bc..dbd7c6a 100644
--- a/src/main/java/hudson/plugins/clearcase/action/UcmSnapshotCheckoutAction.java
+++ b/src/main/java/hudson/plugins/clearcase/action/UcmSnapshotCheckoutAction.java
@@ -1,92 +1,94 @@
package hudson.plugins.clearcase.action;
import hudson.FilePath;
import hudson.Launcher;
import hudson.plugins.clearcase.ClearTool;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* Check out action that will check out files into a UCM snapshot view. Checking
* out the files will also update the load rules in the view.
*/
public class UcmSnapshotCheckoutAction implements CheckOutAction {
private ClearTool cleartool;
private String stream;
private String loadRules;
private boolean useUpdate;
public UcmSnapshotCheckoutAction(ClearTool cleartool, String stream,
String loadRules, boolean useUpdate) {
super();
this.cleartool = cleartool;
this.stream = stream;
this.loadRules = loadRules;
this.useUpdate = useUpdate;
}
public boolean checkout(Launcher launcher, FilePath workspace,
String viewName) throws IOException, InterruptedException {
boolean localViewPathExists = new FilePath(workspace, viewName)
.exists();
if (this.useUpdate) {
if (localViewPathExists) {
String configSpec = cleartool.catcs(viewName);
Set<String> configSpecLoadRules = extractLoadRules(configSpec);
boolean recreate = currentConfigSpecUptodate(configSpecLoadRules);
if (recreate) {
cleartool.rmview(viewName);
cleartool.mkview(viewName, stream);
}
} else {
cleartool.mkview(viewName, stream);
}
} else {
- cleartool.rmview(viewName);
+ if (localViewPathExists) {
+ cleartool.rmview(viewName);
+ }
cleartool.mkview(viewName, stream);
}
for (String loadRule : loadRules.split("\n")) {
cleartool.update(viewName, loadRule.trim());
}
return true;
}
private boolean currentConfigSpecUptodate(Set<String> configSpecLoadRules) {
boolean recreate = false;
for (String loadRule : loadRules.split("\n")) {
if (!configSpecLoadRules.contains(loadRule)) {
System.out
.println("Load rule: "
+ loadRule
+ " not found in current config spec, forcing recreation of view");
recreate = true;
}
}
return recreate;
}
private Set<String> extractLoadRules(String configSpec) {
Set<String> rules = new HashSet<String>();
for (String row : configSpec.split("\n")) {
String trimmedRow = row.toLowerCase().trim();
if (trimmedRow.startsWith("load")) {
String rule = row.trim().substring("load".length()).trim();
rules.add(rule);
if (!rule.startsWith("/")) {
rules.add("/" + rule);
} else {
rules.add(rule.substring(1));
}
}
}
return rules;
}
}
| true | true | public boolean checkout(Launcher launcher, FilePath workspace,
String viewName) throws IOException, InterruptedException {
boolean localViewPathExists = new FilePath(workspace, viewName)
.exists();
if (this.useUpdate) {
if (localViewPathExists) {
String configSpec = cleartool.catcs(viewName);
Set<String> configSpecLoadRules = extractLoadRules(configSpec);
boolean recreate = currentConfigSpecUptodate(configSpecLoadRules);
if (recreate) {
cleartool.rmview(viewName);
cleartool.mkview(viewName, stream);
}
} else {
cleartool.mkview(viewName, stream);
}
} else {
cleartool.rmview(viewName);
cleartool.mkview(viewName, stream);
}
for (String loadRule : loadRules.split("\n")) {
cleartool.update(viewName, loadRule.trim());
}
return true;
}
| public boolean checkout(Launcher launcher, FilePath workspace,
String viewName) throws IOException, InterruptedException {
boolean localViewPathExists = new FilePath(workspace, viewName)
.exists();
if (this.useUpdate) {
if (localViewPathExists) {
String configSpec = cleartool.catcs(viewName);
Set<String> configSpecLoadRules = extractLoadRules(configSpec);
boolean recreate = currentConfigSpecUptodate(configSpecLoadRules);
if (recreate) {
cleartool.rmview(viewName);
cleartool.mkview(viewName, stream);
}
} else {
cleartool.mkview(viewName, stream);
}
} else {
if (localViewPathExists) {
cleartool.rmview(viewName);
}
cleartool.mkview(viewName, stream);
}
for (String loadRule : loadRules.split("\n")) {
cleartool.update(viewName, loadRule.trim());
}
return true;
}
|
diff --git a/src/me/limebyte/battlenight/core/Listeners/CommandBlocker.java b/src/me/limebyte/battlenight/core/Listeners/CommandBlocker.java
index bf79d9b..d145eaf 100644
--- a/src/me/limebyte/battlenight/core/Listeners/CommandBlocker.java
+++ b/src/me/limebyte/battlenight/core/Listeners/CommandBlocker.java
@@ -1,55 +1,56 @@
package me.limebyte.battlenight.core.Listeners;
import java.util.List;
import me.limebyte.battlenight.core.BattleNight;
import org.bukkit.command.Command;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandBlocker implements Listener {
// Get Main Class
public static BattleNight plugin;
public CommandBlocker(BattleNight instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.isCancelled()) return;
if (!plugin.BattleUsersTeam.containsKey(event.getPlayer().getName())) return;
if (!plugin.config.getBoolean("Commands.Block")) return;
List<String> whitelist = plugin.config.getStringList("Commands.Whitelist");
whitelist.add("bn");
String[] cmdArg = event.getMessage().split(" ");
+ String cmdString = cmdArg[0].trim().substring(1).toLowerCase();
try {
- Command command = plugin.getServer().getPluginCommand(cmdArg[0].trim().replaceFirst("/", ""));
+ Command command = plugin.getServer().getPluginCommand(cmdString);
// Check if the command is listed
if (whitelist.contains(command.getLabel().toLowerCase())) return;
// Check if there are any aliases listed
if (!command.getAliases().isEmpty()) {
for (String alias : command.getAliases()) {
if (whitelist.contains(alias.toLowerCase())) return;
}
}
} catch (NullPointerException e) {
// Check if the command is listed
- if (whitelist.contains(cmdArg[0].trim().replaceFirst("/", "").toLowerCase())) return;
+ if (whitelist.contains(cmdString)) return;
}
// Its not listed so block it
event.setCancelled(true);
plugin.tellPlayer(event.getPlayer(), "You are not permitted to perform this command while in a Battle.");
return;
}
}
| false | true | public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.isCancelled()) return;
if (!plugin.BattleUsersTeam.containsKey(event.getPlayer().getName())) return;
if (!plugin.config.getBoolean("Commands.Block")) return;
List<String> whitelist = plugin.config.getStringList("Commands.Whitelist");
whitelist.add("bn");
String[] cmdArg = event.getMessage().split(" ");
try {
Command command = plugin.getServer().getPluginCommand(cmdArg[0].trim().replaceFirst("/", ""));
// Check if the command is listed
if (whitelist.contains(command.getLabel().toLowerCase())) return;
// Check if there are any aliases listed
if (!command.getAliases().isEmpty()) {
for (String alias : command.getAliases()) {
if (whitelist.contains(alias.toLowerCase())) return;
}
}
} catch (NullPointerException e) {
// Check if the command is listed
if (whitelist.contains(cmdArg[0].trim().replaceFirst("/", "").toLowerCase())) return;
}
// Its not listed so block it
event.setCancelled(true);
plugin.tellPlayer(event.getPlayer(), "You are not permitted to perform this command while in a Battle.");
return;
}
| public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.isCancelled()) return;
if (!plugin.BattleUsersTeam.containsKey(event.getPlayer().getName())) return;
if (!plugin.config.getBoolean("Commands.Block")) return;
List<String> whitelist = plugin.config.getStringList("Commands.Whitelist");
whitelist.add("bn");
String[] cmdArg = event.getMessage().split(" ");
String cmdString = cmdArg[0].trim().substring(1).toLowerCase();
try {
Command command = plugin.getServer().getPluginCommand(cmdString);
// Check if the command is listed
if (whitelist.contains(command.getLabel().toLowerCase())) return;
// Check if there are any aliases listed
if (!command.getAliases().isEmpty()) {
for (String alias : command.getAliases()) {
if (whitelist.contains(alias.toLowerCase())) return;
}
}
} catch (NullPointerException e) {
// Check if the command is listed
if (whitelist.contains(cmdString)) return;
}
// Its not listed so block it
event.setCancelled(true);
plugin.tellPlayer(event.getPlayer(), "You are not permitted to perform this command while in a Battle.");
return;
}
|
diff --git a/tapestry-core/src/test/java/org/apache/tapestry5/internal/services/LocalizationSetterImplTest.java b/tapestry-core/src/test/java/org/apache/tapestry5/internal/services/LocalizationSetterImplTest.java
index f72c1d1ef..f3363bb24 100644
--- a/tapestry-core/src/test/java/org/apache/tapestry5/internal/services/LocalizationSetterImplTest.java
+++ b/tapestry-core/src/test/java/org/apache/tapestry5/internal/services/LocalizationSetterImplTest.java
@@ -1,232 +1,232 @@
// Copyright 2006, 2009, 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.services;
import static org.apache.tapestry5.ioc.internal.util.CollectionFactory.newSet;
import java.util.List;
import java.util.Locale;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.internal.test.InternalBaseTestCase;
import org.apache.tapestry5.ioc.services.ThreadLocale;
import org.apache.tapestry5.ioc.test.TestBase;
import org.apache.tapestry5.services.LocalizationSetter;
import org.apache.tapestry5.services.PersistentLocale;
import org.apache.tapestry5.services.Request;
import org.testng.annotations.Test;
public class LocalizationSetterImplTest extends InternalBaseTestCase
{
@Test
public void locale_split()
{
assertEquals(LocalizationSetterImpl.stripTerm("foo_bar_Baz"), "foo_bar");
assertEquals(LocalizationSetterImpl.stripTerm("foo_bar"), "foo");
assertEquals(LocalizationSetterImpl.stripTerm("foo"), "");
}
@Test
public void to_locale_is_cached()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en");
Locale l1 = setter.toLocale("en");
assertEquals(l1.toString(), "en");
checkLocale(l1, "en", "", "");
assertSame(setter.toLocale("en"), l1);
}
private void checkLocale(Locale l, String expectedLanguage, String expectedCountry, String expectedVariant)
{
assertEquals(l.getLanguage(), expectedLanguage);
assertEquals(l.getCountry(), expectedCountry);
assertEquals(l.getVariant(), expectedVariant);
}
@Test
public void to_locale()
{
LocalizationSetterImpl setter = new LocalizationSetterImpl(null, null, null, "en");
checkLocale(setter.toLocale("en"), "en", "", "");
checkLocale(setter.toLocale("klingon_Gach"), "klingon", "GACH", "");
checkLocale(setter.toLocale("klingon_Gach_snuff"), "klingon", "GACH", "snuff");
}
@Test
public void known_locale()
{
PersistentLocale pl = mockPersistentLocale();
ThreadLocale tl = mockThreadLocale();
Request request = mockRequest();
tl.setLocale(Locale.FRENCH);
pl.set(Locale.FRENCH);
replay();
LocalizationSetter setter = new LocalizationSetterImpl(request, pl, tl, "en,fr");
assertTrue(setter.setLocaleFromLocaleName("fr"));
verify();
}
@Test
public void get_selected_locales()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en,fr");
assertListsEquals(setter.getSupportedLocales(), Locale.ENGLISH, Locale.FRENCH);
}
@Test
public void get_selected_locale_names()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en,fr");
Object localeNames = TestBase.get(setter, "supportedLocaleNames");
assertTrue(newSet("en", "fr").equals(localeNames));
}
@Test
public void get_selected_locale_names_with_whitespaces()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en, fr, de");
Object localeNames = TestBase.get(setter, "supportedLocaleNames");
assertTrue(newSet("en", "fr", "de").equals(localeNames));
}
@Test
public void get_locale_model()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en,fr");
SelectModel model = setter.getSupportedLocalesModel();
assertNull(model.getOptionGroups());
List<OptionModel> options = model.getOptions();
assertEquals(options.size(), 2);
assertEquals(options.get(0).getLabel(), "English");
// Note that the label is localized to the underlying locale, not the default locale.
- // That's why its "fran�ais" (i.e., as a French speaker would say it), not "French"
+ // That's why its "français" (i.e., as a French speaker would say it), not "French"
// (like an English speaker).
assertEquals(options.get(1).getLabel(), "fran\u00e7ais");
assertEquals(options.get(0).getValue(), Locale.ENGLISH);
assertEquals(options.get(1).getValue(), Locale.FRENCH);
}
protected final PersistentLocale mockPersistentLocale()
{
return newMock(PersistentLocale.class);
}
@Test
public void unknown_locale_uses_locale_from_request()
{
PersistentLocale pl = mockPersistentLocale();
ThreadLocale tl = mockThreadLocale();
Request request = mockRequest();
tl.setLocale(Locale.FRENCH);
train_getLocale(request, Locale.CANADA_FRENCH);
replay();
LocalizationSetterImpl setter = new LocalizationSetterImpl(request, pl, tl, "en,fr");
assertFalse(setter.setLocaleFromLocaleName("unknown"));
verify();
}
@Test
public void unsupported_locale_in_request_uses_default_locale()
{
PersistentLocale pl = mockPersistentLocale();
ThreadLocale tl = mockThreadLocale();
Request request = mockRequest();
tl.setLocale(Locale.ITALIAN);
train_getLocale(request, Locale.CHINESE);
replay();
LocalizationSetterImpl setter = new LocalizationSetterImpl(request, pl, tl, "it,en,fr");
assertFalse(setter.setLocaleFromLocaleName("unknown"));
verify();
}
@Test
public void set_nonpersistent_locale()
{
PersistentLocale pl = mockPersistentLocale();
ThreadLocale tl = mockThreadLocale();
Request request = mockRequest();
tl.setLocale(Locale.FRENCH);
replay();
LocalizationSetterImpl setter = new LocalizationSetterImpl(request, pl, tl, "en,fr");
setter.setNonPeristentLocaleFromLocaleName("fr_BE");
verify();
}
@Test
public void is_supported_locale_name()
{
PersistentLocale pl = mockPersistentLocale();
ThreadLocale tl = mockThreadLocale();
Request request = mockRequest();
replay();
LocalizationSetterImpl setter = new LocalizationSetterImpl(request, pl, tl, "de, de_DE, de_CH,en");
assertTrue(setter.isSupportedLocaleName("de"));
assertTrue(setter.isSupportedLocaleName("de_de"));
assertTrue(setter.isSupportedLocaleName("de_de"));
assertTrue(setter.isSupportedLocaleName("de_DE"));
assertTrue(setter.isSupportedLocaleName("de_ch"));
assertTrue(setter.isSupportedLocaleName("de_CH"));
assertTrue(setter.isSupportedLocaleName("en"));
verify();
}
}
| true | true | public void get_locale_model()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en,fr");
SelectModel model = setter.getSupportedLocalesModel();
assertNull(model.getOptionGroups());
List<OptionModel> options = model.getOptions();
assertEquals(options.size(), 2);
assertEquals(options.get(0).getLabel(), "English");
// Note that the label is localized to the underlying locale, not the default locale.
// That's why its "fran�ais" (i.e., as a French speaker would say it), not "French"
// (like an English speaker).
assertEquals(options.get(1).getLabel(), "fran\u00e7ais");
assertEquals(options.get(0).getValue(), Locale.ENGLISH);
assertEquals(options.get(1).getValue(), Locale.FRENCH);
}
| public void get_locale_model()
{
LocalizationSetter setter = new LocalizationSetterImpl(null, null, null, "en,fr");
SelectModel model = setter.getSupportedLocalesModel();
assertNull(model.getOptionGroups());
List<OptionModel> options = model.getOptions();
assertEquals(options.size(), 2);
assertEquals(options.get(0).getLabel(), "English");
// Note that the label is localized to the underlying locale, not the default locale.
// That's why its "français" (i.e., as a French speaker would say it), not "French"
// (like an English speaker).
assertEquals(options.get(1).getLabel(), "fran\u00e7ais");
assertEquals(options.get(0).getValue(), Locale.ENGLISH);
assertEquals(options.get(1).getValue(), Locale.FRENCH);
}
|
diff --git a/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelCoordinatesView.java b/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelCoordinatesView.java
index 75a58b073..c1a76110c 100644
--- a/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelCoordinatesView.java
+++ b/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelCoordinatesView.java
@@ -1,369 +1,369 @@
/**
* Copyright (c) 2010, 2013 Darmstadt University of Technology.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marcel Bruch - initial API and implementation.
*/
package org.eclipse.recommenders.internal.models.rcp;
import static org.eclipse.recommenders.rcp.SharedImages.ELCL_REFRESH;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import javax.inject.Inject;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.recommenders.models.Coordinates;
import org.eclipse.recommenders.models.IModelIndex;
import org.eclipse.recommenders.models.ModelCoordinate;
import org.eclipse.recommenders.models.ProjectCoordinate;
import org.eclipse.recommenders.models.rcp.ModelEvents.ModelArchiveDownloadedEvent;
import org.eclipse.recommenders.models.rcp.ModelEvents.ModelIndexOpenedEvent;
import org.eclipse.recommenders.rcp.SharedImages;
import org.eclipse.recommenders.rcp.utils.Selections;
import org.eclipse.recommenders.utils.Constants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class ModelCoordinatesView extends ViewPart {
private DataBindingContext m_bindingContext;
private Table table;
@Inject
IModelIndex index;
@Inject
SharedImages images;
@Inject
EclipseModelRepository repo;
@Inject
EventBus bus;
private TableViewer tableViewer;
private Multimap<ProjectCoordinate, String> models;
private Text txtSearch;
@Override
public void createPartControl(Composite parent) {
bus.register(this);
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout());
txtSearch = new Text(container, SWT.BORDER | SWT.ICON_SEARCH | SWT.SEARCH | SWT.CANCEL);
txtSearch.setMessage("type filter text");
txtSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtSearch.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN && table.getItemCount() != 0) {
table.setFocus();
table.setSelection(0);
}
}
});
Composite composite = new Composite(container, SWT.NONE);
TableColumnLayout tableLayout = new TableColumnLayout();
composite.setLayout(tableLayout);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
ColumnViewerToolTipSupport.enableFor(tableViewer);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableViewerColumn tvcPrimary = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn tcPrimary = tvcPrimary.getColumn();
tableLayout.setColumnData(tcPrimary, new ColumnWeightData(1, ColumnWeightData.MINIMUM_WIDTH, true));
tcPrimary.setText("Primary");
tvcPrimary.setLabelProvider(new ColumnLabelProvider());
newColumn(tableLayout, Constants.CLASS_CALL_MODELS);
newColumn(tableLayout, Constants.CLASS_OVRD_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRP_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRM_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFC_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFM_MODEL);
tableViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
return ((Multimap<?, ?>) inputElement).keySet().toArray();
}
});
tableViewer.setSorter(new ViewerSorter());
initializeContent();
addRefreshButton();
addDeleteButton();
addContextMenu();
m_bindingContext = initDataBindings();
}
private void addRefreshButton() {
IAction refreshAction = new Action() {
@Override
public void run() {
refreshData();
}
};
refreshAction.setToolTipText("Refresh");
refreshAction.setImageDescriptor(images.getDescriptor(ELCL_REFRESH));
getViewSite().getActionBars().getToolBarManager().add(refreshAction);
}
private void addDeleteButton() {
IAction deleteAction = new Action() {
@Override
public void run() {
deleteCacheAndRefresh();
}
};
deleteAction.setText("Delete models");
deleteAction.setImageDescriptor(images.getDescriptor(SharedImages.ELCL_DELETE));
getViewSite().getActionBars().getMenuManager().add(deleteAction);
}
private void addContextMenu() {
final MenuManager menuManager = new MenuManager();
Menu contextMenu = menuManager.createContextMenu(table);
menuManager.setRemoveAllWhenShown(true);
table.setMenu(contextMenu);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
Set<ProjectCoordinate> pcs = Selections.toSet(tableViewer.getSelection());
if (!pcs.isEmpty()) {
menuManager.add(new TriggerModelDownloadActionForProjectCoordinates("Download models", pcs, index,
repo, bus));
}
}
});
}
private void newColumn(TableColumnLayout tableLayout, final String classifier) {
TableViewerColumn tvColumn = new TableViewerColumn(tableViewer, SWT.CENTER);
TableColumn column = tvColumn.getColumn();
column.setMoveable(true);
column.setResizable(false);
tableLayout.setColumnData(column, new ColumnPixelData(20, false, true));
column.setText(classifier.toUpperCase());
tvColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return null;
}
@Override
public String getToolTipText(Object element) {
ProjectCoordinate pc = (ProjectCoordinate) element;
ModelCoordinate mc = Coordinates.toModelCoordinate(pc, classifier, "zip");
if (!containsModel(classifier, element)) {
return "No model registered";
} else if (isDownloaded(mc)) {
return "Locally available";
} else {
return "Remotely available";
}
}
private boolean containsModel(final String classifier, Object element) {
Collection<String> values = models.get((ProjectCoordinate) element);
boolean contains = values.contains(classifier);
return contains;
}
@Override
public Image getImage(Object element) {
ProjectCoordinate pc = (ProjectCoordinate) element;
ModelCoordinate mc = Coordinates.toModelCoordinate(pc, classifier, "zip");
if (!containsModel(classifier, element)) {
return images.getImage(SharedImages.OBJ_CROSS_RED);
} else if (!isDownloaded(mc)) {
return images.getImage(SharedImages.OBJ_BULLET_BLUE);
} else {
return images.getImage(SharedImages.OBJ_CHECK_GREEN);
}
}
private boolean isDownloaded(final ModelCoordinate mc) {
return repo.getLocation(mc, false).isPresent();
}
});
}
private void initializeContent() {
models = LinkedListMultimap.create();
addClassifierToIndex(models, Constants.CLASS_CALL_MODELS);
addClassifierToIndex(models, Constants.CLASS_OVRD_MODEL);
addClassifierToIndex(models, Constants.CLASS_OVRM_MODEL);
addClassifierToIndex(models, Constants.CLASS_OVRP_MODEL);
addClassifierToIndex(models, Constants.CLASS_SELFC_MODEL);
addClassifierToIndex(models, Constants.CLASS_SELFM_MODEL);
tableViewer.setInput(models);
}
private void addClassifierToIndex(Multimap<ProjectCoordinate, String> models, String classifier) {
for (ModelCoordinate mc : index.getKnownModels(classifier)) {
ProjectCoordinate pc = Coordinates.toProjectCoordinate(mc);
models.put(pc, classifier);
}
}
@Override
public void setFocus() {
table.setFocus();
}
// needs to be public to work with PojoProperties
public void setFilter(final String filter) {
tableViewer.setFilters(new ViewerFilter[] { new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
ProjectCoordinate coord = (ProjectCoordinate) element;
for (String s : coord.toString().split(":")) {
if (s.startsWith(filter)) {
return true;
}
}
return false;
}
}
});
}
@Override
public void dispose() {
super.dispose();
m_bindingContext.dispose();
bus.unregister(this);
}
@Subscribe
public void onModelIndexOpened(ModelIndexOpenedEvent e) {
refreshData();
}
@Subscribe
public void onModelArchiveDownloaded(final ModelArchiveDownloadedEvent e) {
new UIJob("") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ProjectCoordinate pc = Coordinates.toProjectCoordinate(e.model);
tableViewer.refresh(pc);
return Status.OK_STATUS;
}
}.schedule();
}
private void refreshData() {
new UIJob("Refreshing Model Index View...") {
{
schedule();
}
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
initializeContent();
return Status.OK_STATUS;
}
};
}
private void deleteCacheAndRefresh() {
new Job("Deleting model cache...") {
{
schedule();
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
repo.deleteModels();
// TODO Would be nice to have something like schule(job1).then(job2), rather than having the first
// job schedule the second.
refreshData();
return Status.OK_STATUS;
} catch (IOException e) {
return new Status(Status.ERROR, org.eclipse.recommenders.internal.models.rcp.Constants.BUNDLE_ID,
"Failed to delete model cache");
}
}
};
}
protected DataBindingContext initDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
IObservableValue search = WidgetProperties.text(SWT.Modify).observeDelayed(400, txtSearch);
IObservableValue filter = PojoProperties.value("filter").observe(this);
bindingContext.bindValue(filter, search, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER), null);
return bindingContext;
}
}
| true | true | public void createPartControl(Composite parent) {
bus.register(this);
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout());
txtSearch = new Text(container, SWT.BORDER | SWT.ICON_SEARCH | SWT.SEARCH | SWT.CANCEL);
txtSearch.setMessage("type filter text");
txtSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtSearch.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN && table.getItemCount() != 0) {
table.setFocus();
table.setSelection(0);
}
}
});
Composite composite = new Composite(container, SWT.NONE);
TableColumnLayout tableLayout = new TableColumnLayout();
composite.setLayout(tableLayout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
ColumnViewerToolTipSupport.enableFor(tableViewer);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableViewerColumn tvcPrimary = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn tcPrimary = tvcPrimary.getColumn();
tableLayout.setColumnData(tcPrimary, new ColumnWeightData(1, ColumnWeightData.MINIMUM_WIDTH, true));
tcPrimary.setText("Primary");
tvcPrimary.setLabelProvider(new ColumnLabelProvider());
newColumn(tableLayout, Constants.CLASS_CALL_MODELS);
newColumn(tableLayout, Constants.CLASS_OVRD_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRP_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRM_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFC_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFM_MODEL);
tableViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
return ((Multimap<?, ?>) inputElement).keySet().toArray();
}
});
tableViewer.setSorter(new ViewerSorter());
initializeContent();
addRefreshButton();
addDeleteButton();
addContextMenu();
m_bindingContext = initDataBindings();
}
| public void createPartControl(Composite parent) {
bus.register(this);
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout());
txtSearch = new Text(container, SWT.BORDER | SWT.ICON_SEARCH | SWT.SEARCH | SWT.CANCEL);
txtSearch.setMessage("type filter text");
txtSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtSearch.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN && table.getItemCount() != 0) {
table.setFocus();
table.setSelection(0);
}
}
});
Composite composite = new Composite(container, SWT.NONE);
TableColumnLayout tableLayout = new TableColumnLayout();
composite.setLayout(tableLayout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
ColumnViewerToolTipSupport.enableFor(tableViewer);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableViewerColumn tvcPrimary = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn tcPrimary = tvcPrimary.getColumn();
tableLayout.setColumnData(tcPrimary, new ColumnWeightData(1, ColumnWeightData.MINIMUM_WIDTH, true));
tcPrimary.setText("Primary");
tvcPrimary.setLabelProvider(new ColumnLabelProvider());
newColumn(tableLayout, Constants.CLASS_CALL_MODELS);
newColumn(tableLayout, Constants.CLASS_OVRD_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRP_MODEL);
newColumn(tableLayout, Constants.CLASS_OVRM_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFC_MODEL);
newColumn(tableLayout, Constants.CLASS_SELFM_MODEL);
tableViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
return ((Multimap<?, ?>) inputElement).keySet().toArray();
}
});
tableViewer.setSorter(new ViewerSorter());
initializeContent();
addRefreshButton();
addDeleteButton();
addContextMenu();
m_bindingContext = initDataBindings();
}
|
diff --git a/src/main/java/net/pms/encoders/MEncoderVideo.java b/src/main/java/net/pms/encoders/MEncoderVideo.java
index 9d9464c27..92eab9fc4 100644
--- a/src/main/java/net/pms/encoders/MEncoderVideo.java
+++ b/src/main/java/net/pms/encoders/MEncoderVideo.java
@@ -1,2790 +1,2790 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.encoders;
import bsh.EvalError;
import bsh.Interpreter;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.FormatConfiguration;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.*;
import net.pms.formats.Format;
import static net.pms.formats.v2.AudioUtils.getLPCMChannelMappingForMencoder;
import net.pms.formats.v2.SubtitleType;
import net.pms.formats.v2.SubtitleUtils;
import net.pms.io.*;
import net.pms.network.HTTPResource;
import net.pms.newgui.CustomJButton;
import net.pms.newgui.FontFileFilter;
import net.pms.newgui.LooksFrame;
import net.pms.newgui.MyComboBoxModel;
import net.pms.newgui.RestrictedFileSystemView;
import net.pms.util.CodecUtil;
import net.pms.util.FileUtil;
import net.pms.util.FormLayoutUtil;
import net.pms.util.ProcessUtil;
import static org.apache.commons.lang.BooleanUtils.isTrue;
import static org.apache.commons.lang.StringUtils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MEncoderVideo extends Player {
private static final Logger LOGGER = LoggerFactory.getLogger(MEncoderVideo.class);
private static final String COL_SPEC = "left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, pref:grow";
private static final String ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu,p, 3dlu, p, 3dlu, p, 3dlu, p, 9dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p";
private static final String REMOVE_OPTION = "---REMOVE-ME---"; // use an out-of-band option that can't be confused with a real option
private JTextField mencoder_ass_scale;
private JTextField mencoder_ass_margin;
private JTextField mencoder_ass_outline;
private JTextField mencoder_ass_shadow;
private JTextField mencoder_noass_scale;
private JTextField mencoder_noass_subpos;
private JTextField mencoder_noass_blur;
private JTextField mencoder_noass_outline;
private JTextField mencoder_custom_options;
private JTextField langs;
private JTextField defaultsubs;
private JTextField forcedsub;
private JTextField forcedtags;
private JTextField defaultaudiosubs;
private JTextField defaultfont;
private JComboBox subtitleCodePage;
private JTextField subq;
private JCheckBox forcefps;
private JCheckBox yadif;
private JCheckBox scaler;
private JTextField scaleX;
private JTextField scaleY;
private JCheckBox assdefaultstyle;
private JCheckBox fc;
private JCheckBox ass;
private JCheckBox checkBox;
private JCheckBox mencodermt;
private JCheckBox videoremux;
private JCheckBox noskip;
private JCheckBox intelligentsync;
private JTextField alternateSubFolder;
private CustomJButton subColor;
private JTextField ocw;
private JTextField och;
private JCheckBox subs;
private JCheckBox fribidi;
private final PmsConfiguration configuration;
private static final String[] INVALID_CUSTOM_OPTIONS = {
"-of",
"-oac",
"-ovc",
"-mpegopts"
};
private static final String INVALID_CUSTOM_OPTIONS_LIST = Arrays.toString(INVALID_CUSTOM_OPTIONS);
public static final int MENCODER_MAX_THREADS = 8;
public static final String ID = "mencoder";
// TODO (breaking change): most (probably all) of these
// protected fields should be private. And at least two
// shouldn't be fields
@Deprecated
protected boolean dvd;
@Deprecated
protected String overriddenMainArgs[];
protected boolean dtsRemux;
protected boolean pcm;
protected boolean ovccopy;
protected boolean ac3Remux;
protected boolean mpegts;
protected boolean wmv;
public static final String DEFAULT_CODEC_CONF_SCRIPT =
Messages.getString("MEncoderVideo.68")
+ Messages.getString("MEncoderVideo.69")
+ Messages.getString("MEncoderVideo.70")
+ Messages.getString("MEncoderVideo.71")
+ Messages.getString("MEncoderVideo.72")
+ Messages.getString("MEncoderVideo.73")
+ Messages.getString("MEncoderVideo.75")
+ Messages.getString("MEncoderVideo.76")
+ Messages.getString("MEncoderVideo.77")
+ Messages.getString("MEncoderVideo.78")
+ Messages.getString("MEncoderVideo.79")
+ "#\n"
+ Messages.getString("MEncoderVideo.80")
+ "container == iso :: -nosync\n"
+ "(container == avi || container == matroska) && vcodec == mpeg4 && acodec == mp3 :: -mc 0.1\n"
+ "container == flv :: -mc 0.1\n"
+ "container == mov :: -mc 0.1\n"
+ "container == rm :: -mc 0.1\n"
+ "container == matroska && framerate == 29.97 :: -nomux -mc 0\n"
+ "container == mp4 && vcodec == h264 :: -mc 0.1\n"
+ "\n"
+ Messages.getString("MEncoderVideo.87")
+ Messages.getString("MEncoderVideo.88")
+ Messages.getString("MEncoderVideo.89")
+ Messages.getString("MEncoderVideo.91");
public JCheckBox getCheckBox() {
return checkBox;
}
public JCheckBox getNoskip() {
return noskip;
}
public JCheckBox getSubs() {
return subs;
}
public MEncoderVideo(PmsConfiguration configuration) {
this.configuration = configuration;
}
@Override
public JComponent config() {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
checkBox = new JCheckBox(Messages.getString("MEncoderVideo.0"));
checkBox.setContentAreaFilled(false);
if (configuration.getSkipLoopFilterEnabled()) {
checkBox.setSelected(true);
}
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setSkipLoopFilterEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
mencodermt = new JCheckBox(Messages.getString("MEncoderVideo.35"));
mencodermt.setContentAreaFilled(false);
if (configuration.getMencoderMT()) {
mencodermt.setSelected(true);
}
mencodermt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setMencoderMT(mencodermt.isSelected());
}
});
mencodermt.setEnabled(Platform.isWindows() || Platform.isMac());
builder.add(mencodermt, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
builder.add(checkBox, FormLayoutUtil.flip(cc.xyw(3, 3, 12), colSpec, orientation));
noskip = new JCheckBox(Messages.getString("MEncoderVideo.2"));
noskip.setContentAreaFilled(false);
if (configuration.isMencoderNoOutOfSync()) {
noskip.setSelected(true);
}
noskip.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderNoOutOfSync((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(noskip, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation));
CustomJButton button = new CustomJButton(Messages.getString("MEncoderVideo.29"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel codecPanel = new JPanel(new BorderLayout());
final JTextArea textArea = new JTextArea();
textArea.setText(configuration.getCodecSpecificConfig());
textArea.setFont(new Font("Courier", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new java.awt.Dimension(900, 100));
final JTextArea textAreaDefault = new JTextArea();
textAreaDefault.setText(DEFAULT_CODEC_CONF_SCRIPT);
textAreaDefault.setBackground(Color.WHITE);
textAreaDefault.setFont(new Font("Courier", Font.PLAIN, 12));
textAreaDefault.setEditable(false);
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
JScrollPane scrollPaneDefault = new JScrollPane(textAreaDefault);
scrollPaneDefault.setPreferredSize(new java.awt.Dimension(900, 450));
JPanel customPanel = new JPanel(new BorderLayout());
intelligentsync = new JCheckBox(Messages.getString("MEncoderVideo.3"));
intelligentsync.setContentAreaFilled(false);
if (configuration.isMencoderIntelligentSync()) {
intelligentsync.setSelected(true);
}
intelligentsync.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderIntelligentSync((e.getStateChange() == ItemEvent.SELECTED));
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
}
});
JLabel label = new JLabel(Messages.getString("MEncoderVideo.33"));
customPanel.add(label, BorderLayout.NORTH);
customPanel.add(scrollPane, BorderLayout.SOUTH);
codecPanel.add(intelligentsync, BorderLayout.NORTH);
codecPanel.add(scrollPaneDefault, BorderLayout.CENTER);
codecPanel.add(customPanel, BorderLayout.SOUTH);
while (JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
codecPanel, Messages.getString("MEncoderVideo.34"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
String newCodecparam = textArea.getText();
DLNAMediaInfo fakemedia = new DLNAMediaInfo();
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setCodecA("ac3");
fakemedia.setCodecV("mpeg4");
fakemedia.setContainer("matroska");
fakemedia.setDuration(45d*60);
audio.getAudioProperties().setNumberOfChannels(2);
fakemedia.setWidth(1280);
fakemedia.setHeight(720);
audio.setSampleFrequency("48000");
fakemedia.setFrameRate("23.976");
fakemedia.getAudioTracksList().add(audio);
String result[] = getSpecificCodecOptions(newCodecparam, fakemedia, new OutputParams(configuration), "dummy.mpg", "dummy.srt", false, true);
if (result.length > 0 && result[0].startsWith("@@")) {
String errorMessage = result[0].substring(2);
JOptionPane.showMessageDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
errorMessage,
Messages.getString("Dialog.Error"),
JOptionPane.ERROR_MESSAGE
);
} else {
configuration.setCodecSpecificConfig(newCodecparam);
break;
}
}
}
});
builder.add(button, FormLayoutUtil.flip(cc.xy(1, 11), colSpec, orientation));
forcefps = new JCheckBox(Messages.getString("MEncoderVideo.4"));
forcefps.setContentAreaFilled(false);
if (configuration.isMencoderForceFps()) {
forcefps.setSelected(true);
}
forcefps.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderForceFps(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcefps, FormLayoutUtil.flip(cc.xyw(1, 7, 2), colSpec, orientation));
yadif = new JCheckBox(Messages.getString("MEncoderVideo.26"));
yadif.setContentAreaFilled(false);
if (configuration.isMencoderYadif()) {
yadif.setSelected(true);
}
yadif.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderYadif(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(yadif, FormLayoutUtil.flip(cc.xyw(3, 7, 7), colSpec, orientation));
scaler = new JCheckBox(Messages.getString("MEncoderVideo.27"));
scaler.setContentAreaFilled(false);
scaler.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderScaler(e.getStateChange() == ItemEvent.SELECTED);
scaleX.setEnabled(configuration.isMencoderScaler());
scaleY.setEnabled(configuration.isMencoderScaler());
}
});
builder.add(scaler, FormLayoutUtil.flip(cc.xyw(3, 5, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28"), FormLayoutUtil.flip(cc.xy(9, 5, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleX = new JTextField("" + configuration.getMencoderScaleX());
scaleX.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleX(Integer.parseInt(scaleX.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleX from \"" + scaleX.getText() + "\"");
}
}
});
builder.add(scaleX, FormLayoutUtil.flip(cc.xy(11, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30"), FormLayoutUtil.flip(cc.xy(13, 5, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleY = new JTextField("" + configuration.getMencoderScaleY());
scaleY.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleY(Integer.parseInt(scaleY.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleY from \"" + scaleY.getText() + "\"");
}
}
});
builder.add(scaleY, FormLayoutUtil.flip(cc.xy(15, 5), colSpec, orientation));
if (configuration.isMencoderScaler()) {
scaler.setSelected(true);
} else {
scaleX.setEnabled(false);
scaleY.setEnabled(false);
}
videoremux = new JCheckBox("<html>" + Messages.getString("MEncoderVideo.38") + "</html>");
videoremux.setContentAreaFilled(false);
if (configuration.isMencoderMuxWhenCompatible()) {
videoremux.setSelected(true);
}
videoremux.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderMuxWhenCompatible((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(videoremux, FormLayoutUtil.flip(cc.xyw(1, 9, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.6"), FormLayoutUtil.flip(cc.xy(1, 17), colSpec, orientation));
mencoder_custom_options = new JTextField(configuration.getMencoderCustomOptions());
mencoder_custom_options.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderCustomOptions(mencoder_custom_options.getText());
}
});
builder.add(mencoder_custom_options, FormLayoutUtil.flip(cc.xyw(3, 17, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.7"), FormLayoutUtil.flip(cc.xy(1, 19), colSpec, orientation));
langs = new JTextField(configuration.getMencoderAudioLanguages());
langs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAudioLanguages(langs.getText());
}
});
builder.add(langs, FormLayoutUtil.flip(cc.xyw(3, 19, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.93"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28") + " (%)", FormLayoutUtil.flip(cc.xy(1, 21, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ocw = new JTextField(configuration.getMencoderOverscanCompensationWidth());
ocw.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationWidth(ocw.getText());
}
});
builder.add(ocw, FormLayoutUtil.flip(cc.xyw(3, 21, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30") + " (%)", FormLayoutUtil.flip(cc.xy(5, 21), colSpec, orientation));
och = new JTextField(configuration.getMencoderOverscanCompensationHeight());
och.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationHeight(och.getText());
}
});
builder.add(och, FormLayoutUtil.flip(cc.xyw(7, 21, 1), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("MEncoderVideo.8"), FormLayoutUtil.flip(cc.xyw(1, 23, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("MEncoderVideo.9"), FormLayoutUtil.flip(cc.xy(1, 25), colSpec, orientation));
defaultsubs = new JTextField(configuration.getMencoderSubLanguages());
defaultsubs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderSubLanguages(defaultsubs.getText());
}
});
builder.add(defaultsubs, FormLayoutUtil.flip(cc.xyw(3, 25, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.94"), FormLayoutUtil.flip(cc.xyw(8, 25, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedsub = new JTextField(configuration.getMencoderForcedSubLanguage());
forcedsub.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderForcedSubLanguage(forcedsub.getText());
}
});
builder.add(forcedsub, FormLayoutUtil.flip(cc.xy(11, 25), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.95") + " ", FormLayoutUtil.flip(cc.xyw(12, 25, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedtags = new JTextField(configuration.getMencoderForcedSubTags());
forcedtags.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderForcedSubTags(forcedtags.getText());
}
});
builder.add(forcedtags, FormLayoutUtil.flip(cc.xyw(14, 25, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 27), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getMencoderAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 27, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 29), colSpec, orientation));
Object data[] = new Object[]{
configuration.getMencoderSubCp(),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subtitleCodePage = new JComboBox(cbm);
subtitleCodePage.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setMencoderSubCp(s);
}
}
});
subtitleCodePage.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
subtitleCodePage.getItemListeners()[0].itemStateChanged(new ItemEvent(subtitleCodePage, 0, subtitleCodePage.getEditor().getItem(), ItemEvent.SELECTED));
}
});
subtitleCodePage.setEditable(true);
builder.add(subtitleCodePage, FormLayoutUtil.flip(cc.xyw(3, 29, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 29, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 31), colSpec, orientation));
defaultfont = new JTextField(configuration.getMencoderFont());
defaultfont.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 31, 8), colSpec, orientation));
CustomJButton fontselect = new CustomJButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setMencoderFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xyw(11, 31, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.37"), FormLayoutUtil.flip(cc.xyw(1, 33, 2), colSpec, orientation));
alternateSubFolder = new JTextField(configuration.getAlternateSubsFolder());
alternateSubFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateSubsFolder(alternateSubFolder.getText());
}
});
builder.add(alternateSubFolder, FormLayoutUtil.flip(cc.xyw(3, 33, 8), colSpec, orientation));
CustomJButton select = new CustomJButton("...");
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
alternateSubFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setAlternateSubsFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(select, FormLayoutUtil.flip(cc.xyw(11, 33, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.133"), FormLayoutUtil.flip(cc.xy(1, 37, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_ass_scale = new JTextField(configuration.getMencoderAssScale());
mencoder_ass_scale.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssScale(mencoder_ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 37), colSpec, orientation));
mencoder_ass_outline = new JTextField(configuration.getMencoderAssOutline());
mencoder_ass_outline.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssOutline(mencoder_ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 37), colSpec, orientation));
mencoder_ass_shadow = new JTextField(configuration.getMencoderAssShadow());
mencoder_ass_shadow.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssShadow(mencoder_ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 37), colSpec, orientation));
mencoder_ass_margin = new JTextField(configuration.getMencoderAssMargin());
mencoder_ass_margin.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssMargin(mencoder_ass_margin.getText());
}
});
builder.add(mencoder_ass_scale, FormLayoutUtil.flip(cc.xy(3, 37), colSpec, orientation));
builder.add(mencoder_ass_outline, FormLayoutUtil.flip(cc.xy(7, 37), colSpec, orientation));
builder.add(mencoder_ass_shadow, FormLayoutUtil.flip(cc.xy(11, 37), colSpec, orientation));
builder.add(mencoder_ass_margin, FormLayoutUtil.flip(cc.xy(15, 37), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.16"), FormLayoutUtil.flip(cc.xy(1, 39), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.133"), FormLayoutUtil.flip(cc.xy(1, 39, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_noass_scale = new JTextField(configuration.getMencoderNoAssScale());
mencoder_noass_scale.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssScale(mencoder_noass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.17"), FormLayoutUtil.flip(cc.xy(5, 39), colSpec, orientation));
mencoder_noass_outline = new JTextField(configuration.getMencoderNoAssOutline());
mencoder_noass_outline.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssOutline(mencoder_noass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.18"), FormLayoutUtil.flip(cc.xy(9, 39), colSpec, orientation));
mencoder_noass_blur = new JTextField(configuration.getMencoderNoAssBlur());
mencoder_noass_blur.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssBlur(mencoder_noass_blur.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.19"), FormLayoutUtil.flip(cc.xy(13, 39), colSpec, orientation));
mencoder_noass_subpos = new JTextField(configuration.getMencoderNoAssSubPos());
mencoder_noass_subpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssSubPos(mencoder_noass_subpos.getText());
}
});
builder.add(mencoder_noass_scale, FormLayoutUtil.flip(cc.xy(3, 39), colSpec, orientation));
builder.add(mencoder_noass_outline, FormLayoutUtil.flip(cc.xy(7, 39), colSpec, orientation));
builder.add(mencoder_noass_blur, FormLayoutUtil.flip(cc.xy(11, 39), colSpec, orientation));
builder.add(mencoder_noass_subpos, FormLayoutUtil.flip(cc.xy(15, 39), colSpec, orientation));
ass = new JCheckBox(Messages.getString("MEncoderVideo.20"));
ass.setContentAreaFilled(false);
ass.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e != null) {
configuration.setMencoderAss(e.getStateChange() == ItemEvent.SELECTED);
}
}
});
builder.add(ass, FormLayoutUtil.flip(cc.xy(1, 35), colSpec, orientation));
ass.setSelected(configuration.isMencoderAss());
ass.getItemListeners()[0].itemStateChanged(null);
fc = new JCheckBox(Messages.getString("MEncoderVideo.21"));
fc.setContentAreaFilled(false);
fc.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderFontConfig(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fc, FormLayoutUtil.flip(cc.xyw(3, 35, 5), colSpec, orientation));
fc.setSelected(configuration.isMencoderFontConfig());
assdefaultstyle = new JCheckBox(Messages.getString("MEncoderVideo.36"));
assdefaultstyle.setContentAreaFilled(false);
assdefaultstyle.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderAssDefaultStyle(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(assdefaultstyle, FormLayoutUtil.flip(cc.xyw(8, 35, 4), colSpec, orientation));
assdefaultstyle.setSelected(configuration.isMencoderAssDefaultStyle());
subColor = new CustomJButton(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(13, 35, 3), colSpec, orientation));
subs = new JCheckBox(Messages.getString("MEncoderVideo.22"));
subs.setContentAreaFilled(false);
if (configuration.isAutoloadSubtitles()) {
subs.setSelected(true);
}
subs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoloadSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 41, 15), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.92"), FormLayoutUtil.flip(cc.xy(1, 43), colSpec, orientation));
subq = new JTextField(configuration.getMencoderVobsubSubtitleQuality());
subq.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderVobsubSubtitleQuality(subq.getText());
}
});
builder.add(subq, FormLayoutUtil.flip(cc.xyw(3, 43, 1), colSpec, orientation));
JCheckBox disableSubs = ((LooksFrame) PMS.get().getFrame()).getTr().getDisableSubs();
disableSubs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderDisableSubs(e.getStateChange() == ItemEvent.SELECTED);
subs.setEnabled(!configuration.isMencoderDisableSubs());
subq.setEnabled(!configuration.isMencoderDisableSubs());
defaultsubs.setEnabled(!configuration.isMencoderDisableSubs());
subtitleCodePage.setEnabled(!configuration.isMencoderDisableSubs());
ass.setEnabled(!configuration.isMencoderDisableSubs());
assdefaultstyle.setEnabled(!configuration.isMencoderDisableSubs());
fribidi.setEnabled(!configuration.isMencoderDisableSubs());
fc.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_scale.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_outline.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_shadow.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_margin.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_scale.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_outline.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_blur.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_subpos.setEnabled(!configuration.isMencoderDisableSubs());
forcedsub.setEnabled(!configuration.isMencoderDisableSubs());
forcedtags.setEnabled(!configuration.isMencoderDisableSubs());
defaultaudiosubs.setEnabled(!configuration.isMencoderDisableSubs());
defaultfont.setEnabled(!configuration.isMencoderDisableSubs());
alternateSubFolder.setEnabled(!configuration.isMencoderDisableSubs());
if (!configuration.isMencoderDisableSubs()) {
ass.getItemListeners()[0].itemStateChanged(null);
}
}
});
if (configuration.isMencoderDisableSubs()) {
disableSubs.setSelected(true);
}
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
@Override
public int purpose() {
return VIDEO_SIMPLEFILE_PLAYER;
}
@Override
public String id() {
return ID;
}
@Override
public boolean avisynth() {
return false;
}
@Override
public boolean isTimeSeekable() {
return true;
}
protected String[] getDefaultArgs() {
List<String> defaultArgsList = new ArrayList<String>();
defaultArgsList.add("-msglevel");
defaultArgsList.add("statusline=2");
defaultArgsList.add("-oac");
defaultArgsList.add((ac3Remux || dtsRemux) ? "copy" : (pcm ? "pcm" : "lavc"));
defaultArgsList.add("-of");
defaultArgsList.add((wmv || mpegts) ? "lavf" : ((pcm && avisynth()) ? "avi" : ((pcm || dtsRemux) ? "rawvideo" : "mpeg")));
if (wmv) {
defaultArgsList.add("-lavfopts");
defaultArgsList.add("format=asf");
} else if (mpegts) {
defaultArgsList.add("-lavfopts");
defaultArgsList.add("format=mpegts");
}
defaultArgsList.add("-mpegopts");
defaultArgsList.add("format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64");
defaultArgsList.add("-ovc");
defaultArgsList.add(ovccopy ? "copy" : "lavc");
String[] defaultArgsArray = new String[defaultArgsList.size()];
defaultArgsList.toArray(defaultArgsArray);
return defaultArgsArray;
}
private String[] sanitizeArgs(String[] args) {
List<String> sanitized = new ArrayList<String>();
int i = 0;
while (i < args.length) {
String name = args[i];
String value = null;
for (String option : INVALID_CUSTOM_OPTIONS) {
if (option.equals(name)) {
if ((i + 1) < args.length) {
value = " " + args[i + 1];
++i;
} else {
value = "";
}
LOGGER.warn(
"Ignoring custom MEncoder option: {}{}; the following options cannot be changed: " + INVALID_CUSTOM_OPTIONS_LIST,
name,
value
);
break;
}
}
if (value == null) {
sanitized.add(args[i]);
}
++i;
}
return sanitized.toArray(new String[sanitized.size()]);
}
@Override
public String[] args() {
String args[];
String defaultArgs[] = getDefaultArgs();
if (overriddenMainArgs != null) {
// add the sanitized custom MEncoder options.
// not cached because they may be changed on the fly in the GUI
// TODO if/when we upgrade to org.apache.commons.lang3:
// args = ArrayUtils.addAll(defaultArgs, sanitizeArgs(overriddenMainArgs))
String[] sanitizedCustomArgs = sanitizeArgs(overriddenMainArgs);
args = new String[defaultArgs.length + sanitizedCustomArgs.length];
System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length);
System.arraycopy(sanitizedCustomArgs, 0, args, defaultArgs.length, sanitizedCustomArgs.length);
} else {
args = defaultArgs;
}
return args;
}
@Override
public String executable() {
return configuration.getMencoderPath();
}
private int[] getVideoBitrateConfig(String bitrate) {
int bitrates[] = new int[2];
if (bitrate.contains("(") && bitrate.contains(")")) {
bitrates[1] = Integer.parseInt(bitrate.substring(bitrate.indexOf("(") + 1, bitrate.indexOf(")")));
}
if (bitrate.contains("(")) {
bitrate = bitrate.substring(0, bitrate.indexOf("(")).trim();
}
if (isBlank(bitrate)) {
bitrate = "0";
}
bitrates[0] = (int) Double.parseDouble(bitrate);
return bitrates;
}
/**
* Note: This is not exact. The bitrate can go above this but it is generally pretty good.
* @return The maximum bitrate the video should be along with the buffer size using MEncoder vars
*/
private String addMaximumBitrateConstraints(String encodeSettings, DLNAMediaInfo media, String quality, RendererConfiguration mediaRenderer, String audioType) {
int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate());
int rendererMaxBitrates[] = new int[2];
if (mediaRenderer.getMaxVideoBitrate() != null) {
rendererMaxBitrates = getVideoBitrateConfig(mediaRenderer.getMaxVideoBitrate());
}
if ((rendererMaxBitrates[0] > 0) && ((defaultMaxBitrates[0] == 0) || (rendererMaxBitrates[0] < defaultMaxBitrates[0]))) {
defaultMaxBitrates = rendererMaxBitrates;
}
if (mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0 && !quality.contains("vrc_buf_size") && !quality.contains("vrc_maxrate") && !quality.contains("vbitrate")) {
// Convert value from Mb to Kb
defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0];
// Halve it since it seems to send up to 1 second of video in advance
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2;
int bufSize = 1835;
if (media.isHDVideo()) {
bufSize = defaultMaxBitrates[0] / 3;
}
if (bufSize > 7000) {
bufSize = 7000;
}
if (defaultMaxBitrates[1] > 0) {
bufSize = defaultMaxBitrates[1];
}
if (mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) {
bufSize = 1835;
}
// Make room for audio
// If audio is PCM, subtract 4600kb/s
if ("pcm".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 4600;
}
// If audio is DTS, subtract 1510kb/s
else if ("dts".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 1510;
}
// If audio is AC3, subtract the configured amount (usually 640)
else if ("ac3".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate();
}
// Round down to the nearest Mb
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000;
encodeSettings += ":vrc_maxrate=" + defaultMaxBitrates[0] + ":vrc_buf_size=" + bufSize;
}
return encodeSettings;
}
/*
* Collapse the multiple internal ways of saying "subtitles are disabled" into a single method
* which returns true if any of the following are true:
*
* 1) configuration.isMencoderDisableSubs()
* 2) params.sid == null
* 3) avisynth()
*/
private boolean isDisableSubtitles(OutputParams params) {
return configuration.isMencoderDisableSubs() || (params.sid == null) || avisynth();
}
@Override
public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(PMS.getConfiguration().getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTSMuxerVideoEngineEnabled = PMS.getConfiguration().getEnginesAsList(PMS.get().getRegistry()).contains(TSMuxerVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTSMuxerVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTSMuxerVideoEngineEnabled &&
configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = defaultString(globalMencoderOptions)
+ " "
+ defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/*
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
- if (rendererMencoderOptions.contains("expand=") || dvd) {
+ if (rendererMencoderOptions.contains("expand=") && dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = MEncoderAviSynth.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// MKV: in some circumstances, MEncoder automatically selects an internal sub unless we explicitly disable (internal) subtitles
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=14&t=15891
cmdList.add("-nosub");
// make sure external subs are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
@Override
public String mimeType() {
return HTTPResource.VIDEO_TRANSCODE;
}
@Override
public String name() {
return "MEncoder";
}
@Override
public int type() {
return Format.VIDEO;
}
private String[] getSpecificCodecOptions(
String codecParam,
DLNAMediaInfo media,
OutputParams params,
String filename,
String externalSubtitlesFileName,
boolean enable,
boolean verifyOnly
) {
StringBuilder sb = new StringBuilder();
String codecs = enable ? DEFAULT_CODEC_CONF_SCRIPT : "";
codecs += "\n" + codecParam;
StringTokenizer stLines = new StringTokenizer(codecs, "\n");
try {
Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);
ArrayList<String> types = CodecUtil.getPossibleCodecs();
int rank = 1;
if (types != null) {
for (String type : types) {
int r = rank++;
interpreter.set("" + type, r);
String secondaryType = "dummy";
if ("matroska".equals(type)) {
secondaryType = "mkv";
interpreter.set(secondaryType, r);
} else if ("rm".equals(type)) {
secondaryType = "rmvb";
interpreter.set(secondaryType, r);
} else if ("mpeg2".startsWith(type)) {
secondaryType = "mpeg2";
interpreter.set(secondaryType, r);
} else if ("mpeg1video".equals(type)) {
secondaryType = "mpeg1";
interpreter.set(secondaryType, r);
}
if (media.getContainer() != null && (media.getContainer().equals(type) || media.getContainer().equals(secondaryType))) {
interpreter.set("container", r);
} else if (media.getCodecV() != null && (media.getCodecV().equals(type) || media.getCodecV().equals(secondaryType))) {
interpreter.set("vcodec", r);
} else if (params.aid != null && params.aid.getCodecA() != null && params.aid.getCodecA().equals(type)) {
interpreter.set("acodec", r);
}
}
} else {
return null;
}
interpreter.set("filename", filename);
interpreter.set("audio", params.aid != null);
interpreter.set("subtitles", params.sid != null);
interpreter.set("srtfile", externalSubtitlesFileName);
if (params.aid != null) {
interpreter.set("samplerate", params.aid.getSampleRate());
}
String frameRateNumber = null;
if (media != null) {
frameRateNumber = media.getValidFps(false);
}
try {
if (frameRateNumber != null) {
interpreter.set("framerate", Double.parseDouble(frameRateNumber));
}
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse framerate from \"" + frameRateNumber + "\"");
}
interpreter.set("duration", media.getDurationInSeconds());
if (params.aid != null) {
interpreter.set("channels", params.aid.getAudioProperties().getNumberOfChannels());
}
interpreter.set("height", media.getHeight());
interpreter.set("width", media.getWidth());
while (stLines.hasMoreTokens()) {
String line = stLines.nextToken();
if (!line.startsWith("#") && line.trim().length() > 0) {
int separator = line.indexOf("::");
if (separator > -1) {
String key = null;
try {
key = line.substring(0, separator).trim();
String value = line.substring(separator + 2).trim();
if (value.length() > 0) {
if (key.length() == 0) {
key = "1 == 1";
}
Object result = interpreter.eval(key);
if (result != null && result instanceof Boolean && (Boolean) result) {
sb.append(" ");
sb.append(value);
}
}
} catch (Throwable e) {
LOGGER.debug("Error while executing: " + key + " : " + e.getMessage());
if (verifyOnly) {
return new String[]{"@@Error while parsing: " + e.getMessage()};
}
}
} else if (verifyOnly) {
return new String[]{"@@Malformatted line: " + line};
}
}
}
} catch (EvalError e) {
LOGGER.debug("BeanShell error: " + e.getMessage());
}
String completeLine = sb.toString();
ArrayList<String> args = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(completeLine, " ");
while (st.hasMoreTokens()) {
String arg = st.nextToken().trim();
if (arg.length() > 0) {
args.add(arg);
}
}
String definitiveArgs[] = new String[args.size()];
args.toArray(definitiveArgs);
return definitiveArgs;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCompatible(DLNAResource resource) {
if (resource == null || resource.getFormat().getType() != Format.VIDEO) {
return false;
}
Format format = resource.getFormat();
if (format != null) {
Format.Identifier id = format.getIdentifier();
if (id.equals(Format.Identifier.ISO)
|| id.equals(Format.Identifier.MKV)
|| id.equals(Format.Identifier.MPG)) {
return true;
}
}
return false;
}
}
| true | true | public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(PMS.getConfiguration().getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTSMuxerVideoEngineEnabled = PMS.getConfiguration().getEnginesAsList(PMS.get().getRegistry()).contains(TSMuxerVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTSMuxerVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTSMuxerVideoEngineEnabled &&
configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = defaultString(globalMencoderOptions)
+ " "
+ defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/*
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") || dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = MEncoderAviSynth.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// MKV: in some circumstances, MEncoder automatically selects an internal sub unless we explicitly disable (internal) subtitles
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=14&t=15891
cmdList.add("-nosub");
// make sure external subs are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
| public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(PMS.getConfiguration().getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTSMuxerVideoEngineEnabled = PMS.getConfiguration().getEnginesAsList(PMS.get().getRegistry()).contains(TSMuxerVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTSMuxerVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTSMuxerVideoEngineEnabled &&
configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = defaultString(globalMencoderOptions)
+ " "
+ defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/*
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") && dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = MEncoderAviSynth.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// MKV: in some circumstances, MEncoder automatically selects an internal sub unless we explicitly disable (internal) subtitles
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=14&t=15891
cmdList.add("-nosub");
// make sure external subs are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
|
diff --git a/src/plugins/org.drftpd.commands.dir/src/org/drftpd/commands/dir/Dir.java b/src/plugins/org.drftpd.commands.dir/src/org/drftpd/commands/dir/Dir.java
index 0156e9bb..108352ff 100644
--- a/src/plugins/org.drftpd.commands.dir/src/org/drftpd/commands/dir/Dir.java
+++ b/src/plugins/org.drftpd.commands.dir/src/org/drftpd/commands/dir/Dir.java
@@ -1,760 +1,762 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DrFTPD 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.commands.dir;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.drftpd.Bytes;
import org.drftpd.Checksum;
import org.drftpd.GlobalContext;
import org.drftpd.commandmanager.CommandInterface;
import org.drftpd.commandmanager.CommandRequest;
import org.drftpd.commandmanager.CommandResponse;
import org.drftpd.commandmanager.ImproperUsageException;
import org.drftpd.commandmanager.StandardCommandManager;
import org.drftpd.dynamicdata.Key;
import org.drftpd.event.DirectoryFtpEvent;
import org.drftpd.exceptions.FileExistsException;
import org.drftpd.exceptions.NoAvailableSlaveException;
import org.drftpd.io.PermissionDeniedException;
import org.drftpd.master.Session;
import org.drftpd.usermanager.User;
import org.drftpd.vfs.DirectoryHandle;
import org.drftpd.vfs.FileHandle;
import org.drftpd.vfs.InodeHandle;
import org.drftpd.vfs.LinkHandle;
import org.drftpd.vfs.ListUtils;
import org.drftpd.vfs.ObjectNotValidException;
import org.drftpd.vfs.VirtualFileSystem;
/**
* @author mog
* @author djb61
* @version $Id$
*/
public class Dir extends CommandInterface {
private final static SimpleDateFormat DATE_FMT = new SimpleDateFormat(
"yyyyMMddHHmmss.SSS");
private static final Logger logger = Logger.getLogger(Dir.class);
private static final Key<InodeHandle> RENAMEFROM = new Key<InodeHandle>(Dir.class, "renamefrom");
// This Keys are place holders for usefull information that gets removed during
// deletion operations but are need to process hooks.
public static final Key<String> USERNAME = new Key<String>(Dir.class, "username");
public static final Key<Long> FILESIZE = new Key<Long>(Dir.class, "fileSize");
public static final Key<String> FILENAME = new Key<String>(Dir.class, "fileName");
public static final Key<Boolean> ISFILE = new Key<Boolean>(Dir.class, "isFile");
public static final Key<Long> XFERTIME = new Key<Long>(Dir.class, "xferTime");
/**
* <code>CDUP <CRLF></code><br>
*
* This command is a special case of CWD, and is included to
* simplify the implementation of programs for transferring
* directory trees between operating systems having different
* syntaxes for naming the parent directory. The reply codes
* shall be identical to the reply codes of CWD.
*/
public CommandResponse doCDUP(CommandRequest request) {
// change directory
if (request.getCurrentDirectory().isRoot()) {
return new CommandResponse(250,
"Directory remains " + request.getCurrentDirectory().getPath());
}
DirectoryHandle newCurrentDirectory = request.getCurrentDirectory().getParent();
return new CommandResponse(250,
"Directory changed to " + newCurrentDirectory.getPath(),
newCurrentDirectory, request.getUser());
}
/**
* <code>CWD <SP> <pathname> <CRLF></code><br>
*
* This command allows the user to work with a different
* directory for file storage or retrieval without
* altering his login or accounting information. Transfer
* parameters are similarly unchanged. The argument is a
* pathname specifying a directory.
*/
public CommandResponse doCWD(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
DirectoryHandle newCurrentDirectory = null;
User user = request.getSession().getUserNull(request.getUser());
try {
newCurrentDirectory = request.getCurrentDirectory().getDirectory(request.getArgument(), user);
} catch (FileNotFoundException ex) {
return new CommandResponse(550, ex.getMessage());
} catch (ObjectNotValidException e) {
return new CommandResponse(550, request.getArgument() + ": is not a directory");
}
CommandResponse response = new CommandResponse(250,
"Directory changed to " + newCurrentDirectory.getPath(),
newCurrentDirectory, request.getUser());
return response;
}
private void addVictimInformationToResponse(InodeHandle victim,
CommandResponse response) throws FileNotFoundException {
response.setObject(FILENAME, victim.getName());
response.setObject(FILESIZE, Long.valueOf(victim.getSize()));
response.setObject(USERNAME, victim.getUsername());
response.setObject(ISFILE, victim.isFile());
response.setObject(XFERTIME, victim.isFile() ? ((FileHandle)victim).getXfertime() : 0L);
}
/**
* <code>DELE <SP> <pathname> <CRLF></code><br>
*
* This command causes the file specified in the pathname to be
* deleted at the server site.
*/
public CommandResponse doDELE(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
// out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR);
return StandardCommandManager
.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
CommandResponse response = StandardCommandManager
.genericResponse("RESPONSE_250_ACTION_OKAY");
User user = request.getSession().getUserNull(request.getUser());
InodeHandle victim = null;
try {
victim = request.getCurrentDirectory().getInodeHandle(fileName,
user);
addVictimInformationToResponse(victim, response);
if (victim.isDirectory()) {
DirectoryHandle victimDir = (DirectoryHandle) victim;
if (!victimDir.isEmpty(user)) {
return new CommandResponse(550, victim.getPath()
+ ": Directory not empty");
}
}
victim.delete(user); // the file is only deleted here.
} catch (FileNotFoundException e) {
// this isn't good or bad, there could have easily been a race in
// another thread to delete this file
return new CommandResponse(550, e.getMessage());
} catch (PermissionDeniedException e) {
return StandardCommandManager
.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
if (victim.isFile() || victim.isLink()) { // link or file
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(
request.getUser()), "DELE", victim.getParent()));
// strange that we're sending the parent directory of the file being
// deleted without mentioning the file that was deleted...
} else { // if (requestedFile.isDirectory()) {
GlobalContext.getEventService()
.publishAsync(
new DirectoryFtpEvent(request.getSession()
.getUserNull(request.getUser()), "RMD",
(DirectoryHandle) victim));
}
return response;
}
/**
* <code>MDTM <SP> <pathname> <CRLF></code><br>
*
* Returns the date and time of when a file was modified.
*/
public CommandResponse doMDTM(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
InodeHandle reqFile;
User user = request.getSession().getUserNull(request.getUser());
try {
reqFile = request.getCurrentDirectory().getInodeHandle(fileName, user);
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
try {
synchronized(DATE_FMT) {
return new CommandResponse(213,
DATE_FMT.format(new Date(reqFile.lastModified())));
}
} catch (FileNotFoundException e) {
return new CommandResponse(550, e.getMessage());
}
//out.print(ftpStatus.getResponse(213, request, user, args));
//} else {
// out.write(ftpStatus.getResponse(550, request, user, null));
//}
}
/**
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be created as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*
*
* MKD
* 257
* 500, 501, 502, 421, 530, 550
*/
public CommandResponse doMKD(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
Session session = request.getSession();
String path = VirtualFileSystem.fixPath(request.getArgument());
DirectoryHandle fakeDirectory = request.getCurrentDirectory().getNonExistentDirectoryHandle(path);
String dirName = fakeDirectory.getName();
if (!ListUtils.isLegalFileName(dirName)) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN");
}
try {
try {
if (!fakeDirectory.getParent().equals(request.getCurrentDirectory()) &&
InodeHandle.isLink(fakeDirectory.getParent().getPath())) {
fakeDirectory = new LinkHandle(fakeDirectory.getParent().getPath())
.getTargetDirectory(session.getUserNull(request.getUser()))
.getNonExistentDirectoryHandle(dirName);
}
} catch (FileNotFoundException e1) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (ObjectNotValidException e) {
return new CommandResponse(550, "Parent directory does not exist");
}
DirectoryHandle newDir = null;
try {
newDir = fakeDirectory.getParent().createDirectory(session.getUserNull(request.getUser()), dirName);
} catch (FileNotFoundException e) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
GlobalContext.getEventService().publishAsync(new DirectoryFtpEvent(
session.getUserNull(request.getUser()), "MKD", newDir));
return new CommandResponse(257, "\"" + newDir.getPath() +
"\" created.");
} catch (FileExistsException ex) {
return new CommandResponse(550,
"directory " + dirName + " already exists");
}
}
/**
* <code>PWD <CRLF></code><br>
*
* This command causes the name of the current working
* directory to be returned in the reply.
*/
public CommandResponse doPWD(CommandRequest request) {
return new CommandResponse(257,
"\"" + request.getCurrentDirectory().getPath() +
"\" is current directory");
}
/**
* <code>RMD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be removed as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*/
public CommandResponse doRMD(CommandRequest request) {
return doDELE(request);
}
/**
* <code>RNFR <SP> <pathname> <CRLF></code><br>
*
* This command specifies the old pathname of the file which is
* to be renamed. This command must be immediately followed by
* a "rename to" command specifying the new file pathname.
*
* RNFR
450, 550
500, 501, 502, 421, 530
350
*/
public CommandResponse doRNFR(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
User user = request.getSession().getUserNull(request.getUser());
try {
request.getSession().setObject(RENAMEFROM, request.getCurrentDirectory().getInodeHandle(request.getArgument(), user));
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
return new CommandResponse(350, "File exists, ready for destination name");
}
/**
* <code>RNTO <SP> <pathname> <CRLF></code><br>
*
* This command specifies the new pathname of the file
* specified in the immediately preceding "rename from"
* command. Together the two commands cause a file to be
* renamed.
*/
public CommandResponse doRNTO(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// set state variables
InodeHandle fromInode = request.getSession().getObject(RENAMEFROM, null);
if (fromInode == null) {
return StandardCommandManager.genericResponse("RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS");
}
String argument = VirtualFileSystem.fixPath(request.getArgument());
if (!(argument.startsWith(VirtualFileSystem.separator))) {
// Not a full path, let's make it one
if (request.getCurrentDirectory().isRoot()) {
argument = VirtualFileSystem.separator + argument;
} else {
argument = request.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument;
}
}
DirectoryHandle toDir = null;
String newName = null;
User user = request.getSession().getUserNull(request.getUser());
try {
toDir = request.getCurrentDirectory().getDirectory(argument, user);
// toDir exists and is a directory, so we're just changing the parent directory and not the name
// unless toInode and fromInode are the same (i.e. a case change)
if (fromInode.isDirectory() && fromInode.equals(toDir)) {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} else {
// There are two possibilites here, the target is an existing link or a directory
// Check to see if a link with the target name exists
newName = fromInode.getName();
try {
DirectoryHandle linkParentDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
String linkName = VirtualFileSystem.getLast(argument);
// If a link exists and is the same link as the from inode this is valid
try {
InodeHandle linkHandle = linkParentDir.getLink(linkName, user);
if (fromInode.isLink() && fromInode.equals(linkHandle)) {
// Changing case of existing link
toDir = linkParentDir;
newName = linkName;
}
} catch (FileNotFoundException e2) {
// No link exists so we are moving an inode to a new parent without changing its name
} catch (ObjectNotValidException e2) {
// Target is an existing directory
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
} catch (FileNotFoundException e) {
// Directory does not exist, that means they may have specified _renameFrom's new name
// as the last part of the argument
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} catch (FileNotFoundException e1) {
// Destination doesn't exist
logger.debug("Destination doesn't exist", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory
logger.debug("Destination isn't a Directory", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
} catch (ObjectNotValidException e) {
// Target exists but is not a dir, this is invalid unless the target is a file and the same
// file as the source (i.e. a case change)
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
if (!toDir.equals(fromInode.getParent()) || !newName.equalsIgnoreCase(fromInode.getName())) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
InodeHandle toInode = null;
if (fromInode.isDirectory()) {
toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isFile()) {
toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isLink()) {
toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else {
return new CommandResponse(500, "Someone has extended the VFS beyond File/Directory/Link");
}
try {
/*logger.debug("before rename toInode-" +toInode);
logger.debug("before rename toInode.getPath()-" + toInode.getPath());
logger.debug("before rename toInode.getParent()-" + toInode.getParent());
logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
fromInode.renameTo(request.getSession().getUserNull(request.getUser()), toInode);
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
} catch (FileNotFoundException e) {
logger.info("FileNotFoundException on renameTo()", e);
return new CommandResponse(500, "FileNotFound - " + e.getMessage());
} catch (IOException e) {
logger.info("IOException on renameTo()", e);
return new CommandResponse(500, "IOException - " + e.getMessage());
}
/*logger.debug("after rename toInode-" +toInode);
logger.debug("after rename toInode.getPath()-" + toInode.getPath());
logger.debug("after rename toInode.getParent()-" + toInode.getParent());
logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
return new CommandResponse(250, request.getCommand().toUpperCase() + " command successful.");
}
public CommandResponse doSITE_CHOWN(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument());
if (st.countTokens() < 2) {
throw new ImproperUsageException();
}
String owner = st.nextToken();
String group = null;
boolean recursive = false;
if (owner.equalsIgnoreCase("-r")) {
recursive = true;
owner = st.nextToken();
}
int pos = owner.indexOf(':');
if (pos > 0) {
// Both user and group specified
group = owner.substring(pos + 1);
owner = owner.substring(0, pos);
} else if (pos == 0) {
// First char is ':', only change group
group = owner.substring(1);
owner = null;
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
User user = request.getSession().getUserNull(request.getUser());
if (!st.hasMoreTokens()) {
throw new ImproperUsageException();
}
while (st.hasMoreTokens()) {
try {
InodeHandle file = request.getCurrentDirectory().getInodeHandle(st.nextToken(), user);
if (owner != null) {
file.setUsername(owner);
}
if (group != null) {
file.setGroup(group);
}
if (file.isDirectory() && recursive) {
recursiveCHOWN((DirectoryHandle)file, owner, group, user, response);
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
return response;
}
private void recursiveCHOWN(DirectoryHandle dir, String owner, String group, User user, CommandResponse response) {
try {
for (InodeHandle inode : dir.getInodeHandles(user)) {
if (owner != null) {
inode.setUsername(owner);
}
if (group != null) {
inode.setGroup(group);
}
if (inode.isDirectory()) {
recursiveCHOWN((DirectoryHandle)inode, owner, group, user, response);
}
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
public CommandResponse doSITE_LINK(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument(),
" ");
if (st.countTokens() != 2) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String targetName = st.nextToken();
String linkName = st.nextToken();
User user = request.getSession().getUserNull(request.getUser());
try {
request.getCurrentDirectory().getInodeHandleUnchecked(targetName); // checks if the inode exists.
request.getCurrentDirectory().createLink(user, linkName, targetName); // create the link
} catch (FileExistsException e) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* USAGE: site wipe [-r] <file/directory>
*
* This is similar to the UNIX rm command.
* In glftpd, if you just delete a file, the uploader loses credits and
* upload stats for it. There are many people who didn't like that and
* were unable/too lazy to write a shell script to do it for them, so I
* wrote this command to get them off my back.
*
* If the argument is a file, it will simply be deleted. If it's a
* directory, it and the files it contains will be deleted. If the
* directory contains other directories, the deletion will be aborted.
*
* To remove a directory containing subdirectories, you need to use
* "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND.
* Glftpd will check if the parent directory of the file/directory you're
* trying to delete is writable by its owner. If not, wipe will not
* execute, so to protect directories from being wiped, make their parent
* 555.
*
* Also, wipe will only work where you have the right to delete (in
* glftpd.conf). Delete right and parent directory's mode of 755/777/etc
* will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory.
* "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO
* BE CAREFUL.
*
* This command will remove the deleted files/directories from the dirlog
* and dupefile databases.
*
* To give access to this command, add "-wipe -user flag =group" to the
* config file (similar to other site commands).
*
* @param request
* @param out
*/
public CommandResponse doSITE_WIPE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String arg = request.getArgument();
boolean recursive;
if (arg.startsWith("-r ")) {
arg = arg.substring(3);
recursive = true;
} else {
recursive = false;
}
InodeHandle wipeFile;
User user = request.getSession().getUserNull(request.getUser());
try {
wipeFile = request.getCurrentDirectory().getInodeHandle(arg, user);
if (wipeFile.isDirectory() && !recursive) {
if (((DirectoryHandle) wipeFile).isEmpty(user)) {
return new CommandResponse(550, "Can't wipe, directory not empty");
}
}
if (wipeFile.isLink()) {
+ InodeHandle linkFile = wipeFile;
wipeFile = ((LinkHandle) wipeFile).getTargetInodeUnchecked();
+ linkFile.delete(request.getSession().getUserNull(request.getUser()));
}
wipeFile.delete(request.getSession().getUserNull(request.getUser()));
if (wipeFile.isDirectory()) {
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(request.getUser()), "WIPE", (DirectoryHandle)wipeFile));
}
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* <code>SIZE <SP> <pathname> <CRLF></code><br>
*
* Returns the size of the file in bytes.
*/
public CommandResponse doSIZE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
InodeHandle file;
User user = request.getSession().getUserNull(request.getUser());
try {
file = request.getCurrentDirectory().getInodeHandle(request.getArgument(), user);
return new CommandResponse(213, Long.toString(file.getSize()));
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
/**
* http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm
*
* Originally implemented by CuteFTP Pro and Globalscape FTP Server
*/
public CommandResponse doXCRC(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
StringTokenizer st = new StringTokenizer(request.getArgument());
FileHandle myFile;
User user = request.getSession().getUserNull(request.getUser());
try {
myFile = request.getCurrentDirectory().getFile(st.nextToken(), user);
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
try {
if (st.hasMoreTokens()) {
if (!st.nextToken().equals("0")
|| !st.nextToken().equals(
Long.toString(myFile.getSize()))) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
}
return new CommandResponse(250, "XCRC Successful. "
+ Checksum.formatChecksum(myFile.getCheckSum()));
} catch (NoAvailableSlaveException e1) {
logger.warn("", e1);
return new CommandResponse(550, "NoAvailableSlaveException: "
+ e1.getMessage());
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
public CommandResponse doSITE_FIXSIZE(CommandRequest request) {
long difference = 0;
try {
difference = request.getCurrentDirectory().validateSizeRecursive();
} catch (FileNotFoundException e) {
return new CommandResponse(500, e.getMessage());
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
response.addComment("Difference was of " + Bytes.formatBytes(difference));
return response;
}
}
| false | true | public CommandResponse doDELE(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
// out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR);
return StandardCommandManager
.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
CommandResponse response = StandardCommandManager
.genericResponse("RESPONSE_250_ACTION_OKAY");
User user = request.getSession().getUserNull(request.getUser());
InodeHandle victim = null;
try {
victim = request.getCurrentDirectory().getInodeHandle(fileName,
user);
addVictimInformationToResponse(victim, response);
if (victim.isDirectory()) {
DirectoryHandle victimDir = (DirectoryHandle) victim;
if (!victimDir.isEmpty(user)) {
return new CommandResponse(550, victim.getPath()
+ ": Directory not empty");
}
}
victim.delete(user); // the file is only deleted here.
} catch (FileNotFoundException e) {
// this isn't good or bad, there could have easily been a race in
// another thread to delete this file
return new CommandResponse(550, e.getMessage());
} catch (PermissionDeniedException e) {
return StandardCommandManager
.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
if (victim.isFile() || victim.isLink()) { // link or file
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(
request.getUser()), "DELE", victim.getParent()));
// strange that we're sending the parent directory of the file being
// deleted without mentioning the file that was deleted...
} else { // if (requestedFile.isDirectory()) {
GlobalContext.getEventService()
.publishAsync(
new DirectoryFtpEvent(request.getSession()
.getUserNull(request.getUser()), "RMD",
(DirectoryHandle) victim));
}
return response;
}
/**
* <code>MDTM <SP> <pathname> <CRLF></code><br>
*
* Returns the date and time of when a file was modified.
*/
public CommandResponse doMDTM(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
InodeHandle reqFile;
User user = request.getSession().getUserNull(request.getUser());
try {
reqFile = request.getCurrentDirectory().getInodeHandle(fileName, user);
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
try {
synchronized(DATE_FMT) {
return new CommandResponse(213,
DATE_FMT.format(new Date(reqFile.lastModified())));
}
} catch (FileNotFoundException e) {
return new CommandResponse(550, e.getMessage());
}
//out.print(ftpStatus.getResponse(213, request, user, args));
//} else {
// out.write(ftpStatus.getResponse(550, request, user, null));
//}
}
/**
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be created as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*
*
* MKD
* 257
* 500, 501, 502, 421, 530, 550
*/
public CommandResponse doMKD(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
Session session = request.getSession();
String path = VirtualFileSystem.fixPath(request.getArgument());
DirectoryHandle fakeDirectory = request.getCurrentDirectory().getNonExistentDirectoryHandle(path);
String dirName = fakeDirectory.getName();
if (!ListUtils.isLegalFileName(dirName)) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN");
}
try {
try {
if (!fakeDirectory.getParent().equals(request.getCurrentDirectory()) &&
InodeHandle.isLink(fakeDirectory.getParent().getPath())) {
fakeDirectory = new LinkHandle(fakeDirectory.getParent().getPath())
.getTargetDirectory(session.getUserNull(request.getUser()))
.getNonExistentDirectoryHandle(dirName);
}
} catch (FileNotFoundException e1) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (ObjectNotValidException e) {
return new CommandResponse(550, "Parent directory does not exist");
}
DirectoryHandle newDir = null;
try {
newDir = fakeDirectory.getParent().createDirectory(session.getUserNull(request.getUser()), dirName);
} catch (FileNotFoundException e) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
GlobalContext.getEventService().publishAsync(new DirectoryFtpEvent(
session.getUserNull(request.getUser()), "MKD", newDir));
return new CommandResponse(257, "\"" + newDir.getPath() +
"\" created.");
} catch (FileExistsException ex) {
return new CommandResponse(550,
"directory " + dirName + " already exists");
}
}
/**
* <code>PWD <CRLF></code><br>
*
* This command causes the name of the current working
* directory to be returned in the reply.
*/
public CommandResponse doPWD(CommandRequest request) {
return new CommandResponse(257,
"\"" + request.getCurrentDirectory().getPath() +
"\" is current directory");
}
/**
* <code>RMD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be removed as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*/
public CommandResponse doRMD(CommandRequest request) {
return doDELE(request);
}
/**
* <code>RNFR <SP> <pathname> <CRLF></code><br>
*
* This command specifies the old pathname of the file which is
* to be renamed. This command must be immediately followed by
* a "rename to" command specifying the new file pathname.
*
* RNFR
450, 550
500, 501, 502, 421, 530
350
*/
public CommandResponse doRNFR(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
User user = request.getSession().getUserNull(request.getUser());
try {
request.getSession().setObject(RENAMEFROM, request.getCurrentDirectory().getInodeHandle(request.getArgument(), user));
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
return new CommandResponse(350, "File exists, ready for destination name");
}
/**
* <code>RNTO <SP> <pathname> <CRLF></code><br>
*
* This command specifies the new pathname of the file
* specified in the immediately preceding "rename from"
* command. Together the two commands cause a file to be
* renamed.
*/
public CommandResponse doRNTO(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// set state variables
InodeHandle fromInode = request.getSession().getObject(RENAMEFROM, null);
if (fromInode == null) {
return StandardCommandManager.genericResponse("RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS");
}
String argument = VirtualFileSystem.fixPath(request.getArgument());
if (!(argument.startsWith(VirtualFileSystem.separator))) {
// Not a full path, let's make it one
if (request.getCurrentDirectory().isRoot()) {
argument = VirtualFileSystem.separator + argument;
} else {
argument = request.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument;
}
}
DirectoryHandle toDir = null;
String newName = null;
User user = request.getSession().getUserNull(request.getUser());
try {
toDir = request.getCurrentDirectory().getDirectory(argument, user);
// toDir exists and is a directory, so we're just changing the parent directory and not the name
// unless toInode and fromInode are the same (i.e. a case change)
if (fromInode.isDirectory() && fromInode.equals(toDir)) {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} else {
// There are two possibilites here, the target is an existing link or a directory
// Check to see if a link with the target name exists
newName = fromInode.getName();
try {
DirectoryHandle linkParentDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
String linkName = VirtualFileSystem.getLast(argument);
// If a link exists and is the same link as the from inode this is valid
try {
InodeHandle linkHandle = linkParentDir.getLink(linkName, user);
if (fromInode.isLink() && fromInode.equals(linkHandle)) {
// Changing case of existing link
toDir = linkParentDir;
newName = linkName;
}
} catch (FileNotFoundException e2) {
// No link exists so we are moving an inode to a new parent without changing its name
} catch (ObjectNotValidException e2) {
// Target is an existing directory
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
} catch (FileNotFoundException e) {
// Directory does not exist, that means they may have specified _renameFrom's new name
// as the last part of the argument
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} catch (FileNotFoundException e1) {
// Destination doesn't exist
logger.debug("Destination doesn't exist", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory
logger.debug("Destination isn't a Directory", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
} catch (ObjectNotValidException e) {
// Target exists but is not a dir, this is invalid unless the target is a file and the same
// file as the source (i.e. a case change)
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
if (!toDir.equals(fromInode.getParent()) || !newName.equalsIgnoreCase(fromInode.getName())) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
InodeHandle toInode = null;
if (fromInode.isDirectory()) {
toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isFile()) {
toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isLink()) {
toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else {
return new CommandResponse(500, "Someone has extended the VFS beyond File/Directory/Link");
}
try {
/*logger.debug("before rename toInode-" +toInode);
logger.debug("before rename toInode.getPath()-" + toInode.getPath());
logger.debug("before rename toInode.getParent()-" + toInode.getParent());
logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
fromInode.renameTo(request.getSession().getUserNull(request.getUser()), toInode);
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
} catch (FileNotFoundException e) {
logger.info("FileNotFoundException on renameTo()", e);
return new CommandResponse(500, "FileNotFound - " + e.getMessage());
} catch (IOException e) {
logger.info("IOException on renameTo()", e);
return new CommandResponse(500, "IOException - " + e.getMessage());
}
/*logger.debug("after rename toInode-" +toInode);
logger.debug("after rename toInode.getPath()-" + toInode.getPath());
logger.debug("after rename toInode.getParent()-" + toInode.getParent());
logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
return new CommandResponse(250, request.getCommand().toUpperCase() + " command successful.");
}
public CommandResponse doSITE_CHOWN(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument());
if (st.countTokens() < 2) {
throw new ImproperUsageException();
}
String owner = st.nextToken();
String group = null;
boolean recursive = false;
if (owner.equalsIgnoreCase("-r")) {
recursive = true;
owner = st.nextToken();
}
int pos = owner.indexOf(':');
if (pos > 0) {
// Both user and group specified
group = owner.substring(pos + 1);
owner = owner.substring(0, pos);
} else if (pos == 0) {
// First char is ':', only change group
group = owner.substring(1);
owner = null;
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
User user = request.getSession().getUserNull(request.getUser());
if (!st.hasMoreTokens()) {
throw new ImproperUsageException();
}
while (st.hasMoreTokens()) {
try {
InodeHandle file = request.getCurrentDirectory().getInodeHandle(st.nextToken(), user);
if (owner != null) {
file.setUsername(owner);
}
if (group != null) {
file.setGroup(group);
}
if (file.isDirectory() && recursive) {
recursiveCHOWN((DirectoryHandle)file, owner, group, user, response);
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
return response;
}
private void recursiveCHOWN(DirectoryHandle dir, String owner, String group, User user, CommandResponse response) {
try {
for (InodeHandle inode : dir.getInodeHandles(user)) {
if (owner != null) {
inode.setUsername(owner);
}
if (group != null) {
inode.setGroup(group);
}
if (inode.isDirectory()) {
recursiveCHOWN((DirectoryHandle)inode, owner, group, user, response);
}
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
public CommandResponse doSITE_LINK(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument(),
" ");
if (st.countTokens() != 2) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String targetName = st.nextToken();
String linkName = st.nextToken();
User user = request.getSession().getUserNull(request.getUser());
try {
request.getCurrentDirectory().getInodeHandleUnchecked(targetName); // checks if the inode exists.
request.getCurrentDirectory().createLink(user, linkName, targetName); // create the link
} catch (FileExistsException e) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* USAGE: site wipe [-r] <file/directory>
*
* This is similar to the UNIX rm command.
* In glftpd, if you just delete a file, the uploader loses credits and
* upload stats for it. There are many people who didn't like that and
* were unable/too lazy to write a shell script to do it for them, so I
* wrote this command to get them off my back.
*
* If the argument is a file, it will simply be deleted. If it's a
* directory, it and the files it contains will be deleted. If the
* directory contains other directories, the deletion will be aborted.
*
* To remove a directory containing subdirectories, you need to use
* "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND.
* Glftpd will check if the parent directory of the file/directory you're
* trying to delete is writable by its owner. If not, wipe will not
* execute, so to protect directories from being wiped, make their parent
* 555.
*
* Also, wipe will only work where you have the right to delete (in
* glftpd.conf). Delete right and parent directory's mode of 755/777/etc
* will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory.
* "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO
* BE CAREFUL.
*
* This command will remove the deleted files/directories from the dirlog
* and dupefile databases.
*
* To give access to this command, add "-wipe -user flag =group" to the
* config file (similar to other site commands).
*
* @param request
* @param out
*/
public CommandResponse doSITE_WIPE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String arg = request.getArgument();
boolean recursive;
if (arg.startsWith("-r ")) {
arg = arg.substring(3);
recursive = true;
} else {
recursive = false;
}
InodeHandle wipeFile;
User user = request.getSession().getUserNull(request.getUser());
try {
wipeFile = request.getCurrentDirectory().getInodeHandle(arg, user);
if (wipeFile.isDirectory() && !recursive) {
if (((DirectoryHandle) wipeFile).isEmpty(user)) {
return new CommandResponse(550, "Can't wipe, directory not empty");
}
}
if (wipeFile.isLink()) {
wipeFile = ((LinkHandle) wipeFile).getTargetInodeUnchecked();
}
wipeFile.delete(request.getSession().getUserNull(request.getUser()));
if (wipeFile.isDirectory()) {
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(request.getUser()), "WIPE", (DirectoryHandle)wipeFile));
}
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* <code>SIZE <SP> <pathname> <CRLF></code><br>
*
* Returns the size of the file in bytes.
*/
public CommandResponse doSIZE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
InodeHandle file;
User user = request.getSession().getUserNull(request.getUser());
try {
file = request.getCurrentDirectory().getInodeHandle(request.getArgument(), user);
return new CommandResponse(213, Long.toString(file.getSize()));
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
/**
* http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm
*
* Originally implemented by CuteFTP Pro and Globalscape FTP Server
*/
public CommandResponse doXCRC(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
StringTokenizer st = new StringTokenizer(request.getArgument());
FileHandle myFile;
User user = request.getSession().getUserNull(request.getUser());
try {
myFile = request.getCurrentDirectory().getFile(st.nextToken(), user);
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
try {
if (st.hasMoreTokens()) {
if (!st.nextToken().equals("0")
|| !st.nextToken().equals(
Long.toString(myFile.getSize()))) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
}
return new CommandResponse(250, "XCRC Successful. "
+ Checksum.formatChecksum(myFile.getCheckSum()));
} catch (NoAvailableSlaveException e1) {
logger.warn("", e1);
return new CommandResponse(550, "NoAvailableSlaveException: "
+ e1.getMessage());
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
public CommandResponse doSITE_FIXSIZE(CommandRequest request) {
long difference = 0;
try {
difference = request.getCurrentDirectory().validateSizeRecursive();
} catch (FileNotFoundException e) {
return new CommandResponse(500, e.getMessage());
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
response.addComment("Difference was of " + Bytes.formatBytes(difference));
return response;
}
}
| public CommandResponse doDELE(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
// out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR);
return StandardCommandManager
.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
CommandResponse response = StandardCommandManager
.genericResponse("RESPONSE_250_ACTION_OKAY");
User user = request.getSession().getUserNull(request.getUser());
InodeHandle victim = null;
try {
victim = request.getCurrentDirectory().getInodeHandle(fileName,
user);
addVictimInformationToResponse(victim, response);
if (victim.isDirectory()) {
DirectoryHandle victimDir = (DirectoryHandle) victim;
if (!victimDir.isEmpty(user)) {
return new CommandResponse(550, victim.getPath()
+ ": Directory not empty");
}
}
victim.delete(user); // the file is only deleted here.
} catch (FileNotFoundException e) {
// this isn't good or bad, there could have easily been a race in
// another thread to delete this file
return new CommandResponse(550, e.getMessage());
} catch (PermissionDeniedException e) {
return StandardCommandManager
.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
if (victim.isFile() || victim.isLink()) { // link or file
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(
request.getUser()), "DELE", victim.getParent()));
// strange that we're sending the parent directory of the file being
// deleted without mentioning the file that was deleted...
} else { // if (requestedFile.isDirectory()) {
GlobalContext.getEventService()
.publishAsync(
new DirectoryFtpEvent(request.getSession()
.getUserNull(request.getUser()), "RMD",
(DirectoryHandle) victim));
}
return response;
}
/**
* <code>MDTM <SP> <pathname> <CRLF></code><br>
*
* Returns the date and time of when a file was modified.
*/
public CommandResponse doMDTM(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// get filenames
String fileName = request.getArgument();
InodeHandle reqFile;
User user = request.getSession().getUserNull(request.getUser());
try {
reqFile = request.getCurrentDirectory().getInodeHandle(fileName, user);
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
try {
synchronized(DATE_FMT) {
return new CommandResponse(213,
DATE_FMT.format(new Date(reqFile.lastModified())));
}
} catch (FileNotFoundException e) {
return new CommandResponse(550, e.getMessage());
}
//out.print(ftpStatus.getResponse(213, request, user, args));
//} else {
// out.write(ftpStatus.getResponse(550, request, user, null));
//}
}
/**
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be created as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*
*
* MKD
* 257
* 500, 501, 502, 421, 530, 550
*/
public CommandResponse doMKD(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
Session session = request.getSession();
String path = VirtualFileSystem.fixPath(request.getArgument());
DirectoryHandle fakeDirectory = request.getCurrentDirectory().getNonExistentDirectoryHandle(path);
String dirName = fakeDirectory.getName();
if (!ListUtils.isLegalFileName(dirName)) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN");
}
try {
try {
if (!fakeDirectory.getParent().equals(request.getCurrentDirectory()) &&
InodeHandle.isLink(fakeDirectory.getParent().getPath())) {
fakeDirectory = new LinkHandle(fakeDirectory.getParent().getPath())
.getTargetDirectory(session.getUserNull(request.getUser()))
.getNonExistentDirectoryHandle(dirName);
}
} catch (FileNotFoundException e1) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (ObjectNotValidException e) {
return new CommandResponse(550, "Parent directory does not exist");
}
DirectoryHandle newDir = null;
try {
newDir = fakeDirectory.getParent().createDirectory(session.getUserNull(request.getUser()), dirName);
} catch (FileNotFoundException e) {
return new CommandResponse(550, "Parent directory does not exist");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
GlobalContext.getEventService().publishAsync(new DirectoryFtpEvent(
session.getUserNull(request.getUser()), "MKD", newDir));
return new CommandResponse(257, "\"" + newDir.getPath() +
"\" created.");
} catch (FileExistsException ex) {
return new CommandResponse(550,
"directory " + dirName + " already exists");
}
}
/**
* <code>PWD <CRLF></code><br>
*
* This command causes the name of the current working
* directory to be returned in the reply.
*/
public CommandResponse doPWD(CommandRequest request) {
return new CommandResponse(257,
"\"" + request.getCurrentDirectory().getPath() +
"\" is current directory");
}
/**
* <code>RMD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be removed as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*/
public CommandResponse doRMD(CommandRequest request) {
return doDELE(request);
}
/**
* <code>RNFR <SP> <pathname> <CRLF></code><br>
*
* This command specifies the old pathname of the file which is
* to be renamed. This command must be immediately followed by
* a "rename to" command specifying the new file pathname.
*
* RNFR
450, 550
500, 501, 502, 421, 530
350
*/
public CommandResponse doRNFR(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
User user = request.getSession().getUserNull(request.getUser());
try {
request.getSession().setObject(RENAMEFROM, request.getCurrentDirectory().getInodeHandle(request.getArgument(), user));
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
return new CommandResponse(350, "File exists, ready for destination name");
}
/**
* <code>RNTO <SP> <pathname> <CRLF></code><br>
*
* This command specifies the new pathname of the file
* specified in the immediately preceding "rename from"
* command. Together the two commands cause a file to be
* renamed.
*/
public CommandResponse doRNTO(CommandRequest request) {
// argument check
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
// set state variables
InodeHandle fromInode = request.getSession().getObject(RENAMEFROM, null);
if (fromInode == null) {
return StandardCommandManager.genericResponse("RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS");
}
String argument = VirtualFileSystem.fixPath(request.getArgument());
if (!(argument.startsWith(VirtualFileSystem.separator))) {
// Not a full path, let's make it one
if (request.getCurrentDirectory().isRoot()) {
argument = VirtualFileSystem.separator + argument;
} else {
argument = request.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument;
}
}
DirectoryHandle toDir = null;
String newName = null;
User user = request.getSession().getUserNull(request.getUser());
try {
toDir = request.getCurrentDirectory().getDirectory(argument, user);
// toDir exists and is a directory, so we're just changing the parent directory and not the name
// unless toInode and fromInode are the same (i.e. a case change)
if (fromInode.isDirectory() && fromInode.equals(toDir)) {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} else {
// There are two possibilites here, the target is an existing link or a directory
// Check to see if a link with the target name exists
newName = fromInode.getName();
try {
DirectoryHandle linkParentDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
String linkName = VirtualFileSystem.getLast(argument);
// If a link exists and is the same link as the from inode this is valid
try {
InodeHandle linkHandle = linkParentDir.getLink(linkName, user);
if (fromInode.isLink() && fromInode.equals(linkHandle)) {
// Changing case of existing link
toDir = linkParentDir;
newName = linkName;
}
} catch (FileNotFoundException e2) {
// No link exists so we are moving an inode to a new parent without changing its name
} catch (ObjectNotValidException e2) {
// Target is an existing directory
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
} catch (FileNotFoundException e) {
// Directory does not exist, that means they may have specified _renameFrom's new name
// as the last part of the argument
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
} catch (FileNotFoundException e1) {
// Destination doesn't exist
logger.debug("Destination doesn't exist", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory
logger.debug("Destination isn't a Directory", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
} catch (ObjectNotValidException e) {
// Target exists but is not a dir, this is invalid unless the target is a file and the same
// file as the source (i.e. a case change)
try {
toDir = request.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument), user);
newName = VirtualFileSystem.getLast(argument);
if (!toDir.equals(fromInode.getParent()) || !newName.equalsIgnoreCase(fromInode.getName())) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
}
} catch (FileNotFoundException e1) {
// Destination doesn't exist, shouldn't be possible as the full argument does exist
logger.warn("Destination doesn't exist, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e1) {
// Destination isn't a Directory, shouldn't be possible as the full argument is a dir
logger.warn("Destination isn't a Directory, this shouldn't happen", e1);
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
InodeHandle toInode = null;
if (fromInode.isDirectory()) {
toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isFile()) {
toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else if (fromInode.isLink()) {
toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName);
} else {
return new CommandResponse(500, "Someone has extended the VFS beyond File/Directory/Link");
}
try {
/*logger.debug("before rename toInode-" +toInode);
logger.debug("before rename toInode.getPath()-" + toInode.getPath());
logger.debug("before rename toInode.getParent()-" + toInode.getParent());
logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
fromInode.renameTo(request.getSession().getUserNull(request.getUser()), toInode);
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
} catch (FileNotFoundException e) {
logger.info("FileNotFoundException on renameTo()", e);
return new CommandResponse(500, "FileNotFound - " + e.getMessage());
} catch (IOException e) {
logger.info("IOException on renameTo()", e);
return new CommandResponse(500, "IOException - " + e.getMessage());
}
/*logger.debug("after rename toInode-" +toInode);
logger.debug("after rename toInode.getPath()-" + toInode.getPath());
logger.debug("after rename toInode.getParent()-" + toInode.getParent());
logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/
return new CommandResponse(250, request.getCommand().toUpperCase() + " command successful.");
}
public CommandResponse doSITE_CHOWN(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument());
if (st.countTokens() < 2) {
throw new ImproperUsageException();
}
String owner = st.nextToken();
String group = null;
boolean recursive = false;
if (owner.equalsIgnoreCase("-r")) {
recursive = true;
owner = st.nextToken();
}
int pos = owner.indexOf(':');
if (pos > 0) {
// Both user and group specified
group = owner.substring(pos + 1);
owner = owner.substring(0, pos);
} else if (pos == 0) {
// First char is ':', only change group
group = owner.substring(1);
owner = null;
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
User user = request.getSession().getUserNull(request.getUser());
if (!st.hasMoreTokens()) {
throw new ImproperUsageException();
}
while (st.hasMoreTokens()) {
try {
InodeHandle file = request.getCurrentDirectory().getInodeHandle(st.nextToken(), user);
if (owner != null) {
file.setUsername(owner);
}
if (group != null) {
file.setGroup(group);
}
if (file.isDirectory() && recursive) {
recursiveCHOWN((DirectoryHandle)file, owner, group, user, response);
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
return response;
}
private void recursiveCHOWN(DirectoryHandle dir, String owner, String group, User user, CommandResponse response) {
try {
for (InodeHandle inode : dir.getInodeHandles(user)) {
if (owner != null) {
inode.setUsername(owner);
}
if (group != null) {
inode.setGroup(group);
}
if (inode.isDirectory()) {
recursiveCHOWN((DirectoryHandle)inode, owner, group, user, response);
}
}
} catch (FileNotFoundException e) {
response.addComment(e.getMessage());
}
}
public CommandResponse doSITE_LINK(CommandRequest request) throws ImproperUsageException {
if (!request.hasArgument()) {
throw new ImproperUsageException();
}
StringTokenizer st = new StringTokenizer(request.getArgument(),
" ");
if (st.countTokens() != 2) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String targetName = st.nextToken();
String linkName = st.nextToken();
User user = request.getSession().getUserNull(request.getUser());
try {
request.getCurrentDirectory().getInodeHandleUnchecked(targetName); // checks if the inode exists.
request.getCurrentDirectory().createLink(user, linkName, targetName); // create the link
} catch (FileExistsException e) {
return StandardCommandManager.genericResponse("RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS");
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* USAGE: site wipe [-r] <file/directory>
*
* This is similar to the UNIX rm command.
* In glftpd, if you just delete a file, the uploader loses credits and
* upload stats for it. There are many people who didn't like that and
* were unable/too lazy to write a shell script to do it for them, so I
* wrote this command to get them off my back.
*
* If the argument is a file, it will simply be deleted. If it's a
* directory, it and the files it contains will be deleted. If the
* directory contains other directories, the deletion will be aborted.
*
* To remove a directory containing subdirectories, you need to use
* "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND.
* Glftpd will check if the parent directory of the file/directory you're
* trying to delete is writable by its owner. If not, wipe will not
* execute, so to protect directories from being wiped, make their parent
* 555.
*
* Also, wipe will only work where you have the right to delete (in
* glftpd.conf). Delete right and parent directory's mode of 755/777/etc
* will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory.
* "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO
* BE CAREFUL.
*
* This command will remove the deleted files/directories from the dirlog
* and dupefile databases.
*
* To give access to this command, add "-wipe -user flag =group" to the
* config file (similar to other site commands).
*
* @param request
* @param out
*/
public CommandResponse doSITE_WIPE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
String arg = request.getArgument();
boolean recursive;
if (arg.startsWith("-r ")) {
arg = arg.substring(3);
recursive = true;
} else {
recursive = false;
}
InodeHandle wipeFile;
User user = request.getSession().getUserNull(request.getUser());
try {
wipeFile = request.getCurrentDirectory().getInodeHandle(arg, user);
if (wipeFile.isDirectory() && !recursive) {
if (((DirectoryHandle) wipeFile).isEmpty(user)) {
return new CommandResponse(550, "Can't wipe, directory not empty");
}
}
if (wipeFile.isLink()) {
InodeHandle linkFile = wipeFile;
wipeFile = ((LinkHandle) wipeFile).getTargetInodeUnchecked();
linkFile.delete(request.getSession().getUserNull(request.getUser()));
}
wipeFile.delete(request.getSession().getUserNull(request.getUser()));
if (wipeFile.isDirectory()) {
GlobalContext.getEventService().publishAsync(
new DirectoryFtpEvent(request.getSession().getUserNull(request.getUser()), "WIPE", (DirectoryHandle)wipeFile));
}
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (PermissionDeniedException e) {
return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
}
return StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
}
/**
* <code>SIZE <SP> <pathname> <CRLF></code><br>
*
* Returns the size of the file in bytes.
*/
public CommandResponse doSIZE(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
InodeHandle file;
User user = request.getSession().getUserNull(request.getUser());
try {
file = request.getCurrentDirectory().getInodeHandle(request.getArgument(), user);
return new CommandResponse(213, Long.toString(file.getSize()));
} catch (FileNotFoundException ex) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
/**
* http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm
*
* Originally implemented by CuteFTP Pro and Globalscape FTP Server
*/
public CommandResponse doXCRC(CommandRequest request) {
if (!request.hasArgument()) {
return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
}
StringTokenizer st = new StringTokenizer(request.getArgument());
FileHandle myFile;
User user = request.getSession().getUserNull(request.getUser());
try {
myFile = request.getCurrentDirectory().getFile(st.nextToken(), user);
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
} catch (ObjectNotValidException e) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
try {
if (st.hasMoreTokens()) {
if (!st.nextToken().equals("0")
|| !st.nextToken().equals(
Long.toString(myFile.getSize()))) {
return StandardCommandManager.genericResponse("RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM");
}
}
return new CommandResponse(250, "XCRC Successful. "
+ Checksum.formatChecksum(myFile.getCheckSum()));
} catch (NoAvailableSlaveException e1) {
logger.warn("", e1);
return new CommandResponse(550, "NoAvailableSlaveException: "
+ e1.getMessage());
} catch (FileNotFoundException e) {
return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN");
}
}
public CommandResponse doSITE_FIXSIZE(CommandRequest request) {
long difference = 0;
try {
difference = request.getCurrentDirectory().validateSizeRecursive();
} catch (FileNotFoundException e) {
return new CommandResponse(500, e.getMessage());
}
CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
response.addComment("Difference was of " + Bytes.formatBytes(difference));
return response;
}
}
|
diff --git a/Model/src/java/fr/cg95/cvq/dao/users/hibernate/IndividualDAO.java b/Model/src/java/fr/cg95/cvq/dao/users/hibernate/IndividualDAO.java
index eaf790f12..1e0ba9581 100644
--- a/Model/src/java/fr/cg95/cvq/dao/users/hibernate/IndividualDAO.java
+++ b/Model/src/java/fr/cg95/cvq/dao/users/hibernate/IndividualDAO.java
@@ -1,292 +1,292 @@
package fr.cg95.cvq.dao.users.hibernate;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.type.Type;
import fr.cg95.cvq.business.QoS;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.RoleType;
import fr.cg95.cvq.business.users.UserState;
import fr.cg95.cvq.dao.jpa.JpaTemplate;
import fr.cg95.cvq.dao.jpa.JpaUtil;
import fr.cg95.cvq.dao.hibernate.HibernateUtil;
import fr.cg95.cvq.dao.users.IIndividualDAO;
import fr.cg95.cvq.util.Critere;
/**
* The "Individual" service Hibernate implementation. This class is responsible
* for data access logic functions
*
* @author [email protected]
*/
public class IndividualDAO extends JpaTemplate<Individual,Long> implements IIndividualDAO {
private static Logger logger = Logger.getLogger(IndividualDAO.class);
private static HibernateUtil hUtil = new HibernateUtil();
public Individual findByFederationKey(final String federationKey) {
Criteria crit = HibernateUtil.getSession().createCriteria(Individual.class);
crit.add(Critere.compose("federationKey", federationKey, Critere.EQUALS));
return (Individual) crit.uniqueResult();
}
@Override
public boolean hasSimilarIndividuals(String firstName, String lastName, String email,
String phone, String streetNumber, String streetName, String postalCode, String city) {
Query query = HibernateUtil.getSession().createSQLQuery(
"select count(*) from adult a right outer join individual i using(id) left outer join child c using(id)" +
"where first_name = :firstName and last_name = :lastName and (" +
" email = :email or home_phone = :phone or (" +
(streetNumber != null ?
"((select street_number from address where id = i.address_id) is null or (select street_number from address where id = i.address_id) = :streetNumber) and "
: "") +
" (select street_name from address where id = i.address_id) = :streetName" +
" and (select postal_code from address where id = i.address_id) = :postalCode" +
" and (select city from address where id = i.address_id) = :city" +
"));");
query.setString("firstName", firstName);
query.setString("lastName", lastName);
query.setString("email", email);
query.setString("phone", phone);
if (streetNumber != null) query.setString("streetNumber", streetNumber);
query.setString("streetName", streetName);
query.setString("postalCode", postalCode);
query.setString("city", city);
return !BigInteger.ZERO.equals(query.uniqueResult());
}
public List<Individual> listByHomeFolder(Long homeFolderId) {
String hql = "from Individual as individual"
+ " where individual.homeFolder.id = :homeFolderId"
+ " and individual.state in (:states)";
return HibernateUtil.getSession()
.createQuery(hql)
.setParameter("homeFolderId", homeFolderId.longValue())
.setParameterList("states", UserState.activeStates)
.list();
}
public List<String> getSimilarLogins(final String baseLogin) {
return JpaUtil.getEntityManager()
.createQuery("select adult.login from Adult as adult where adult.login like ?")
.setParameter(1, baseLogin + "%").getResultList();
}
@Override
public List<Individual> listByHomeFolderRole(Long homeFolderId, RoleType role) {
StringBuffer sb = new StringBuffer();
sb.append("select individual from Individual as individual")
.append(" join individual.individualRoles individualRole ")
.append(" where individualRole.homeFolderId = ?");
if (role != null)
sb.append(" and individualRole.role = ?");
sb.append(" and individual.homeFolder != null");
Query query = HibernateUtil.getSession()
.createQuery(sb.toString())
.setLong(0, homeFolderId);
if (role != null)
query.setString(1, role.name());
return query.list();
}
@Override
public List<Individual> listByHomeFolderRoles(Long homeFolderId, RoleType[] roles,
boolean onlyExternals) {
StringBuffer sb = new StringBuffer();
sb.append("select individual from Individual as individual")
.append(" join individual.individualRoles individualRole ")
.append(" where individualRole.homeFolderId = ?");
sb.append(" and (");
for (int i = 0; i < roles.length; i++) {
sb.append(" individualRole.role = ? ");
if (i < roles.length - 1)
sb.append(" or ");
}
sb.append(")");
if (onlyExternals)
sb.append(" and individual.homeFolder = null");
else
sb.append(" and individual.homeFolder != null");
Query query = HibernateUtil.getSession()
.createQuery(sb.toString())
.setLong(0, homeFolderId);
for (int i = 0; i < roles.length; i++) {
query.setString(i + 1, roles[i].name());
}
return query.list();
}
@Override
public List<Individual> listBySubjectRole(Long subjectId, RoleType role) {
StringBuffer sb = new StringBuffer();
sb.append("select individual from Individual as individual")
.append(" join individual.individualRoles individualRole ")
.append(" where individualRole.individualId = ?");
if (role != null)
sb.append(" and individualRole.role = ?");
sb.append(" and individual.homeFolder != null");
Query query = HibernateUtil.getSession()
.createQuery(sb.toString())
.setLong(0, subjectId);
if (role != null)
query.setString(1, role.name());
return query.list();
}
@Override
public List<Individual> listBySubjectRoles(Long subjectId, RoleType[] roles, boolean onlyExternals) {
StringBuffer sb = new StringBuffer(
"select * from individual where id in (select owner_id from individual_role where individual_id = ? and (");
for (int i = 0; i < roles.length; i++) {
sb.append(" role = ? ");
if (i < roles.length - 1)
sb.append(" or ");
}
sb.append("))");
if (onlyExternals)
sb.append(" and home_folder_id is null");
else
sb.append(" and home_folder_id is not null");
Query query = HibernateUtil.getSession().createSQLQuery(sb.toString())
.addEntity(Individual.class).setLong(0, subjectId);
for (int i = 0; i < roles.length; i++) {
query.setString(i + 1, roles[i].name());
}
return query.list();
}
public List<Individual> search(Set<Critere> criterias, Map<String,String>sortParams,
Integer max, Integer offset) {
List<Type> types = new ArrayList<Type>();
List<Object> values = new ArrayList<Object>();
StringBuffer sb = this.buildStatement(criterias,types,values,"select distinct individual ");
hUtil.buildSort(sortParams,sb);
return hUtil.execute(sb.toString(),types,values,max,offset);
}
public Integer searchCount(Set<Critere> criterias) {
List<Type> types = new ArrayList<Type>();
List<Object> values = new ArrayList<Object>();
StringBuffer sb = this.buildStatement(criterias,types,values,"select count(distinct individual.id) ");
return (hUtil.execute(sb.toString(),types,values)).intValue();
}
protected StringBuffer buildStatement(Set<Critere> criterias,List<Type> typeList,
List<Object> objectList,String prefix) {
StringBuffer sb = new StringBuffer();
sb.append(prefix != null ? prefix : "")
.append("from Individual as individual left join individual.individualRoles roles")
.append(" where 1 = 1 ");
// we filter the individual who don't get a home folder
sb.append(" and individual.homeFolder is not null ");
// TODO (rdj) : I know this is apoor solution
boolean searchByUserState = false;
// go through all the criteria and create the query
for (Critere criteria : criterias) {
if (criteria.getAttribut().equals(Individual.SEARCH_BY_LASTNAME)) {
sb.append(" and lower(individual.lastName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_FIRSTNAME)) {
sb.append(" and lower(individual.firstName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if (criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_ID)) {
sb.append(" and individual.homeFolder.id ")
.append(criteria.getSqlComparatif())
.append(" ?");
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_INDIVIDUAL_ID)) {
sb.append(String.format(" and individual.id %1$s ? ",criteria.getSqlComparatif()));
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_STATE)) {
sb.append(String.format(" and lower(individual.homeFolder.state) %1$s lower(?) ",criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else if(criteria.getAttribut().equals(Individual.SEARCH_IS_HOME_FOLDER_RESPONSIBLE)) {
- sb.append(" and roles.role = 'HomeFolderResponsible' ");
+ sb.append(" and roles.role = 'HOME_FOLDER_RESPONSIBLE' ");
} else if (Individual.SEARCH_BY_USER_STATE.equals(criteria.getAttribut())) {
sb.append(String.format(" and lower(individual.state) %1$s lower(?) ", criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else {
logger.warn("Unknown search criteria for Individual object");
}
}
// exclude archived individual if no UserState filter is used
if (!searchByUserState) {
sb.append(" and individual.state != ?");
objectList.add(UserState.ARCHIVED.name());
typeList.add(Hibernate.STRING);
}
return sb;
}
@Override
public List<Individual> listTasks(QoS qoS, int max) {
Query query = HibernateUtil.getSession()
.createQuery("from Individual i where i.qoS = :qoS and homeFolder != null order by i.lastModificationDate")
.setString("qoS", qoS.name());
if (max > 0)
query.setMaxResults(max);
return query.list();
}
@Override
public Long countTasks(QoS qoS) {
return (Long)HibernateUtil.getSession()
.createQuery("select count(*) from Individual i where i.qoS = :qoS and homeFolder != null")
.setString("qoS", qoS.name())
.iterate().next();
}
@Override
public List<Individual> searchTasks(Date date) {
return HibernateUtil.getSession()
.createQuery("from Individual i where i.state in (:new, :modified, :invalid) and (i.lastModificationDate is null or i.lastModificationDate <= :limitDate) and homeFolder != null order by i.lastModificationDate")
.setString("new", UserState.NEW.name())
.setString("modified", UserState.MODIFIED.name())
.setString("invalid", UserState.INVALID.name())
.setTimestamp("limitDate", date)
.list();
}
}
| true | true | protected StringBuffer buildStatement(Set<Critere> criterias,List<Type> typeList,
List<Object> objectList,String prefix) {
StringBuffer sb = new StringBuffer();
sb.append(prefix != null ? prefix : "")
.append("from Individual as individual left join individual.individualRoles roles")
.append(" where 1 = 1 ");
// we filter the individual who don't get a home folder
sb.append(" and individual.homeFolder is not null ");
// TODO (rdj) : I know this is apoor solution
boolean searchByUserState = false;
// go through all the criteria and create the query
for (Critere criteria : criterias) {
if (criteria.getAttribut().equals(Individual.SEARCH_BY_LASTNAME)) {
sb.append(" and lower(individual.lastName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_FIRSTNAME)) {
sb.append(" and lower(individual.firstName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if (criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_ID)) {
sb.append(" and individual.homeFolder.id ")
.append(criteria.getSqlComparatif())
.append(" ?");
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_INDIVIDUAL_ID)) {
sb.append(String.format(" and individual.id %1$s ? ",criteria.getSqlComparatif()));
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_STATE)) {
sb.append(String.format(" and lower(individual.homeFolder.state) %1$s lower(?) ",criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else if(criteria.getAttribut().equals(Individual.SEARCH_IS_HOME_FOLDER_RESPONSIBLE)) {
sb.append(" and roles.role = 'HomeFolderResponsible' ");
} else if (Individual.SEARCH_BY_USER_STATE.equals(criteria.getAttribut())) {
sb.append(String.format(" and lower(individual.state) %1$s lower(?) ", criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else {
logger.warn("Unknown search criteria for Individual object");
}
}
// exclude archived individual if no UserState filter is used
if (!searchByUserState) {
sb.append(" and individual.state != ?");
objectList.add(UserState.ARCHIVED.name());
typeList.add(Hibernate.STRING);
}
return sb;
}
| protected StringBuffer buildStatement(Set<Critere> criterias,List<Type> typeList,
List<Object> objectList,String prefix) {
StringBuffer sb = new StringBuffer();
sb.append(prefix != null ? prefix : "")
.append("from Individual as individual left join individual.individualRoles roles")
.append(" where 1 = 1 ");
// we filter the individual who don't get a home folder
sb.append(" and individual.homeFolder is not null ");
// TODO (rdj) : I know this is apoor solution
boolean searchByUserState = false;
// go through all the criteria and create the query
for (Critere criteria : criterias) {
if (criteria.getAttribut().equals(Individual.SEARCH_BY_LASTNAME)) {
sb.append(" and lower(individual.lastName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_FIRSTNAME)) {
sb.append(" and lower(individual.firstName) ")
.append(criteria.getSqlComparatif())
.append(" lower(?)");
objectList.add(criteria.getSqlStringValue());
typeList.add(Hibernate.STRING);
} else if (criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_ID)) {
sb.append(" and individual.homeFolder.id ")
.append(criteria.getSqlComparatif())
.append(" ?");
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_INDIVIDUAL_ID)) {
sb.append(String.format(" and individual.id %1$s ? ",criteria.getSqlComparatif()));
objectList.add(criteria.getLongValue());
typeList.add(Hibernate.LONG);
} else if(criteria.getAttribut().equals(Individual.SEARCH_BY_HOME_FOLDER_STATE)) {
sb.append(String.format(" and lower(individual.homeFolder.state) %1$s lower(?) ",criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else if(criteria.getAttribut().equals(Individual.SEARCH_IS_HOME_FOLDER_RESPONSIBLE)) {
sb.append(" and roles.role = 'HOME_FOLDER_RESPONSIBLE' ");
} else if (Individual.SEARCH_BY_USER_STATE.equals(criteria.getAttribut())) {
sb.append(String.format(" and lower(individual.state) %1$s lower(?) ", criteria.getSqlComparatif()));
objectList.add(criteria.getValue());
typeList.add(Hibernate.STRING);
searchByUserState = true;
} else {
logger.warn("Unknown search criteria for Individual object");
}
}
// exclude archived individual if no UserState filter is used
if (!searchByUserState) {
sb.append(" and individual.state != ?");
objectList.add(UserState.ARCHIVED.name());
typeList.add(Hibernate.STRING);
}
return sb;
}
|
diff --git a/media/android/NewsBlur/src/com/newsblur/activity/SocialFeedReading.java b/media/android/NewsBlur/src/com/newsblur/activity/SocialFeedReading.java
index 2d1d3ca6c..5c82bc714 100644
--- a/media/android/NewsBlur/src/com/newsblur/activity/SocialFeedReading.java
+++ b/media/android/NewsBlur/src/com/newsblur/activity/SocialFeedReading.java
@@ -1,138 +1,139 @@
package com.newsblur.activity;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.newsblur.database.FeedProvider;
import com.newsblur.database.MixedFeedsReadingAdapter;
import com.newsblur.domain.SocialFeed;
import com.newsblur.domain.Story;
import com.newsblur.network.MarkSocialStoryAsReadTask;
import com.newsblur.service.SyncService;
public class SocialFeedReading extends Reading {
MarkSocialAsReadUpdate markSocialAsReadList;
private String userId;
private String username;
private SocialFeed socialFeed;
private boolean requestedPage;
private boolean stopLoading = false;
private int currentPage;
@Override
protected void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
setResult(RESULT_OK);
userId = getIntent().getStringExtra(Reading.EXTRA_USERID);
username = getIntent().getStringExtra(Reading.EXTRA_USERNAME);
markSocialAsReadList = new MarkSocialAsReadUpdate(userId);
Uri socialFeedUri = FeedProvider.SOCIAL_FEEDS_URI.buildUpon().appendPath(userId).build();
socialFeed = SocialFeed.fromCursor(contentResolver.query(socialFeedUri, null, null, null, null));
Uri storiesURI = FeedProvider.SOCIALFEED_STORIES_URI.buildUpon().appendPath(userId).build();
stories = contentResolver.query(storiesURI, null, FeedProvider.getStorySelectionFromState(currentState), null, null);
setTitle(getIntent().getStringExtra(EXTRA_USERNAME));
readingAdapter = new MixedFeedsReadingAdapter(getSupportFragmentManager(), getContentResolver(), stories);
setupPager();
Story story = readingAdapter.getStory(passedPosition);
+ addStoryToMarkAsRead(story);
markSocialAsReadList.add(story.feedId, story.id);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Story story = readingAdapter.getStory(position);
if (story != null) {
markSocialAsReadList.add(story.feedId, story.id);
addStoryToMarkAsRead(story);
}
checkStoryCount(position);
}
@Override
protected void onDestroy() {
new MarkSocialStoryAsReadTask(this, syncFragment, markSocialAsReadList).execute();
super.onDestroy();
}
public class MarkSocialAsReadUpdate {
public String userId;
HashMap<String, Set<String>> feedStoryMap;
public MarkSocialAsReadUpdate(final String userId) {
this.userId = userId;
feedStoryMap = new HashMap<String, Set<String>>();
}
public void add(final String feedId, final String storyId) {
if (feedStoryMap.get(feedId) == null) {
Set<String> storiesForFeed = new HashSet<String>();
storiesForFeed.add(storyId);
feedStoryMap.put(feedId, storiesForFeed);
} else {
feedStoryMap.get(feedId).add(storyId);
}
}
public Object getJsonObject() {
HashMap<String, HashMap<String, Set<String>>> jsonMap = new HashMap<String, HashMap<String, Set<String>>>();
jsonMap.put(userId, feedStoryMap);
return jsonMap;
}
}
@Override
public void triggerRefresh() {
triggerRefresh(0);
}
@Override
public void triggerRefresh(int page) {
setSupportProgressBarIndeterminateVisibility(true);
final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, SyncService.class);
intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, syncFragment.receiver);
intent.putExtra(SyncService.SYNCSERVICE_TASK, SyncService.EXTRA_TASK_SOCIALFEED_UPDATE);
intent.putExtra(SyncService.EXTRA_TASK_SOCIALFEED_ID, userId);
if (page > 1) {
intent.putExtra(SyncService.EXTRA_TASK_PAGE_NUMBER, Integer.toString(page));
}
intent.putExtra(SyncService.EXTRA_TASK_SOCIALFEED_USERNAME, username);
startService(intent);
}
@Override
public void checkStoryCount(int position) {
if (position == stories.getCount() - 1) {
if (!requestedPage && !stopLoading) {
currentPage += 1;
requestedPage = true;
triggerRefresh(currentPage);
} else {
Log.d(TAG, "No need");
}
}
}
@Override
public void setNothingMoreToUpdate() {
stopLoading = true;
}
@Override
public void closeAfterUpdate() { }
}
| true | true | protected void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
setResult(RESULT_OK);
userId = getIntent().getStringExtra(Reading.EXTRA_USERID);
username = getIntent().getStringExtra(Reading.EXTRA_USERNAME);
markSocialAsReadList = new MarkSocialAsReadUpdate(userId);
Uri socialFeedUri = FeedProvider.SOCIAL_FEEDS_URI.buildUpon().appendPath(userId).build();
socialFeed = SocialFeed.fromCursor(contentResolver.query(socialFeedUri, null, null, null, null));
Uri storiesURI = FeedProvider.SOCIALFEED_STORIES_URI.buildUpon().appendPath(userId).build();
stories = contentResolver.query(storiesURI, null, FeedProvider.getStorySelectionFromState(currentState), null, null);
setTitle(getIntent().getStringExtra(EXTRA_USERNAME));
readingAdapter = new MixedFeedsReadingAdapter(getSupportFragmentManager(), getContentResolver(), stories);
setupPager();
Story story = readingAdapter.getStory(passedPosition);
markSocialAsReadList.add(story.feedId, story.id);
}
| protected void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
setResult(RESULT_OK);
userId = getIntent().getStringExtra(Reading.EXTRA_USERID);
username = getIntent().getStringExtra(Reading.EXTRA_USERNAME);
markSocialAsReadList = new MarkSocialAsReadUpdate(userId);
Uri socialFeedUri = FeedProvider.SOCIAL_FEEDS_URI.buildUpon().appendPath(userId).build();
socialFeed = SocialFeed.fromCursor(contentResolver.query(socialFeedUri, null, null, null, null));
Uri storiesURI = FeedProvider.SOCIALFEED_STORIES_URI.buildUpon().appendPath(userId).build();
stories = contentResolver.query(storiesURI, null, FeedProvider.getStorySelectionFromState(currentState), null, null);
setTitle(getIntent().getStringExtra(EXTRA_USERNAME));
readingAdapter = new MixedFeedsReadingAdapter(getSupportFragmentManager(), getContentResolver(), stories);
setupPager();
Story story = readingAdapter.getStory(passedPosition);
addStoryToMarkAsRead(story);
markSocialAsReadList.add(story.feedId, story.id);
}
|
diff --git a/org.eclipse.virgo.kernel.shell/src/main/java/org/eclipse/virgo/kernel/shell/internal/CommandRegistryCommandInvoker.java b/org.eclipse.virgo.kernel.shell/src/main/java/org/eclipse/virgo/kernel/shell/internal/CommandRegistryCommandInvoker.java
index 97fa3fc2..fffe799b 100644
--- a/org.eclipse.virgo.kernel.shell/src/main/java/org/eclipse/virgo/kernel/shell/internal/CommandRegistryCommandInvoker.java
+++ b/org.eclipse.virgo.kernel.shell/src/main/java/org/eclipse/virgo/kernel/shell/internal/CommandRegistryCommandInvoker.java
@@ -1,174 +1,174 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.kernel.shell.internal;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.virgo.kernel.shell.Converter;
import org.eclipse.virgo.kernel.shell.internal.converters.ConverterRegistry;
import org.eclipse.virgo.kernel.shell.internal.parsing.ParsedCommand;
import org.springframework.util.ReflectionUtils;
/**
* A <code>CommandInvoker</code> implementation that finds the command to invoke from a {@link CommandRegistry}.
* <p />
*
* <strong>Concurrent Semantics</strong><br />
*
* Thread-safe.
*
*/
final class CommandRegistryCommandInvoker implements CommandInvoker {
private final CommandRegistry commandRegistry;
private final ConverterRegistry converterRegistry;
/**
* @param commandRegistry
* @param converterRegistry
*/
CommandRegistryCommandInvoker(CommandRegistry commandRegistry, ConverterRegistry converterRegistry) {
this.commandRegistry = commandRegistry;
this.converterRegistry = converterRegistry;
}
public List<String> invokeCommand(ParsedCommand command) throws CommandNotFoundException, ParametersMismatchException {
List<CommandDescriptor> commands = commandsOfCommandName(this.commandRegistry, command.getCommand());
if (commands.isEmpty()) {
throw new CommandNotFoundException();
}
String[] arguments = command.getArguments();
String subcommandName = extractSubcommand(arguments);
String[] subcommandArguments = extractSubcommandArguments(arguments);
ParametersMismatchException lastException = null;
for (CommandDescriptor commandDescriptor : commands) {
List<String> objResult = null;
String commandSubcommandName = commandDescriptor.getSubCommandName();
String commandString = commandDescriptor.getCommandName();
try {
if (commandSubcommandName != null && !commandSubcommandName.equals("")) {
if (isSubcommandMatch(commandSubcommandName, subcommandName)) {
commandString += " " + subcommandName;
objResult = attemptExecution(commandDescriptor, subcommandArguments);
return objResult;
}
} else {
objResult = attemptExecution(commandDescriptor, arguments);
return objResult;
}
} catch (ParametersMismatchException e) {
lastException = new ParametersMismatchException("Command " + commandString + ": " + e.getMessage());
}
}
if (lastException != null) {
throw lastException;
}
- throw new ParametersMismatchException("Command '" + command.getCommand() + "' expects a subcommand; try vsh help " + command.getCommand());
+ throw new ParametersMismatchException("Command '" + command.getCommand() + "' expects a subcommand; try help vsh:" + command.getCommand());
}
private static boolean isSubcommandMatch(String commandSubcommandName, String subcommandName) {
if (subcommandName == null) {
return false;
}
if (commandSubcommandName != null) {
if (commandSubcommandName.equals(subcommandName)) {
return true;
}
}
return false;
}
private static String[] extractSubcommandArguments(String[] arguments) {
if (arguments.length > 0) {
String[] result = new String[arguments.length - 1];
System.arraycopy(arguments, 1, result, 0, result.length);
return result;
}
return null;
}
private static String extractSubcommand(String[] arguments) {
if (arguments.length > 0) {
return arguments[0];
}
return null;
}
@SuppressWarnings("unchecked")
private List<String> attemptExecution(CommandDescriptor commandDescriptor, String[] arguments) throws ParametersMismatchException {
Method method = commandDescriptor.getMethod();
Object[] convertedArguments = convertArguments(method, arguments);
ReflectionUtils.makeAccessible(method);
return (List<String>) ReflectionUtils.invokeMethod(method, commandDescriptor.getTarget(), convertedArguments);
}
private static List<CommandDescriptor> commandsOfCommandName(final CommandRegistry commandRegistry, final String commandName) {
List<CommandDescriptor> commands = new ArrayList<CommandDescriptor>();
for (CommandDescriptor commandDescriptor : commandRegistry.getCommandDescriptors()) {
if (commandDescriptor.getCommandName().equals(commandName)) {
commands.add(commandDescriptor);
}
}
return commands;
}
private Object[] convertArguments(final Method method, final String[] arguments) throws ParametersMismatchException {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != arguments.length) {
throw new ParametersMismatchException("Incorrect number of parameters");
}
Object[] parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
Object convertedParameter = convertArgument(arguments[i], parameterTypes[i]);
if (convertedParameter != null) {
parameters[i] = convertedParameter;
} else {
throw new ParametersMismatchException("Cannot convert parameter " + i + ".");
}
}
return parameters;
}
private Object convertArgument(final String argument, Class<?> type) {
Converter converter = this.converterRegistry.getConverter(type);
if (converter == null) {
return null;
}
try {
return converter.convert(type, argument);
} catch (Exception e) {
return null;
}
}
}
| true | true | public List<String> invokeCommand(ParsedCommand command) throws CommandNotFoundException, ParametersMismatchException {
List<CommandDescriptor> commands = commandsOfCommandName(this.commandRegistry, command.getCommand());
if (commands.isEmpty()) {
throw new CommandNotFoundException();
}
String[] arguments = command.getArguments();
String subcommandName = extractSubcommand(arguments);
String[] subcommandArguments = extractSubcommandArguments(arguments);
ParametersMismatchException lastException = null;
for (CommandDescriptor commandDescriptor : commands) {
List<String> objResult = null;
String commandSubcommandName = commandDescriptor.getSubCommandName();
String commandString = commandDescriptor.getCommandName();
try {
if (commandSubcommandName != null && !commandSubcommandName.equals("")) {
if (isSubcommandMatch(commandSubcommandName, subcommandName)) {
commandString += " " + subcommandName;
objResult = attemptExecution(commandDescriptor, subcommandArguments);
return objResult;
}
} else {
objResult = attemptExecution(commandDescriptor, arguments);
return objResult;
}
} catch (ParametersMismatchException e) {
lastException = new ParametersMismatchException("Command " + commandString + ": " + e.getMessage());
}
}
if (lastException != null) {
throw lastException;
}
throw new ParametersMismatchException("Command '" + command.getCommand() + "' expects a subcommand; try vsh help " + command.getCommand());
}
| public List<String> invokeCommand(ParsedCommand command) throws CommandNotFoundException, ParametersMismatchException {
List<CommandDescriptor> commands = commandsOfCommandName(this.commandRegistry, command.getCommand());
if (commands.isEmpty()) {
throw new CommandNotFoundException();
}
String[] arguments = command.getArguments();
String subcommandName = extractSubcommand(arguments);
String[] subcommandArguments = extractSubcommandArguments(arguments);
ParametersMismatchException lastException = null;
for (CommandDescriptor commandDescriptor : commands) {
List<String> objResult = null;
String commandSubcommandName = commandDescriptor.getSubCommandName();
String commandString = commandDescriptor.getCommandName();
try {
if (commandSubcommandName != null && !commandSubcommandName.equals("")) {
if (isSubcommandMatch(commandSubcommandName, subcommandName)) {
commandString += " " + subcommandName;
objResult = attemptExecution(commandDescriptor, subcommandArguments);
return objResult;
}
} else {
objResult = attemptExecution(commandDescriptor, arguments);
return objResult;
}
} catch (ParametersMismatchException e) {
lastException = new ParametersMismatchException("Command " + commandString + ": " + e.getMessage());
}
}
if (lastException != null) {
throw lastException;
}
throw new ParametersMismatchException("Command '" + command.getCommand() + "' expects a subcommand; try help vsh:" + command.getCommand());
}
|
diff --git a/proxy/src/main/java/net/md_5/bungee/ServerConnector.java b/proxy/src/main/java/net/md_5/bungee/ServerConnector.java
index a2ea7601..77d13875 100644
--- a/proxy/src/main/java/net/md_5/bungee/ServerConnector.java
+++ b/proxy/src/main/java/net/md_5/bungee/ServerConnector.java
@@ -1,284 +1,285 @@
package net.md_5.bungee;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import java.security.PublicKey;
import java.util.Objects;
import java.util.Queue;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.event.ServerKickEvent;
import net.md_5.bungee.api.scoreboard.Objective;
import net.md_5.bungee.api.scoreboard.Scoreboard;
import net.md_5.bungee.api.scoreboard.Team;
import net.md_5.bungee.connection.CancelSendSignal;
import net.md_5.bungee.connection.DownstreamBridge;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.CipherDecoder;
import net.md_5.bungee.netty.CipherEncoder;
import net.md_5.bungee.netty.PacketDecoder;
import net.md_5.bungee.packet.DefinedPacket;
import net.md_5.bungee.packet.Packet1Login;
import net.md_5.bungee.packet.Packet9Respawn;
import net.md_5.bungee.packet.PacketCDClientStatus;
import net.md_5.bungee.packet.PacketCEScoreboardObjective;
import net.md_5.bungee.packet.PacketD1Team;
import net.md_5.bungee.packet.PacketFAPluginMessage;
import net.md_5.bungee.packet.PacketFCEncryptionResponse;
import net.md_5.bungee.packet.PacketFDEncryptionRequest;
import net.md_5.bungee.packet.PacketFFKick;
import net.md_5.bungee.packet.PacketHandler;
import net.md_5.bungee.protocol.PacketDefinitions;
@RequiredArgsConstructor
public class ServerConnector extends PacketHandler
{
private final ProxyServer bungee;
private ChannelWrapper ch;
private final UserConnection user;
private final BungeeServerInfo target;
private State thisState = State.ENCRYPT_REQUEST;
private SecretKey secretkey;
private enum State
{
ENCRYPT_REQUEST, ENCRYPT_RESPONSE, LOGIN, FINISHED;
}
@Override
public void exception(Throwable t) throws Exception
{
String message = "Exception Connectiong:" + Util.exception( t );
if ( user.getServer() == null || user.getServer().isForgeWrapper() )
{
user.disconnect( message );
} else
{
user.sendMessage( ChatColor.RED + message );
}
}
@Override
public void connected(ChannelWrapper channel) throws Exception
{
this.ch = channel;
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF( "Login" );
out.writeUTF( user.getAddress().getAddress().getHostAddress() );
out.writeInt( user.getAddress().getPort() );
channel.write( new PacketFAPluginMessage( "BungeeCord", out.toByteArray() ) );
channel.write( user.getPendingConnection().getHandshake() );
// Skip encryption if we are not using Forge
if ( user.getPendingConnection().getForgeLogin() == null )
{
channel.write( PacketCDClientStatus.CLIENT_LOGIN );
}
}
@Override
public void disconnected(ChannelWrapper channel) throws Exception
{
user.getPendingConnects().remove( target );
}
@Override
public void handle(Packet1Login login) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" );
ServerConnection server = new ServerConnection( ch, target, false );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
bungee.getPluginManager().callEvent( event );
+ ch.write( BungeeCord.getInstance().registerChannels() );
Queue<DefinedPacket> packetQueue = target.getPacketQueue();
synchronized ( packetQueue )
{
while ( !packetQueue.isEmpty() )
{
ch.write( packetQueue.poll() );
}
}
for ( PacketFAPluginMessage message : user.getPendingConnection().getLoginMessages() )
{
ch.write( message );
}
if ( user.getSettings() != null )
{
ch.write( user.getSettings() );
}
synchronized ( user.getSwitchMutex() )
{
// TODO: This whole wrapper business is a hack
if ( user.getServer() == null || user.getServer().isForgeWrapper() )
{
// Once again, first connection
user.setClientEntityId( login.entityId );
user.setServerEntityId( login.entityId );
// Set tab list size
Packet1Login modLogin = new Packet1Login(
login.entityId,
login.levelType,
login.gameMode,
(byte) login.dimension,
login.difficulty,
login.unused,
(byte) user.getPendingConnection().getListener().getTabListSize(),
ch.getHandle().pipeline().get( PacketDecoder.class ).getProtocol() == PacketDefinitions.FORGE_PROTOCOL );
user.sendPacket( modLogin );
} else
{
bungee.getTabListHandler().onServerChange( user );
Scoreboard serverScoreboard = user.getServerSentScoreboard();
for ( Objective objective : serverScoreboard.getObjectives() )
{
user.sendPacket( new PacketCEScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) );
}
for ( Team team : serverScoreboard.getTeams() )
{
user.sendPacket( PacketD1Team.destroy( team.getName() ) );
}
serverScoreboard.clear();
user.sendPacket( Packet9Respawn.DIM1_SWITCH );
user.sendPacket( Packet9Respawn.DIM2_SWITCH );
user.setServerEntityId( login.entityId );
user.sendPacket( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
// Remove from old servers
user.getServer().setObsolete( true );
user.getServer().disconnect( "Quitting" );
}
// TODO: Fix this?
if ( !user.isActive() )
{
server.disconnect( "Quitting" );
// Silly server admins see stack trace and die
bungee.getLogger().warning( "No client connected for pending server!" );
return;
}
// Add to new server
// TODO: Move this to the connected() method of DownstreamBridge
target.addPlayer( user );
user.getPendingConnects().remove( target );
user.setServer( server );
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) );
}
thisState = State.FINISHED;
throw new CancelSendSignal();
}
@Override
public void handle(PacketFDEncryptionRequest encryptRequest) throws Exception
{
Preconditions.checkState( thisState == State.ENCRYPT_REQUEST, "Not expecting ENCRYPT_REQUEST" );
// Only need to handle this if we want to use encryption
if ( user.getPendingConnection().getForgeLogin() != null )
{
PublicKey publickey = EncryptionUtil.getPubkey( encryptRequest );
this.secretkey = EncryptionUtil.getSecret();
byte[] shared = EncryptionUtil.encrypt( publickey, secretkey.getEncoded() );
byte[] token = EncryptionUtil.encrypt( publickey, encryptRequest.verifyToken );
ch.write( new PacketFCEncryptionResponse( shared, token ) );
Cipher encrypt = EncryptionUtil.getCipher( Cipher.ENCRYPT_MODE, secretkey );
ch.getHandle().pipeline().addBefore( "decoder", "encrypt", new CipherEncoder( encrypt ) );
thisState = State.ENCRYPT_RESPONSE;
} else
{
thisState = State.LOGIN;
}
}
@Override
public void handle(PacketFCEncryptionResponse encryptResponse) throws Exception
{
Preconditions.checkState( thisState == State.ENCRYPT_RESPONSE, "Not expecting ENCRYPT_RESPONSE" );
Cipher decrypt = EncryptionUtil.getCipher( Cipher.DECRYPT_MODE, secretkey );
ch.getHandle().pipeline().addBefore( "decoder", "decrypt", new CipherDecoder( decrypt ) );
ch.write( user.getPendingConnection().getForgeLogin() );
user.setServer( new ServerConnection( ch, target, true ) );
ch.write( PacketCDClientStatus.CLIENT_LOGIN );
thisState = State.LOGIN;
}
@Override
public void handle(PacketFFKick kick) throws Exception
{
ServerInfo def = bungee.getServerInfo( user.getPendingConnection().getListener().getFallbackServer() );
if ( Objects.equals( target, def ) )
{
def = null;
}
ServerKickEvent event = bungee.getPluginManager().callEvent( new ServerKickEvent( user, kick.message, def ) );
if ( event.isCancelled() && event.getCancelServer() != null )
{
user.connect( event.getCancelServer() );
return;
}
String message = ChatColor.RED + "Kicked whilst connecting to " + target.getName() + ": " + kick.message;
if ( user.getServer() == null )
{
user.disconnect( message );
} else
{
user.sendMessage( message );
}
}
@Override
public void handle(PacketFAPluginMessage pluginMessage) throws Exception
{
if ( ( pluginMessage.data[0] & 0xFF ) == 0 && pluginMessage.tag.equals( "FML" ) )
{
ByteArrayDataInput in = ByteStreams.newDataInput( pluginMessage.data );
in.readUnsignedByte();
for ( int i = 0; i < in.readInt(); i++ )
{
in.readUTF();
}
if ( in.readByte() != 0 )
{
ch.getHandle().pipeline().get( PacketDecoder.class ).setProtocol( PacketDefinitions.FORGE_PROTOCOL );
}
}
user.sendPacket( pluginMessage ); // We have to forward these to the user, especially with Forge as stuff might break
}
@Override
public String toString()
{
return "[" + user.getName() + "] <-> ServerConnector [" + target.getName() + "]";
}
}
| true | true | public void handle(Packet1Login login) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" );
ServerConnection server = new ServerConnection( ch, target, false );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
bungee.getPluginManager().callEvent( event );
Queue<DefinedPacket> packetQueue = target.getPacketQueue();
synchronized ( packetQueue )
{
while ( !packetQueue.isEmpty() )
{
ch.write( packetQueue.poll() );
}
}
for ( PacketFAPluginMessage message : user.getPendingConnection().getLoginMessages() )
{
ch.write( message );
}
if ( user.getSettings() != null )
{
ch.write( user.getSettings() );
}
synchronized ( user.getSwitchMutex() )
{
// TODO: This whole wrapper business is a hack
if ( user.getServer() == null || user.getServer().isForgeWrapper() )
{
// Once again, first connection
user.setClientEntityId( login.entityId );
user.setServerEntityId( login.entityId );
// Set tab list size
Packet1Login modLogin = new Packet1Login(
login.entityId,
login.levelType,
login.gameMode,
(byte) login.dimension,
login.difficulty,
login.unused,
(byte) user.getPendingConnection().getListener().getTabListSize(),
ch.getHandle().pipeline().get( PacketDecoder.class ).getProtocol() == PacketDefinitions.FORGE_PROTOCOL );
user.sendPacket( modLogin );
} else
{
bungee.getTabListHandler().onServerChange( user );
Scoreboard serverScoreboard = user.getServerSentScoreboard();
for ( Objective objective : serverScoreboard.getObjectives() )
{
user.sendPacket( new PacketCEScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) );
}
for ( Team team : serverScoreboard.getTeams() )
{
user.sendPacket( PacketD1Team.destroy( team.getName() ) );
}
serverScoreboard.clear();
user.sendPacket( Packet9Respawn.DIM1_SWITCH );
user.sendPacket( Packet9Respawn.DIM2_SWITCH );
user.setServerEntityId( login.entityId );
user.sendPacket( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
// Remove from old servers
user.getServer().setObsolete( true );
user.getServer().disconnect( "Quitting" );
}
// TODO: Fix this?
if ( !user.isActive() )
{
server.disconnect( "Quitting" );
// Silly server admins see stack trace and die
bungee.getLogger().warning( "No client connected for pending server!" );
return;
}
// Add to new server
// TODO: Move this to the connected() method of DownstreamBridge
target.addPlayer( user );
user.getPendingConnects().remove( target );
user.setServer( server );
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) );
}
thisState = State.FINISHED;
throw new CancelSendSignal();
}
| public void handle(Packet1Login login) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" );
ServerConnection server = new ServerConnection( ch, target, false );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
bungee.getPluginManager().callEvent( event );
ch.write( BungeeCord.getInstance().registerChannels() );
Queue<DefinedPacket> packetQueue = target.getPacketQueue();
synchronized ( packetQueue )
{
while ( !packetQueue.isEmpty() )
{
ch.write( packetQueue.poll() );
}
}
for ( PacketFAPluginMessage message : user.getPendingConnection().getLoginMessages() )
{
ch.write( message );
}
if ( user.getSettings() != null )
{
ch.write( user.getSettings() );
}
synchronized ( user.getSwitchMutex() )
{
// TODO: This whole wrapper business is a hack
if ( user.getServer() == null || user.getServer().isForgeWrapper() )
{
// Once again, first connection
user.setClientEntityId( login.entityId );
user.setServerEntityId( login.entityId );
// Set tab list size
Packet1Login modLogin = new Packet1Login(
login.entityId,
login.levelType,
login.gameMode,
(byte) login.dimension,
login.difficulty,
login.unused,
(byte) user.getPendingConnection().getListener().getTabListSize(),
ch.getHandle().pipeline().get( PacketDecoder.class ).getProtocol() == PacketDefinitions.FORGE_PROTOCOL );
user.sendPacket( modLogin );
} else
{
bungee.getTabListHandler().onServerChange( user );
Scoreboard serverScoreboard = user.getServerSentScoreboard();
for ( Objective objective : serverScoreboard.getObjectives() )
{
user.sendPacket( new PacketCEScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) );
}
for ( Team team : serverScoreboard.getTeams() )
{
user.sendPacket( PacketD1Team.destroy( team.getName() ) );
}
serverScoreboard.clear();
user.sendPacket( Packet9Respawn.DIM1_SWITCH );
user.sendPacket( Packet9Respawn.DIM2_SWITCH );
user.setServerEntityId( login.entityId );
user.sendPacket( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
// Remove from old servers
user.getServer().setObsolete( true );
user.getServer().disconnect( "Quitting" );
}
// TODO: Fix this?
if ( !user.isActive() )
{
server.disconnect( "Quitting" );
// Silly server admins see stack trace and die
bungee.getLogger().warning( "No client connected for pending server!" );
return;
}
// Add to new server
// TODO: Move this to the connected() method of DownstreamBridge
target.addPlayer( user );
user.getPendingConnects().remove( target );
user.setServer( server );
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) );
}
thisState = State.FINISHED;
throw new CancelSendSignal();
}
|
diff --git a/src/main/java/pl/mjedynak/App.java b/src/main/java/pl/mjedynak/App.java
index c394e1a..628e6d0 100644
--- a/src/main/java/pl/mjedynak/App.java
+++ b/src/main/java/pl/mjedynak/App.java
@@ -1,33 +1,33 @@
package pl.mjedynak;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import org.glassfish.grizzly.http.server.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
private static final URI BASE_URI = UriBuilder.fromUri("http://localhost/").port(9998).build();
protected static HttpServer startServer() throws IOException {
logger.debug("Starting grizzly...");
ResourceConfig resourceConfig = new PackagesResourceConfig("pl.mjedynak.resource");
return GrizzlyServerFactory.createHttpServer(BASE_URI, resourceConfig);
}
public static void main(String[] args) throws IOException {
HttpServer httpServer = startServer();
- logger.debug(String.format("Jersey app started with WADL available at %sapplication.wadl"), BASE_URI);
+ logger.debug(String.format("Jersey app started with WADL available at %sapplication.wadl", BASE_URI));
logger.debug(String.format("Try out %sresource\nHit enter to stop it...", BASE_URI));
System.in.read();
httpServer.stop();
}
}
| true | true | public static void main(String[] args) throws IOException {
HttpServer httpServer = startServer();
logger.debug(String.format("Jersey app started with WADL available at %sapplication.wadl"), BASE_URI);
logger.debug(String.format("Try out %sresource\nHit enter to stop it...", BASE_URI));
System.in.read();
httpServer.stop();
}
| public static void main(String[] args) throws IOException {
HttpServer httpServer = startServer();
logger.debug(String.format("Jersey app started with WADL available at %sapplication.wadl", BASE_URI));
logger.debug(String.format("Try out %sresource\nHit enter to stop it...", BASE_URI));
System.in.read();
httpServer.stop();
}
|
diff --git a/plugins/maven-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishScmMojo.java b/plugins/maven-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishScmMojo.java
index 366e99b89..f8547da1a 100644
--- a/plugins/maven-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishScmMojo.java
+++ b/plugins/maven-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishScmMojo.java
@@ -1,273 +1,273 @@
package org.apache.maven.plugins.scmpublish;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.MatchPatterns;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Publish a content to scm in one step. By default, content is taken from default site staging directory
* <code>${project.build.directory}/staging</code>.
* Can be used without project, so usable to update any SCM with any content.
*/
@Mojo(name = "publish-scm", aggregator = true, requiresProject = false)
public class ScmPublishPublishScmMojo
extends ScmPublishPublishMojo
{
/**
* The content to be published.
*/
@Parameter(property = "scmpublish.content", defaultValue = "${project.build.directory}/staging")
private File content;
/**
*/
@Component
protected MavenProject project;
private List<File> deleted = new ArrayList<File>();
private List<File> added = new ArrayList<File>();
private List<File> updated = new ArrayList<File>();
/**
* Update scm checkout directory with content.
*
* @param checkout the scm checkout directory
* @param dir the content to put in scm (can be <code>null</code>)
* @param doNotDeleteDirs directory names that should not be deleted from scm even if not in new content:
* used for modules, which content is available only when staging
* @throws IOException
*/
private void update( File checkout, File dir, List<String> doNotDeleteDirs )
throws IOException
{
String[] files =
checkout.list( new NotFileFilter( new NameFileFilter( scmProvider.getScmSpecificFilename() ) ) );
Set<String> checkoutContent = new HashSet<String>( Arrays.asList( files ) );
List<String> dirContent = ( dir != null ) ? Arrays.asList( dir.list() ) : Collections.<String>emptyList();
Set<String> deleted = new HashSet<String>( checkoutContent );
deleted.removeAll( dirContent );
MatchPatterns ignoreDeleteMatchPatterns = null;
List<String> pathsAsList = new ArrayList<String>( 0 );
if ( ignorePathsToDelete != null && ignorePathsToDelete.length > 0 )
{
ignoreDeleteMatchPatterns = MatchPatterns.from( ignorePathsToDelete );
pathsAsList = Arrays.asList( ignorePathsToDelete );
}
for ( String name : deleted )
{
if ( ignoreDeleteMatchPatterns != null && ignoreDeleteMatchPatterns.matches( name, true ) )
{
- getLog().debug( name + " match one of the patterns '" + pathsAsList + "' do add to deteled files" );
+ getLog().debug( name + " match one of the patterns '" + pathsAsList + "' do not add to deleted files" );
continue;
}
File file = new File( checkout, name );
if ( ( doNotDeleteDirs != null ) && file.isDirectory() && ( doNotDeleteDirs.contains( name ) ) )
{
// ignore directory not available
continue;
}
if ( file.isDirectory() )
{
update( file, null, null );
}
this.deleted.add( file );
}
for ( String name : dirContent )
{
File file = new File( checkout, name );
File source = new File( dir, name );
if ( source.isDirectory() )
{
if ( !checkoutContent.contains( name ) )
{
this.added.add( file );
file.mkdir();
}
update( file, source, null );
}
else
{
if ( checkoutContent.contains( name ) )
{
this.updated.add( file );
}
else
{
this.added.add( file );
}
copyFile( source, file );
}
}
}
/**
* Copy a file content, normalizing newlines when necessary.
*
* @param srcFile the source file
* @param destFile the destination file
* @throws IOException
* @see #requireNormalizeNewlines(File)
*/
private void copyFile( File srcFile, File destFile )
throws IOException
{
if ( requireNormalizeNewlines( srcFile ) )
{
copyAndNormalizeNewlines( srcFile, destFile );
}
else
{
FileUtils.copyFile( srcFile, destFile );
}
}
/**
* Copy and normalize newlines.
*
* @param srcFile the source file
* @param destFile the destination file
* @throws IOException
*/
private void copyAndNormalizeNewlines( File srcFile, File destFile )
throws IOException
{
BufferedReader in = null;
PrintWriter out = null;
try
{
in = new BufferedReader( new InputStreamReader( new FileInputStream( srcFile ), siteOutputEncoding ) );
out = new PrintWriter( new OutputStreamWriter( new FileOutputStream( destFile ), siteOutputEncoding ) );
String line;
while ( ( line = in.readLine() ) != null )
{
if ( in.ready() )
{
out.println( line );
}
else
{
out.print( line );
}
}
}
finally
{
IOUtils.closeQuietly( out );
IOUtils.closeQuietly( in );
}
}
public void scmPublishExecute()
throws MojoExecutionException, MojoFailureException
{
if ( siteOutputEncoding == null )
{
getLog().warn( "No output encoding, defaulting to UTF-8." );
siteOutputEncoding = "utf-8";
}
if ( !content.canRead() )
{
throw new MojoExecutionException( "can't read content directory: " + content );
}
checkoutExisting();
try
{
logInfo( "Updating content..." );
update( checkoutDirectory, content, ( project == null ) ? null : project.getModel().getModules() );
}
catch ( IOException ioe )
{
throw new MojoExecutionException( "could not copy content to scm checkout", ioe );
}
logInfo( "Publish files: %d addition(s), %d update(s), %d delete(s)", added.size(), updated.size(),
deleted.size() );
if ( isDryRun() )
{
for ( File addedFile : added )
{
logInfo( "Added %s", addedFile.getAbsolutePath() );
}
for ( File deletedFile : deleted )
{
logInfo( "Deleted %s", deletedFile.getAbsolutePath() );
}
for ( File updatedFile : updated )
{
logInfo( "Updated %s", updatedFile.getAbsolutePath() );
}
return;
}
if ( !added.isEmpty() )
{
addFiles( added );
}
if ( !deleted.isEmpty() )
{
deleteFiles( deleted );
}
logInfo( "Checking in SCM..." );
checkinFiles();
}
}
| true | true | private void update( File checkout, File dir, List<String> doNotDeleteDirs )
throws IOException
{
String[] files =
checkout.list( new NotFileFilter( new NameFileFilter( scmProvider.getScmSpecificFilename() ) ) );
Set<String> checkoutContent = new HashSet<String>( Arrays.asList( files ) );
List<String> dirContent = ( dir != null ) ? Arrays.asList( dir.list() ) : Collections.<String>emptyList();
Set<String> deleted = new HashSet<String>( checkoutContent );
deleted.removeAll( dirContent );
MatchPatterns ignoreDeleteMatchPatterns = null;
List<String> pathsAsList = new ArrayList<String>( 0 );
if ( ignorePathsToDelete != null && ignorePathsToDelete.length > 0 )
{
ignoreDeleteMatchPatterns = MatchPatterns.from( ignorePathsToDelete );
pathsAsList = Arrays.asList( ignorePathsToDelete );
}
for ( String name : deleted )
{
if ( ignoreDeleteMatchPatterns != null && ignoreDeleteMatchPatterns.matches( name, true ) )
{
getLog().debug( name + " match one of the patterns '" + pathsAsList + "' do add to deteled files" );
continue;
}
File file = new File( checkout, name );
if ( ( doNotDeleteDirs != null ) && file.isDirectory() && ( doNotDeleteDirs.contains( name ) ) )
{
// ignore directory not available
continue;
}
if ( file.isDirectory() )
{
update( file, null, null );
}
this.deleted.add( file );
}
for ( String name : dirContent )
{
File file = new File( checkout, name );
File source = new File( dir, name );
if ( source.isDirectory() )
{
if ( !checkoutContent.contains( name ) )
{
this.added.add( file );
file.mkdir();
}
update( file, source, null );
}
else
{
if ( checkoutContent.contains( name ) )
{
this.updated.add( file );
}
else
{
this.added.add( file );
}
copyFile( source, file );
}
}
}
| private void update( File checkout, File dir, List<String> doNotDeleteDirs )
throws IOException
{
String[] files =
checkout.list( new NotFileFilter( new NameFileFilter( scmProvider.getScmSpecificFilename() ) ) );
Set<String> checkoutContent = new HashSet<String>( Arrays.asList( files ) );
List<String> dirContent = ( dir != null ) ? Arrays.asList( dir.list() ) : Collections.<String>emptyList();
Set<String> deleted = new HashSet<String>( checkoutContent );
deleted.removeAll( dirContent );
MatchPatterns ignoreDeleteMatchPatterns = null;
List<String> pathsAsList = new ArrayList<String>( 0 );
if ( ignorePathsToDelete != null && ignorePathsToDelete.length > 0 )
{
ignoreDeleteMatchPatterns = MatchPatterns.from( ignorePathsToDelete );
pathsAsList = Arrays.asList( ignorePathsToDelete );
}
for ( String name : deleted )
{
if ( ignoreDeleteMatchPatterns != null && ignoreDeleteMatchPatterns.matches( name, true ) )
{
getLog().debug( name + " match one of the patterns '" + pathsAsList + "' do not add to deleted files" );
continue;
}
File file = new File( checkout, name );
if ( ( doNotDeleteDirs != null ) && file.isDirectory() && ( doNotDeleteDirs.contains( name ) ) )
{
// ignore directory not available
continue;
}
if ( file.isDirectory() )
{
update( file, null, null );
}
this.deleted.add( file );
}
for ( String name : dirContent )
{
File file = new File( checkout, name );
File source = new File( dir, name );
if ( source.isDirectory() )
{
if ( !checkoutContent.contains( name ) )
{
this.added.add( file );
file.mkdir();
}
update( file, source, null );
}
else
{
if ( checkoutContent.contains( name ) )
{
this.updated.add( file );
}
else
{
this.added.add( file );
}
copyFile( source, file );
}
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
index 9e761de04..a2fa3057b 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
@@ -1,261 +1,264 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2005 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Abstract class for chekcs which need to collect information about
* declared members/parameters/variables.
*
* @author o_sukhodolsky
*/
public abstract class DeclarationCollector extends Check
{
/** Stack of variable declaration frames. */
private FrameStack mFrames;
/** {@inheritDoc} */
public void beginTree(DetailAST aRootAST)
{
mFrames = new FrameStack();
}
/** {@inheritDoc} */
public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
- case TokenTypes.CLASS_DEF : {
+ case TokenTypes.CLASS_DEF :
+ case TokenTypes.INTERFACE_DEF :
+ case TokenTypes.ENUM_DEF :
+ case TokenTypes.ANNOTATION_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
/** {@inheritDoc} */
public void leaveToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.CLASS_DEF :
case TokenTypes.INTERFACE_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ANNOTATION_DEF :
case TokenTypes.SLIST :
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.leave();
break;
default :
// do nothing
}
}
/**
* Check if given name is a name for declafred variable/parameter/member in
* current environment.
* @param aName a name to check
* @return true is the given name is declare one.
*/
protected final boolean isDeclared(String aName)
{
return (null != mFrames.findFrame(aName));
}
/**
* Check if given name is a name for class field in current environment.
* @param aName a name to check
* @return true is the given name is name of method or member.
*/
protected final boolean isClassField(String aName)
{
return (mFrames.findFrame(aName) instanceof ClassFrame);
}
}
/**
* A declaration frame.
* @author Stephen Bloch
* June 19, 2003
*/
abstract class LexicalFrame
{
/** Set of name of variables declared in this frame. */
private HashSet mVarNames;
/** constructor -- invocable only via super() from subclasses */
protected LexicalFrame()
{
mVarNames = new HashSet();
}
/** add a name to the frame.
* @param aNameToAdd the name we're adding
*/
void addName(String aNameToAdd)
{
this.mVarNames.add(aNameToAdd);
}
/** check whether the frame contains a given name.
* @param aNameToFind the name we're looking for
* @return whether it was found
*/
boolean contains(String aNameToFind)
{
return this.mVarNames.contains(aNameToFind);
}
}
/**
* The global frame; should hold only class names.
* @author Stephen Bloch
*/
class GlobalFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
GlobalFrame()
{
super();
}
}
/**
* A frame initiated at method definition; holds parameter names.
* @author Stephen Bloch
*/
class MethodFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
MethodFrame()
{
super();
}
}
/**
* A frame initiated at class definition; holds instance variable
* names. For the present, I'm not worried about other class names,
* method names, etc.
* @author Stephen Bloch
*/
class ClassFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
ClassFrame()
{
super();
}
}
/**
* A frame initiated on entering a statement list; holds local variable
* names. For the present, I'm not worried about other class names,
* method names, etc.
* @author Stephen Bloch
*/
class BlockFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
BlockFrame()
{
super();
}
}
/**
* A stack of LexicalFrames. Standard issue....
* @author Stephen Bloch
*/
class FrameStack
{
/** List of lexical frames. */
private LinkedList mFrameList;
/** Creates an empty FrameStack. */
FrameStack()
{
mFrameList = new LinkedList();
this.enter(new GlobalFrame());
}
/**
* Enter a scope, i.e. push a frame on the stack.
* @param aNewFrame the already-created frame to push
*/
void enter(LexicalFrame aNewFrame)
{
mFrameList.addFirst(aNewFrame);
}
/** Leave a scope, i.e. pop a frame from the stack. */
void leave()
{
mFrameList.removeFirst();
}
/**
* Get current scope, i.e. top frame on the stack.
* @return the current frame
*/
LexicalFrame current()
{
return (LexicalFrame) mFrameList.getFirst();
}
/**
* Search this and containing frames for a given name.
* @param aNameToFind the name we're looking for
* @return the frame in which it was found, or null if not found
*/
LexicalFrame findFrame(String aNameToFind)
{
final Iterator it = mFrameList.iterator();
while (it.hasNext()) {
final LexicalFrame thisFrame = (LexicalFrame) it.next();
if (thisFrame.contains(aNameToFind)) {
return thisFrame;
}
}
return null;
}
}
| true | true | public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
case TokenTypes.CLASS_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
| public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
case TokenTypes.CLASS_DEF :
case TokenTypes.INTERFACE_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ANNOTATION_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
|
diff --git a/src/org/vesalainen/parsers/sql/dsql/Statistics.java b/src/org/vesalainen/parsers/sql/dsql/Statistics.java
index 4f2c7cf..a1c54c7 100644
--- a/src/org/vesalainen/parsers/sql/dsql/Statistics.java
+++ b/src/org/vesalainen/parsers/sql/dsql/Statistics.java
@@ -1,263 +1,263 @@
/*
* Copyright (C) 2012 Timo Vesalainen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.parsers.sql.dsql;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Index;
import com.google.appengine.api.datastore.Index.IndexState;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.vesalainen.parsers.sql.ColumnMetadata;
import org.vesalainen.parsers.sql.TableMetadata;
/**
* @author Timo Vesalainen
*/
public class Statistics
{
private static final long DAY = 24*60*60*1000;
private long nextUpdate;
private DatastoreService datastore;
private final Map<String, TableMetadata> map = new TreeMap<>();
private Map<Index, IndexState> indexes;
public Statistics(DatastoreService datastore)
{
this.datastore = datastore;
update();
}
public void update()
{
synchronized(map)
{
if (System.currentTimeMillis() > nextUpdate)
{
indexes = datastore.getIndexes();
map.clear();
- Query q0 = new Query("__Stat_Total__");
+ Query q0 = new Query("__Stat_Ns_Total__");
Entity total = datastore.prepare(q0).asSingleEntity();
if (total != null)
{
Date timestamp = (Date) total.getProperty("timestamp");
nextUpdate = timestamp.getTime() + DAY;
- Query q1 = new Query("__Stat_PropertyName_Kind__");
+ Query q1 = new Query("__Stat_Ns_PropertyName_Kind__");
q1.addFilter("timestamp", Query.FilterOperator.EQUAL, timestamp);
PreparedQuery p1 = datastore.prepare(q1);
for (Entity prop : p1.asIterable())
{
String kind = (String) prop.getProperty("kind_name");
if (!kind.startsWith("_"))
{
String property = (String) prop.getProperty("property_name");
long count = (long) prop.getProperty("count");
long indexCount = (long) prop.getProperty("builtin_index_count");
KindEntry kindEntry = (KindEntry) map.get(kind.toUpperCase());
if (kindEntry == null)
{
kindEntry = new KindEntry(kind);
map.put(kind.toUpperCase(), kindEntry);
}
kindEntry.addProperty(property, count, indexCount > 0);
}
}
}
}
}
}
public Map<Index, IndexState> getIndexes()
{
return indexes;
}
public TableMetadata getKind(String name)
{
if (name != null)
{
return map.get(name.toUpperCase());
}
return null;
}
public ColumnMetadata getProperty(String kind, String property)
{
KindEntry kindEntry = (KindEntry) getKind(kind);
if (kindEntry != null)
{
return kindEntry.getColumnMetadata(property);
}
return null;
}
public Iterable<TableMetadata> getTables()
{
return map.values();
}
public class KindEntry implements TableMetadata, Iterable<ColumnMetadata>
{
private String name;
private long entityCount;
private Map<String,ColumnMetadata> properties = new HashMap<>();
private PropertyEntry key;
public KindEntry(String name)
{
this.name = name;
}
public void addProperty(String name, long count, boolean indexed)
{
if (!properties.containsKey(name))
{
properties.put(name.toUpperCase(), new PropertyEntry(name, count, indexed));
}
if (entityCount < count)
{
entityCount = count;
}
}
@Override
public ColumnMetadata getColumnMetadata(String name)
{
if (Entity.KEY_RESERVED_PROPERTY.equals(name))
{
if (key == null)
{
key = new PropertyEntry(name, entityCount, true, true);
}
return key;
}
return properties.get(name.toUpperCase());
}
public long getEntityCount()
{
return entityCount;
}
@Override
public String getName()
{
return name;
}
@Override
public long getCount()
{
return entityCount;
}
@Override
public Iterable<ColumnMetadata> getColumns()
{
return this;
}
@Override
public Iterator<ColumnMetadata> iterator()
{
return properties.values().iterator();
}
@Override
public String toString()
{
return name;
}
}
public class PropertyEntry implements ColumnMetadata
{
private String name;
private long count;
private boolean indexed;
private boolean unique;
public PropertyEntry(String name, long count, boolean indexed)
{
this.name = name;
this.count = count;
this.indexed = indexed;
}
public PropertyEntry(String name, long count, boolean indexed, boolean unique)
{
this.name = name;
this.count = count;
this.indexed = indexed;
this.unique = unique;
}
@Override
public long getCount()
{
return count;
}
@Override
public boolean isUnique()
{
return unique;
}
@Override
public boolean isIndexed()
{
return indexed;
}
public long getEstimatedCount()
{
if (indexed)
{
return count / 10;
}
else
{
return count;
}
}
@Override
public String getName()
{
return name;
}
@Override
public float getSelectivity()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String toString()
{
return name;
}
}
}
| false | true | public void update()
{
synchronized(map)
{
if (System.currentTimeMillis() > nextUpdate)
{
indexes = datastore.getIndexes();
map.clear();
Query q0 = new Query("__Stat_Total__");
Entity total = datastore.prepare(q0).asSingleEntity();
if (total != null)
{
Date timestamp = (Date) total.getProperty("timestamp");
nextUpdate = timestamp.getTime() + DAY;
Query q1 = new Query("__Stat_PropertyName_Kind__");
q1.addFilter("timestamp", Query.FilterOperator.EQUAL, timestamp);
PreparedQuery p1 = datastore.prepare(q1);
for (Entity prop : p1.asIterable())
{
String kind = (String) prop.getProperty("kind_name");
if (!kind.startsWith("_"))
{
String property = (String) prop.getProperty("property_name");
long count = (long) prop.getProperty("count");
long indexCount = (long) prop.getProperty("builtin_index_count");
KindEntry kindEntry = (KindEntry) map.get(kind.toUpperCase());
if (kindEntry == null)
{
kindEntry = new KindEntry(kind);
map.put(kind.toUpperCase(), kindEntry);
}
kindEntry.addProperty(property, count, indexCount > 0);
}
}
}
}
}
}
| public void update()
{
synchronized(map)
{
if (System.currentTimeMillis() > nextUpdate)
{
indexes = datastore.getIndexes();
map.clear();
Query q0 = new Query("__Stat_Ns_Total__");
Entity total = datastore.prepare(q0).asSingleEntity();
if (total != null)
{
Date timestamp = (Date) total.getProperty("timestamp");
nextUpdate = timestamp.getTime() + DAY;
Query q1 = new Query("__Stat_Ns_PropertyName_Kind__");
q1.addFilter("timestamp", Query.FilterOperator.EQUAL, timestamp);
PreparedQuery p1 = datastore.prepare(q1);
for (Entity prop : p1.asIterable())
{
String kind = (String) prop.getProperty("kind_name");
if (!kind.startsWith("_"))
{
String property = (String) prop.getProperty("property_name");
long count = (long) prop.getProperty("count");
long indexCount = (long) prop.getProperty("builtin_index_count");
KindEntry kindEntry = (KindEntry) map.get(kind.toUpperCase());
if (kindEntry == null)
{
kindEntry = new KindEntry(kind);
map.put(kind.toUpperCase(), kindEntry);
}
kindEntry.addProperty(property, count, indexCount > 0);
}
}
}
}
}
}
|
diff --git a/src/main/java/hudson/plugins/warnings/WarningsPublisher.java b/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
index 1fa00bd5..7fbff602 100644
--- a/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
+++ b/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
@@ -1,384 +1,383 @@
package hudson.plugins.warnings;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.plugins.analysis.core.AnnotationsClassifier;
import hudson.plugins.analysis.core.FilesParser;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.util.ModuleDetector;
import hudson.plugins.analysis.util.NullModuleDetector;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.warnings.parser.FileWarningsParser;
import hudson.plugins.warnings.parser.ParserRegistry;
import hudson.plugins.warnings.parser.ParsingCanceledException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Publishes the results of the warnings analysis (freestyle project type).
*
* @author Ulli Hafner
*/
// CHECKSTYLE:COUPLING-OFF
public class WarningsPublisher extends HealthAwarePublisher {
private static final String PLUGIN_NAME = "WARNINGS";
private static final long serialVersionUID = -5936973521277401764L;
/** Ant file-set pattern of files to include to report. */
private final String includePattern;
/** Ant file-set pattern of files to exclude from report. */
private final String excludePattern;
/** File pattern and parser configurations. @since 3.19 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE")
private final List<ParserConfiguration> parserConfigurations = Lists.newArrayList();
/** Parser configurations of the console. @since 4.6 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE")
private List<ConsoleParser> consoleParsers = Lists.newArrayList();
/**
* Creates a new instance of <code>WarningPublisher</code>.
*
* @param healthy
* Report health as 100% when the number of annotations is less
* than this value
* @param unHealthy
* Report health as 0% when the number of annotations is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
* @param unstableTotalAll
* annotation threshold
* @param unstableTotalHigh
* annotation threshold
* @param unstableTotalNormal
* annotation threshold
* @param unstableTotalLow
* annotation threshold
* @param unstableNewAll
* annotation threshold
* @param unstableNewHigh
* annotation threshold
* @param unstableNewNormal
* annotation threshold
* @param unstableNewLow
* annotation threshold
* @param failedTotalAll
* annotation threshold
* @param failedTotalHigh
* annotation threshold
* @param failedTotalNormal
* annotation threshold
* @param failedTotalLow
* annotation threshold
* @param failedNewAll
* annotation threshold
* @param failedNewHigh
* annotation threshold
* @param failedNewNormal
* annotation threshold
* @param failedNewLow
* annotation threshold
* @param canRunOnFailed
* determines whether the plug-in can run for failed builds, too
* @param shouldDetectModules
* determines whether module names should be derived from Maven POM or Ant build files
* @param includePattern
* Ant file-set pattern of files to include in report
* @param excludePattern
* Ant file-set pattern of files to exclude from report
* @param canResolveRelativePaths
* determines whether relative paths in warnings should be
* resolved using a time expensive operation that scans the whole
* workspace for matching files.
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public WarningsPublisher(final String healthy, final String unHealthy, final String thresholdLimit,
final String defaultEncoding, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final boolean shouldDetectModules, final boolean canComputeNew,
final String includePattern, final String excludePattern, final boolean canResolveRelativePaths,
final List<ParserConfiguration> parserConfigurations, final List<ConsoleParser> consoleParsers) {
super(healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues,
unstableTotalAll, unstableTotalHigh, unstableTotalNormal, unstableTotalLow,
unstableNewAll, unstableNewHigh, unstableNewNormal, unstableNewLow,
failedTotalAll, failedTotalHigh, failedTotalNormal, failedTotalLow,
failedNewAll, failedNewHigh, failedNewNormal, failedNewLow,
canRunOnFailed, shouldDetectModules, canComputeNew, canResolveRelativePaths, PLUGIN_NAME);
this.includePattern = StringUtils.stripToNull(includePattern);
this.excludePattern = StringUtils.stripToNull(excludePattern);
if (consoleParsers != null) {
this.consoleParsers.addAll(consoleParsers);
}
if (parserConfigurations != null) {
this.parserConfigurations.addAll(parserConfigurations);
}
}
// CHECKSTYLE:ON
/**
* Returns the names of the configured parsers for the console log.
*
* @return the parser names
*/
public ConsoleParser[] getConsoleParsers() {
return ConsoleParser.filterExisting(consoleParsers);
}
/**
* Returns the parserConfigurations.
*
* @return the parserConfigurations
*/
public ParserConfiguration[] getParserConfigurations() {
return ParserConfiguration.filterExisting(parserConfigurations);
}
/**
* Upgrade for release 4.5 or older.
*
* @return this
*/
@Override
protected Object readResolve() {
super.readResolve();
if (consoleParsers == null) {
consoleParsers = Lists.newArrayList();
for (String parser : consoleLogParsers) {
consoleParsers.add(new ConsoleParser(parser));
}
}
return this;
}
/**
* Returns the Ant file-set pattern of files to include in report.
*
* @return Ant file-set pattern of files to include in report
*/
public String getIncludePattern() {
return includePattern;
}
/**
* Returns the Ant file-set pattern of files to exclude from report.
*
* @return Ant file-set pattern of files to exclude from report
*/
public String getExcludePattern() {
return excludePattern;
}
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
throw new IllegalStateException("Not available since release 4.0.");
}
@Override
public Collection<? extends Action> getProjectActions(final AbstractProject<?, ?> project) {
List<Action> actions = Lists.newArrayList();
for (String parserName : getParsers()) {
actions.add(new WarningsProjectAction(project, parserName));
}
return actions;
}
private Set<String> getParsers() {
Set<String> parsers = Sets.newHashSet();
for (ConsoleParser configuration : getConsoleParsers()) {
parsers.add(configuration.getParserName());
}
for (ParserConfiguration configuration : getParserConfigurations()) {
parsers.add(configuration.getParserName());
}
return parsers;
}
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger)
throws InterruptedException, IOException {
try {
if (!hasConsoleParsers() && !hasFileParsers()) {
throw new IOException("Error: No warning parsers defined in the job configuration.");
}
List<ParserResult> fileResults = parseFiles(build, logger);
List<ParserResult> consoleResults = parseConsoleLog(build, logger);
ParserResult totals = new ParserResult();
add(totals, consoleResults);
add(totals, fileResults);
return new WarningsResult(build, new WarningsBuildHistory(build, null), totals, getDefaultEncoding(), null);
}
catch (ParsingCanceledException exception) {
throw createInterruptedException();
}
}
@Override
protected void updateBuildResult(final BuildResult result, final PluginLogger logger) {
for (WarningsResultAction action : result.getOwner().getActions(WarningsResultAction.class)) {
action.getResult().evaluateStatus(getThresholds(), getUseDeltaValues(), canComputeNew(), logger,
action.getUrlName());
}
}
private boolean hasFileParsers() {
return getParserConfigurations().length > 0;
}
private boolean hasConsoleParsers() {
return getConsoleParsers().length > 0;
}
private void add(final ParserResult totals, final List<ParserResult> results) {
for (ParserResult result : results) {
totals.addProject(result);
}
}
private InterruptedException createInterruptedException() {
return new InterruptedException("Canceling parsing since build has been aborted.");
}
private void returnIfCanceled() throws InterruptedException {
if (Thread.interrupted()) {
throw createInterruptedException();
}
}
private List<ParserResult> parseConsoleLog(final AbstractBuild<?, ?> build,
final PluginLogger logger) throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ConsoleParser parser : getConsoleParsers()) {
String parserName = parser.getParserName();
logger.log("Parsing warnings in console log with parser " + parserName);
Collection<FileAnnotation> warnings = new ParserRegistry(
ParserRegistry.getParsers(parserName),
getDefaultEncoding(), getIncludePattern(), getExcludePattern()).parse(build
.getLogFile());
if (!build.getWorkspace().isRemote()) {
guessModuleNames(build, warnings);
}
ParserResult project;
if (canResolveRelativePaths()) {
project = new ParserResult(build.getWorkspace());
}
else {
project = new ParserResult();
}
- project = new ParserResult(build.getWorkspace());
project.addAnnotations(warnings);
results.add(annotate(build, project, parserName));
}
return results;
}
private void guessModuleNames(final AbstractBuild<?, ?> build, final Collection<FileAnnotation> warnings) {
String workspace = build.getWorkspace().getRemote();
ModuleDetector detector = createModuleDetector(workspace);
for (FileAnnotation annotation : warnings) {
String module = detector.guessModuleName(annotation.getFileName());
annotation.setModuleName(module);
}
}
private List<ParserResult> parseFiles(final AbstractBuild<?, ?> build, final PluginLogger logger)
throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ParserConfiguration configuration : getParserConfigurations()) {
String filePattern = configuration.getPattern();
String parserName = configuration.getParserName();
logger.log("Parsing warnings in files '" + filePattern + "' with parser " + parserName);
FilesParser parser = new FilesParser(PLUGIN_NAME, filePattern,
new FileWarningsParser(ParserRegistry.getParsers(parserName), getDefaultEncoding(), getIncludePattern(), getExcludePattern()),
shouldDetectModules(), isMavenBuild(build), canResolveRelativePaths());
ParserResult project = build.getWorkspace().act(parser);
logger.logLines(project.getLogMessages());
returnIfCanceled();
results.add(annotate(build, project, configuration.getParserName()));
}
return results;
}
private ParserResult annotate(final AbstractBuild<?, ?> build, final ParserResult input, final String parserName)
throws IOException, InterruptedException {
ParserResult output = build.getWorkspace().act(
new AnnotationsClassifier(input, getDefaultEncoding()));
for (FileAnnotation annotation : output.getAnnotations()) {
annotation.setPathName(build.getWorkspace().getRemote());
}
WarningsResult result = new WarningsResult(build, new WarningsBuildHistory(build, parserName),
output, getDefaultEncoding(), parserName);
build.getActions().add(new WarningsResultAction(build, this, result, parserName));
return output;
}
private ModuleDetector createModuleDetector(final String workspace) {
if (shouldDetectModules()) {
return new ModuleDetector(new File(workspace));
}
else {
return new NullModuleDetector();
}
}
@Override
public WarningsDescriptor getDescriptor() {
return (WarningsDescriptor)super.getDescriptor();
}
/** {@inheritDoc} */
public MatrixAggregator createAggregator(final MatrixBuild build, final Launcher launcher, final BuildListener listener) {
return new WarningsAnnotationsAggregator(build, launcher, listener, this, getDefaultEncoding());
}
/** Name of parsers to use for scanning the logs. */
@SuppressWarnings({"unused", "PMD"})
private transient Set<String> parserNames;
/** Determines whether the console should be ignored. */
@SuppressWarnings({"unused", "PMD"})
private transient boolean ignoreConsole;
/** Ant file-set pattern of files to work with. */
@SuppressWarnings({"unused", "PMD"})
private transient String pattern;
/** Parser to scan the console log. @since 3.19 */
private transient Set<String> consoleLogParsers;
}
| true | true | private List<ParserResult> parseConsoleLog(final AbstractBuild<?, ?> build,
final PluginLogger logger) throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ConsoleParser parser : getConsoleParsers()) {
String parserName = parser.getParserName();
logger.log("Parsing warnings in console log with parser " + parserName);
Collection<FileAnnotation> warnings = new ParserRegistry(
ParserRegistry.getParsers(parserName),
getDefaultEncoding(), getIncludePattern(), getExcludePattern()).parse(build
.getLogFile());
if (!build.getWorkspace().isRemote()) {
guessModuleNames(build, warnings);
}
ParserResult project;
if (canResolveRelativePaths()) {
project = new ParserResult(build.getWorkspace());
}
else {
project = new ParserResult();
}
project = new ParserResult(build.getWorkspace());
project.addAnnotations(warnings);
results.add(annotate(build, project, parserName));
}
return results;
}
| private List<ParserResult> parseConsoleLog(final AbstractBuild<?, ?> build,
final PluginLogger logger) throws IOException, InterruptedException {
List<ParserResult> results = Lists.newArrayList();
for (ConsoleParser parser : getConsoleParsers()) {
String parserName = parser.getParserName();
logger.log("Parsing warnings in console log with parser " + parserName);
Collection<FileAnnotation> warnings = new ParserRegistry(
ParserRegistry.getParsers(parserName),
getDefaultEncoding(), getIncludePattern(), getExcludePattern()).parse(build
.getLogFile());
if (!build.getWorkspace().isRemote()) {
guessModuleNames(build, warnings);
}
ParserResult project;
if (canResolveRelativePaths()) {
project = new ParserResult(build.getWorkspace());
}
else {
project = new ParserResult();
}
project.addAnnotations(warnings);
results.add(annotate(build, project, parserName));
}
return results;
}
|
diff --git a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
index 9140227db..3bd3a325f 100644
--- a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
+++ b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
@@ -1,126 +1,126 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.requesthandlers.experimentpage;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ebi.gxa.R.AtlasRFactory;
import uk.ac.ebi.gxa.R.AtlasRFactoryBuilder;
import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService;
import uk.ac.ebi.gxa.analytics.compute.ComputeException;
import uk.ac.ebi.gxa.analytics.compute.ComputeTask;
import uk.ac.ebi.gxa.requesthandlers.experimentpage.result.SimilarityResultSet;
import uk.ac.ebi.rcloud.server.RServices;
import uk.ac.ebi.rcloud.server.RType.RDataFrame;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 17-Nov-2009
*/
public class SimilarGeneListTest extends TestCase {
private AtlasComputeService svc;
@Before
public void setUp() {
try {
// build default rFactory - reads R.properties from classpath
AtlasRFactory rFactory = AtlasRFactoryBuilder.getAtlasRFactoryBuilder().buildAtlasRFactory();
// build service
svc = new AtlasComputeService();
svc.setAtlasRFactory(rFactory);
}
catch (Exception e) {
e.printStackTrace();
fail("Caught exception whilst setting up");
}
}
@After
public void tearDown() {
svc.shutdown();
}
@Test
public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
- final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "");
+ final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "/ebi/ArrayExpress-files/NetCDFs.ATLAS");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
private String getRCodeFromResource(String resourcePath) throws IOException {
// open a stream to the resource
InputStream in = getClass().getClassLoader().getResourceAsStream(resourcePath);
// create a reader to read in code
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
in.close();
return sb.toString();
}
}
| true | true | public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
| public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "/ebi/ArrayExpress-files/NetCDFs.ATLAS");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
|
diff --git a/src/de/hdodenhof/holoreader/services/RefreshFeedService.java b/src/de/hdodenhof/holoreader/services/RefreshFeedService.java
index b2b9d6c..d0ffe11 100644
--- a/src/de/hdodenhof/holoreader/services/RefreshFeedService.java
+++ b/src/de/hdodenhof/holoreader/services/RefreshFeedService.java
@@ -1,538 +1,537 @@
package de.hdodenhof.holoreader.services;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.TimeZone;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import de.hdodenhof.holoreader.R;
import de.hdodenhof.holoreader.provider.RSSContentProvider;
import de.hdodenhof.holoreader.provider.SQLiteHelper;
import de.hdodenhof.holoreader.provider.SQLiteHelper.ArticleDAO;
import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO;
public class RefreshFeedService extends WakefulIntentService {
@SuppressWarnings("unused")
private static final String TAG = RefreshFeedService.class.getSimpleName();
private static final String NO_ACTION = "no_action";
private static final int KEEP_READ_ARTICLES_DAYS = 3;
private static final int KEEP_UNREAD_ARTICLES_DAYS = 7;
private static final int SUMMARY_MAXLENGTH = 250;
private static final String DATE_FORMATS[] = { "EEE, dd MMM yyyy HH:mm:ss Z", "EEE, dd MMM yyyy HH:mm:ss z", "yyyy-MM-dd'T'HH:mm:ssz",
"yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ" };
private SimpleDateFormat mSimpleDateFormats[] = new SimpleDateFormat[DATE_FORMATS.length];
private ContentResolver mContentResolver;
private SharedPreferences mSharedPrefs;
private HashSet<Integer> mFeedsUpdating;
public RefreshFeedService() {
super("RefreshFeedService");
}
@Override
public void onCreate() {
super.onCreate();
for (int i = 0; i < DATE_FORMATS.length; i++) {
mSimpleDateFormats[i] = new SimpleDateFormat(DATE_FORMATS[i], Locale.US);
mSimpleDateFormats[i].setTimeZone(TimeZone.getTimeZone("GMT"));
}
mContentResolver = getContentResolver();
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFeedsUpdating = new HashSet<Integer>();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int feedID = intent.getIntExtra("feedid", -1);
if (mFeedsUpdating.contains(feedID)) {
intent.setAction(NO_ACTION);
} else {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean("refreshing", true);
editor.commit();
mFeedsUpdating.add(feedID);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void doWakefulWork(Intent intent) {
if (intent.getAction() == NO_ACTION) {
return;
}
int feedID = intent.getIntExtra("feedid", -1);
ArrayList<ContentValues> contentValuesArrayList = new ArrayList<ContentValues>();
boolean isArticle = false;
boolean linkOverride = false;
String title = null;
String summary = null;
String content = null;
String guid = null;
Date pubdate = null;
Date updated = null;
String link = null;
try {
deleteOldArticles(feedID);
ArrayList<String> existingArticles = queryArticles(feedID);
Date minimumDate = getMinimumDate(feedID);
InputStream inputStream = getURLInputStream(queryURL(feedID));
XmlPullParser pullParser = getParser(inputStream);
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String currentTag = pullParser.getName();
String currentPrefix = pullParser.getPrefix() != null ? pullParser.getPrefix() : "";
if (isItemTag(currentTag, currentPrefix)) {
isArticle = true;
} else if (isTitleTag(currentTag, currentPrefix) && isArticle) {
title = safeNextText(pullParser);
} else if (isSummaryTag(currentTag, currentPrefix) && isArticle) {
summary = safeNextText(pullParser);
} else if (isContentTag(currentTag, currentPrefix) && isArticle) {
content = extractContent(pullParser);
} else if (isGuidTag(currentTag, currentPrefix) && isArticle) {
guid = safeNextText(pullParser);
} else if (isDateTag(currentTag, currentPrefix) && isArticle) {
pubdate = parsePubdate(safeNextText(pullParser));
} else if (isUpdatedTag(currentTag, currentPrefix) && isArticle) {
updated = parsePubdate(safeNextText(pullParser));
} else if (isLinkTag(currentTag, currentPrefix) && isArticle) {
if (!linkOverride) {
link = extractLink(pullParser);
}
} else if (isOrigLinkTag(currentTag, currentPrefix) && isArticle) {
link = safeNextText(pullParser);
linkOverride = true;
}
} else if (eventType == XmlPullParser.END_TAG && isItemTag(pullParser.getName(), "")) {
pubdate = pubdate != null ? pubdate : updated;
guid = guid != null ? guid : link;
if (pubdate.before(minimumDate)) {
break;
}
if (!existingArticles.contains(guid)) {
ContentValues newArticle = prepareArticle(feedID, guid, link, pubdate, title, summary, content);
if (newArticle != null) {
contentValuesArrayList.add(newArticle);
}
}
isArticle = false;
title = null;
summary = null;
content = null;
guid = null;
pubdate = null;
updated = null;
link = null;
}
eventType = pullParser.next();
}
inputStream.close();
storeArticles(contentValuesArrayList);
} catch (IOException e) {
} catch (XmlPullParserException e) {
} catch (Exception e) {
- e.printStackTrace();
} finally {
mFeedsUpdating.remove(feedID);
if (mFeedsUpdating.size() == 0) {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean("refreshing", false);
editor.putLong("lastRefresh", SystemClock.elapsedRealtime());
editor.commit();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("de.hdodenhof.holoreader.FEEDS_REFRESHED");
sendBroadcast(broadcastIntent);
}
}
}
private boolean isItemTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("item") || currentTag.equalsIgnoreCase("entry");
}
private boolean isTitleTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("title") && currentPrefix.equalsIgnoreCase("");
}
private boolean isSummaryTag(String currentTag, String currentPrefix) {
return (currentTag.equalsIgnoreCase("summary") || currentTag.equalsIgnoreCase("description")) && currentPrefix.equalsIgnoreCase("");
}
private boolean isContentTag(String currentTag, String currentPrefix) {
return (currentTag.equalsIgnoreCase("encoded") && currentPrefix.equalsIgnoreCase("content"))
|| (currentTag.equalsIgnoreCase("content") && currentPrefix.equalsIgnoreCase(""));
}
private boolean isGuidTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("guid") || currentTag.equalsIgnoreCase("id");
}
private boolean isDateTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("pubdate") || currentTag.equalsIgnoreCase("published") || currentTag.equalsIgnoreCase("date");
}
private boolean isUpdatedTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("updated");
}
private boolean isLinkTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("link");
}
private boolean isOrigLinkTag(String currentTag, String currentPrefix) {
return currentTag.equalsIgnoreCase("origLink");
}
private XmlPullParser getParser(InputStream inputStream) throws XmlPullParserException {
XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
XmlPullParser pullParser = parserFactory.newPullParser();
pullParser.setInput(inputStream, null);
return pullParser;
}
private InputStream getURLInputStream(String feedURL) throws IOException, MalformedURLException {
URLConnection connection = new URL(feedURL).openConnection();
connection.setRequestProperty("User-agent", getResources().getString(R.string.AppName) + "/" + getResources().getString(R.string.AppVersionName));
connection.connect();
return connection.getInputStream();
}
private Date getMinimumDate(int feedID) {
Date newestArticleDate = queryNewestArticleDate(feedID);
Date articleNotOlderThan = pastDate(KEEP_UNREAD_ARTICLES_DAYS);
if (newestArticleDate == null) {
return articleNotOlderThan;
} else {
return articleNotOlderThan.before(newestArticleDate) ? newestArticleDate : articleNotOlderThan;
}
}
private void deleteOldArticles(int feedID) {
ContentValues contentValues = new ContentValues();
contentValues.put(ArticleDAO.ISDELETED, 1);
mContentResolver.update(RSSContentProvider.URI_ARTICLES, contentValues, ArticleDAO.FEEDID + " = ? AND " + ArticleDAO.PUBDATE + " < ? AND "
+ ArticleDAO.READ + " IS NOT NULL", new String[] { String.valueOf(feedID), SQLiteHelper.fromDate(pastDate(KEEP_READ_ARTICLES_DAYS)) });
mContentResolver.delete(RSSContentProvider.URI_ARTICLES, ArticleDAO.FEEDID + " = ? AND " + ArticleDAO.PUBDATE + " < ?",
new String[] { String.valueOf(feedID), SQLiteHelper.fromDate(pastDate(KEEP_UNREAD_ARTICLES_DAYS)) });
}
private void storeArticles(ArrayList<ContentValues> contentValuesArrayList) {
ContentValues[] contentValuesArray = new ContentValues[contentValuesArrayList.size()];
contentValuesArray = contentValuesArrayList.toArray(contentValuesArray);
mContentResolver.bulkInsert(RSSContentProvider.URI_ARTICLES, contentValuesArray);
}
private String extractLink(XmlPullParser pullParser) throws XmlPullParserException, IOException {
String link = null;
if (pullParser.getAttributeCount() > 0) {
for (int i = 0; i < pullParser.getAttributeCount(); i++) {
if (pullParser.getAttributeName(i).equals("href")) {
link = pullParser.getAttributeValue(i);
break;
}
}
}
if (link == null) {
pullParser.next();
link = pullParser.getText();
}
pullParser.next();
return link;
}
private String extractContent(XmlPullParser pullParser) throws XmlPullParserException, IOException {
String content = "";
if (pullParser.getAttributeCount() > 0) {
boolean isEncodedContent = false;
for (int i = 0; i < pullParser.getAttributeCount(); i++) {
if (pullParser.getAttributeName(i).equals("type")) {
isEncodedContent = (pullParser.getAttributeValue(i).equals("html") || pullParser.getAttributeValue(i).equals("xhtml"));
break;
}
}
if (isEncodedContent) {
content = parseEncodedContent(pullParser);
}
} else {
content = safeNextText(pullParser);
}
return content;
}
private String parseEncodedContent(XmlPullParser pullParser) throws XmlPullParserException, IOException {
StringBuilder sb = new StringBuilder();
pullParser.next();
int eventType = pullParser.getEventType();
if (eventType == XmlPullParser.TEXT) {
String txt = cleanText(pullParser.getText());
if (txt.length() > 0) {
pullParser.next();
return txt;
} else {
eventType = pullParser.next();
}
}
if (eventType == XmlPullParser.START_TAG) {
while (!isContentEnd(pullParser)) {
if (eventType == XmlPullParser.START_TAG) {
if (pullParser.isEmptyElementTag()) {
String tag = pullParser.getName();
sb.append("<");
sb.append(tag);
if (tag.equals("img")) {
sb.append(getAttribute(pullParser, "src"));
}
sb.append("/>");
pullParser.next();
} else {
String tag = pullParser.getName();
sb.append("<");
sb.append(pullParser.getName());
if (tag.equals("a")) {
sb.append(getAttribute(pullParser, "href"));
}
sb.append(">");
}
} else if (eventType == XmlPullParser.TEXT) {
sb.append(cleanText(pullParser.getText()));
} else if (eventType == XmlPullParser.END_TAG) {
sb.append("</");
sb.append(pullParser.getName());
sb.append(">");
}
eventType = pullParser.next();
}
}
return sb.toString();
}
private String cleanText(String text) {
return text.replace("\n", "").replace("\t", "").replace("\r", "").trim();
}
private String getAttribute(XmlPullParser pullParser, String name) {
StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append(name);
sb.append("=\"");
for (int i = 0; i < pullParser.getAttributeCount(); i++) {
if (pullParser.getAttributeName(i).equals(name)) {
sb.append(pullParser.getAttributeValue(i));
break;
}
}
sb.append("\"");
return sb.toString();
}
private boolean isContentEnd(XmlPullParser pullParser) throws XmlPullParserException {
if (pullParser.getEventType() != XmlPullParser.END_TAG) {
return false;
}
if (pullParser.getName().equals("content")) {
return true;
}
return false;
}
/*
* Work around a bug in early XMLPullParser versions, see http://android-developers.blogspot.de/2011/12/watch-out-for-xmlpullparsernexttext.html
*/
private String safeNextText(XmlPullParser parser) throws XmlPullParserException, IOException {
String result = parser.nextText();
if (parser.getEventType() != XmlPullParser.END_TAG) {
parser.nextTag();
}
return result;
}
private ArrayList<String> queryArticles(int feedID) {
ArrayList<String> articles = new ArrayList<String>();
Cursor cursor = mContentResolver.query(RSSContentProvider.URI_ARTICLES, new String[] { ArticleDAO._ID, ArticleDAO.GUID, ArticleDAO.PUBDATE },
ArticleDAO.FEEDID + " = ?", new String[] { String.valueOf(feedID) }, ArticleDAO.PUBDATE + " DESC");
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
articles.add(cursor.getString(cursor.getColumnIndex(ArticleDAO.GUID)));
} while (cursor.moveToNext());
}
cursor.close();
return articles;
}
private Date queryNewestArticleDate(int feedID) {
Date maxDate = null;
Cursor cursor = mContentResolver.query(RSSContentProvider.URI_ARTICLES, new String[] { ArticleDAO._ID, ArticleDAO.PUBDATE },
ArticleDAO.FEEDID + " = ?", new String[] { String.valueOf(feedID) }, ArticleDAO.PUBDATE + " DESC");
if (cursor.getCount() > 0) {
cursor.moveToFirst();
maxDate = SQLiteHelper.toDate(cursor.getString(cursor.getColumnIndex(ArticleDAO.PUBDATE)));
}
cursor.close();
return maxDate;
}
private Date pastDate(int interval) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -interval);
return calendar.getTime();
}
private String queryURL(int feedID) {
String feedURL = "";
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(RSSContentProvider.URI_FEEDS, new String[] { FeedDAO._ID, FeedDAO.URL }, FeedDAO._ID + " = ?",
new String[] { String.valueOf(feedID) }, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
feedURL = cursor.getString(cursor.getColumnIndex(FeedDAO.URL));
}
cursor.close();
return feedURL;
}
private Date parsePubdate(String rawDate) throws XmlPullParserException {
Date parsedDate = null;
for (int j = 0; j < DATE_FORMATS.length; j++) {
try {
parsedDate = mSimpleDateFormats[j].parse(rawDate.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)", "$1$2"));
break;
} catch (ParseException mParserException) {
if (j == DATE_FORMATS.length - 1) {
throw new XmlPullParserException(mParserException.getMessage());
}
}
}
return parsedDate;
}
private ContentValues prepareArticle(int feedID, String guid, String link, Date pubdate, String title, String summary, String content) {
boolean missingContent = false;
boolean missingSummary = false;
if (content == null) {
missingContent = true;
}
if (summary == null) {
missingSummary = true;
}
if (missingContent && missingSummary) {
return null;
}
if (missingContent) {
content = summary;
} else if (missingSummary) {
summary = content;
}
Document parsedContent = Jsoup.parse(content);
Elements iframes = parsedContent.getElementsByTag("iframe");
TextNode placeholder = new TextNode("(video removed)", null);
for (Element mIframe : iframes) {
mIframe.replaceWith(placeholder);
}
content = parsedContent.html();
Document parsedSummary = Jsoup.parse(summary);
Elements pics = parsedSummary.getElementsByTag("img");
for (Element pic : pics) {
pic.remove();
}
summary = parsedSummary.text();
if (summary.length() > SUMMARY_MAXLENGTH) {
summary = summary.substring(0, SUMMARY_MAXLENGTH) + "...";
}
Element image = parsedContent.select("img").first();
ContentValues contentValues = new ContentValues();
contentValues.put(ArticleDAO.FEEDID, feedID);
contentValues.put(ArticleDAO.GUID, guid);
contentValues.put(ArticleDAO.LINK, link);
contentValues.put(ArticleDAO.PUBDATE, SQLiteHelper.fromDate(pubdate));
contentValues.put(ArticleDAO.TITLE, title);
contentValues.put(ArticleDAO.SUMMARY, summary);
contentValues.put(ArticleDAO.CONTENT, content);
if (image != null) {
contentValues.put(ArticleDAO.IMAGE, image.absUrl("src"));
}
contentValues.put(ArticleDAO.ISDELETED, 0);
return contentValues;
}
}
| true | true | protected void doWakefulWork(Intent intent) {
if (intent.getAction() == NO_ACTION) {
return;
}
int feedID = intent.getIntExtra("feedid", -1);
ArrayList<ContentValues> contentValuesArrayList = new ArrayList<ContentValues>();
boolean isArticle = false;
boolean linkOverride = false;
String title = null;
String summary = null;
String content = null;
String guid = null;
Date pubdate = null;
Date updated = null;
String link = null;
try {
deleteOldArticles(feedID);
ArrayList<String> existingArticles = queryArticles(feedID);
Date minimumDate = getMinimumDate(feedID);
InputStream inputStream = getURLInputStream(queryURL(feedID));
XmlPullParser pullParser = getParser(inputStream);
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String currentTag = pullParser.getName();
String currentPrefix = pullParser.getPrefix() != null ? pullParser.getPrefix() : "";
if (isItemTag(currentTag, currentPrefix)) {
isArticle = true;
} else if (isTitleTag(currentTag, currentPrefix) && isArticle) {
title = safeNextText(pullParser);
} else if (isSummaryTag(currentTag, currentPrefix) && isArticle) {
summary = safeNextText(pullParser);
} else if (isContentTag(currentTag, currentPrefix) && isArticle) {
content = extractContent(pullParser);
} else if (isGuidTag(currentTag, currentPrefix) && isArticle) {
guid = safeNextText(pullParser);
} else if (isDateTag(currentTag, currentPrefix) && isArticle) {
pubdate = parsePubdate(safeNextText(pullParser));
} else if (isUpdatedTag(currentTag, currentPrefix) && isArticle) {
updated = parsePubdate(safeNextText(pullParser));
} else if (isLinkTag(currentTag, currentPrefix) && isArticle) {
if (!linkOverride) {
link = extractLink(pullParser);
}
} else if (isOrigLinkTag(currentTag, currentPrefix) && isArticle) {
link = safeNextText(pullParser);
linkOverride = true;
}
} else if (eventType == XmlPullParser.END_TAG && isItemTag(pullParser.getName(), "")) {
pubdate = pubdate != null ? pubdate : updated;
guid = guid != null ? guid : link;
if (pubdate.before(minimumDate)) {
break;
}
if (!existingArticles.contains(guid)) {
ContentValues newArticle = prepareArticle(feedID, guid, link, pubdate, title, summary, content);
if (newArticle != null) {
contentValuesArrayList.add(newArticle);
}
}
isArticle = false;
title = null;
summary = null;
content = null;
guid = null;
pubdate = null;
updated = null;
link = null;
}
eventType = pullParser.next();
}
inputStream.close();
storeArticles(contentValuesArrayList);
} catch (IOException e) {
} catch (XmlPullParserException e) {
} catch (Exception e) {
e.printStackTrace();
} finally {
mFeedsUpdating.remove(feedID);
if (mFeedsUpdating.size() == 0) {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean("refreshing", false);
editor.putLong("lastRefresh", SystemClock.elapsedRealtime());
editor.commit();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("de.hdodenhof.holoreader.FEEDS_REFRESHED");
sendBroadcast(broadcastIntent);
}
}
}
| protected void doWakefulWork(Intent intent) {
if (intent.getAction() == NO_ACTION) {
return;
}
int feedID = intent.getIntExtra("feedid", -1);
ArrayList<ContentValues> contentValuesArrayList = new ArrayList<ContentValues>();
boolean isArticle = false;
boolean linkOverride = false;
String title = null;
String summary = null;
String content = null;
String guid = null;
Date pubdate = null;
Date updated = null;
String link = null;
try {
deleteOldArticles(feedID);
ArrayList<String> existingArticles = queryArticles(feedID);
Date minimumDate = getMinimumDate(feedID);
InputStream inputStream = getURLInputStream(queryURL(feedID));
XmlPullParser pullParser = getParser(inputStream);
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String currentTag = pullParser.getName();
String currentPrefix = pullParser.getPrefix() != null ? pullParser.getPrefix() : "";
if (isItemTag(currentTag, currentPrefix)) {
isArticle = true;
} else if (isTitleTag(currentTag, currentPrefix) && isArticle) {
title = safeNextText(pullParser);
} else if (isSummaryTag(currentTag, currentPrefix) && isArticle) {
summary = safeNextText(pullParser);
} else if (isContentTag(currentTag, currentPrefix) && isArticle) {
content = extractContent(pullParser);
} else if (isGuidTag(currentTag, currentPrefix) && isArticle) {
guid = safeNextText(pullParser);
} else if (isDateTag(currentTag, currentPrefix) && isArticle) {
pubdate = parsePubdate(safeNextText(pullParser));
} else if (isUpdatedTag(currentTag, currentPrefix) && isArticle) {
updated = parsePubdate(safeNextText(pullParser));
} else if (isLinkTag(currentTag, currentPrefix) && isArticle) {
if (!linkOverride) {
link = extractLink(pullParser);
}
} else if (isOrigLinkTag(currentTag, currentPrefix) && isArticle) {
link = safeNextText(pullParser);
linkOverride = true;
}
} else if (eventType == XmlPullParser.END_TAG && isItemTag(pullParser.getName(), "")) {
pubdate = pubdate != null ? pubdate : updated;
guid = guid != null ? guid : link;
if (pubdate.before(minimumDate)) {
break;
}
if (!existingArticles.contains(guid)) {
ContentValues newArticle = prepareArticle(feedID, guid, link, pubdate, title, summary, content);
if (newArticle != null) {
contentValuesArrayList.add(newArticle);
}
}
isArticle = false;
title = null;
summary = null;
content = null;
guid = null;
pubdate = null;
updated = null;
link = null;
}
eventType = pullParser.next();
}
inputStream.close();
storeArticles(contentValuesArrayList);
} catch (IOException e) {
} catch (XmlPullParserException e) {
} catch (Exception e) {
} finally {
mFeedsUpdating.remove(feedID);
if (mFeedsUpdating.size() == 0) {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean("refreshing", false);
editor.putLong("lastRefresh", SystemClock.elapsedRealtime());
editor.commit();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("de.hdodenhof.holoreader.FEEDS_REFRESHED");
sendBroadcast(broadcastIntent);
}
}
}
|
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/DefaultTokenResolverGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/DefaultTokenResolverGenerator.java
index a748aa8a8..d76176e26 100644
--- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/DefaultTokenResolverGenerator.java
+++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/DefaultTokenResolverGenerator.java
@@ -1,110 +1,120 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.resource.generators;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ECORE_UTIL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ATTRIBUTE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_DATA_TYPE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ENUM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ENUM_LITERAL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_STRUCTURAL_FEATURE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.OBJECT;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.codegen.parameters.ArtifactParameter;
import org.emftext.sdk.codegen.resource.GenerationContext;
public class DefaultTokenResolverGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> {
@Override
public void generateJavaContents(JavaComposite sc) {
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.addJavadoc("A default implementation for token resolvers. It tries to resolve lexems using Java methods.");
sc.add("public class " + getResourceClassName() + " implements " + iTokenResolverClassName + " {");
sc.addLineBreak();
addFields(sc);
addMethods(sc);
sc.add("}");
}
private void addMethods(StringComposite sc) {
addDeResolveMethod(sc);
addResolveMethod(sc);
addSetOptionsMethod(sc);
addGetOptionsMethod(sc);
}
private void addGetOptionsMethod(StringComposite sc) {
sc.add("public " + MAP + "<?, ?> getOptions() {");
sc.add("return options;");
sc.add("}");
}
private void addSetOptionsMethod(StringComposite sc) {
sc.add("public void setOptions(" + MAP + "<?, ?> options) {");
sc.add("this.options = options;");
sc.add("}");
sc.addLineBreak();
}
private void addResolveMethod(StringComposite sc) {
sc.add("public void resolve(String lexem, " + E_STRUCTURAL_FEATURE + " feature, " + iTokenResolveResultClassName + " result) {");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add("if (feature.getEType() instanceof " + E_ENUM + ") {");
sc.add(E_ENUM_LITERAL + " literal = ((" + E_ENUM + ") feature.getEType()).getEEnumLiteralByLiteral(lexem);");
sc.add("if (literal != null) {");
sc.add("result.setResolvedToken(literal.getInstance());");
sc.add("return;");
sc.add("} else {");
sc.add("result.setErrorMessage(\"Could not map lexem '\" + lexem + \"' to enum '\" + feature.getEType().getName() + \"'.\");");
sc.add("return;");
sc.add("}");
sc.add("} else if (feature.getEType() instanceof " + E_DATA_TYPE + ") {");
sc.add("try {");
sc.add("result.setResolvedToken(" + ECORE_UTIL + ".createFromString((" + E_DATA_TYPE + ") feature.getEType(), lexem));");
sc.add("} catch (Exception e) {");
sc.add("result.setErrorMessage(\"Could not convert '\" + lexem + \"' to '\" + feature.getEType().getName() + \"'.\");");
sc.add("}");
+ sc.add("String typeName = feature.getEType().getInstanceClassName();");
+ sc.add("if (typeName.equals(\"boolean\") || java.lang.Boolean.class.getName().equals(typeName)) {");
+ sc.add("String featureName = feature.getName();");
+ sc.add("boolean featureNameMatchesLexem = featureName.equals(lexem);");
+ sc.add("if (featureName.length() > 2 && featureName.startsWith(\"is\")) {");
+ sc.add("featureNameMatchesLexem |= (featureName.substring(2, 3).toLowerCase() + featureName.substring(3)).equals(lexem);");
+ sc.add("}");
+ sc.add("result.setResolvedToken(Boolean.parseBoolean(lexem) || featureNameMatchesLexem);");
+ sc.add("return;");
+ sc.add("}");
sc.add("} else {");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.add("result.setResolvedToken(lexem);");
sc.add("return;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
private void addDeResolveMethod(StringComposite sc) {
sc.add("public String deResolve(" + OBJECT + " value, " + E_STRUCTURAL_FEATURE + " feature, " + E_OBJECT + " container) {");
sc.add("if (value == null) {");
sc.add("return \"null\";");
sc.add("}");
sc.add("return value.toString();");
sc.add("}");
sc.addLineBreak();
}
private void addFields(StringComposite sc) {
sc.add("private " + MAP + "<?, ?> options;");
sc.addLineBreak();
}
}
| true | true | private void addResolveMethod(StringComposite sc) {
sc.add("public void resolve(String lexem, " + E_STRUCTURAL_FEATURE + " feature, " + iTokenResolveResultClassName + " result) {");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add("if (feature.getEType() instanceof " + E_ENUM + ") {");
sc.add(E_ENUM_LITERAL + " literal = ((" + E_ENUM + ") feature.getEType()).getEEnumLiteralByLiteral(lexem);");
sc.add("if (literal != null) {");
sc.add("result.setResolvedToken(literal.getInstance());");
sc.add("return;");
sc.add("} else {");
sc.add("result.setErrorMessage(\"Could not map lexem '\" + lexem + \"' to enum '\" + feature.getEType().getName() + \"'.\");");
sc.add("return;");
sc.add("}");
sc.add("} else if (feature.getEType() instanceof " + E_DATA_TYPE + ") {");
sc.add("try {");
sc.add("result.setResolvedToken(" + ECORE_UTIL + ".createFromString((" + E_DATA_TYPE + ") feature.getEType(), lexem));");
sc.add("} catch (Exception e) {");
sc.add("result.setErrorMessage(\"Could not convert '\" + lexem + \"' to '\" + feature.getEType().getName() + \"'.\");");
sc.add("}");
sc.add("} else {");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.add("result.setResolvedToken(lexem);");
sc.add("return;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
| private void addResolveMethod(StringComposite sc) {
sc.add("public void resolve(String lexem, " + E_STRUCTURAL_FEATURE + " feature, " + iTokenResolveResultClassName + " result) {");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add("if (feature.getEType() instanceof " + E_ENUM + ") {");
sc.add(E_ENUM_LITERAL + " literal = ((" + E_ENUM + ") feature.getEType()).getEEnumLiteralByLiteral(lexem);");
sc.add("if (literal != null) {");
sc.add("result.setResolvedToken(literal.getInstance());");
sc.add("return;");
sc.add("} else {");
sc.add("result.setErrorMessage(\"Could not map lexem '\" + lexem + \"' to enum '\" + feature.getEType().getName() + \"'.\");");
sc.add("return;");
sc.add("}");
sc.add("} else if (feature.getEType() instanceof " + E_DATA_TYPE + ") {");
sc.add("try {");
sc.add("result.setResolvedToken(" + ECORE_UTIL + ".createFromString((" + E_DATA_TYPE + ") feature.getEType(), lexem));");
sc.add("} catch (Exception e) {");
sc.add("result.setErrorMessage(\"Could not convert '\" + lexem + \"' to '\" + feature.getEType().getName() + \"'.\");");
sc.add("}");
sc.add("String typeName = feature.getEType().getInstanceClassName();");
sc.add("if (typeName.equals(\"boolean\") || java.lang.Boolean.class.getName().equals(typeName)) {");
sc.add("String featureName = feature.getName();");
sc.add("boolean featureNameMatchesLexem = featureName.equals(lexem);");
sc.add("if (featureName.length() > 2 && featureName.startsWith(\"is\")) {");
sc.add("featureNameMatchesLexem |= (featureName.substring(2, 3).toLowerCase() + featureName.substring(3)).equals(lexem);");
sc.add("}");
sc.add("result.setResolvedToken(Boolean.parseBoolean(lexem) || featureNameMatchesLexem);");
sc.add("return;");
sc.add("}");
sc.add("} else {");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.add("result.setResolvedToken(lexem);");
sc.add("return;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
|
diff --git a/src/main/java/com/caindonaghey/commandbin/listeners/AxeListener.java b/src/main/java/com/caindonaghey/commandbin/listeners/AxeListener.java
index 768abbb..0bbfb3e 100644
--- a/src/main/java/com/caindonaghey/commandbin/listeners/AxeListener.java
+++ b/src/main/java/com/caindonaghey/commandbin/listeners/AxeListener.java
@@ -1,42 +1,42 @@
package com.caindonaghey.commandbin.listeners;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
import com.caindonaghey.commandbin.CommandBin;
public class AxeListener implements Listener {
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {
Block block = e.getBlock();
Material type = block.getType();
Player player = e.getPlayer();
if(CommandBin.woodCutter) {
if(player.hasPermission("CommandBin.axe")) {
if(player.getItemInHand().getType() == Material.IRON_AXE) {
if(block.getRelative(0, -1, 0).getType() == Material.DIRT || block.getRelative(0, -1, 0).getType() == Material.GRASS) {
if(type == Material.LOG) {
for (int i = 0; i < 30; i++) {
if(block.getRelative(0, i, 0).getType() == Material.LOG) {
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.SMOKE, 5);
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.MOBSPAWNER_FLAMES, 5);
- block.getRelative(0, i, 0).breakNaturally(new ItemStack(Material.LOG, 1));
+ block.getRelative(0, i, 0).breakNaturally(new ItemStack(block.getRelative(0, i, 0).getType(), 1));
}
}
}
}
}
}
}
}
}
| true | true | public void onBlockBreak(BlockBreakEvent e) {
Block block = e.getBlock();
Material type = block.getType();
Player player = e.getPlayer();
if(CommandBin.woodCutter) {
if(player.hasPermission("CommandBin.axe")) {
if(player.getItemInHand().getType() == Material.IRON_AXE) {
if(block.getRelative(0, -1, 0).getType() == Material.DIRT || block.getRelative(0, -1, 0).getType() == Material.GRASS) {
if(type == Material.LOG) {
for (int i = 0; i < 30; i++) {
if(block.getRelative(0, i, 0).getType() == Material.LOG) {
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.SMOKE, 5);
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.MOBSPAWNER_FLAMES, 5);
block.getRelative(0, i, 0).breakNaturally(new ItemStack(Material.LOG, 1));
}
}
}
}
}
}
}
}
| public void onBlockBreak(BlockBreakEvent e) {
Block block = e.getBlock();
Material type = block.getType();
Player player = e.getPlayer();
if(CommandBin.woodCutter) {
if(player.hasPermission("CommandBin.axe")) {
if(player.getItemInHand().getType() == Material.IRON_AXE) {
if(block.getRelative(0, -1, 0).getType() == Material.DIRT || block.getRelative(0, -1, 0).getType() == Material.GRASS) {
if(type == Material.LOG) {
for (int i = 0; i < 30; i++) {
if(block.getRelative(0, i, 0).getType() == Material.LOG) {
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.SMOKE, 5);
block.getRelative(0, i, 0).getWorld().playEffect(block.getRelative(0, i, 0).getLocation(), Effect.MOBSPAWNER_FLAMES, 5);
block.getRelative(0, i, 0).breakNaturally(new ItemStack(block.getRelative(0, i, 0).getType(), 1));
}
}
}
}
}
}
}
}
|
diff --git a/src/test/java/com/salesforce/phoenix/arithmatic/ArithmeticOperationTest.java b/src/test/java/com/salesforce/phoenix/arithmatic/ArithmeticOperationTest.java
index fc40c537..36a17351 100644
--- a/src/test/java/com/salesforce/phoenix/arithmatic/ArithmeticOperationTest.java
+++ b/src/test/java/com/salesforce/phoenix/arithmatic/ArithmeticOperationTest.java
@@ -1,258 +1,261 @@
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.salesforce.phoenix.arithmatic;
import static com.salesforce.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Properties;
import org.junit.Test;
import com.salesforce.phoenix.end2end.BaseHBaseManagedTimeTest;
public class ArithmeticOperationTest extends BaseHBaseManagedTimeTest {
@Test
public void testDeciamlDefinition() throws Exception {
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
String ddl = "CREATE TABLE IF NOT EXISTS testDecimalArithmatic" +
" (pk VARCHAR NOT NULL PRIMARY KEY, " +
"col1 DECIMAL, col2 DECIMAL(5), col3 DECIMAL(5,2))";
createTestTable(getUrl(), ddl);
// Test upsert correct values.
String query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, "insertGoodValues");
stmt.setBigDecimal(2, new BigDecimal("123456789123456789"));
stmt.setBigDecimal(3, new BigDecimal("123.45"));
stmt.setBigDecimal(4, new BigDecimal("1234.5"));
stmt.execute();
conn.commit();
query = "SELECT col1, col2, col3 FROM testDecimalArithmatic WHERE pk = 'valueOne' LIMIT 1";
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
assertEquals(new BigDecimal("123456789123456789"), rs.getBigDecimal(1));
assertEquals(new BigDecimal("123.45"), rs.getBigDecimal(2));
assertEquals(new BigDecimal("1234.5"), rs.getBigDecimal(3));
assertFalse(rs.next());
// Test upsert incorrect values and confirm exceptions would be thrown.
try {
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "badValues");
// one more than max_precision
stmt.setBigDecimal(2, new BigDecimal("12345678901234567890123456789012"));
stmt.setBigDecimal(3, new BigDecimal("123.45"));
stmt.setBigDecimal(4, new BigDecimal("1234.5"));
stmt.execute();
conn.commit();
fail("Should have caught bad values.");
} catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("ERROR 206 (22003): The value does not fit into the column. value=12345678901234567890123456789012 columnName=COL1"));
}
try {
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "badValues");
stmt.setBigDecimal(2, new BigDecimal("123456"));
// Exceeds specified precision by 1
stmt.setBigDecimal(3, new BigDecimal("123456"));
stmt.setBigDecimal(4, new BigDecimal("1234.5"));
stmt.execute();
conn.commit();
fail("Should have caught bad values.");
} catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("ERROR 206 (22003): The value does not fit into the column. value=123456 columnName=COL2"));
}
try {
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "badValues");
stmt.setBigDecimal(2, new BigDecimal("123456"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
// Exceeds specified scale by 1
stmt.setBigDecimal(4, new BigDecimal("12.345"));
stmt.execute();
conn.commit();
fail("Should have caught bad values.");
} catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("ERROR 206 (22003): The value does not fit into the column. value=12.345 columnName=COL3"));
}
} finally {
conn.close();
}
}
@Test
public void testDecimalArithmetic() throws Exception {
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
String ddl = "CREATE TABLE IF NOT EXISTS testDecimalArithmatic" +
" (pk VARCHAR NOT NULL PRIMARY KEY, " +
"col1 DECIMAL, col2 DECIMAL(5), col3 DECIMAL(5,2))";
createTestTable(getUrl(), ddl);
String query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueOne");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("123.45"));
stmt.execute();
conn.commit();
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueTwo");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("0.01"));
stmt.execute();
conn.commit();
// Addition
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 + col2 should be good with precision 31 and scale 0.
query = "SELECT col1 + col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
BigDecimal result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345691246"), result);
// col2 + col3 should be good with precision 8 and scale 2.
query = "SELECT col2 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12468.45"), result);
// col1 + col3 would be bad due to exceeding scale.
query = "SELECT col1 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Subtraction
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 - col2 should be good with precision 31 and scale 0
query = "SELECT col1 - col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345666556"), result);
// col2 - col3 should be good with precision 8 and scale 2.
query = "SELECT col2 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12221.55"), result);
// col1 - col3 would be bad due to exceeding scale.
query = "SELECT col1 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Multiplication
// result scale should be: ls + rs
// result precision should be: lp + rp
//
// col1 * col2 should be good with precision 31 and scale 0
query = "SELECT col1 * col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// col2 * col3 should be good with precision 10 and scale 2.
query = "SELECT col2 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1523990.25"), result);
// col1 * col3 would be bad due to exceeding scale.
query = "SELECT col1 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// Division
// result scale should be: 31 - lp + ls - rs
// result precision should be: lp - ls + rp + max(ls + rp - rs + 1, 4)
//
// col1 / col2 should be good with precision ? and scale 0.
query = "SELECT col1 / col2 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("100005499402467135602458135"), result);
// col2 / col3 should be good with precision ? and scale ?.
query = "SELECT col2 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
- assertEquals(new BigDecimal("1234500.000000000000000000000000"), result);
+ // The value should be 1234500.0000...00 because we set to scale to be 24. However, in
+ // PhoenixResultSet.getBigDecimal, the case to (BigDecimal) actually cause the scale to be eradicated. As
+ // a result, the resulting value does not have the right form.
+ assertEquals(0, new BigDecimal("1234500").compareTo(result));
// col1 / col3 would be bad due to exceeding scale.
query = "SELECT col1 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
} finally {
conn.close();
}
}
}
| true | true | public void testDecimalArithmetic() throws Exception {
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
String ddl = "CREATE TABLE IF NOT EXISTS testDecimalArithmatic" +
" (pk VARCHAR NOT NULL PRIMARY KEY, " +
"col1 DECIMAL, col2 DECIMAL(5), col3 DECIMAL(5,2))";
createTestTable(getUrl(), ddl);
String query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueOne");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("123.45"));
stmt.execute();
conn.commit();
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueTwo");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("0.01"));
stmt.execute();
conn.commit();
// Addition
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 + col2 should be good with precision 31 and scale 0.
query = "SELECT col1 + col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
BigDecimal result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345691246"), result);
// col2 + col3 should be good with precision 8 and scale 2.
query = "SELECT col2 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12468.45"), result);
// col1 + col3 would be bad due to exceeding scale.
query = "SELECT col1 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Subtraction
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 - col2 should be good with precision 31 and scale 0
query = "SELECT col1 - col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345666556"), result);
// col2 - col3 should be good with precision 8 and scale 2.
query = "SELECT col2 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12221.55"), result);
// col1 - col3 would be bad due to exceeding scale.
query = "SELECT col1 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Multiplication
// result scale should be: ls + rs
// result precision should be: lp + rp
//
// col1 * col2 should be good with precision 31 and scale 0
query = "SELECT col1 * col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// col2 * col3 should be good with precision 10 and scale 2.
query = "SELECT col2 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1523990.25"), result);
// col1 * col3 would be bad due to exceeding scale.
query = "SELECT col1 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// Division
// result scale should be: 31 - lp + ls - rs
// result precision should be: lp - ls + rp + max(ls + rp - rs + 1, 4)
//
// col1 / col2 should be good with precision ? and scale 0.
query = "SELECT col1 / col2 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("100005499402467135602458135"), result);
// col2 / col3 should be good with precision ? and scale ?.
query = "SELECT col2 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234500.000000000000000000000000"), result);
// col1 / col3 would be bad due to exceeding scale.
query = "SELECT col1 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
} finally {
conn.close();
}
}
| public void testDecimalArithmetic() throws Exception {
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
String ddl = "CREATE TABLE IF NOT EXISTS testDecimalArithmatic" +
" (pk VARCHAR NOT NULL PRIMARY KEY, " +
"col1 DECIMAL, col2 DECIMAL(5), col3 DECIMAL(5,2))";
createTestTable(getUrl(), ddl);
String query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueOne");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("123.45"));
stmt.execute();
conn.commit();
query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, "testValueTwo");
stmt.setBigDecimal(2, new BigDecimal("1234567890123456789012345678901"));
stmt.setBigDecimal(3, new BigDecimal("12345"));
stmt.setBigDecimal(4, new BigDecimal("0.01"));
stmt.execute();
conn.commit();
// Addition
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 + col2 should be good with precision 31 and scale 0.
query = "SELECT col1 + col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
BigDecimal result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345691246"), result);
// col2 + col3 should be good with precision 8 and scale 2.
query = "SELECT col2 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12468.45"), result);
// col1 + col3 would be bad due to exceeding scale.
query = "SELECT col1 + col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Subtraction
// result scale should be: max(ls, rs)
// result precision should be: max(lp - ls, rp - rs) + 1 + max(ls, rs)
//
// col1 - col2 should be good with precision 31 and scale 0
query = "SELECT col1 - col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1234567890123456789012345666556"), result);
// col2 - col3 should be good with precision 8 and scale 2.
query = "SELECT col2 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("12221.55"), result);
// col1 - col3 would be bad due to exceeding scale.
query = "SELECT col1 - col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
// Multiplication
// result scale should be: ls + rs
// result precision should be: lp + rp
//
// col1 * col2 should be good with precision 31 and scale 0
query = "SELECT col1 * col2 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// col2 * col3 should be good with precision 10 and scale 2.
query = "SELECT col2 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("1523990.25"), result);
// col1 * col3 would be bad due to exceeding scale.
query = "SELECT col1 * col3 FROM testDecimalArithmatic WHERE pk='testValueOne'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result); // Value too big.
// Division
// result scale should be: 31 - lp + ls - rs
// result precision should be: lp - ls + rp + max(ls + rp - rs + 1, 4)
//
// col1 / col2 should be good with precision ? and scale 0.
query = "SELECT col1 / col2 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("100005499402467135602458135"), result);
// col2 / col3 should be good with precision ? and scale ?.
query = "SELECT col2 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
// The value should be 1234500.0000...00 because we set to scale to be 24. However, in
// PhoenixResultSet.getBigDecimal, the case to (BigDecimal) actually cause the scale to be eradicated. As
// a result, the resulting value does not have the right form.
assertEquals(0, new BigDecimal("1234500").compareTo(result));
// col1 / col3 would be bad due to exceeding scale.
query = "SELECT col1 / col3 FROM testDecimalArithmatic WHERE pk='testValueTwo'";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertNull(result);
} finally {
conn.close();
}
}
|
diff --git a/src/org/flowvisor/config/ConfDBHandler.java b/src/org/flowvisor/config/ConfDBHandler.java
index f99113a..8c120ef 100644
--- a/src/org/flowvisor/config/ConfDBHandler.java
+++ b/src/org/flowvisor/config/ConfDBHandler.java
@@ -1,127 +1,127 @@
package org.flowvisor.config;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
/**
* Defines a connection pool to derby.
* Guarantees that the status of a returned connection
* is valid.
*
*
* @author ash
*
*/
public class ConfDBHandler implements ConfDBSettings {
private String protocol = null;
private String dbName = null;
private String username = null;
private String password = null;
private ConnectionFactory cf = null;
@SuppressWarnings("unused")
private PoolableConnectionFactory pcf = null;
private GenericObjectPool gop = null;
private PoolingDataSource pds = null;
private Boolean autoCommit = false;
public ConfDBHandler(String protocol, String dbName, String username, String password, Boolean autoCommit) {
this.protocol = protocol;
this.dbName = System.getProperty("derby.system.home") + "/" + dbName;
this.username = username;
this.password = password;
this.autoCommit = autoCommit;
}
public ConfDBHandler() {
this("jdbc:derby:", "FlowVisorDB", "", "", true);
}
private DataSource getDataSource() {
if (pds != null)
return pds;
gop = new GenericObjectPool(null);
gop.setTestOnBorrow(true);
gop.setTestWhileIdle(true);
cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password);
- pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1 FROM flowvisor",false, autoCommit);
+ pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1",false, autoCommit);
pds = new PoolingDataSource(pcf.getPool());
return pds;
}
@Override
public Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
@Override
public Connection getConnection(String user, String pass)
throws SQLException {
return getDataSource().getConnection(user, pass);
}
@Override
public void returnConnection(Connection conn) {
try {
gop.returnObject(conn);
} catch (Exception e) {
FVLog.log(LogLevel.CRIT, null, "Unable to return connection");
}
}
@Override
public int getNumActive() {
return gop.getNumActive();
}
@Override
public int getNumIdle() {
return gop.getNumIdle();
}
@Override
public int getMaxActive() {
return gop.getMaxActive();
}
@Override
public int getMaxIdle() {
return gop.getMaxIdle();
}
@Override
public Boolean getDefaultAutoCommit() {
return autoCommit;
}
@Override
public void shutdown() {
try {
gop.close();
((EmbeddedDataSource) getDataSource()).setShutdownDatabase("shutdown");
} catch (ClassCastException cce) {
//Isn't this a derby db?
} catch (Exception e) {
FVLog.log(LogLevel.WARN, null, "Error on closing connection pool to derby");
}
}
}
| true | true | private DataSource getDataSource() {
if (pds != null)
return pds;
gop = new GenericObjectPool(null);
gop.setTestOnBorrow(true);
gop.setTestWhileIdle(true);
cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password);
pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1 FROM flowvisor",false, autoCommit);
pds = new PoolingDataSource(pcf.getPool());
return pds;
}
| private DataSource getDataSource() {
if (pds != null)
return pds;
gop = new GenericObjectPool(null);
gop.setTestOnBorrow(true);
gop.setTestWhileIdle(true);
cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password);
pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1",false, autoCommit);
pds = new PoolingDataSource(pcf.getPool());
return pds;
}
|
diff --git a/src/classes/com/sun/opengl/util/texture/TextureData.java b/src/classes/com/sun/opengl/util/texture/TextureData.java
index 39075e387..67e5d347e 100755
--- a/src/classes/com/sun/opengl/util/texture/TextureData.java
+++ b/src/classes/com/sun/opengl/util/texture/TextureData.java
@@ -1,623 +1,623 @@
/*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*/
package com.sun.opengl.util.texture;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.color.*;
import java.awt.image.*;
import java.nio.*;
import javax.media.opengl.*;
import com.sun.opengl.util.*;
/**
* Represents the data for an OpenGL texture. This is separated from
* the notion of a Texture to support things like streaming in of
* textures in a background thread without requiring an OpenGL context
* to be current on that thread.
*
* @author Chris Campbell
* @author Kenneth Russell
*/
public class TextureData {
private int width;
private int height;
private int border;
private int pixelFormat;
private int pixelType;
private int internalFormat; // perhaps inferred from pixelFormat?
private boolean mipmap; // indicates whether mipmaps should be generated
// (ignored if mipmaps are supplied from the file)
private boolean dataIsCompressed;
private boolean mustFlipVertically; // Must flip texture coordinates
// vertically to get OpenGL output
// to look correct
private Buffer buffer; // the actual data...
private Buffer[] mipmapData; // ...or a series of mipmaps
private Flusher flusher;
private int rowLength;
private int alignment; // 1, 2, or 4 bytes
private int estimatedMemorySize;
// Mechanism for lazily converting input BufferedImages with custom
// ColorModels to standard ones for uploading to OpenGL, as well as
// backing off from the optimization of hoping that GL_EXT_abgr is
// present
private BufferedImage imageForLazyCustomConversion;
private boolean expectingEXTABGR;
private boolean haveEXTABGR;
private static final ColorModel rgbaColorModel =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8, 8, 8, 8}, true, true,
Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
private static final ColorModel rgbColorModel =
new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8, 8, 8, 0}, false, false,
Transparency.OPAQUE,
DataBuffer.TYPE_BYTE);
/**
* Constructs a new TextureData object with the specified parameters
* and data contained in the given Buffer. The optional Flusher can
* be used to clean up native resources associated with this
* TextureData when processing is complete; for example, closing of
* memory-mapped files that might otherwise require a garbage
* collection to reclaim and close.
*
* @param internalFormat the OpenGL internal format for the
* resulting texture; must be specified, may
* not be 0
* @param width the width in pixels of the texture
* @param height the height in pixels of the texture
* @param border the number of pixels of border this texture
* data has (0 or 1)
* @param pixelFormat the OpenGL pixel format for the
* resulting texture; must be specified, may
* not be 0
* @param pixelType the OpenGL type of the pixels of the texture
* @param mipmap indicates whether mipmaps should be
* autogenerated (using GLU) for the resulting
* texture. Currently if mipmap is true then
* dataIsCompressed may not be true.
* @param dataIsCompressed indicates whether the texture data is in
* compressed form
* (e.g. GL_COMPRESSED_RGB_S3TC_DXT1_EXT)
* @param mustFlipVertically indicates whether the texture
* coordinates must be flipped vertically
* in order to properly display the
* texture
* @param buffer the buffer containing the texture data
* @param flusher optional flusher to perform cleanup tasks
* upon call to flush()
*
* @throws IllegalArgumentException if any parameters of the texture
* data were invalid, such as requesting mipmap generation for a
* compressed texture
*/
public TextureData(int internalFormat,
int width,
int height,
int border,
int pixelFormat,
int pixelType,
boolean mipmap,
boolean dataIsCompressed,
boolean mustFlipVertically,
Buffer buffer,
Flusher flusher) throws IllegalArgumentException {
if (mipmap && dataIsCompressed) {
throw new IllegalArgumentException("Can not generate mipmaps for compressed textures");
}
this.width = width;
this.height = height;
this.border = border;
this.pixelFormat = pixelFormat;
this.pixelType = pixelType;
this.internalFormat = internalFormat;
this.mipmap = mipmap;
this.dataIsCompressed = dataIsCompressed;
this.mustFlipVertically = mustFlipVertically;
this.buffer = buffer;
this.flusher = flusher;
alignment = 1; // FIXME: is this correct enough in all situations?
estimatedMemorySize = estimatedMemorySize(buffer);
}
/**
* Constructs a new TextureData object with the specified parameters
* and data for multiple mipmap levels contained in the given array
* of Buffers. The optional Flusher can be used to clean up native
* resources associated with this TextureData when processing is
* complete; for example, closing of memory-mapped files that might
* otherwise require a garbage collection to reclaim and close.
*
* @param internalFormat the OpenGL internal format for the
* resulting texture; must be specified, may
* not be 0
* @param width the width in pixels of the topmost mipmap
* level of the texture
* @param height the height in pixels of the topmost mipmap
* level of the texture
* @param border the number of pixels of border this texture
* data has (0 or 1)
* @param pixelFormat the OpenGL pixel format for the
* resulting texture; must be specified, may
* not be 0
* @param pixelType the OpenGL type of the pixels of the texture
* @param dataIsCompressed indicates whether the texture data is in
* compressed form
* (e.g. GL_COMPRESSED_RGB_S3TC_DXT1_EXT)
* @param mustFlipVertically indicates whether the texture
* coordinates must be flipped vertically
* in order to properly display the
* texture
* @param mipmapData the buffers containing all mipmap levels
* of the texture's data
* @param flusher optional flusher to perform cleanup tasks
* upon call to flush()
*
* @throws IllegalArgumentException if any parameters of the texture
* data were invalid, such as requesting mipmap generation for a
* compressed texture
*/
public TextureData(int internalFormat,
int width,
int height,
int border,
int pixelFormat,
int pixelType,
boolean dataIsCompressed,
boolean mustFlipVertically,
Buffer[] mipmapData,
Flusher flusher) throws IllegalArgumentException {
this.width = width;
this.height = height;
this.border = border;
this.pixelFormat = pixelFormat;
this.pixelType = pixelType;
this.internalFormat = internalFormat;
this.dataIsCompressed = dataIsCompressed;
this.mustFlipVertically = mustFlipVertically;
this.mipmapData = (Buffer[]) mipmapData.clone();
this.flusher = flusher;
alignment = 1; // FIXME: is this correct enough in all situations?
for (int i = 0; i < mipmapData.length; i++) {
estimatedMemorySize += estimatedMemorySize(mipmapData[i]);
}
}
/**
* Constructs a new TextureData object with the specified parameters
* and data contained in the given BufferedImage. The resulting
* TextureData "wraps" the contents of the BufferedImage, so if a
* modification is made to the BufferedImage between the time the
* TextureData is constructed and when a Texture is made from the
* TextureData, that modification will be visible in the resulting
* Texture.
*
* @param internalFormat the OpenGL internal format for the
* resulting texture; may be 0, in which case
* it is inferred from the image's type
* @param pixelFormat the OpenGL internal format for the
* resulting texture; may be 0, in which case
* it is inferred from the image's type (note:
* this argument is currently always ignored)
* @param mipmap indicates whether mipmaps should be
* autogenerated (using GLU) for the resulting
* texture
* @param image the image containing the texture data
*/
public TextureData(int internalFormat,
int pixelFormat,
boolean mipmap,
BufferedImage image) {
if (internalFormat == 0) {
this.internalFormat = image.getColorModel().hasAlpha() ? GL.GL_RGBA : GL.GL_RGB;
} else {
this.internalFormat = internalFormat;
}
createFromImage(image);
this.mipmap = mipmap;
estimatedMemorySize = estimatedMemorySize(buffer);
}
/** Returns the width in pixels of the texture data. */
public int getWidth() { return width; }
/** Returns the height in pixels of the texture data. */
public int getHeight() { return height; }
/** Returns the border in pixels of the texture data. */
public int getBorder() { return border; }
/** Returns the intended OpenGL pixel format of the texture data. */
public int getPixelFormat() { return pixelFormat; }
/** Returns the intended OpenGL pixel type of the texture data. */
public int getPixelType() { return pixelType; }
/** Returns the intended OpenGL internal format of the texture data. */
public int getInternalFormat() { return internalFormat; }
/** Returns whether mipmaps should be generated for the texture data. */
public boolean getMipmap() { return mipmap; }
/** Indicates whether the texture data is in compressed form. */
public boolean isDataCompressed() { return dataIsCompressed; }
/** Indicates whether the texture coordinates must be flipped
vertically for proper display. */
public boolean getMustFlipVertically() { return mustFlipVertically; }
/** Returns the texture data, or null if it is specified as a set of mipmaps. */
public Buffer getBuffer() {
if (imageForLazyCustomConversion != null) {
if (!expectingEXTABGR ||
(expectingEXTABGR && !haveEXTABGR)) {
// Must present the illusion to the end user that we are simply
// wrapping the input BufferedImage
createFromCustom(imageForLazyCustomConversion);
}
}
return buffer;
}
/** Returns all mipmap levels for the texture data, or null if it is
specified as a single image. */
public Buffer[] getMipmapData() { return mipmapData; }
/** Returns the required byte alignment for the texture data. */
public int getAlignment() { return alignment; }
/** Returns the row length needed for correct GL_UNPACK_ROW_LENGTH
specification. This is currently only supported for
non-mipmapped, non-compressed textures. */
public int getRowLength() { return rowLength; }
/** Sets the width in pixels of the texture data. */
public void setWidth(int width) { this.width = width; }
/** Sets the height in pixels of the texture data. */
public void setHeight(int height) { this.height = height; }
/** Sets the border in pixels of the texture data. */
public void setBorder(int border) { this.border = border; }
/** Sets the intended OpenGL pixel format of the texture data. */
public void setPixelFormat(int pixelFormat) { this.pixelFormat = pixelFormat; }
/** Sets the intended OpenGL pixel type of the texture data. */
public void setPixelType(int pixelType) { this.pixelType = pixelType; }
/** Sets the intended OpenGL internal format of the texture data. */
public void setInternalFormat(int internalFormat) { this.internalFormat = internalFormat; }
/** Sets whether mipmaps should be generated for the texture data. */
public void setMipmap(boolean mipmap) { this.mipmap = mipmap; }
/** Sets whether the texture data is in compressed form. */
public void setIsDataCompressed(boolean compressed) { this.dataIsCompressed = compressed; }
/** Sets whether the texture coordinates must be flipped vertically
for proper display. */
public void setMustFlipVertically(boolean mustFlipVertically) { this.mustFlipVertically = mustFlipVertically; }
/** Sets the texture data. */
public void setBuffer(Buffer buffer) { this.buffer = buffer; }
/** Sets the required byte alignment for the texture data. */
public void setAlignment(int alignment) { this.alignment = alignment; }
/** Sets the row length needed for correct GL_UNPACK_ROW_LENGTH
specification. This is currently only supported for
non-mipmapped, non-compressed textures. */
public void setRowLength(int rowLength) { this.rowLength = rowLength; }
/** Indicates to this TextureData whether the GL_EXT_abgr extension
is available. Used for optimization along some code paths to
avoid data copies. */
public void setHaveEXTABGR(boolean haveEXTABGR) {
this.haveEXTABGR = haveEXTABGR;
}
/** Returns an estimate of the amount of memory in bytes this
TextureData will consume once uploaded to the graphics card. It
should only be treated as an estimate; most applications should
not need to query this but instead let the OpenGL implementation
page textures in and out as necessary. */
public int getEstimatedMemorySize() {
return estimatedMemorySize;
}
/** Flushes resources associated with this TextureData by calling
Flusher.flush(). */
public void flush() {
if (flusher != null) {
flusher.flush();
flusher = null;
}
}
/** Defines a callback mechanism to allow the user to explicitly
deallocate native resources (memory-mapped files, etc.)
associated with a particular TextureData. */
public static interface Flusher {
/** Flushes any native resources associated with this
TextureData. */
public void flush();
}
//----------------------------------------------------------------------
// Internals only below this point
//
private void createNIOBufferFromImage(BufferedImage image) {
//
// Note: Grabbing the DataBuffer will defeat Java2D's image
// management mechanism (as of JDK 5/6, at least). This shouldn't
// be a problem for most JOGL apps, but those that try to upload
// the image into an OpenGL texture and then use the same image in
// Java2D rendering might find the 2D rendering is not as fast as
// it could be.
//
DataBuffer data = image.getRaster().getDataBuffer();
if (data instanceof DataBufferByte) {
buffer = ByteBuffer.wrap(((DataBufferByte) data).getData());
} else if (data instanceof DataBufferDouble) {
throw new RuntimeException("DataBufferDouble rasters not supported by OpenGL");
} else if (data instanceof DataBufferFloat) {
buffer = FloatBuffer.wrap(((DataBufferFloat) data).getData());
} else if (data instanceof DataBufferInt) {
buffer = IntBuffer.wrap(((DataBufferInt) data).getData());
} else if (data instanceof DataBufferShort) {
buffer = ShortBuffer.wrap(((DataBufferShort) data).getData());
} else if (data instanceof DataBufferUShort) {
buffer = ShortBuffer.wrap(((DataBufferUShort) data).getData());
} else {
throw new RuntimeException("Unexpected DataBuffer type?");
}
}
private void createFromImage(BufferedImage image) {
pixelType = 0; // Determine from image
mustFlipVertically = true;
width = image.getWidth();
height = image.getHeight();
int scanlineStride;
SampleModel sm = image.getRaster().getSampleModel();
if (sm instanceof SinglePixelPackedSampleModel) {
scanlineStride =
((SinglePixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof MultiPixelPackedSampleModel) {
scanlineStride =
((MultiPixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof ComponentSampleModel) {
scanlineStride =
((ComponentSampleModel)sm).getScanlineStride();
} else {
// This will only happen for TYPE_CUSTOM anyway
setupLazyCustomConversion(image);
return;
}
switch (image.getType()) {
case BufferedImage.TYPE_INT_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_BGR:
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_3BYTE_BGR:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
if ((scanlineStride % 3) == 0) {
pixelFormat = GL.GL_BGR;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 3;
alignment = 1;
} else {
setupLazyCustomConversion(image);
return;
}
}
break;
case BufferedImage.TYPE_4BYTE_ABGR:
case BufferedImage.TYPE_4BYTE_ABGR_PRE:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
// and only if the GL_EXT_abgr extension is present
// NOTE: disabling this code path for now as it appears it's
// buggy at least on some NVidia drivers and doesn't perform
// the necessary byte swapping (FIXME: needs more
// investigation)
if ((scanlineStride % 4) == 0 && false) {
pixelFormat = GL.GL_ABGR_EXT;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4;
alignment = 4;
// Store a reference to the original image for later in
// case it turns out that we don't have GL_EXT_abgr at the
// time we're going to do the texture upload to OpenGL
setupLazyCustomConversion(image);
expectingEXTABGR = true;
break;
} else {
setupLazyCustomConversion(image);
return;
}
}
case BufferedImage.TYPE_USHORT_565_RGB:
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_SHORT_5_6_5;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_USHORT_555_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_SHORT_1_5_5_5_REV;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride;
alignment = 1;
break;
case BufferedImage.TYPE_USHORT_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_SHORT;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_BINARY:
case BufferedImage.TYPE_BYTE_INDEXED:
case BufferedImage.TYPE_CUSTOM:
default:
ColorModel cm = image.getColorModel();
if (cm.equals(rgbColorModel)) {
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_BYTE;
- rowLength = scanlineStride / 4; // FIXME: correct?
+ rowLength = scanlineStride / 3;
alignment = 1;
} else if (cm.equals(rgbaColorModel)) {
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4; // FIXME: correct?
alignment = 4;
} else {
setupLazyCustomConversion(image);
return;
}
break;
}
createNIOBufferFromImage(image);
}
private void setupLazyCustomConversion(BufferedImage image) {
imageForLazyCustomConversion = image;
boolean hasAlpha = image.getColorModel().hasAlpha();
pixelFormat = hasAlpha ? GL.GL_RGBA : GL.GL_RGB;
alignment = 1; // FIXME: do we need better?
rowLength = width; // FIXME: correct in all cases?
// Allow previously-selected pixelType (if any) to override that
// we can infer from the DataBuffer
DataBuffer data = image.getRaster().getDataBuffer();
if (data instanceof DataBufferByte) {
if (pixelType == 0) pixelType = GL.GL_UNSIGNED_BYTE;
} else if (data instanceof DataBufferDouble) {
throw new RuntimeException("DataBufferDouble rasters not supported by OpenGL");
} else if (data instanceof DataBufferFloat) {
if (pixelType == 0) pixelType = GL.GL_FLOAT;
} else if (data instanceof DataBufferInt) {
// FIXME: should we support signed ints?
if (pixelType == 0) pixelType = GL.GL_UNSIGNED_INT;
} else if (data instanceof DataBufferShort) {
if (pixelType == 0) pixelType = GL.GL_SHORT;
} else if (data instanceof DataBufferUShort) {
if (pixelType == 0) pixelType = GL.GL_UNSIGNED_SHORT;
} else {
throw new RuntimeException("Unexpected DataBuffer type?");
}
}
private void createFromCustom(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
// create a temporary image that is compatible with OpenGL
boolean hasAlpha = image.getColorModel().hasAlpha();
ColorModel cm = null;
int dataBufferType = image.getRaster().getDataBuffer().getDataType();
if (dataBufferType == DataBuffer.TYPE_BYTE) {
cm = hasAlpha ? rgbaColorModel : rgbColorModel;
} else {
if (hasAlpha) {
cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
null, true, true,
Transparency.TRANSLUCENT,
dataBufferType);
} else {
cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
null, false, false,
Transparency.OPAQUE,
dataBufferType);
}
}
boolean premult = cm.isAlphaPremultiplied();
WritableRaster raster =
cm.createCompatibleWritableRaster(width, height);
BufferedImage texImage = new BufferedImage(cm, raster, premult, null);
// copy the source image into the temporary image
Graphics2D g = texImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.drawImage(image, 0, 0, null);
g.dispose();
// Wrap the buffer from the temporary image
createNIOBufferFromImage(texImage);
}
private int estimatedMemorySize(Buffer buffer) {
if (buffer == null) {
return 0;
}
int capacity = buffer.capacity();
if (buffer instanceof ByteBuffer) {
return capacity;
} else if (buffer instanceof IntBuffer) {
return capacity * BufferUtil.SIZEOF_INT;
} else if (buffer instanceof FloatBuffer) {
return capacity * BufferUtil.SIZEOF_FLOAT;
} else if (buffer instanceof ShortBuffer) {
return capacity * BufferUtil.SIZEOF_SHORT;
} else if (buffer instanceof LongBuffer) {
return capacity * BufferUtil.SIZEOF_LONG;
} else if (buffer instanceof DoubleBuffer) {
return capacity * BufferUtil.SIZEOF_DOUBLE;
}
throw new RuntimeException("Unexpected buffer type " +
buffer.getClass().getName());
}
}
| true | true | private void createFromImage(BufferedImage image) {
pixelType = 0; // Determine from image
mustFlipVertically = true;
width = image.getWidth();
height = image.getHeight();
int scanlineStride;
SampleModel sm = image.getRaster().getSampleModel();
if (sm instanceof SinglePixelPackedSampleModel) {
scanlineStride =
((SinglePixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof MultiPixelPackedSampleModel) {
scanlineStride =
((MultiPixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof ComponentSampleModel) {
scanlineStride =
((ComponentSampleModel)sm).getScanlineStride();
} else {
// This will only happen for TYPE_CUSTOM anyway
setupLazyCustomConversion(image);
return;
}
switch (image.getType()) {
case BufferedImage.TYPE_INT_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_BGR:
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_3BYTE_BGR:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
if ((scanlineStride % 3) == 0) {
pixelFormat = GL.GL_BGR;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 3;
alignment = 1;
} else {
setupLazyCustomConversion(image);
return;
}
}
break;
case BufferedImage.TYPE_4BYTE_ABGR:
case BufferedImage.TYPE_4BYTE_ABGR_PRE:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
// and only if the GL_EXT_abgr extension is present
// NOTE: disabling this code path for now as it appears it's
// buggy at least on some NVidia drivers and doesn't perform
// the necessary byte swapping (FIXME: needs more
// investigation)
if ((scanlineStride % 4) == 0 && false) {
pixelFormat = GL.GL_ABGR_EXT;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4;
alignment = 4;
// Store a reference to the original image for later in
// case it turns out that we don't have GL_EXT_abgr at the
// time we're going to do the texture upload to OpenGL
setupLazyCustomConversion(image);
expectingEXTABGR = true;
break;
} else {
setupLazyCustomConversion(image);
return;
}
}
case BufferedImage.TYPE_USHORT_565_RGB:
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_SHORT_5_6_5;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_USHORT_555_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_SHORT_1_5_5_5_REV;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride;
alignment = 1;
break;
case BufferedImage.TYPE_USHORT_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_SHORT;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_BINARY:
case BufferedImage.TYPE_BYTE_INDEXED:
case BufferedImage.TYPE_CUSTOM:
default:
ColorModel cm = image.getColorModel();
if (cm.equals(rgbColorModel)) {
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4; // FIXME: correct?
alignment = 1;
} else if (cm.equals(rgbaColorModel)) {
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4; // FIXME: correct?
alignment = 4;
} else {
setupLazyCustomConversion(image);
return;
}
break;
}
createNIOBufferFromImage(image);
}
| private void createFromImage(BufferedImage image) {
pixelType = 0; // Determine from image
mustFlipVertically = true;
width = image.getWidth();
height = image.getHeight();
int scanlineStride;
SampleModel sm = image.getRaster().getSampleModel();
if (sm instanceof SinglePixelPackedSampleModel) {
scanlineStride =
((SinglePixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof MultiPixelPackedSampleModel) {
scanlineStride =
((MultiPixelPackedSampleModel)sm).getScanlineStride();
} else if (sm instanceof ComponentSampleModel) {
scanlineStride =
((ComponentSampleModel)sm).getScanlineStride();
} else {
// This will only happen for TYPE_CUSTOM anyway
setupLazyCustomConversion(image);
return;
}
switch (image.getType()) {
case BufferedImage.TYPE_INT_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_INT_BGR:
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
rowLength = scanlineStride;
alignment = 4;
break;
case BufferedImage.TYPE_3BYTE_BGR:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
if ((scanlineStride % 3) == 0) {
pixelFormat = GL.GL_BGR;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 3;
alignment = 1;
} else {
setupLazyCustomConversion(image);
return;
}
}
break;
case BufferedImage.TYPE_4BYTE_ABGR:
case BufferedImage.TYPE_4BYTE_ABGR_PRE:
{
// we can pass the image data directly to OpenGL only if
// we have an integral number of pixels in each scanline
// and only if the GL_EXT_abgr extension is present
// NOTE: disabling this code path for now as it appears it's
// buggy at least on some NVidia drivers and doesn't perform
// the necessary byte swapping (FIXME: needs more
// investigation)
if ((scanlineStride % 4) == 0 && false) {
pixelFormat = GL.GL_ABGR_EXT;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4;
alignment = 4;
// Store a reference to the original image for later in
// case it turns out that we don't have GL_EXT_abgr at the
// time we're going to do the texture upload to OpenGL
setupLazyCustomConversion(image);
expectingEXTABGR = true;
break;
} else {
setupLazyCustomConversion(image);
return;
}
}
case BufferedImage.TYPE_USHORT_565_RGB:
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_SHORT_5_6_5;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_USHORT_555_RGB:
pixelFormat = GL.GL_BGRA;
pixelType = GL.GL_UNSIGNED_SHORT_1_5_5_5_REV;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride;
alignment = 1;
break;
case BufferedImage.TYPE_USHORT_GRAY:
pixelFormat = GL.GL_LUMINANCE;
pixelType = GL.GL_UNSIGNED_SHORT;
rowLength = scanlineStride;
alignment = 2;
break;
case BufferedImage.TYPE_BYTE_BINARY:
case BufferedImage.TYPE_BYTE_INDEXED:
case BufferedImage.TYPE_CUSTOM:
default:
ColorModel cm = image.getColorModel();
if (cm.equals(rgbColorModel)) {
pixelFormat = GL.GL_RGB;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 3;
alignment = 1;
} else if (cm.equals(rgbaColorModel)) {
pixelFormat = GL.GL_RGBA;
pixelType = GL.GL_UNSIGNED_BYTE;
rowLength = scanlineStride / 4; // FIXME: correct?
alignment = 4;
} else {
setupLazyCustomConversion(image);
return;
}
break;
}
createNIOBufferFromImage(image);
}
|
diff --git a/src/no/runsafe/nchat/events/PlayerDeath.java b/src/no/runsafe/nchat/events/PlayerDeath.java
index 88d868b..8d5fef3 100644
--- a/src/no/runsafe/nchat/events/PlayerDeath.java
+++ b/src/no/runsafe/nchat/events/PlayerDeath.java
@@ -1,85 +1,85 @@
package no.runsafe.nchat.events;
import no.runsafe.framework.configuration.IConfiguration;
import no.runsafe.framework.event.IConfigurationChanged;
import no.runsafe.framework.event.player.IPlayerDeathEvent;
import no.runsafe.framework.output.IOutput;
import no.runsafe.framework.server.RunsafeServer;
import no.runsafe.framework.server.event.player.RunsafePlayerDeathEvent;
import no.runsafe.framework.server.player.RunsafePlayer;
import no.runsafe.nchat.Death;
import no.runsafe.nchat.DeathParser;
import java.util.ArrayList;
import java.util.List;
public class PlayerDeath implements IPlayerDeathEvent, IConfigurationChanged
{
public PlayerDeath(DeathParser deathParser, IOutput console)
{
this.deathParser = deathParser;
this.console = console;
}
@Override
public void OnPlayerDeathEvent(RunsafePlayerDeathEvent runsafePlayerDeathEvent)
{
+ String originalMessage = runsafePlayerDeathEvent.getDeathMessage();
runsafePlayerDeathEvent.setDeathMessage("");
if (!this.hideDeathWorlds.contains(runsafePlayerDeathEvent.getEntity().getWorld().getName()))
{
- String originalMessage = runsafePlayerDeathEvent.getDeathMessage();
Death deathType = this.deathParser.getDeathType(originalMessage);
if (deathType == Death.UNKNOWN)
{
console.writeColoured("Unknown death message detected: \"%s\"", originalMessage);
}
String deathName = deathType.name().toLowerCase();
String deathTag = deathName;
String entityName = null;
String killerName = null;
if (deathType.hasEntityInvolved())
{
killerName = this.deathParser.getInvolvedEntityName(originalMessage, deathType);
entityName = this.deathParser.isEntityName(killerName);
deathTag = String.format(
"%s_%s",
deathName,
(entityName != null ? entityName : "Player")
);
}
String customDeathMessage = this.deathParser.getCustomDeathMessage(deathTag);
if (customDeathMessage == null)
{
console.writeColoured("No custom death message '%s' defined, using original..", deathTag);
return;
}
RunsafePlayer player = runsafePlayerDeathEvent.getEntity();
if (deathType.hasEntityInvolved() && entityName == null)
{
RunsafePlayer killer = RunsafeServer.Instance.getPlayer(killerName);
if (killer != null)
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName(), killer.getPrettyName()));
}
else
{
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName()));
}
}
}
@Override
public void OnConfigurationChanged(IConfiguration iConfiguration)
{
this.hideDeathWorlds = iConfiguration.getConfigValueAsList("hideDeaths");
}
private final DeathParser deathParser;
private final IOutput console;
private List<String> hideDeathWorlds = new ArrayList<String>();
}
| false | true | public void OnPlayerDeathEvent(RunsafePlayerDeathEvent runsafePlayerDeathEvent)
{
runsafePlayerDeathEvent.setDeathMessage("");
if (!this.hideDeathWorlds.contains(runsafePlayerDeathEvent.getEntity().getWorld().getName()))
{
String originalMessage = runsafePlayerDeathEvent.getDeathMessage();
Death deathType = this.deathParser.getDeathType(originalMessage);
if (deathType == Death.UNKNOWN)
{
console.writeColoured("Unknown death message detected: \"%s\"", originalMessage);
}
String deathName = deathType.name().toLowerCase();
String deathTag = deathName;
String entityName = null;
String killerName = null;
if (deathType.hasEntityInvolved())
{
killerName = this.deathParser.getInvolvedEntityName(originalMessage, deathType);
entityName = this.deathParser.isEntityName(killerName);
deathTag = String.format(
"%s_%s",
deathName,
(entityName != null ? entityName : "Player")
);
}
String customDeathMessage = this.deathParser.getCustomDeathMessage(deathTag);
if (customDeathMessage == null)
{
console.writeColoured("No custom death message '%s' defined, using original..", deathTag);
return;
}
RunsafePlayer player = runsafePlayerDeathEvent.getEntity();
if (deathType.hasEntityInvolved() && entityName == null)
{
RunsafePlayer killer = RunsafeServer.Instance.getPlayer(killerName);
if (killer != null)
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName(), killer.getPrettyName()));
}
else
{
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName()));
}
}
}
| public void OnPlayerDeathEvent(RunsafePlayerDeathEvent runsafePlayerDeathEvent)
{
String originalMessage = runsafePlayerDeathEvent.getDeathMessage();
runsafePlayerDeathEvent.setDeathMessage("");
if (!this.hideDeathWorlds.contains(runsafePlayerDeathEvent.getEntity().getWorld().getName()))
{
Death deathType = this.deathParser.getDeathType(originalMessage);
if (deathType == Death.UNKNOWN)
{
console.writeColoured("Unknown death message detected: \"%s\"", originalMessage);
}
String deathName = deathType.name().toLowerCase();
String deathTag = deathName;
String entityName = null;
String killerName = null;
if (deathType.hasEntityInvolved())
{
killerName = this.deathParser.getInvolvedEntityName(originalMessage, deathType);
entityName = this.deathParser.isEntityName(killerName);
deathTag = String.format(
"%s_%s",
deathName,
(entityName != null ? entityName : "Player")
);
}
String customDeathMessage = this.deathParser.getCustomDeathMessage(deathTag);
if (customDeathMessage == null)
{
console.writeColoured("No custom death message '%s' defined, using original..", deathTag);
return;
}
RunsafePlayer player = runsafePlayerDeathEvent.getEntity();
if (deathType.hasEntityInvolved() && entityName == null)
{
RunsafePlayer killer = RunsafeServer.Instance.getPlayer(killerName);
if (killer != null)
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName(), killer.getPrettyName()));
}
else
{
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName()));
}
}
}
|
diff --git a/src/com/nolanlawson/apptracker/util/DatetimeUtil.java b/src/com/nolanlawson/apptracker/util/DatetimeUtil.java
index 8d67843..ae3b983 100644
--- a/src/com/nolanlawson/apptracker/util/DatetimeUtil.java
+++ b/src/com/nolanlawson/apptracker/util/DatetimeUtil.java
@@ -1,46 +1,46 @@
package com.nolanlawson.apptracker.util;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class DatetimeUtil {
/**
* Returns some kind of human readable representation of a past date, e.g. "4 mins ago," "2 days ago"
* @param date
* @return
*/
public static String getHumanReadableDateDiff(Date pastDate) {
Date currentDate = new Date();
long timeDiff = currentDate.getTime() - pastDate.getTime();
if (timeDiff < TimeUnit.SECONDS.toMillis(60)) { // less than a minute ago
return "<1 min ago";
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60)) { // less than an hour ago
long mins = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / 60.0);
if (mins == 1) {
return "1 min ago";
} else {
return mins + " mins ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24)) { // less than a day ago
- long hours = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / 60.0 * 60);
+ long hours = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / (60.0 * 60));
if (hours == 1) {
return "1 hour ago";
} else {
return hours + " hours ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24 * 31)) { // less than 31 days ago
long days = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / (60.0 * 60 * 24));
if (days == 1) {
return "1 day ago";
} else {
return days +" days ago";
}
} else {
return ">1 month ago";
}
}
}
| true | true | public static String getHumanReadableDateDiff(Date pastDate) {
Date currentDate = new Date();
long timeDiff = currentDate.getTime() - pastDate.getTime();
if (timeDiff < TimeUnit.SECONDS.toMillis(60)) { // less than a minute ago
return "<1 min ago";
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60)) { // less than an hour ago
long mins = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / 60.0);
if (mins == 1) {
return "1 min ago";
} else {
return mins + " mins ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24)) { // less than a day ago
long hours = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / 60.0 * 60);
if (hours == 1) {
return "1 hour ago";
} else {
return hours + " hours ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24 * 31)) { // less than 31 days ago
long days = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / (60.0 * 60 * 24));
if (days == 1) {
return "1 day ago";
} else {
return days +" days ago";
}
} else {
return ">1 month ago";
}
}
| public static String getHumanReadableDateDiff(Date pastDate) {
Date currentDate = new Date();
long timeDiff = currentDate.getTime() - pastDate.getTime();
if (timeDiff < TimeUnit.SECONDS.toMillis(60)) { // less than a minute ago
return "<1 min ago";
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60)) { // less than an hour ago
long mins = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / 60.0);
if (mins == 1) {
return "1 min ago";
} else {
return mins + " mins ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24)) { // less than a day ago
long hours = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / (60.0 * 60));
if (hours == 1) {
return "1 hour ago";
} else {
return hours + " hours ago";
}
} else if (timeDiff < TimeUnit.SECONDS.toMillis(60 * 60 * 24 * 31)) { // less than 31 days ago
long days = Math.round(TimeUnit.SECONDS.convert(timeDiff, TimeUnit.MILLISECONDS) / (60.0 * 60 * 24));
if (days == 1) {
return "1 day ago";
} else {
return days +" days ago";
}
} else {
return ">1 month ago";
}
}
|
diff --git a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/SearchableListModel.java b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/SearchableListModel.java
index 4e44bfbd..ebb3b808 100644
--- a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/SearchableListModel.java
+++ b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/SearchableListModel.java
@@ -1,655 +1,655 @@
package org.ovirt.engine.ui.uicommonweb.models;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommonweb.*;
import org.ovirt.engine.ui.uicommonweb.models.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.ui.uicommonweb.dataprovider.*;
import org.ovirt.engine.core.common.interfaces.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.ui.uicommonweb.*;
/**
Represents a list model with ability to fetch items both sync and async.
*/
@SuppressWarnings("unused")
public abstract class SearchableListModel extends ListModel
{
private static final int UnknownInteger = -1;
private static final String PAGE_STRING_REGEX = "[\\s]+page[\\s]+[1-9]+[0-9]*[\\s]*$";
private static final String PAGE_NUMBER_REGEX = "[1-9]+[0-9]*$";
private UICommand privateSearchCommand;
public UICommand getSearchCommand()
{
return privateSearchCommand;
}
private void setSearchCommand(UICommand value)
{
privateSearchCommand = value;
}
private UICommand privateSearchNextPageCommand;
public UICommand getSearchNextPageCommand()
{
return privateSearchNextPageCommand;
}
private void setSearchNextPageCommand(UICommand value)
{
privateSearchNextPageCommand = value;
}
private UICommand privateSearchPreviousPageCommand;
public UICommand getSearchPreviousPageCommand()
{
return privateSearchPreviousPageCommand;
}
private void setSearchPreviousPageCommand(UICommand value)
{
privateSearchPreviousPageCommand = value;
}
private UICommand privateForceRefreshCommand;
public UICommand getForceRefreshCommand()
{
return privateForceRefreshCommand;
}
private void setForceRefreshCommand(UICommand value)
{
privateForceRefreshCommand = value;
}
private boolean privateIsQueryFirstTime;
public boolean getIsQueryFirstTime()
{
return privateIsQueryFirstTime;
}
public void setIsQueryFirstTime(boolean value)
{
privateIsQueryFirstTime = value;
}
private boolean privateIsTimerDisabled;
public boolean getIsTimerDisabled()
{
return privateIsTimerDisabled;
}
public void setIsTimerDisabled(boolean value)
{
privateIsTimerDisabled = value;
}
// Update IsAsync wisely! Set it once after initializing the SearchableListModel object.
private boolean privateIsAsync;
public boolean getIsAsync()
{
return privateIsAsync;
}
public void setIsAsync(boolean value)
{
privateIsAsync = value;
}
private String privateDefaultSearchString;
public String getDefaultSearchString()
{
return privateDefaultSearchString;
}
public void setDefaultSearchString(String value)
{
privateDefaultSearchString = value;
}
private int privateSearchPageSize;
public int getSearchPageSize()
{
return privateSearchPageSize;
}
public void setSearchPageSize(int value)
{
privateSearchPageSize = value;
}
private RegistrationResult asyncResult;
public RegistrationResult getAsyncResult()
{
return asyncResult;
}
public void setAsyncResult(RegistrationResult value)
{
if (asyncResult != value)
{
AsyncResultChanging(value, asyncResult);
asyncResult = value;
OnPropertyChanged(new PropertyChangedEventArgs("AsyncResult"));
}
}
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String value)
{
if (!StringHelper.stringsEqual(searchString, value))
{
searchString = value;
SearchStringChanged();
OnPropertyChanged(new PropertyChangedEventArgs("SearchString"));
}
}
public int getSearchPageNumber()
{
if (StringHelper.isNullOrEmpty(getSearchString()))
{
return 1;
}
// try getting the end of SearchString in the form of "page <n>"
String pageStringRegex = PAGE_STRING_REGEX;
Match match = Regex.Match(getSearchString(), pageStringRegex, RegexOptions.IgnoreCase);
if (match.Success())
{
// retrieve the page number itself:
String pageString = match.getValue(); // == "page <n>"
String pageNumberRegex = PAGE_NUMBER_REGEX;
match = Regex.Match(pageString, pageNumberRegex);
if (match.Success())
{
int retValue = 0;
RefObject<Integer> tempRef_retValue = new RefObject<Integer>(retValue);
boolean tempVar = IntegerCompat.TryParse(match.getValue(), tempRef_retValue);
retValue = tempRef_retValue.argvalue;
if (tempVar)
{
return retValue;
}
}
}
return 1;
}
public int getNextSearchPageNumber()
{
return getSearchPageNumber() + 1;
}
public int getPreviousSearchPageNumber()
{
return getSearchPageNumber() == 1 ? 1 : getSearchPageNumber() - 1;
}
private PrivateAsyncCallback asyncCallback;
protected SearchableListModel()
{
//Configure this instance.
getConfigurator().Configure(this);
setSearchCommand(new UICommand("Search", this));
setSearchNextPageCommand(new UICommand("SearchNextPage", this));
setSearchPreviousPageCommand(new UICommand("SearchPreviousPage", this));
setForceRefreshCommand(new UICommand("ForceRefresh", this));
setSearchPageSize(UnknownInteger);
asyncCallback = new PrivateAsyncCallback(this);
// Most of SearchableListModels will not have paging. The ones that
// should have paging will set it explicitly in their constructors.
getSearchNextPageCommand().setIsAvailable(false);
getSearchPreviousPageCommand().setIsAvailable(false);
}
/**
Returns value indicating whether the specified search string is
matching this list model.
*/
public boolean IsSearchStringMatch(String searchString)
{
return true;
}
private ITimer privatetimer;
public ITimer gettimer()
{
return privatetimer;
}
public void settimer(ITimer value)
{
privatetimer = value;
}
public ITimer getTimer()
{
if (gettimer() == null)
{
settimer((ITimer)TypeResolver.getInstance().Resolve(ITimer.class));
gettimer().setInterval(getConfigurator().getPollingTimerInterval());
gettimer().getTickEvent().addListener(this);
}
return gettimer();
}
protected void SearchStringChanged()
{
}
public void Search()
{
//Defer search if there max result limit was not yet retrieved.
if (getSearchPageSize() == UnknownInteger)
{
asyncCallback.RequestSearch();
}
else
{
EnsureAsyncSearchStopped();
if (getIsQueryFirstTime())
{
setSelectedItem(null);
setSelectedItems(null);
}
if (getIsAsync())
{
AsyncSearch();
}
else
{
if (getIsTimerDisabled() == false)
{
setIsQueryFirstTime(true);
SyncSearch();
setIsQueryFirstTime(false);
getTimer().start();
}
else
{
SyncSearch();
}
}
}
}
public void ForceRefresh()
{
getTimer().stop();
SyncSearch();
if (!getIsTimerDisabled())
{
getTimer().start();
}
}
private void AsyncResultChanging(RegistrationResult newValue, RegistrationResult oldValue)
{
if (oldValue != null)
{
oldValue.getRetrievedEvent().removeListener(this);
}
if (newValue != null)
{
newValue.getRetrievedEvent().addListener(this);
}
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args)
{
super.eventRaised(ev, sender, args);
if (ev.equals(RegistrationResult.RetrievedEventDefinition))
{
AsyncResult_Retrieved();
}
if (ev.equals(ProvideTickEvent.Definition))
{
SyncSearch();
}
}
private void AsyncResult_Retrieved()
{
//Update IsEmpty flag.
// Note: Do NOT use IList. 'Items' is not necissarily IList
// (e.g in Monitor models, the different ListModels' Items are
// of type 'valueObjectEnumerableList', which is not IList).
if (getItems() != null)
{
java.util.Iterator enumerator = getItems().iterator();
setIsEmpty(enumerator.hasNext() ? false : true);
}
else
{
setIsEmpty(true);
}
}
private void ResetIsEmpty()
{
// Note: Do NOT use IList: 'Items' is not necissarily IList
// (e.g in Monitor models, the different ListModels' Items are
// of type 'valueObjectEnumerableList', which is not IList).
if (getItems() != null)
{
java.util.Iterator enumerator = getItems().iterator();
if (enumerator.hasNext())
{
setIsEmpty(false);
}
}
}
@Override
protected void ItemsChanged()
{
super.ItemsChanged();
ResetIsEmpty();
UpdatePagingAvailability();
}
@Override
protected void ItemsCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
{
super.ItemsCollectionChanged(sender, e);
ResetIsEmpty();
UpdatePagingAvailability();
}
protected void UpdatePagingAvailability()
{
getSearchNextPageCommand().setIsExecutionAllowed(getSearchNextPageCommand().getIsAvailable() && getNextSearchPageAllowed());
getSearchPreviousPageCommand().setIsExecutionAllowed(getSearchPreviousPageCommand().getIsAvailable() && getPreviousSearchPageAllowed());
}
private void SetSearchStringPage(int newSearchPageNumber)
{
if (Regex.IsMatch(getSearchString(), PAGE_STRING_REGEX, RegexOptions.IgnoreCase))
{
setSearchString(Regex.replace(getSearchString(), PAGE_STRING_REGEX, StringFormat.format(" page %1$s", newSearchPageNumber)));
}
else
{
setSearchString(StringFormat.format("%1$s page %2$s", getSearchString(), newSearchPageNumber));
}
}
protected void SearchNextPage()
{
SetSearchStringPage(getNextSearchPageNumber());
getSearchCommand().Execute();
}
protected void SearchPreviousPage()
{
SetSearchStringPage(getPreviousSearchPageNumber());
getSearchCommand().Execute();
}
protected boolean getNextSearchPageAllowed()
{
if (!getSearchNextPageCommand().getIsAvailable() || getItems() == null || IteratorUtils.moveNext(getItems().iterator()) == false)
{
return false;
}
boolean retValue = true;
// ** TODO: Inefficient performance-wise! If 'Items' was ICollection or IList
// ** it would be better, since we could simply check its 'Count' property.
int pageSize = getSearchPageSize();
if (pageSize > 0)
{
java.util.Iterator e = getItems().iterator();
int itemsCountInCurrentPage = 0;
while (IteratorUtils.moveNext(e))
{
itemsCountInCurrentPage++;
}
if (itemsCountInCurrentPage < pageSize)
{
// current page contains results quantity smaller than
// the pageSize -> there is no next page:
retValue = false;
}
}
return retValue;
}
protected boolean getPreviousSearchPageAllowed()
{
return getSearchPreviousPageCommand().getIsAvailable() && getSearchPageNumber() > 1;
}
/**
Override this method to take care on sync fetching.
*/
protected void SyncSearch()
{
}
@Override
public Iterable getItems()
{
return items;
}
@Override
public void setItems(Iterable value)
{
if (items != value)
{
IVdcQueryable lastSelectedItem = (IVdcQueryable)getSelectedItem();
java.util.ArrayList<IVdcQueryable> lastSelectedItems = new java.util.ArrayList<IVdcQueryable>();
if (getSelectedItems() != null)
{
if (getSelectedItems() instanceof java.util.ArrayList)
{
for (Object item : getSelectedItems())
{
lastSelectedItems.add((IVdcQueryable) item);
}
}
else
{
java.util.Iterator iterator = getSelectedItems().iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
}
ItemsChanging(value, items);
items = value;
- ItemsChanged();
+ UpdatePagingAvailability();
getItemsChangedEvent().raise(this, EventArgs.Empty);
OnPropertyChanged(new PropertyChangedEventArgs("Items"));
selectedItem = null;
if (getSelectedItems() != null)
{
getSelectedItems().clear();
}
if (lastSelectedItem != null && value != null)
{
IVdcQueryable newSelectedItem = null;
java.util.ArrayList<IVdcQueryable> newItems = new java.util.ArrayList<IVdcQueryable>();
if (value instanceof java.util.ArrayList)
{
for (Object item : value)
{
newItems.add((IVdcQueryable)item);
}
}
else
{
java.util.Iterator iterator = value.iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
if (newItems != null)
{
for (IVdcQueryable newItem : newItems)
{
// Search for selected item
if (newItem.getQueryableId().equals(lastSelectedItem.getQueryableId()))
{
newSelectedItem = newItem;
}
else
{
// Search for selected items
for (IVdcQueryable item : lastSelectedItems)
{
if (newItem.getQueryableId().equals(item.getQueryableId()))
{
selectedItems.add(newItem);
}
}
}
}
}
if (newSelectedItem != null)
{
selectedItem = newSelectedItem;
if (selectedItems != null)
{
selectedItems.add(newSelectedItem);
}
}
}
OnSelectedItemChanged();
}
}
public void SyncSearch(VdcQueryType vdcQueryType, VdcQueryParametersBase vdcQueryParametersBase)
{
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() { public void OnSuccess(Object model, Object ReturnValue)
{
SearchableListModel searchableListModel = (SearchableListModel)model;
searchableListModel.setItems((Iterable)((VdcQueryReturnValue)ReturnValue).getReturnValue());
}};
vdcQueryParametersBase.setRefresh(getIsQueryFirstTime());
Frontend.RunQuery(vdcQueryType, vdcQueryParametersBase, _asyncQuery);
setIsQueryFirstTime(false);
}
/**
Override this method to take care on async fetching.
*/
protected void AsyncSearch()
{
}
public void EnsureAsyncSearchStopped()
{
getTimer().stop();
if (getAsyncResult() != null && !getAsyncResult().getId().equals(Guid.Empty))
{
Frontend.UnregisterQuery(getAsyncResult().getId());
setAsyncResult(null);
}
}
@Override
public void ExecuteCommand(UICommand command)
{
super.ExecuteCommand(command);
if (command == getSearchCommand())
{
Search();
}
else if (command == getSearchNextPageCommand())
{
SearchNextPage();
}
else if (command == getSearchPreviousPageCommand())
{
SearchPreviousPage();
}
else if (command == getForceRefreshCommand())
{
ForceRefresh();
}
}
public final static class PrivateAsyncCallback
{
private SearchableListModel model;
private boolean searchRequested;
public PrivateAsyncCallback(SearchableListModel model)
{
this.model = model;
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(this);
_asyncQuery1.asyncCallback = new INewAsyncCallback() { public void OnSuccess(Object model1, Object result1)
{
PrivateAsyncCallback privateAsyncCallback1 = (PrivateAsyncCallback)model1;
privateAsyncCallback1.ApplySearchPageSize((Integer)result1);
}};
AsyncDataProvider.GetSearchResultsLimit(_asyncQuery1);
}
public void RequestSearch()
{
searchRequested = true;
}
private void ApplySearchPageSize(int value)
{
model.setSearchPageSize(value);
//If there search was requested before max result limit was retrieved, do it now.
if (searchRequested && model.getIsTimerDisabled())
{
model.getSearchCommand().Execute();
}
//Sure paging functionality.
model.UpdatePagingAvailability();
}
}
}
| true | true | public void setItems(Iterable value)
{
if (items != value)
{
IVdcQueryable lastSelectedItem = (IVdcQueryable)getSelectedItem();
java.util.ArrayList<IVdcQueryable> lastSelectedItems = new java.util.ArrayList<IVdcQueryable>();
if (getSelectedItems() != null)
{
if (getSelectedItems() instanceof java.util.ArrayList)
{
for (Object item : getSelectedItems())
{
lastSelectedItems.add((IVdcQueryable) item);
}
}
else
{
java.util.Iterator iterator = getSelectedItems().iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
}
ItemsChanging(value, items);
items = value;
ItemsChanged();
getItemsChangedEvent().raise(this, EventArgs.Empty);
OnPropertyChanged(new PropertyChangedEventArgs("Items"));
selectedItem = null;
if (getSelectedItems() != null)
{
getSelectedItems().clear();
}
if (lastSelectedItem != null && value != null)
{
IVdcQueryable newSelectedItem = null;
java.util.ArrayList<IVdcQueryable> newItems = new java.util.ArrayList<IVdcQueryable>();
if (value instanceof java.util.ArrayList)
{
for (Object item : value)
{
newItems.add((IVdcQueryable)item);
}
}
else
{
java.util.Iterator iterator = value.iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
if (newItems != null)
{
for (IVdcQueryable newItem : newItems)
{
// Search for selected item
if (newItem.getQueryableId().equals(lastSelectedItem.getQueryableId()))
{
newSelectedItem = newItem;
}
else
{
// Search for selected items
for (IVdcQueryable item : lastSelectedItems)
{
if (newItem.getQueryableId().equals(item.getQueryableId()))
{
selectedItems.add(newItem);
}
}
}
}
}
if (newSelectedItem != null)
{
selectedItem = newSelectedItem;
if (selectedItems != null)
{
selectedItems.add(newSelectedItem);
}
}
}
OnSelectedItemChanged();
}
}
| public void setItems(Iterable value)
{
if (items != value)
{
IVdcQueryable lastSelectedItem = (IVdcQueryable)getSelectedItem();
java.util.ArrayList<IVdcQueryable> lastSelectedItems = new java.util.ArrayList<IVdcQueryable>();
if (getSelectedItems() != null)
{
if (getSelectedItems() instanceof java.util.ArrayList)
{
for (Object item : getSelectedItems())
{
lastSelectedItems.add((IVdcQueryable) item);
}
}
else
{
java.util.Iterator iterator = getSelectedItems().iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
}
ItemsChanging(value, items);
items = value;
UpdatePagingAvailability();
getItemsChangedEvent().raise(this, EventArgs.Empty);
OnPropertyChanged(new PropertyChangedEventArgs("Items"));
selectedItem = null;
if (getSelectedItems() != null)
{
getSelectedItems().clear();
}
if (lastSelectedItem != null && value != null)
{
IVdcQueryable newSelectedItem = null;
java.util.ArrayList<IVdcQueryable> newItems = new java.util.ArrayList<IVdcQueryable>();
if (value instanceof java.util.ArrayList)
{
for (Object item : value)
{
newItems.add((IVdcQueryable)item);
}
}
else
{
java.util.Iterator iterator = value.iterator();
while (iterator.hasNext())
{
lastSelectedItems.add((IVdcQueryable)iterator.next());
}
}
if (newItems != null)
{
for (IVdcQueryable newItem : newItems)
{
// Search for selected item
if (newItem.getQueryableId().equals(lastSelectedItem.getQueryableId()))
{
newSelectedItem = newItem;
}
else
{
// Search for selected items
for (IVdcQueryable item : lastSelectedItems)
{
if (newItem.getQueryableId().equals(item.getQueryableId()))
{
selectedItems.add(newItem);
}
}
}
}
}
if (newSelectedItem != null)
{
selectedItem = newSelectedItem;
if (selectedItems != null)
{
selectedItems.add(newSelectedItem);
}
}
}
OnSelectedItemChanged();
}
}
|
diff --git a/src/java/davmail/exchange/ExchangeSession.java b/src/java/davmail/exchange/ExchangeSession.java
index ffe0d13..ae8d983 100644
--- a/src/java/davmail/exchange/ExchangeSession.java
+++ b/src/java/davmail/exchange/ExchangeSession.java
@@ -1,2406 +1,2403 @@
/*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2009 Mickael Guessant
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package davmail.exchange;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.exception.DavMailAuthenticationException;
import davmail.exception.DavMailException;
import davmail.http.DavGatewayHttpClientFacade;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.CopyMethod;
import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod;
import org.apache.jackrabbit.webdav.property.*;
import org.apache.jackrabbit.webdav.xml.Namespace;
import org.apache.log4j.Logger;
import org.htmlcleaner.CommentToken;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimePart;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.NoRouteToHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Exchange session through Outlook Web Access (DAV)
*/
public class ExchangeSession {
protected static final Logger LOGGER = Logger.getLogger("davmail.exchange.ExchangeSession");
/**
* Reference GMT timezone to format dates
*/
public static final SimpleTimeZone GMT_TIMEZONE = new SimpleTimeZone(0, "GMT");
protected static final int FREE_BUSY_INTERVAL = 15;
protected static final Namespace URN_SCHEMAS_HTTPMAIL = Namespace.getNamespace("urn:schemas:httpmail:");
protected static final Namespace SCHEMAS_MAPI_PROPTAG = Namespace.getNamespace("http://schemas.microsoft.com/mapi/proptag/");
protected static final DavPropertyNameSet EVENT_REQUEST_PROPERTIES = new DavPropertyNameSet();
static {
EVENT_REQUEST_PROPERTIES.add(DavPropertyName.GETETAG);
}
protected static final DavPropertyNameSet WELL_KNOWN_FOLDERS = new DavPropertyNameSet();
static {
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("inbox", URN_SCHEMAS_HTTPMAIL));
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("deleteditems", URN_SCHEMAS_HTTPMAIL));
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("sentitems", URN_SCHEMAS_HTTPMAIL));
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("sendmsg", URN_SCHEMAS_HTTPMAIL));
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("drafts", URN_SCHEMAS_HTTPMAIL));
WELL_KNOWN_FOLDERS.add(DavPropertyName.create("calendar", URN_SCHEMAS_HTTPMAIL));
}
protected static final DavPropertyNameSet DISPLAY_NAME = new DavPropertyNameSet();
static {
DISPLAY_NAME.add(DavPropertyName.DISPLAYNAME);
}
protected static final DavPropertyNameSet FOLDER_PROPERTIES = new DavPropertyNameSet();
static {
FOLDER_PROPERTIES.add(DavPropertyName.create("hassubs"));
FOLDER_PROPERTIES.add(DavPropertyName.create("nosubs"));
FOLDER_PROPERTIES.add(DavPropertyName.create("unreadcount", URN_SCHEMAS_HTTPMAIL));
FOLDER_PROPERTIES.add(DavPropertyName.create("contenttag", Namespace.getNamespace("http://schemas.microsoft.com/repl/")));
}
protected static final DavPropertyNameSet CONTENT_TAG = new DavPropertyNameSet();
static {
CONTENT_TAG.add(DavPropertyName.create("contenttag", Namespace.getNamespace("http://schemas.microsoft.com/repl/")));
}
protected static final DavPropertyNameSet RESOURCE_TAG = new DavPropertyNameSet();
static {
RESOURCE_TAG.add(DavPropertyName.create("resourcetag", Namespace.getNamespace("http://schemas.microsoft.com/repl/")));
}
/**
* Various standard mail boxes Urls
*/
private String inboxUrl;
private String deleteditemsUrl;
private String sentitemsUrl;
private String sendmsgUrl;
private String draftsUrl;
private String calendarUrl;
/**
* Base user mailboxes path (used to select folder)
*/
private String mailPath;
private String email;
private String alias;
private final HttpClient httpClient;
private final ExchangeSessionFactory.PoolKey poolKey;
private boolean disableGalLookup;
private static final String YYYY_MM_DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";
private static final String YYYYMMDD_T_HHMMSS_Z = "yyyyMMdd'T'HHmmss'Z'";
private static final String YYYY_MM_DD_T_HHMMSS_Z = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/**
* Create an exchange session for the given URL.
* The session is not actually established until a call to login()
*
* @param poolKey session pool key
* @throws IOException on error
*/
ExchangeSession(ExchangeSessionFactory.PoolKey poolKey) throws IOException {
this.poolKey = poolKey;
try {
boolean isBasicAuthentication = isBasicAuthentication(poolKey.url);
// get proxy configuration from setttings properties
URL urlObject = new URL(poolKey.url);
// webdavresource is unable to create the correct url type
HttpURL httpURL;
if (poolKey.url.startsWith("http://")) {
httpURL = new HttpURL(poolKey.userName, poolKey.password,
urlObject.getHost(), urlObject.getPort());
} else if (poolKey.url.startsWith("https://")) {
httpURL = new HttpsURL(poolKey.userName, poolKey.password,
urlObject.getHost(), urlObject.getPort());
} else {
throw new DavMailException("LOG_INVALID_URL", poolKey.url);
}
httpClient = DavGatewayHttpClientFacade.getInstance(httpURL);
// avoid 401 roundtrips
httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
// get webmail root url
// providing credentials
// manually follow redirect
HttpMethod method = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, poolKey.url);
if (isBasicAuthentication) {
int status = method.getStatusCode();
if (status == HttpStatus.SC_UNAUTHORIZED) {
method.releaseConnection();
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
} else if (status != HttpStatus.SC_OK) {
method.releaseConnection();
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
} else {
method = formLogin(httpClient, method, poolKey.userName, poolKey.password);
}
buildMailPath(method);
// got base http mailbox http url
getWellKnownFolders();
} catch (DavMailAuthenticationException exc) {
LOGGER.error(exc.getLogMessage());
throw exc;
} catch (UnknownHostException exc) {
BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(), exc.getMessage());
ExchangeSession.LOGGER.error(message);
throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
} catch (IOException exc) {
LOGGER.error(BundleMessage.formatLog("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc));
throw new DavMailException("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc);
}
LOGGER.debug("Session " + this + " created");
}
protected String formatSearchDate(Date date) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS, Locale.ENGLISH);
dateFormatter.setTimeZone(GMT_TIMEZONE);
return dateFormatter.format(date);
}
protected SimpleDateFormat getZuluDateFormat() {
SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDD_T_HHMMSS_Z, Locale.ENGLISH);
dateFormat.setTimeZone(GMT_TIMEZONE);
return dateFormat;
}
protected SimpleDateFormat getExchangeZuluDateFormat() {
SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_Z, Locale.ENGLISH);
dateFormat.setTimeZone(GMT_TIMEZONE);
return dateFormat;
}
protected Date parseDate(String dateString) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
dateFormat.setTimeZone(GMT_TIMEZONE);
return dateFormat.parse(dateString);
}
/**
* Test if the session expired.
*
* @return true this session expired
* @throws NoRouteToHostException on error
* @throws UnknownHostException on error
*/
public boolean isExpired() throws NoRouteToHostException, UnknownHostException {
boolean isExpired = false;
try {
DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(inboxUrl), 0, DISPLAY_NAME);
} catch (UnknownHostException exc) {
throw exc;
} catch (NoRouteToHostException exc) {
throw exc;
} catch (IOException e) {
isExpired = true;
}
return isExpired;
}
/**
* Test authentication mode : form based or basic.
*
* @param url exchange base URL
* @return true if basic authentication detected
* @throws IOException unable to connect to exchange
*/
protected boolean isBasicAuthentication(String url) throws IOException {
return DavGatewayHttpClientFacade.getHttpStatus(url) == HttpStatus.SC_UNAUTHORIZED;
}
protected String getAbsolutePathOrUri(HttpMethod method, String path) throws URIException {
if (path == null) {
return method.getURI().getURI();
} else if (path.startsWith("/")) {
return path;
} else {
String currentPath = method.getPath();
int end = currentPath.lastIndexOf('/');
if (end >= 0) {
return currentPath.substring(0, end + 1) + path;
} else {
return path;
}
}
}
/**
* Try to find logon method path from logon form body.
*
* @param httpClient httpClient instance
* @param initmethod form body http method
* @return logon method
* @throws IOException on error
*/
protected PostMethod buildLogonMethod(HttpClient httpClient, HttpMethod initmethod) throws IOException {
PostMethod logonMethod = null;
// create an instance of HtmlCleaner
HtmlCleaner cleaner = new HtmlCleaner();
try {
TagNode node = cleaner.clean(initmethod.getResponseBodyAsStream());
List forms = node.getElementListByName("form", true);
if (forms.size() == 1) {
TagNode form = (TagNode) forms.get(0);
String logonMethodPath = form.getAttributeByName("action");
logonMethod = new PostMethod(getAbsolutePathOrUri(initmethod, logonMethodPath));
List inputList = form.getElementListByName("input", true);
for (Object input : inputList) {
String type = ((TagNode) input).getAttributeByName("type");
String name = ((TagNode) input).getAttributeByName("name");
String value = ((TagNode) input).getAttributeByName("value");
if ("hidden".equalsIgnoreCase(type) && name != null && value != null) {
logonMethod.addParameter(name, value);
}
}
} else {
List frameList = node.getElementListByName("frame", true);
if (frameList.size() == 1) {
String src = ((TagNode) frameList.get(0)).getAttributeByName("src");
if (src != null) {
LOGGER.debug("Frames detected in form page, try frame content");
initmethod.releaseConnection();
HttpMethod newInitMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, src);
logonMethod = buildLogonMethod(httpClient, newInitMethod);
}
} else {
// another failover for script based logon forms (Exchange 2007)
List scriptList = node.getElementListByName("script", true);
for (Object script : scriptList) {
List contents = ((TagNode) script).getChildren();
for (Object content : contents) {
if (content instanceof CommentToken) {
String scriptValue = ((CommentToken) content).getCommentedContent();
int a_sUrlIndex = scriptValue.indexOf("var a_sUrl = \"");
int a_sLgnIndex = scriptValue.indexOf("var a_sLgn = \"");
if (a_sUrlIndex >= 0 && a_sLgnIndex >= 0) {
a_sUrlIndex += "var a_sUrl = \"".length();
a_sLgnIndex += "var a_sLgn = \"".length();
int a_sUrlEndIndex = scriptValue.indexOf('\"', a_sUrlIndex);
int a_sLgnEndIndex = scriptValue.indexOf('\"', a_sLgnIndex);
if (a_sUrlEndIndex >= 0 && a_sLgnEndIndex >= 0) {
String src = getAbsolutePathOrUri(initmethod,
scriptValue.substring(a_sLgnIndex, a_sLgnEndIndex) +
scriptValue.substring(a_sUrlIndex, a_sUrlEndIndex));
LOGGER.debug("Detected script based logon, redirect to form at " + src);
HttpMethod newInitMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, src);
logonMethod = buildLogonMethod(httpClient, newInitMethod);
}
} else {
a_sLgnIndex = scriptValue.indexOf("var a_sLgnQS = \"");
if (a_sUrlIndex >= 0 && a_sLgnIndex >= 0) {
a_sUrlIndex += "var a_sUrl = \"".length();
a_sLgnIndex += "var a_sLgnQS = \"".length();
int a_sUrlEndIndex = scriptValue.indexOf('\"', a_sUrlIndex);
int a_sLgnEndIndex = scriptValue.indexOf('\"', a_sLgnIndex);
if (a_sUrlEndIndex >= 0 && a_sLgnEndIndex >= 0) {
String src = initmethod.getPath() +
scriptValue.substring(a_sLgnIndex, a_sLgnEndIndex) +
scriptValue.substring(a_sUrlIndex, a_sUrlEndIndex);
LOGGER.debug("Detected script based logon, redirect to form at " + src);
HttpMethod newInitMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, src);
logonMethod = buildLogonMethod(httpClient, newInitMethod);
}
}
}
}
}
}
}
}
} catch (IOException e) {
LOGGER.error("Error parsing login form at " + initmethod.getURI());
} finally {
initmethod.releaseConnection();
}
if (logonMethod == null) {
throw new DavMailException("EXCEPTION_AUTHENTICATION_FORM_NOT_FOUND", initmethod.getURI());
}
return logonMethod;
}
protected HttpMethod formLogin(HttpClient httpClient, HttpMethod initmethod, String userName, String password) throws IOException {
LOGGER.debug("Form based authentication detected");
HttpMethod logonMethod = buildLogonMethod(httpClient, initmethod);
((PostMethod) logonMethod).addParameter("username", userName);
((PostMethod) logonMethod).addParameter("password", password);
logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);
// test form based authentication
checkFormLoginQueryString(logonMethod);
// workaround for post logon script redirect
if (httpClient.getState().getCookies().length == 0) {
logonMethod = buildLogonMethod(httpClient, logonMethod);
logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);
checkFormLoginQueryString(logonMethod);
}
return logonMethod;
}
protected void checkFormLoginQueryString(HttpMethod logonMethod) throws DavMailAuthenticationException {
String queryString = logonMethod.getQueryString();
if (queryString != null && queryString.contains("reason=2")) {
logonMethod.releaseConnection();
if (poolKey.userName != null && poolKey.userName.contains("\\")) {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
} else {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_RETRY");
}
}
}
protected void buildMailPath(HttpMethod method) throws DavMailAuthenticationException {
// find base url
final String BASE_HREF = "<base href=\"";
String line;
// get user mail URL from html body (multi frame)
BufferedReader mainPageReader = null;
try {
mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
//noinspection StatementWithEmptyBody
while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) {
}
if (line != null) {
int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length();
int end = line.indexOf('\"', start);
String mailBoxBaseHref = line.substring(start, end);
URL baseURL = new URL(mailBoxBaseHref);
mailPath = baseURL.getPath();
LOGGER.debug("Base href found in body, mailPath is " + mailPath);
buildEmail(method.getURI().getHost(), method.getPath());
LOGGER.debug("Current user email is " + email);
} else {
// failover for Exchange 2007 : build standard mailbox link with email
buildEmail(method.getURI().getHost(), method.getPath());
mailPath = "/exchange/" + email + '/';
LOGGER.debug("Current user email is " + email + ", mailPath is " + mailPath);
}
} catch (IOException e) {
LOGGER.error("Error parsing main page at " + method.getPath(), e);
} finally {
if (mainPageReader != null) {
try {
mainPageReader.close();
} catch (IOException e) {
LOGGER.error("Error parsing main page at " + method.getPath());
}
}
method.releaseConnection();
}
if (mailPath == null || email == null) {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED");
}
}
protected String getPropertyIfExists(DavPropertySet properties, String name, Namespace namespace) {
DavProperty property = properties.get(name, namespace);
if (property == null) {
return null;
} else {
return (String) property.getValue();
}
}
protected String getPropertyIfExists(DavPropertySet properties, DavPropertyName davPropertyName) {
DavProperty property = properties.get(davPropertyName);
if (property == null) {
return null;
} else {
return (String) property.getValue();
}
}
protected int getIntPropertyIfExists(DavPropertySet properties, String name, Namespace namespace) {
DavProperty property = properties.get(name, namespace);
if (property == null) {
return 0;
} else {
return Integer.parseInt((String) property.getValue());
}
}
protected long getLongPropertyIfExists(DavPropertySet properties, String name, Namespace namespace) {
DavProperty property = properties.get(name, namespace);
if (property == null) {
return 0;
} else {
return Long.parseLong((String) property.getValue());
}
}
protected String getURIPropertyIfExists(DavPropertySet properties, String name, Namespace namespace) throws URIException {
DavProperty property = properties.get(name, namespace);
if (property == null) {
return null;
} else {
return URIUtil.decode((String) property.getValue());
}
}
protected void getWellKnownFolders() throws IOException {
// Retrieve well known URLs
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(mailPath), 0, WELL_KNOWN_FOLDERS);
if (responses.length == 0) {
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDERS");
}
DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK);
inboxUrl = getURIPropertyIfExists(properties, "inbox", URN_SCHEMAS_HTTPMAIL);
deleteditemsUrl = getURIPropertyIfExists(properties, "deleteditems", URN_SCHEMAS_HTTPMAIL);
sentitemsUrl = getURIPropertyIfExists(properties, "sentitems", URN_SCHEMAS_HTTPMAIL);
sendmsgUrl = getURIPropertyIfExists(properties, "sendmsg", URN_SCHEMAS_HTTPMAIL);
draftsUrl = getURIPropertyIfExists(properties, "drafts", URN_SCHEMAS_HTTPMAIL);
calendarUrl = getURIPropertyIfExists(properties, "calendar", URN_SCHEMAS_HTTPMAIL);
LOGGER.debug("Inbox URL : " + inboxUrl +
" Trash URL : " + deleteditemsUrl +
" Sent URL : " + sentitemsUrl +
" Send URL : " + sendmsgUrl +
" Drafts URL : " + draftsUrl +
" Calendar URL : " + calendarUrl
);
}
/**
* Create message in specified folder.
* Will overwrite an existing message with same subject in the same folder
*
* @param folderPath Exchange folder path
* @param messageName message name
* @param properties message properties (flags)
* @param messageBody mail body
* @throws IOException when unable to create message
*/
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, String messageBody) throws IOException {
String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName + ".EML");
PropPatchMethod patchMethod;
// create the message first as draft
if (properties.containsKey("draft")) {
patchMethod = new PropPatchMethod(messageUrl, buildProperties(properties));
try {
// update message with blind carbon copy and other flags
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
patchMethod.releaseConnection();
}
}
PutMethod putmethod = new PutMethod(messageUrl);
putmethod.setRequestHeader("Translate", "f");
putmethod.setRequestHeader("Content-Type", "message/rfc822");
try {
// use same encoding as client socket reader
putmethod.setRequestEntity(new ByteArrayRequestEntity(messageBody.getBytes()));
int code = httpClient.executeMethod(putmethod);
if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine());
}
} finally {
putmethod.releaseConnection();
}
// add bcc and other properties
if (!properties.isEmpty()) {
patchMethod = new PropPatchMethod(messageUrl, buildProperties(properties));
try {
// update message with blind carbon copy and other flags
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_PATCH_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
patchMethod.releaseConnection();
}
}
}
protected Message buildMessage(MultiStatusResponse responseEntity) throws URIException {
Message message = new Message();
message.messageUrl = URIUtil.decode(responseEntity.getHref());
DavPropertySet properties = responseEntity.getProperties(HttpStatus.SC_OK);
message.size = getIntPropertyIfExists(properties, "x0e080003", SCHEMAS_MAPI_PROPTAG);
message.uid = getPropertyIfExists(properties, "uid", Namespace.getNamespace("DAV:"));
message.imapUid = getLongPropertyIfExists(properties, "x0e230003", SCHEMAS_MAPI_PROPTAG);
message.read = "1".equals(getPropertyIfExists(properties, "read", URN_SCHEMAS_HTTPMAIL));
message.junk = "1".equals(getPropertyIfExists(properties, "x10830003", SCHEMAS_MAPI_PROPTAG));
message.flagged = "2".equals(getPropertyIfExists(properties, "x10900003", SCHEMAS_MAPI_PROPTAG));
message.draft = "9".equals(getPropertyIfExists(properties, "x0E070003", SCHEMAS_MAPI_PROPTAG));
String x10810003 = getPropertyIfExists(properties, "x10810003", SCHEMAS_MAPI_PROPTAG);
message.answered = "102".equals(x10810003) || "103".equals(x10810003);
message.forwarded = "104".equals(x10810003);
message.date = getPropertyIfExists(properties, "date", Namespace.getNamespace("urn:schemas:mailheader:"));
message.deleted = "1".equals(getPropertyIfExists(properties, "isdeleted", Namespace.getNamespace("DAV:")));
message.messageId = getPropertyIfExists(properties, "message-id", Namespace.getNamespace("urn:schemas:mailheader:"));
if (message.messageId != null && message.messageId.startsWith("<") && message.messageId.endsWith(">")) {
message.messageId = message.messageId.substring(1, message.messageId.length() - 1);
}
return message;
}
protected List<DavProperty> buildProperties(Map<String, String> properties) {
ArrayList<DavProperty> list = new ArrayList<DavProperty>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
if ("read".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("read", URN_SCHEMAS_HTTPMAIL), entry.getValue()));
} else if ("junk".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10830003", SCHEMAS_MAPI_PROPTAG), entry.getValue()));
} else if ("flagged".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10900003", SCHEMAS_MAPI_PROPTAG), entry.getValue()));
} else if ("answered".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10810003", SCHEMAS_MAPI_PROPTAG), entry.getValue()));
if ("102".equals(entry.getValue())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10800003", SCHEMAS_MAPI_PROPTAG), "261"));
}
} else if ("forwarded".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10810003", SCHEMAS_MAPI_PROPTAG), entry.getValue()));
if ("104".equals(entry.getValue())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x10800003", SCHEMAS_MAPI_PROPTAG), "262"));
}
} else if ("bcc".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("bcc", Namespace.getNamespace("urn:schemas:mailheader:")), entry.getValue()));
} else if ("draft".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("x0E070003", SCHEMAS_MAPI_PROPTAG), entry.getValue()));
} else if ("deleted".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("isdeleted"), entry.getValue()));
} else if ("datereceived".equals(entry.getKey())) {
list.add(new DefaultDavProperty(DavPropertyName.create("datereceived", URN_SCHEMAS_HTTPMAIL), entry.getValue()));
}
}
return list;
}
/**
* Update given properties on message.
*
* @param message Exchange message
* @param properties Webdav properties map
* @throws IOException on error
*/
public void updateMessage(Message message, Map<String, String> properties) throws IOException {
PropPatchMethod patchMethod = new PropPatchMethod(URIUtil.encodePathQuery(message.messageUrl), buildProperties(properties));
try {
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE");
}
} finally {
patchMethod.releaseConnection();
}
}
/**
* Return folder message list with id and size only (for POP3 listener).
*
* @param folderName Exchange folder name
* @return folder message list
* @throws IOException on error
*/
public MessageList getAllMessageUidAndSize(String folderName) throws IOException {
return searchMessages(folderName, "\"DAV:uid\", \"http://schemas.microsoft.com/mapi/proptag/x0e080003\"", "");
}
/**
* Search folder for messages matching conditions, with attributes needed by IMAP listener.
*
* @param folderName Exchange folder name
* @param conditions conditions string in Exchange SQL syntax
* @return message list
* @throws IOException on error
*/
public MessageList searchMessages(String folderName, String conditions) throws IOException {
return searchMessages(folderName, "\"DAV:uid\", \"http://schemas.microsoft.com/mapi/proptag/x0e080003\"" +
" ,\"http://schemas.microsoft.com/mapi/proptag/x0e230003\"" +
" ,\"http://schemas.microsoft.com/mapi/proptag/x10830003\", \"http://schemas.microsoft.com/mapi/proptag/x10900003\"" +
" ,\"http://schemas.microsoft.com/mapi/proptag/x0E070003\", \"http://schemas.microsoft.com/mapi/proptag/x10810003\"" +
" ,\"urn:schemas:mailheader:message-id\", \"urn:schemas:httpmail:read\", \"DAV:isdeleted\", \"urn:schemas:mailheader:date\"", conditions);
}
/**
* Search folder for messages matching conditions, with given attributes.
*
* @param folderName Exchange folder name
* @param attributes requested Webdav attributes
* @param conditions conditions string in Exchange SQL syntax
* @return message list
* @throws IOException on error
*/
public MessageList searchMessages(String folderName, String attributes, String conditions) throws IOException {
String folderUrl = getFolderPath(folderName);
MessageList messages = new MessageList();
String searchRequest = "Select " + attributes +
" FROM Scope('SHALLOW TRAVERSAL OF \"" + folderUrl + "\"')\n" +
" WHERE \"DAV:ishidden\" = False AND \"DAV:isfolder\" = False\n";
if (conditions != null) {
searchRequest += conditions;
}
searchRequest += " ORDER BY \"urn:schemas:httpmail:date\" ASC";
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeSearchMethod(
httpClient, URIUtil.encodePath(folderUrl), searchRequest);
for (MultiStatusResponse response : responses) {
Message message = buildMessage(response);
messages.add(message);
}
Collections.sort(messages);
return messages;
}
/**
* Search folders under given folder
*
* @param folderName Exchange folder name
* @param recursive deep search if true
* @return list of folders
* @throws IOException on error
*/
public List<Folder> getSubFolders(String folderName, boolean recursive) throws IOException {
String mode = recursive ? "DEEP" : "SHALLOW";
List<Folder> folders = new ArrayList<Folder>();
String searchRequest = "Select \"DAV:nosubs\", \"DAV:hassubs\"," +
" \"DAV:hassubs\",\"urn:schemas:httpmail:unreadcount\"" +
" FROM Scope('" + mode + " TRAVERSAL OF \"" + getFolderPath(folderName) + "\"')\n" +
" WHERE \"DAV:ishidden\" = False AND \"DAV:isfolder\" = True \n" +
" AND (\"DAV:contentclass\"='urn:content-classes:mailfolder' OR \"DAV:contentclass\"='urn:content-classes:folder')";
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeSearchMethod(
httpClient, URIUtil.encodePath(getFolderPath(folderName)), searchRequest);
for (MultiStatusResponse response : responses) {
folders.add(buildFolder(response));
}
return folders;
}
protected Folder buildFolder(MultiStatusResponse entity) throws IOException {
String href = URIUtil.decode(entity.getHref());
Folder folder = new Folder();
DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK);
folder.hasChildren = "1".equals(getPropertyIfExists(properties, "hassubs", Namespace.getNamespace("DAV:")));
folder.noInferiors = "1".equals(getPropertyIfExists(properties, "nosubs", Namespace.getNamespace("DAV:")));
folder.unreadCount = getIntPropertyIfExists(properties, "unreadcount", URN_SCHEMAS_HTTPMAIL);
folder.contenttag = getPropertyIfExists(properties, "contenttag", Namespace.getNamespace("http://schemas.microsoft.com/repl/"));
if (href.endsWith("/")) {
href = href.substring(0, href.length() - 1);
}
// replace well known folder names
if (href.startsWith(inboxUrl)) {
folder.folderPath = href.replaceFirst(inboxUrl, "INBOX");
} else if (href.startsWith(sentitemsUrl)) {
folder.folderPath = href.replaceFirst(sentitemsUrl, "Sent");
} else if (href.startsWith(draftsUrl)) {
folder.folderPath = href.replaceFirst(draftsUrl, "Drafts");
} else if (href.startsWith(deleteditemsUrl)) {
folder.folderPath = href.replaceFirst(deleteditemsUrl, "Trash");
} else {
int index = href.indexOf(mailPath.substring(0, mailPath.length() - 1));
if (index >= 0) {
if (index + mailPath.length() > href.length()) {
folder.folderPath = "";
} else {
folder.folderPath = href.substring(index + mailPath.length());
}
} else {
throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", folder.folderPath);
}
}
return folder;
}
/**
* Delete oldest messages in trash.
* keepDelay is the number of days to keep messages in trash before delete
*
* @throws IOException when unable to purge messages
*/
public void purgeOldestTrashAndSentMessages() throws IOException {
int keepDelay = Settings.getIntProperty("davmail.keepDelay");
if (keepDelay != 0) {
purgeOldestFolderMessages(deleteditemsUrl, keepDelay);
}
// this is a new feature, default is : do nothing
int sentKeepDelay = Settings.getIntProperty("davmail.sentKeepDelay");
if (sentKeepDelay != 0) {
purgeOldestFolderMessages(sentitemsUrl, sentKeepDelay);
}
}
protected void purgeOldestFolderMessages(String folderUrl, int keepDelay) throws IOException {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -keepDelay);
LOGGER.debug("Delete messages in " + folderUrl + " since " + cal.getTime());
String searchRequest = "Select \"DAV:uid\"" +
" FROM Scope('SHALLOW TRAVERSAL OF \"" + folderUrl + "\"')\n" +
" WHERE \"DAV:isfolder\" = False\n" +
" AND \"DAV:getlastmodified\" < '" + formatSearchDate(cal.getTime()) + "'\n";
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeSearchMethod(
httpClient, URIUtil.encodePath(folderUrl), searchRequest);
for (MultiStatusResponse response : responses) {
String messageUrl = URIUtil.decode(response.getHref());
LOGGER.debug("Delete " + messageUrl);
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, URIUtil.encodePath(messageUrl));
}
}
/**
* Send message in reader to recipients.
* Detect visible recipients in message body to determine bcc recipients
*
* @param recipients recipients list
* @param reader message stream
* @throws IOException on error
*/
public void sendMessage(List<String> recipients, BufferedReader reader) throws IOException {
String line = reader.readLine();
StringBuilder mailBuffer = new StringBuilder();
StringBuilder recipientBuffer = new StringBuilder();
boolean inHeader = true;
boolean inRecipientHeader = false;
while (!".".equals(line)) {
mailBuffer.append(line).append((char) 13).append((char) 10);
line = reader.readLine();
// Exchange 2007 : skip From: header
if ((inHeader && line.length() >= 5)) {
String prefix = line.substring(0, 5).toLowerCase();
if ("from:".equals(prefix)) {
line = reader.readLine();
}
}
if (inHeader && line.length() == 0) {
inHeader = false;
}
inRecipientHeader = inRecipientHeader && line.startsWith(" ");
if ((inHeader && line.length() >= 3) || inRecipientHeader) {
String prefix = line.substring(0, 3).toLowerCase();
if ("to:".equals(prefix) || "cc:".equals(prefix) || inRecipientHeader) {
inRecipientHeader = true;
recipientBuffer.append(line);
}
}
}
// remove visible recipients from list
List<String> visibleRecipients = new ArrayList<String>();
for (String recipient : recipients) {
if (recipientBuffer.indexOf(recipient) >= 0) {
visibleRecipients.add(recipient);
}
}
recipients.removeAll(visibleRecipients);
StringBuilder bccBuffer = new StringBuilder();
for (String recipient : recipients) {
if (bccBuffer.length() > 0) {
bccBuffer.append(',');
}
bccBuffer.append('<');
bccBuffer.append(recipient);
bccBuffer.append('>');
}
String bcc = bccBuffer.toString();
HashMap<String, String> properties = new HashMap<String, String>();
if (bcc.length() > 0) {
properties.put("bcc", bcc);
}
String messageName = UUID.randomUUID().toString();
createMessage("Drafts", messageName, properties, mailBuffer.toString());
String tempUrl = draftsUrl + '/' + messageName + ".EML";
MoveMethod method = new MoveMethod(URIUtil.encodePath(tempUrl), URIUtil.encodePath(sendmsgUrl), true);
int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
if (status != HttpStatus.SC_OK) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
}
/**
* Convert logical or relative folder path to absolute folder path.
*
* @param folderName folder name
* @return folder path
*/
public String getFolderPath(String folderName) {
String folderPath;
if (folderName.startsWith("INBOX")) {
folderPath = folderName.replaceFirst("INBOX", inboxUrl);
} else if (folderName.startsWith("Trash")) {
folderPath = folderName.replaceFirst("Trash", deleteditemsUrl);
} else if (folderName.startsWith("Drafts")) {
folderPath = folderName.replaceFirst("Drafts", draftsUrl);
} else if (folderName.startsWith("Sent")) {
folderPath = folderName.replaceFirst("Sent", sentitemsUrl);
} else if (folderName.startsWith("calendar")) {
folderPath = folderName.replaceFirst("calendar", calendarUrl);
// absolute folder path
} else if (folderName.startsWith("/")) {
folderPath = folderName;
} else {
folderPath = mailPath + folderName;
}
return folderPath;
}
/**
* Get folder object.
* Folder name can be logical names INBOX, Drafts, Trash or calendar,
* or a path relative to user base folder or absolute path.
*
* @param folderName folder name
* @return Folder object
* @throws IOException on error
*/
public Folder getFolder(String folderName) throws IOException {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(getFolderPath(folderName)), 0, FOLDER_PROPERTIES);
Folder folder = null;
if (responses.length > 0) {
folder = buildFolder(responses[0]);
folder.folderName = folderName;
}
return folder;
}
/**
* Check folder ctag and reload messages as needed.
*
* @param currentFolder current folder
* @return current folder or new refreshed folder
* @throws IOException on error
* @deprecated no longer used: breaks Outlook IMAP
*/
public Folder refreshFolder(Folder currentFolder) throws IOException {
Folder newFolder = getFolder(currentFolder.folderName);
if (currentFolder.contenttag == null || !currentFolder.contenttag.equals(newFolder.contenttag)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Contenttag changed on " + currentFolder.folderName + ' '
+ currentFolder.contenttag + " => " + newFolder.contenttag + ", reloading messages");
}
newFolder.loadMessages();
return newFolder;
} else {
return currentFolder;
}
}
/**
* Create Exchange folder
*
* @param folderName logical folder name
* @throws IOException on error
*/
public void createFolder(String folderName) throws IOException {
String folderPath = getFolderPath(folderName);
ArrayList<DavProperty> list = new ArrayList<DavProperty>();
list.add(new DefaultDavProperty(DavPropertyName.create("outlookfolderclass", Namespace.getNamespace("http://schemas.microsoft.com/exchange/")), "IPF.Note"));
// standard MkColMethod does not take properties, override PropPatchMethod instead
PropPatchMethod method = new PropPatchMethod(URIUtil.encodePath(folderPath), list) {
@Override
public String getName() {
return "MKCOL";
}
};
int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
// ok or alredy exists
if (status != HttpStatus.SC_MULTI_STATUS && status != HttpStatus.SC_METHOD_NOT_ALLOWED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
}
/**
* Copy message to target folder
*
* @param message Exchange message
* @param targetFolder target folder
* @throws IOException on error
*/
public void copyMessage(Message message, String targetFolder) throws IOException {
String messageUrl = message.messageUrl;
String targetPath = getFolderPath(targetFolder) + messageUrl.substring(messageUrl.lastIndexOf('/'));
CopyMethod method = new CopyMethod(URIUtil.encodePath(messageUrl), URIUtil.encodePath(targetPath), false);
// allow rename if a message with the same name exists
method.addRequestHeader("Allow-Rename", "t");
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new DavMailException("EXCEPTION_UNABLE_TO_COPY_MESSAGE");
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
} finally {
method.releaseConnection();
}
}
/**
* Move folder to target name.
*
* @param folderName current folder name/path
* @param targetName target folder name/path
* @throws IOException on error
*/
public void moveFolder(String folderName, String targetName) throws IOException {
String folderPath = getFolderPath(folderName);
String targetPath = getFolderPath(targetName);
MoveMethod method = new MoveMethod(URIUtil.encodePath(folderPath), URIUtil.encodePath(targetPath), false);
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_FOLDER");
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
} finally {
method.releaseConnection();
}
}
protected void moveToTrash(String encodedPath, String encodedMessageName) throws IOException {
String source = encodedPath + '/' + encodedMessageName;
String destination = URIUtil.encodePath(deleteditemsUrl) + '/' + encodedMessageName;
LOGGER.debug("Deleting : " + source + " to " + destination);
MoveMethod method = new MoveMethod(source, destination, false);
method.addRequestHeader("Allow-rename", "t");
int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
// do not throw error if already deleted
if (status != HttpStatus.SC_CREATED && status != HttpStatus.SC_NOT_FOUND) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
if (method.getResponseHeader("Location") != null) {
destination = method.getResponseHeader("Location").getValue();
}
LOGGER.debug("Deleted to :" + destination);
}
/**
* Exchange folder with IMAP properties
*/
public class Folder {
/**
* Logical (IMAP) folder path.
*/
public String folderPath;
/**
* Folder unread message count.
*/
public int unreadCount;
/**
* true if folder has subfolders (DAV:hassubs).
*/
public boolean hasChildren;
/**
* true if folder has no subfolders (DAV:nosubs).
*/
public boolean noInferiors;
/**
* Requested folder name
* TODO : same as folderPath ?
*/
public String folderName;
/**
* Folder content tag (to detect folder content changes).
*/
public String contenttag;
/**
* Folder message list, empty before loadMessages call.
*/
public ExchangeSession.MessageList messages;
/**
* Get IMAP folder flags.
*
* @return folder flags in IMAP format
*/
public String getFlags() {
if (noInferiors) {
return "\\NoInferiors";
} else if (hasChildren) {
return "\\HasChildren";
} else {
return "\\HasNoChildren";
}
}
/**
* Load folder messages.
*
* @throws IOException on error
*/
public void loadMessages() throws IOException {
messages = searchMessages(folderPath, "");
}
/**
* Folder message count.
*
* @return message count
*/
public int count() {
return messages.size();
}
/**
* Compute IMAP uidnext.
*
* @return max(messageuids)+1
*/
public long getUidNext() {
return messages.get(messages.size() - 1).getImapUid() + 1;
}
/**
* Get message uid at index.
*
* @param index message index
* @return message uid
*/
public long getImapUid(int index) {
return messages.get(index).getImapUid();
}
/**
* Get message at index.
*
* @param index message index
* @return message
*/
public Message get(int index) {
return messages.get(index);
}
}
/**
* Exchange message.
*/
public class Message implements Comparable {
protected String messageUrl;
/**
* Message uid.
*/
protected String uid;
/**
* Message IMAP uid, unique in folder (x0e230003).
*/
protected long imapUid;
/**
* MAPI message size.
*/
public int size;
/**
* Mail header message-id.
*/
protected String messageId;
/**
* Message date (urn:schemas:mailheader:date).
*/
public String date;
/**
* Message flag: read.
*/
public boolean read;
/**
* Message flag: deleted.
*/
public boolean deleted;
/**
* Message flag: junk.
*/
public boolean junk;
/**
* Message flag: flagged.
*/
public boolean flagged;
/**
* Message flag: draft.
*/
public boolean draft;
/**
* Message flag: answered.
*/
public boolean answered;
/**
* Message flag: fowarded.
*/
public boolean forwarded;
/**
* IMAP uid , unique in folder (x0e230003)
*
* @return IMAP uid
*/
public long getImapUid() {
return imapUid;
}
/**
* Exchange uid.
*
* @return uid
*/
public String getUid() {
return uid;
}
/**
* Return message flags in IMAP format.
*
* @return IMAP flags
*/
public String getImapFlags() {
StringBuilder buffer = new StringBuilder();
if (read) {
buffer.append("\\Seen ");
}
if (deleted) {
buffer.append("\\Deleted ");
}
if (flagged) {
buffer.append("\\Flagged ");
}
if (junk) {
buffer.append("Junk ");
}
if (draft) {
buffer.append("\\Draft ");
}
if (answered) {
buffer.append("\\Answered ");
}
if (forwarded) {
buffer.append("$Forwarded ");
}
return buffer.toString().trim();
}
/**
* Write MIME message to os
*
* @param os output stream
* @throws IOException on error
*/
public void write(OutputStream os) throws IOException {
HttpMethod method = null;
BufferedReader reader = null;
try {
method = new GetMethod(URIUtil.encodePath(messageUrl));
method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
method.setRequestHeader("Translate", "f");
httpClient.executeMethod(method);
reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
OutputStreamWriter isoWriter = new OutputStreamWriter(os);
String line;
while ((line = reader.readLine()) != null) {
if (".".equals(line)) {
line = "..";
// patch text/calendar to include utf-8 encoding
} else if ("Content-Type: text/calendar;".equals(line)) {
StringBuilder headerBuffer = new StringBuilder();
headerBuffer.append(line);
while ((line = reader.readLine()) != null && line.startsWith("\t")) {
headerBuffer.append((char) 13);
headerBuffer.append((char) 10);
headerBuffer.append(line);
}
if (headerBuffer.indexOf("charset") < 0) {
headerBuffer.append(";charset=utf-8");
}
headerBuffer.append((char) 13);
headerBuffer.append((char) 10);
headerBuffer.append(line);
line = headerBuffer.toString();
}
isoWriter.write(line);
isoWriter.write((char) 13);
isoWriter.write((char) 10);
}
isoWriter.flush();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
LOGGER.warn("Error closing message input stream", e);
}
}
if (method != null) {
method.releaseConnection();
}
}
}
/**
* Delete message.
*
* @throws IOException on error
*/
public void delete() throws IOException {
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, URIUtil.encodePath(messageUrl));
}
/**
* Move message to trash, mark message read.
*
* @throws IOException on error
*/
public void moveToTrash() throws IOException {
// mark message as read
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("read", "1");
updateMessage(this, properties);
int index = messageUrl.lastIndexOf('/');
if (index < 0) {
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_URL", messageUrl);
}
String encodedPath = URIUtil.encodePath(messageUrl.substring(0, index));
String encodedMessageName = URIUtil.encodePath(messageUrl.substring(index + 1));
ExchangeSession.this.moveToTrash(encodedPath, encodedMessageName);
}
/**
* Comparator to sort messages by IMAP uid
*
* @param message other message
* @return imapUid comparison result
*/
public int compareTo(Object message) {
long compareValue = (imapUid - ((Message) message).imapUid);
if (compareValue > 0) {
return 1;
} else if (compareValue < 0) {
return -1;
} else {
return 0;
}
}
/**
* Override equals, compare IMAP uids
*
* @param message other message
* @return true if IMAP uids are equal
*/
@Override
public boolean equals(Object message) {
return message instanceof Message && imapUid == ((Message) message).imapUid;
}
/**
* Override hashCode, return imapUid hashcode.
*
* @return imapUid hashcode
*/
@Override
public int hashCode() {
return (int) (imapUid ^ (imapUid >>> 32));
}
}
/**
* Message list
*/
public static class MessageList extends ArrayList<Message> {
}
public class Event {
protected String href;
protected String etag;
protected MimePart getCalendarMimePart(MimeMultipart multiPart) throws IOException, MessagingException {
MimePart bodyPart = null;
for (int i = 0; i < multiPart.getCount(); i++) {
String contentType = multiPart.getBodyPart(i).getContentType();
if (contentType.startsWith("text/calendar") || contentType.startsWith("application/ics")) {
bodyPart = (MimePart) multiPart.getBodyPart(i);
break;
} else if (contentType.startsWith("multipart")) {
Object content = multiPart.getBodyPart(i).getContent();
if (content instanceof MimeMultipart) {
bodyPart = getCalendarMimePart((MimeMultipart) content);
}
}
}
return bodyPart;
}
public String getICS() throws IOException {
String result = null;
LOGGER.debug("Get event: " + href);
GetMethod method = new GetMethod(URIUtil.encodePath(href));
method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
method.setRequestHeader("Translate", "f");
try {
int status = httpClient.executeMethod(method);
if (status != HttpStatus.SC_OK) {
LOGGER.warn("Unable to get event at " + href + " status: " + status);
}
MimeMessage mimeMessage = new MimeMessage(null, method.getResponseBodyAsStream());
Object mimeBody = mimeMessage.getContent();
MimePart bodyPart;
if (mimeBody instanceof MimeMultipart) {
bodyPart = getCalendarMimePart((MimeMultipart) mimeBody);
} else {
// no multipart, single body
bodyPart = mimeMessage;
}
if (bodyPart == null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.getDataHandler().writeTo(baos);
baos.close();
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", new String(baos.toByteArray(), "UTF-8"));
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bodyPart.getDataHandler().writeTo(baos);
baos.close();
result = fixICS(new String(baos.toByteArray(), "UTF-8"), true);
} catch (MessagingException e) {
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", e.getMessage());
} finally {
method.releaseConnection();
}
return result;
}
public String getPath() {
int index = href.lastIndexOf('/');
if (index >= 0) {
return href.substring(index + 1);
} else {
return href;
}
}
public String getEtag() {
return etag;
}
}
public List<Event> getEventMessages(String folderPath) throws IOException {
String searchQuery = "Select \"DAV:getetag\"" +
" FROM Scope('SHALLOW TRAVERSAL OF \"" + folderPath + "\"')\n" +
" WHERE \"DAV:contentclass\" = 'urn:content-classes:calendarmessage'\n" +
" AND (NOT \"CALDAV:schedule-state\" = 'CALDAV:schedule-processed')\n" +
" ORDER BY \"urn:schemas:calendar:dtstart\" DESC\n";
return getEvents(folderPath, searchQuery);
}
public List<Event> getAllEvents(String folderPath) throws IOException {
int caldavPastDelay = Settings.getIntProperty("davmail.caldavPastDelay", Integer.MAX_VALUE);
String dateCondition = "";
if (caldavPastDelay != Integer.MAX_VALUE) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -caldavPastDelay);
dateCondition = " AND \"urn:schemas:calendar:dtstart\" > '" + formatSearchDate(cal.getTime()) + "'\n";
}
String searchQuery = "Select \"DAV:getetag\"" +
" FROM Scope('SHALLOW TRAVERSAL OF \"" + folderPath + "\"')\n" +
" WHERE (" +
" \"urn:schemas:calendar:instancetype\" is null OR" +
" \"urn:schemas:calendar:instancetype\" = 1\n" +
" OR (\"urn:schemas:calendar:instancetype\" = 0\n" +
dateCondition +
" )) AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n" +
" ORDER BY \"urn:schemas:calendar:dtstart\" DESC\n";
return getEvents(folderPath, searchQuery);
}
public List<Event> getEvents(String path, String searchQuery) throws IOException {
List<Event> events = new ArrayList<Event>();
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeSearchMethod(httpClient, URIUtil.encodePath(path), searchQuery);
for (MultiStatusResponse response : responses) {
events.add(buildEvent(response));
}
return events;
}
public Event getEvent(String path, String eventName) throws IOException {
String eventPath = URIUtil.encodePath(path + '/' + eventName);
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(httpClient, eventPath, 0, EVENT_REQUEST_PROPERTIES);
if (responses.length == 0) {
throw new DavMailException("EXCEPTION_EVENT_NOT_FOUND");
}
return buildEvent(responses[0]);
}
protected Event buildEvent(MultiStatusResponse calendarResponse) throws URIException {
Event event = new Event();
String href = calendarResponse.getHref();
event.href = URIUtil.decode(href);
event.etag = getPropertyIfExists(calendarResponse.getProperties(HttpStatus.SC_OK), "getetag", Namespace.getNamespace("DAV:"));
return event;
}
protected String fixICS(String icsBody, boolean fromServer) throws IOException {
// first pass : detect
class AllDayState {
boolean isAllDay;
boolean hasCdoAllDay;
boolean isCdoAllDay;
}
// Convert event class from and to iCal
// See https://trac.calendarserver.org/browser/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt
boolean isAppleiCal = false;
boolean hasOrganizer = false;
- boolean hasAttendee = false;
boolean invalidTimezoneId = false;
String eventClass = null;
List<AllDayState> allDayStates = new ArrayList<AllDayState>();
AllDayState currentAllDayState = new AllDayState();
BufferedReader reader = null;
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
int index = line.indexOf(':');
if (index >= 0) {
String key = line.substring(0, index);
String value = line.substring(index + 1);
if ("DTSTART;VALUE=DATE".equals(key)) {
currentAllDayState.isAllDay = true;
} else if ("X-MICROSOFT-CDO-ALLDAYEVENT".equals(key)) {
currentAllDayState.hasCdoAllDay = true;
currentAllDayState.isCdoAllDay = "TRUE".equals(value);
} else if ("END:VEVENT".equals(line)) {
allDayStates.add(currentAllDayState);
currentAllDayState = new AllDayState();
} else if ("PRODID".equals(key) && line.contains("iCal")) {
isAppleiCal = true;
} else if (isAppleiCal && "X-CALENDARSERVER-ACCESS".equals(key)) {
eventClass = value;
} else if (!isAppleiCal && "CLASS".equals(key)) {
eventClass = value;
- } else if (key.startsWith("ATTENDEE")) {
- hasAttendee = true;
} else if (key.startsWith("ORGANIZER")) {
hasOrganizer = true;
} else if (key.startsWith("DTSTART;TZID=\"")) {
invalidTimezoneId = true;
}
}
}
} finally {
if (reader != null) {
reader.close();
}
}
// second pass : fix
int count = 0;
ICSBufferedWriter result = new ICSBufferedWriter();
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
// remove empty properties
if ("CLASS:".equals(line) || "LOCATION:".equals(line)) {
continue;
}
// fix invalid exchange timezoneid
if (invalidTimezoneId && line.indexOf(";TZID=\"") >= 0) {
line = fixTimezoneId(line);
}
if (!fromServer && currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE";
} else if (!fromServer && "END:VEVENT".equals(line) && currentAllDayState.isAllDay && !currentAllDayState.hasCdoAllDay) {
result.writeLine("X-MICROSOFT-CDO-ALLDAYEVENT:TRUE");
} else if (!fromServer && !currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE";
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTSTART") && !line.startsWith("DTSTART;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTEND") && !line.startsWith("DTEND;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (line.startsWith("TZID:") && invalidTimezoneId) {
line = "TZID:TimezoneId";
} else if ("BEGIN:VEVENT".equals(line)) {
currentAllDayState = allDayStates.get(count++);
} else if (line.startsWith("X-CALENDARSERVER-ACCESS:")) {
if (!isAppleiCal) {
continue;
} else {
if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:PRIVATE");
} else if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:CONFIDENTIAL");
} else {
result.writeLine("CLASS:" + eventClass);
}
}
} else if (line.startsWith("EXDATE;TZID=") || line.startsWith("EXDATE:")) {
// Apple iCal doesn't support EXDATE with multiple exceptions
// on one line. Split into multiple EXDATE entries (which is
// also legal according to the caldav standard).
splitExDate(result, line);
continue;
} else if (line.startsWith("X-ENTOURAGE_UUID:")) {
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
continue;
} else if (line.startsWith("CLASS:")) {
if (isAppleiCal) {
continue;
} else {
if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:CONFIDENTIAL");
} else if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:PRIVATE");
} else {
result.writeLine("X-CALENDARSERVER-ACCESS:" + eventClass);
}
}
- // remove organizer line if event has no attendees for iPhone
- } else if (fromServer && line.startsWith("ORGANIZER") && !hasAttendee) {
+ // remove organizer line if user is organizer for iPhone
+ } else if (fromServer && line.startsWith("ORGANIZER") && line.toLowerCase().endsWith(email)) {
continue;
// add organizer line to all events created in Exchange for active sync
} else if (!fromServer && "END:VEVENT".equals(line) && !hasOrganizer) {
result.writeLine("ORGANIZER:MAILTO:" + email);
}
result.writeLine(line);
}
} finally {
reader.close();
}
return result.toString();
}
protected String fixTimezoneId(String line) {
int startIndex = line.indexOf("TZID=\"");
int endIndex = line.indexOf('"', startIndex+6);
if (startIndex >= 0 && endIndex >=0) {
return line.substring(0, startIndex+5)+"TimezoneId"+line.substring(endIndex+1);
} else {
return line;
}
}
protected void splitExDate(ICSBufferedWriter result, String line) {
int cur = line.lastIndexOf(':') + 1;
String start = line.substring(0, cur);
for (int next = line.indexOf(',', cur); next != -1; next = line.indexOf(',', cur)) {
String val = line.substring(cur, next);
result.writeLine(start + val);
cur = next + 1;
}
result.writeLine(start + line.substring(cur));
}
protected String getAllDayLine(String line) throws IOException {
int keyIndex = line.indexOf(';');
int valueIndex = line.lastIndexOf(':');
int valueEndIndex = line.lastIndexOf('T');
if (valueIndex < 0 || valueEndIndex < 0) {
throw new DavMailException("EXCEPTION_INVALID_ICS_LINE", line);
}
String dateValue = line.substring(valueIndex + 1, valueEndIndex);
String key = line.substring(0, Math.max(keyIndex, valueIndex));
return key + ";VALUE=DATE:" + dateValue;
}
public static class EventResult {
public int status;
public String etag;
}
public int sendEvent(String icsBody) throws IOException {
String messageUrl = URIUtil.encodePathQuery(draftsUrl + '/' + UUID.randomUUID().toString() + ".EML");
int status = internalCreateOrUpdateEvent(messageUrl, "urn:content-classes:calendarmessage", icsBody, null, null).status;
if (status != HttpStatus.SC_CREATED) {
return status;
} else {
MoveMethod method = new MoveMethod(URIUtil.encodePath(messageUrl), URIUtil.encodePath(sendmsgUrl), true);
status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
if (status != HttpStatus.SC_OK) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
return status;
}
}
public EventResult createOrUpdateEvent(String path, String eventName, String icsBody, String etag, String noneMatch) throws IOException {
String messageUrl = URIUtil.encodePath(path + '/' + eventName);
return internalCreateOrUpdateEvent(messageUrl, "urn:content-classes:appointment", icsBody, etag, noneMatch);
}
protected String getICSMethod(String icsBody) {
int methodIndex = icsBody.indexOf("METHOD:");
if (methodIndex < 0) {
return "REQUEST";
}
int startIndex = methodIndex + "METHOD:".length();
int endIndex = icsBody.indexOf('\r', startIndex);
if (endIndex < 0) {
return "REQUEST";
}
return icsBody.substring(startIndex, endIndex);
}
static class Participants {
String attendees;
String organizer;
}
/**
* Parse ics event for attendees and organizer.
* For notifications, only include attendees with RSVP=TRUE or PARTSTAT=NEEDS-ACTION
*
* @param icsBody ics event
* @param isNotification get only notified attendees
* @return participants
* @throws IOException on error
*/
protected Participants getParticipants(String icsBody, boolean isNotification) throws IOException {
HashSet<String> attendees = new HashSet<String>();
String organizer = null;
BufferedReader reader = null;
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
int index = line.indexOf(':');
if (index >= 0) {
String key = line.substring(0, index);
String value = line.substring(index + 1);
int semiColon = key.indexOf(';');
if (semiColon >= 0) {
key = key.substring(0, semiColon);
}
if ("ORGANIZER".equals(key) || "ATTENDEE".equals(key)) {
int colonIndex = value.indexOf(':');
if (colonIndex >= 0) {
value = value.substring(colonIndex + 1);
}
if ("ORGANIZER".equals(key)) {
organizer = value;
// exclude current user and invalid values from recipients
// also exclude no action attendees
} else if (!email.equalsIgnoreCase(value) && value.indexOf('@') >= 0
&& (!isNotification
|| line.indexOf("RSVP=TRUE") >= 0
|| line.indexOf("PARTSTAT=NEEDS-ACTION") >= 0)) {
attendees.add(value);
}
}
}
}
} finally {
if (reader != null) {
reader.close();
}
}
Participants participants = new Participants();
StringBuilder result = new StringBuilder();
for (String recipient : attendees) {
if (result.length() > 0) {
result.append(", ");
}
result.append(recipient);
}
participants.attendees = result.toString();
participants.organizer = organizer;
return participants;
}
protected EventResult internalCreateOrUpdateEvent(String messageUrl, String contentClass, String icsBody, String etag, String noneMatch) throws IOException {
String uid = UUID.randomUUID().toString();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(baos, "ASCII");
int status = 0;
PutMethod putmethod = new PutMethod(messageUrl);
putmethod.setRequestHeader("Translate", "f");
putmethod.setRequestHeader("Overwrite", "f");
if (etag != null) {
putmethod.setRequestHeader("If-Match", etag);
}
if (noneMatch != null) {
putmethod.setRequestHeader("If-None-Match", noneMatch);
}
putmethod.setRequestHeader("Content-Type", "message/rfc822");
String method = getICSMethod(icsBody);
writer.write("Content-Transfer-Encoding: 7bit\r\n" +
"Content-class: ");
writer.write(contentClass);
writer.write("\r\n");
if ("urn:content-classes:calendarmessage".equals(contentClass)) {
// need to parse attendees and organizer to build recipients
Participants participants = getParticipants(icsBody, true);
String recipients;
if (email.equalsIgnoreCase(participants.organizer)) {
// current user is organizer => notify all
recipients = participants.attendees;
} else {
// notify only organizer
recipients = participants.organizer;
}
writer.write("To: ");
writer.write(recipients);
writer.write("\r\n");
// do not send notification if no recipients found
if (recipients.length() == 0) {
status = HttpStatus.SC_NO_CONTENT;
}
} else {
// need to parse attendees and organizer to build recipients
Participants participants = getParticipants(icsBody, false);
// storing appointment, full recipients header
if (participants.attendees != null) {
writer.write("To: ");
writer.write(participants.attendees);
writer.write("\r\n");
}
if (participants.organizer != null) {
writer.write("From: ");
writer.write(participants.organizer);
writer.write("\r\n");
}
// if not organizer, set REPLYTIME to force Outlook in attendee mode
if (participants.organizer != null && !email.equalsIgnoreCase(participants.organizer)) {
if (icsBody.indexOf("METHOD:") < 0) {
icsBody = icsBody.replaceAll("BEGIN:VCALENDAR", "BEGIN:VCALENDAR\r\nMETHOD:REQUEST");
}
if (icsBody.indexOf("X-MICROSOFT-CDO-REPLYTIME") < 0) {
icsBody = icsBody.replaceAll("END:VEVENT", "X-MICROSOFT-CDO-REPLYTIME:" +
getZuluDateFormat().format(new Date()) + "\r\nEND:VEVENT");
}
}
}
writer.write("MIME-Version: 1.0\r\n" +
"Content-Type: multipart/alternative;\r\n" +
"\tboundary=\"----=_NextPart_");
writer.write(uid);
writer.write("\"\r\n" +
"\r\n" +
"This is a multi-part message in MIME format.\r\n" +
"\r\n" +
"------=_NextPart_");
writer.write(uid);
writer.write("\r\n" +
"Content-class: ");
writer.write(contentClass);
writer.write("\r\n" +
"Content-Type: text/calendar;\r\n" +
"\tmethod=");
writer.write(method);
writer.write(";\r\n" +
"\tcharset=\"utf-8\"\r\n" +
"Content-Transfer-Encoding: 8bit\r\n\r\n");
writer.flush();
baos.write(fixICS(icsBody, false).getBytes("UTF-8"));
writer.write("------=_NextPart_");
writer.write(uid);
writer.write("--\r\n");
writer.close();
putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray(), "message/rfc822"));
try {
if (status == 0) {
status = httpClient.executeMethod(putmethod);
if (status == HttpURLConnection.HTTP_OK) {
if (etag != null) {
LOGGER.debug("Updated event " + messageUrl);
} else {
LOGGER.warn("Overwritten event " + messageUrl);
}
} else if (status != HttpURLConnection.HTTP_CREATED) {
LOGGER.warn("Unable to create or update message " + status + ' ' + putmethod.getStatusLine());
}
}
} finally {
putmethod.releaseConnection();
}
EventResult eventResult = new EventResult();
eventResult.status = status;
if (putmethod.getResponseHeader("GetETag") != null) {
eventResult.etag = putmethod.getResponseHeader("GetETag").getValue();
}
return eventResult;
}
public void deleteFolder(String path) throws IOException {
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, URIUtil.encodePath(getFolderPath(path)));
}
public int deleteEvent(String path, String eventName) throws IOException {
String eventPath = URIUtil.encodePath(path + '/' + eventName);
int status;
if (inboxUrl.endsWith(path)) {
// do not delete calendar messages, mark read and processed
ArrayList<DavProperty> list = new ArrayList<DavProperty>();
list.add(new DefaultDavProperty(DavPropertyName.create("schedule-state", Namespace.getNamespace("CALDAV:")), "CALDAV:schedule-processed"));
list.add(new DefaultDavProperty(DavPropertyName.create("read", URN_SCHEMAS_HTTPMAIL), "1"));
PropPatchMethod patchMethod = new PropPatchMethod(eventPath, list);
DavGatewayHttpClientFacade.executeMethod(httpClient, patchMethod);
status = HttpStatus.SC_OK;
} else {
status = DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, eventPath);
}
return status;
}
public String getFolderCtag(String folderPath) throws IOException {
return getFolderProperty(folderPath, CONTENT_TAG);
}
public String getFolderResourceTag(String folderPath) throws IOException {
return getFolderProperty(folderPath, RESOURCE_TAG);
}
public String getFolderProperty(String folderPath, DavPropertyNameSet davPropertyNameSet) throws IOException {
String result;
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(folderPath), 0, davPropertyNameSet);
if (responses.length == 0) {
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_FOLDER", folderPath);
}
DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK);
DavPropertyName davPropertyName = davPropertyNameSet.iterator().nextPropertyName();
result = getPropertyIfExists(properties, davPropertyName);
if (result == null) {
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_PROPERTY", davPropertyName);
}
return result;
}
/**
* Get current Exchange alias name from login name
*
* @return user name
*/
protected String getAliasFromLogin() {
// Exchange 2007 : userName is login without domain
String userName = poolKey.userName;
int index = userName.indexOf('\\');
if (index >= 0) {
userName = userName.substring(index + 1);
}
return userName;
}
/**
* Get current Exchange alias name from mailbox name
*
* @return user name
*/
protected String getAliasFromMailPath() {
if (mailPath == null) {
return null;
}
int index = mailPath.lastIndexOf('/', mailPath.length() - 2);
if (index >= 0 && mailPath.endsWith("/")) {
return mailPath.substring(index + 1, mailPath.length() - 1);
} else {
LOGGER.warn(new BundleMessage("EXCEPTION_INVALID_MAIL_PATH", mailPath));
return null;
}
}
public String getAliasFromMailboxDisplayName() {
if (mailPath == null) {
return null;
}
String displayName = null;
try {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(mailPath), 0, DISPLAY_NAME);
if (responses.length == 0) {
LOGGER.warn(new BundleMessage("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER"));
} else {
displayName = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "displayname", Namespace.getNamespace("DAV:"));
}
} catch (IOException e) {
LOGGER.warn(new BundleMessage("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER"));
}
return displayName;
}
public String buildCalendarPath(String principal, String folderName) throws IOException {
StringBuilder buffer = new StringBuilder();
if (principal != null && !alias.equals(principal) && !email.equals(principal)) {
int index = mailPath.lastIndexOf('/', mailPath.length() - 2);
if (index >= 0 && mailPath.endsWith("/")) {
buffer.append(mailPath.substring(0, index + 1)).append(principal).append('/');
} else {
throw new DavMailException("EXCEPTION_INVALID_MAIL_PATH", mailPath);
}
} else if (principal != null) {
buffer.append(mailPath);
}
if ("calendar".equals(folderName)) {
buffer.append(calendarUrl.substring(calendarUrl.lastIndexOf('/') + 1));
} else if ("inbox".equals(folderName)) {
buffer.append(inboxUrl.substring(inboxUrl.lastIndexOf('/') + 1));
} else if (folderName != null && folderName.length() > 0) {
buffer.append(folderName);
}
return buffer.toString();
}
/**
* Build base path for cmd commands (galfind, gallookup).
* This does not work with freebusy, which requires /public/
*
* @return cmd base path
*/
public String getCmdBasePath() {
if (mailPath == null) {
return "/public/";
} else {
return mailPath;
}
}
public String getEmail(String alias) {
String emailResult = null;
if (alias != null) {
GetMethod getMethod = null;
String path = null;
try {
path = getCmdBasePath() + "?Cmd=galfind&AN=" + URIUtil.encodeWithinQuery(alias);
getMethod = new GetMethod(path);
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_EMAIL", getMethod.getPath());
}
Map<String, Map<String, String>> results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "item", "AN");
Map<String, String> result = results.get(alias.toLowerCase());
if (result != null) {
emailResult = result.get("EM");
}
} catch (IOException e) {
LOGGER.debug("GET " + path + " failed: " + e + ' ' + e.getMessage());
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
}
}
}
return emailResult;
}
public void buildEmail(String hostName, String methodPath) {
// first try to get email from login name
alias = getAliasFromLogin();
email = getEmail(alias);
// failover: use mailbox name as alias
if (email == null) {
alias = getAliasFromMailPath();
email = getEmail(alias);
}
// another failover : get alias from mailPath display name
if (email == null) {
alias = getAliasFromMailboxDisplayName();
email = getEmail(alias);
}
if (email == null) {
// failover : get email from Exchange 2007 Options page
alias = getAliasFromOptions(methodPath);
email = getEmail(alias);
// failover: get email from options
if (alias != null && email == null) {
email = getEmailFromOptions(methodPath);
}
}
if (email == null) {
LOGGER.debug("Unable to get user email with alias " + getAliasFromLogin()
+ " or " + getAliasFromMailPath()
+ " or " + getAliasFromOptions(methodPath)
);
// last failover: build email from domain name and mailbox display name
StringBuilder buffer = new StringBuilder();
// most reliable alias
alias = getAliasFromMailboxDisplayName();
if (alias == null) {
alias = getAliasFromLogin();
}
if (alias != null) {
buffer.append(alias);
buffer.append('@');
int dotIndex = hostName.indexOf('.');
if (dotIndex >= 0) {
buffer.append(hostName.substring(dotIndex + 1));
}
}
email = buffer.toString();
}
}
protected String getAliasFromOptions(String path) {
String result = null;
// get user mail URL from html body
BufferedReader optionsPageReader = null;
GetMethod optionsMethod = new GetMethod(path + "?ae=Options&t=About");
try {
httpClient.executeMethod(optionsMethod);
optionsPageReader = new BufferedReader(new InputStreamReader(optionsMethod.getResponseBodyAsStream()));
String line;
// find mailbox full name
final String MAILBOX_BASE = "cn=recipients/cn=";
//noinspection StatementWithEmptyBody
while ((line = optionsPageReader.readLine()) != null && line.toLowerCase().indexOf(MAILBOX_BASE) == -1) {
}
if (line != null) {
int start = line.toLowerCase().indexOf(MAILBOX_BASE) + MAILBOX_BASE.length();
int end = line.indexOf('<', start);
result = line.substring(start, end);
}
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
} finally {
if (optionsPageReader != null) {
try {
optionsPageReader.close();
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
}
}
optionsMethod.releaseConnection();
}
return result;
}
protected String getEmailFromOptions(String path) {
String result = null;
// get user mail URL from html body
BufferedReader optionsPageReader = null;
GetMethod optionsMethod = new GetMethod(path + "?ae=Options&t=About");
try {
httpClient.executeMethod(optionsMethod);
optionsPageReader = new BufferedReader(new InputStreamReader(optionsMethod.getResponseBodyAsStream()));
String line;
// find email
//noinspection StatementWithEmptyBody
while ((line = optionsPageReader.readLine()) != null
&& (line.indexOf('[') == -1
|| line.indexOf('@') == -1
|| line.indexOf(']') == -1)) {
}
if (line != null) {
int start = line.toLowerCase().indexOf('[') + 1;
int end = line.indexOf(']', start);
result = line.substring(start, end);
}
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
} finally {
if (optionsPageReader != null) {
try {
optionsPageReader.close();
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
}
}
optionsMethod.releaseConnection();
}
return result;
}
/**
* Get current user email
*
* @return user email
*/
public String getEmail() {
return email;
}
/**
* Get current user alias
*
* @return user email
*/
public String getAlias() {
return alias;
}
/**
* Search users in global address book
*
* @param searchAttribute exchange search attribute
* @param searchValue search value
* @return List of users
* @throws IOException on error
*/
public Map<String, Map<String, String>> galFind(String searchAttribute, String searchValue) throws IOException {
Map<String, Map<String, String>> results;
GetMethod getMethod = new GetMethod(URIUtil.encodePathQuery(getCmdBasePath() + "?Cmd=galfind&" + searchAttribute + '=' + searchValue));
try {
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new DavMailException("EXCEPTION_UNABLE_TO_FIND_USERS", status, getMethod.getURI());
}
results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "item", "AN");
} finally {
getMethod.releaseConnection();
}
LOGGER.debug("galfind " + searchAttribute + '=' + searchValue + ": " + results.size() + " result(s)");
return results;
}
public void galLookup(Map<String, String> person) {
if (!disableGalLookup) {
GetMethod getMethod = null;
try {
getMethod = new GetMethod(URIUtil.encodePathQuery(getCmdBasePath() + "?Cmd=gallookup&ADDR=" + person.get("EM")));
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new DavMailException("EXCEPTION_UNABLE_TO_FIND_USERS", status, getMethod.getURI());
}
Map<String, Map<String, String>> results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "person", "alias");
// add detailed information
if (!results.isEmpty()) {
Map<String, String> fullperson = results.get(person.get("AN").toLowerCase());
for (Map.Entry<String, String> entry : fullperson.entrySet()) {
person.put(entry.getKey(), entry.getValue());
}
}
} catch (IOException e) {
LOGGER.warn("Unable to gallookup person: " + person + ", disable GalLookup");
disableGalLookup = true;
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
}
}
}
}
public FreeBusy getFreebusy(String attendee, Map<String, String> valueMap) throws IOException {
String startDateValue = valueMap.get("DTSTART");
String endDateValue = valueMap.get("DTEND");
if (attendee.startsWith("mailto:")) {
attendee = attendee.substring("mailto:".length());
}
SimpleDateFormat exchangeZuluDateFormat = getExchangeZuluDateFormat();
SimpleDateFormat icalDateFormat = getZuluDateFormat();
String url;
Date startDate;
Date endDate;
try {
if (startDateValue.length() == 8) {
startDate = parseDate(startDateValue);
} else {
startDate = icalDateFormat.parse(startDateValue);
}
if (endDateValue.length() == 8) {
endDate = parseDate(endDateValue);
} else {
endDate = icalDateFormat.parse(endDateValue);
}
url = "/public/?cmd=freebusy" +
"&start=" + exchangeZuluDateFormat.format(startDate) +
"&end=" + exchangeZuluDateFormat.format(endDate) +
"&interval=" + FREE_BUSY_INTERVAL +
"&u=SMTP:" + attendee;
} catch (ParseException e) {
throw new DavMailException("EXCEPTION_INVALID_DATES", e.getMessage());
}
FreeBusy freeBusy = null;
GetMethod getMethod = new GetMethod(url);
getMethod.setRequestHeader("Content-Type", "text/xml");
try {
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_FREEBUSY", getMethod.getPath(),
status, getMethod.getResponseBodyAsString());
}
String body = getMethod.getResponseBodyAsString();
int startIndex = body.lastIndexOf("<a:fbdata>");
int endIndex = body.lastIndexOf("</a:fbdata>");
if (startIndex >= 0 && endIndex >= 0) {
String fbdata = body.substring(startIndex + "<a:fbdata>".length(), endIndex);
freeBusy = new FreeBusy(icalDateFormat, startDate, fbdata);
}
} finally {
getMethod.releaseConnection();
}
if (freeBusy != null && freeBusy.knownAttendee) {
return freeBusy;
} else {
return null;
}
}
/**
* Exchange to iCalendar Free/Busy parser.
* Free time returns 0, Tentative returns 1, Busy returns 2, and Out of Office (OOF) returns 3
*/
public static final class FreeBusy {
final SimpleDateFormat icalParser;
boolean knownAttendee = true;
static final HashMap<Character, String> FBTYPES = new HashMap<Character, String>();
static {
FBTYPES.put('1', "BUSY-TENTATIVE");
FBTYPES.put('2', "BUSY");
FBTYPES.put('3', "BUSY-UNAVAILABLE");
}
final HashMap<String, StringBuilder> busyMap = new HashMap<String, StringBuilder>();
StringBuilder getBusyBuffer(char type) {
String fbType = FBTYPES.get(Character.valueOf(type));
StringBuilder buffer = busyMap.get(fbType);
if (buffer == null) {
buffer = new StringBuilder();
busyMap.put(fbType, buffer);
}
return buffer;
}
void startBusy(char type, Calendar currentCal) {
if (type == '4') {
knownAttendee = false;
} else if (type != '0') {
StringBuilder busyBuffer = getBusyBuffer(type);
if (busyBuffer.length() > 0) {
busyBuffer.append(',');
}
busyBuffer.append(icalParser.format(currentCal.getTime()));
}
}
void endBusy(char type, Calendar currentCal) {
if (type != '0' && type != '4') {
getBusyBuffer(type).append('/').append(icalParser.format(currentCal.getTime()));
}
}
FreeBusy(SimpleDateFormat icalParser, Date startDate, String fbdata) {
this.icalParser = icalParser;
if (fbdata.length() > 0) {
Calendar currentCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentCal.setTime(startDate);
startBusy(fbdata.charAt(0), currentCal);
for (int i = 1; i < fbdata.length() && knownAttendee; i++) {
currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
char previousState = fbdata.charAt(i - 1);
char currentState = fbdata.charAt(i);
if (previousState != currentState) {
endBusy(previousState, currentCal);
startBusy(currentState, currentCal);
}
}
currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
endBusy(fbdata.charAt(fbdata.length() - 1), currentCal);
}
}
public void appendTo(StringBuilder buffer) {
for (Map.Entry<String, StringBuilder> entry : busyMap.entrySet()) {
buffer.append("FREEBUSY;FBTYPE=").append(entry.getKey())
.append(':').append(entry.getValue()).append((char) 13).append((char) 10);
}
}
}
}
| false | true | protected String fixICS(String icsBody, boolean fromServer) throws IOException {
// first pass : detect
class AllDayState {
boolean isAllDay;
boolean hasCdoAllDay;
boolean isCdoAllDay;
}
// Convert event class from and to iCal
// See https://trac.calendarserver.org/browser/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt
boolean isAppleiCal = false;
boolean hasOrganizer = false;
boolean hasAttendee = false;
boolean invalidTimezoneId = false;
String eventClass = null;
List<AllDayState> allDayStates = new ArrayList<AllDayState>();
AllDayState currentAllDayState = new AllDayState();
BufferedReader reader = null;
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
int index = line.indexOf(':');
if (index >= 0) {
String key = line.substring(0, index);
String value = line.substring(index + 1);
if ("DTSTART;VALUE=DATE".equals(key)) {
currentAllDayState.isAllDay = true;
} else if ("X-MICROSOFT-CDO-ALLDAYEVENT".equals(key)) {
currentAllDayState.hasCdoAllDay = true;
currentAllDayState.isCdoAllDay = "TRUE".equals(value);
} else if ("END:VEVENT".equals(line)) {
allDayStates.add(currentAllDayState);
currentAllDayState = new AllDayState();
} else if ("PRODID".equals(key) && line.contains("iCal")) {
isAppleiCal = true;
} else if (isAppleiCal && "X-CALENDARSERVER-ACCESS".equals(key)) {
eventClass = value;
} else if (!isAppleiCal && "CLASS".equals(key)) {
eventClass = value;
} else if (key.startsWith("ATTENDEE")) {
hasAttendee = true;
} else if (key.startsWith("ORGANIZER")) {
hasOrganizer = true;
} else if (key.startsWith("DTSTART;TZID=\"")) {
invalidTimezoneId = true;
}
}
}
} finally {
if (reader != null) {
reader.close();
}
}
// second pass : fix
int count = 0;
ICSBufferedWriter result = new ICSBufferedWriter();
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
// remove empty properties
if ("CLASS:".equals(line) || "LOCATION:".equals(line)) {
continue;
}
// fix invalid exchange timezoneid
if (invalidTimezoneId && line.indexOf(";TZID=\"") >= 0) {
line = fixTimezoneId(line);
}
if (!fromServer && currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE";
} else if (!fromServer && "END:VEVENT".equals(line) && currentAllDayState.isAllDay && !currentAllDayState.hasCdoAllDay) {
result.writeLine("X-MICROSOFT-CDO-ALLDAYEVENT:TRUE");
} else if (!fromServer && !currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE";
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTSTART") && !line.startsWith("DTSTART;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTEND") && !line.startsWith("DTEND;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (line.startsWith("TZID:") && invalidTimezoneId) {
line = "TZID:TimezoneId";
} else if ("BEGIN:VEVENT".equals(line)) {
currentAllDayState = allDayStates.get(count++);
} else if (line.startsWith("X-CALENDARSERVER-ACCESS:")) {
if (!isAppleiCal) {
continue;
} else {
if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:PRIVATE");
} else if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:CONFIDENTIAL");
} else {
result.writeLine("CLASS:" + eventClass);
}
}
} else if (line.startsWith("EXDATE;TZID=") || line.startsWith("EXDATE:")) {
// Apple iCal doesn't support EXDATE with multiple exceptions
// on one line. Split into multiple EXDATE entries (which is
// also legal according to the caldav standard).
splitExDate(result, line);
continue;
} else if (line.startsWith("X-ENTOURAGE_UUID:")) {
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
continue;
} else if (line.startsWith("CLASS:")) {
if (isAppleiCal) {
continue;
} else {
if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:CONFIDENTIAL");
} else if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:PRIVATE");
} else {
result.writeLine("X-CALENDARSERVER-ACCESS:" + eventClass);
}
}
// remove organizer line if event has no attendees for iPhone
} else if (fromServer && line.startsWith("ORGANIZER") && !hasAttendee) {
continue;
// add organizer line to all events created in Exchange for active sync
} else if (!fromServer && "END:VEVENT".equals(line) && !hasOrganizer) {
result.writeLine("ORGANIZER:MAILTO:" + email);
}
result.writeLine(line);
}
} finally {
reader.close();
}
return result.toString();
}
| protected String fixICS(String icsBody, boolean fromServer) throws IOException {
// first pass : detect
class AllDayState {
boolean isAllDay;
boolean hasCdoAllDay;
boolean isCdoAllDay;
}
// Convert event class from and to iCal
// See https://trac.calendarserver.org/browser/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt
boolean isAppleiCal = false;
boolean hasOrganizer = false;
boolean invalidTimezoneId = false;
String eventClass = null;
List<AllDayState> allDayStates = new ArrayList<AllDayState>();
AllDayState currentAllDayState = new AllDayState();
BufferedReader reader = null;
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
int index = line.indexOf(':');
if (index >= 0) {
String key = line.substring(0, index);
String value = line.substring(index + 1);
if ("DTSTART;VALUE=DATE".equals(key)) {
currentAllDayState.isAllDay = true;
} else if ("X-MICROSOFT-CDO-ALLDAYEVENT".equals(key)) {
currentAllDayState.hasCdoAllDay = true;
currentAllDayState.isCdoAllDay = "TRUE".equals(value);
} else if ("END:VEVENT".equals(line)) {
allDayStates.add(currentAllDayState);
currentAllDayState = new AllDayState();
} else if ("PRODID".equals(key) && line.contains("iCal")) {
isAppleiCal = true;
} else if (isAppleiCal && "X-CALENDARSERVER-ACCESS".equals(key)) {
eventClass = value;
} else if (!isAppleiCal && "CLASS".equals(key)) {
eventClass = value;
} else if (key.startsWith("ORGANIZER")) {
hasOrganizer = true;
} else if (key.startsWith("DTSTART;TZID=\"")) {
invalidTimezoneId = true;
}
}
}
} finally {
if (reader != null) {
reader.close();
}
}
// second pass : fix
int count = 0;
ICSBufferedWriter result = new ICSBufferedWriter();
try {
reader = new ICSBufferedReader(new StringReader(icsBody));
String line;
while ((line = reader.readLine()) != null) {
// remove empty properties
if ("CLASS:".equals(line) || "LOCATION:".equals(line)) {
continue;
}
// fix invalid exchange timezoneid
if (invalidTimezoneId && line.indexOf(";TZID=\"") >= 0) {
line = fixTimezoneId(line);
}
if (!fromServer && currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE";
} else if (!fromServer && "END:VEVENT".equals(line) && currentAllDayState.isAllDay && !currentAllDayState.hasCdoAllDay) {
result.writeLine("X-MICROSOFT-CDO-ALLDAYEVENT:TRUE");
} else if (!fromServer && !currentAllDayState.isAllDay && "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE".equals(line)) {
line = "X-MICROSOFT-CDO-ALLDAYEVENT:FALSE";
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTSTART") && !line.startsWith("DTSTART;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (fromServer && currentAllDayState.isCdoAllDay && line.startsWith("DTEND") && !line.startsWith("DTEND;VALUE=DATE")) {
line = getAllDayLine(line);
} else if (line.startsWith("TZID:") && invalidTimezoneId) {
line = "TZID:TimezoneId";
} else if ("BEGIN:VEVENT".equals(line)) {
currentAllDayState = allDayStates.get(count++);
} else if (line.startsWith("X-CALENDARSERVER-ACCESS:")) {
if (!isAppleiCal) {
continue;
} else {
if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:PRIVATE");
} else if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("CLASS:CONFIDENTIAL");
} else {
result.writeLine("CLASS:" + eventClass);
}
}
} else if (line.startsWith("EXDATE;TZID=") || line.startsWith("EXDATE:")) {
// Apple iCal doesn't support EXDATE with multiple exceptions
// on one line. Split into multiple EXDATE entries (which is
// also legal according to the caldav standard).
splitExDate(result, line);
continue;
} else if (line.startsWith("X-ENTOURAGE_UUID:")) {
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
continue;
} else if (line.startsWith("CLASS:")) {
if (isAppleiCal) {
continue;
} else {
if ("PRIVATE".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:CONFIDENTIAL");
} else if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
result.writeLine("X-CALENDARSERVER-ACCESS:PRIVATE");
} else {
result.writeLine("X-CALENDARSERVER-ACCESS:" + eventClass);
}
}
// remove organizer line if user is organizer for iPhone
} else if (fromServer && line.startsWith("ORGANIZER") && line.toLowerCase().endsWith(email)) {
continue;
// add organizer line to all events created in Exchange for active sync
} else if (!fromServer && "END:VEVENT".equals(line) && !hasOrganizer) {
result.writeLine("ORGANIZER:MAILTO:" + email);
}
result.writeLine(line);
}
} finally {
reader.close();
}
return result.toString();
}
|
diff --git a/DesktopBranding/src/org/gephi/branding/desktop/multilingual/LanguageAction.java b/DesktopBranding/src/org/gephi/branding/desktop/multilingual/LanguageAction.java
index da6165461..bdeb2a022 100644
--- a/DesktopBranding/src/org/gephi/branding/desktop/multilingual/LanguageAction.java
+++ b/DesktopBranding/src/org/gephi/branding/desktop/multilingual/LanguageAction.java
@@ -1,164 +1,164 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Gephi 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.branding.desktop.multilingual;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.LifecycleManager;
import org.openide.util.Exceptions;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.actions.CallableSystemAction;
public final class LanguageAction extends CallableSystemAction {
private static final String APPNAME = "gephi";
public enum Language {
EN_US("en", "English"),
FR_FR("fr", "Français"),
ES_ES("es", "Español");
private String locale;
private String name;
private Language(String locale, String name) {
this.locale = locale;
this.name = name;
}
public String getName() {
return name;
}
public String getLocale() {
return locale;
}
}
@Override
public void performAction() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getName() {
return NbBundle.getMessage(LanguageAction.class, "CTL_LanguageAction");
}
@Override
public HelpCtx getHelpCtx() {
return null;
}
@Override
public JMenuItem getMenuPresenter() {
JMenu menu = new JMenu(NbBundle.getMessage(LanguageAction.class, "CTL_LanguageAction"));
for (final Language lang : Language.values()) {
JMenuItem menuItem = new JMenuItem(new AbstractAction(lang.getName()) {
public void actionPerformed(ActionEvent e) {
String msg = NbBundle.getMessage(LanguageAction.class, "ChangeLang.Confirm.message" + (Utilities.isMac() ? ".mac" : ""));
String title = NbBundle.getMessage(LanguageAction.class, "ChangeLang.Confirm.title");
DialogDescriptor.Confirmation dd = new DialogDescriptor.Confirmation(msg, title, DialogDescriptor.YES_NO_OPTION);
if (DialogDisplayer.getDefault().notify(dd).equals(DialogDescriptor.YES_OPTION)) {
setLanguage(lang);
}
}
});
//Flag icons from http://www.famfamfam.com
Icon icon = ImageUtilities.loadImageIcon("org/gephi/branding/desktop/multilingual/resources/" + lang.getLocale() + ".png", false);
if (icon != null) {
menuItem.setIcon(icon);
}
menu.add(menuItem);
}
return menu;
}
private void setLanguage(Language language) {
String homePath;
- if (Utilities.isMac()) {
+ if (Utilities.isMac() || Utilities.isUnix()) {
homePath = System.getProperty("netbeans.home");
} else {
homePath = System.getProperty("user.dir");
}
File etc = new File(homePath, "etc");
if (!etc.exists()) {
File base = new File(homePath).getParentFile();
etc = new File(base, "etc");
}
File confFile = new File(etc, APPNAME+".conf");
try {
StringBuilder outputBuilder = new StringBuilder();
String match = "-J-Duser.language=";
int langLength = 2;
//In
BufferedReader reader = new BufferedReader(new FileReader(confFile));
String strLine;
while ((strLine = reader.readLine()) != null) {
int i = 0;
if ((i = strLine.indexOf(match)) != -1) {
String locale = strLine.substring(i + match.length());
locale = locale.substring(0, langLength);
String before = strLine.substring(0, i + match.length());
String after = strLine.substring(i + match.length() + langLength);
outputBuilder.append(before);
outputBuilder.append(language.getLocale());
outputBuilder.append(after);
} else {
outputBuilder.append(strLine);
}
outputBuilder.append("\n");
}
reader.close();
//Out
FileWriter writer = new FileWriter(confFile);
writer.write(outputBuilder.toString());
writer.close();
//Restart
if (!Utilities.isMac()) {
//On Mac the change is applied only if restarted manually
LifecycleManager.getDefault().markForRestart();
}
LifecycleManager.getDefault().exit();
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
| true | true | private void setLanguage(Language language) {
String homePath;
if (Utilities.isMac()) {
homePath = System.getProperty("netbeans.home");
} else {
homePath = System.getProperty("user.dir");
}
File etc = new File(homePath, "etc");
if (!etc.exists()) {
File base = new File(homePath).getParentFile();
etc = new File(base, "etc");
}
File confFile = new File(etc, APPNAME+".conf");
try {
StringBuilder outputBuilder = new StringBuilder();
String match = "-J-Duser.language=";
int langLength = 2;
//In
BufferedReader reader = new BufferedReader(new FileReader(confFile));
String strLine;
while ((strLine = reader.readLine()) != null) {
int i = 0;
if ((i = strLine.indexOf(match)) != -1) {
String locale = strLine.substring(i + match.length());
locale = locale.substring(0, langLength);
String before = strLine.substring(0, i + match.length());
String after = strLine.substring(i + match.length() + langLength);
outputBuilder.append(before);
outputBuilder.append(language.getLocale());
outputBuilder.append(after);
} else {
outputBuilder.append(strLine);
}
outputBuilder.append("\n");
}
reader.close();
//Out
FileWriter writer = new FileWriter(confFile);
writer.write(outputBuilder.toString());
writer.close();
//Restart
if (!Utilities.isMac()) {
//On Mac the change is applied only if restarted manually
LifecycleManager.getDefault().markForRestart();
}
LifecycleManager.getDefault().exit();
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
| private void setLanguage(Language language) {
String homePath;
if (Utilities.isMac() || Utilities.isUnix()) {
homePath = System.getProperty("netbeans.home");
} else {
homePath = System.getProperty("user.dir");
}
File etc = new File(homePath, "etc");
if (!etc.exists()) {
File base = new File(homePath).getParentFile();
etc = new File(base, "etc");
}
File confFile = new File(etc, APPNAME+".conf");
try {
StringBuilder outputBuilder = new StringBuilder();
String match = "-J-Duser.language=";
int langLength = 2;
//In
BufferedReader reader = new BufferedReader(new FileReader(confFile));
String strLine;
while ((strLine = reader.readLine()) != null) {
int i = 0;
if ((i = strLine.indexOf(match)) != -1) {
String locale = strLine.substring(i + match.length());
locale = locale.substring(0, langLength);
String before = strLine.substring(0, i + match.length());
String after = strLine.substring(i + match.length() + langLength);
outputBuilder.append(before);
outputBuilder.append(language.getLocale());
outputBuilder.append(after);
} else {
outputBuilder.append(strLine);
}
outputBuilder.append("\n");
}
reader.close();
//Out
FileWriter writer = new FileWriter(confFile);
writer.write(outputBuilder.toString());
writer.close();
//Restart
if (!Utilities.isMac()) {
//On Mac the change is applied only if restarted manually
LifecycleManager.getDefault().markForRestart();
}
LifecycleManager.getDefault().exit();
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
|
diff --git a/Chat/src/ServerMainLoop.java b/Chat/src/ServerMainLoop.java
index 2f75ef2..6d7b2ea 100644
--- a/Chat/src/ServerMainLoop.java
+++ b/Chat/src/ServerMainLoop.java
@@ -1,97 +1,97 @@
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import Communications.*;
import Server.ServerThread;
import Utilities.InputReader;
public class ServerMainLoop {
static TCP tcp=null;
static boolean error=false;
static boolean skip=false;
static boolean done=false;
static InputReader ir = new InputReader();
public static InetAddress ip=null;
static ServerSocket serverSocket=null;
static Socket socket=null;
static Thread t=null;
public static void main(String[] args){
try {
InetAddress address = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback
// interface
Enumeration<InetAddress> addresses = networkInterface
.getInetAddresses();
while (addresses.hasMoreElements()) {
address = addresses.nextElement();
if (!address.getHostAddress().contains("192.168.224"))
continue;
break;
}
if (address != null && address.toString().contains("192.168.224")) {
break;
}
}
ip=address;
}catch(Exception e){
System.out.println("Unable to launch server");
error=true;
}
if(!error){
try{
serverSocket=new ServerSocket(12345, 0, ip);
serverSocket.setSoTimeout(500);
}
catch(Exception e){}
}
Thread irThread=new Thread(ir);
irThread.start();
while(!done && !error){
String input=ir.getSubmitted();
if(input.startsWith(":quit")){
done=true;
System.out.println("Quitting");
continue;
}
try {
socket = serverSocket.accept();
skip = false;
} catch (Exception e) {
skip = true;
}
- if (!error) {
+ if (!skip) {
ServerThread s=new ServerThread();
tcp=new TCP();
tcp.initiator = false;
tcp.socket = socket;
socket=null;
tcp.active = true;
tcp.tr.setSocket(socket);
t = new Thread(tcp.tr);
t.start();
s.setTCP(tcp);
new Thread(s).start();
}
try {
Thread.sleep(10);
} catch (Exception e) {}
}
System.out.println("Hit enter to finish quitting");
tcp.stop();
ir.stop();
System.out.println("If quitting does not occur please make sure there are no connections to the server");
}
}
| true | true | public static void main(String[] args){
try {
InetAddress address = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback
// interface
Enumeration<InetAddress> addresses = networkInterface
.getInetAddresses();
while (addresses.hasMoreElements()) {
address = addresses.nextElement();
if (!address.getHostAddress().contains("192.168.224"))
continue;
break;
}
if (address != null && address.toString().contains("192.168.224")) {
break;
}
}
ip=address;
}catch(Exception e){
System.out.println("Unable to launch server");
error=true;
}
if(!error){
try{
serverSocket=new ServerSocket(12345, 0, ip);
serverSocket.setSoTimeout(500);
}
catch(Exception e){}
}
Thread irThread=new Thread(ir);
irThread.start();
while(!done && !error){
String input=ir.getSubmitted();
if(input.startsWith(":quit")){
done=true;
System.out.println("Quitting");
continue;
}
try {
socket = serverSocket.accept();
skip = false;
} catch (Exception e) {
skip = true;
}
if (!error) {
ServerThread s=new ServerThread();
tcp=new TCP();
tcp.initiator = false;
tcp.socket = socket;
socket=null;
tcp.active = true;
tcp.tr.setSocket(socket);
t = new Thread(tcp.tr);
t.start();
s.setTCP(tcp);
new Thread(s).start();
}
try {
Thread.sleep(10);
} catch (Exception e) {}
}
System.out.println("Hit enter to finish quitting");
tcp.stop();
ir.stop();
System.out.println("If quitting does not occur please make sure there are no connections to the server");
}
| public static void main(String[] args){
try {
InetAddress address = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback
// interface
Enumeration<InetAddress> addresses = networkInterface
.getInetAddresses();
while (addresses.hasMoreElements()) {
address = addresses.nextElement();
if (!address.getHostAddress().contains("192.168.224"))
continue;
break;
}
if (address != null && address.toString().contains("192.168.224")) {
break;
}
}
ip=address;
}catch(Exception e){
System.out.println("Unable to launch server");
error=true;
}
if(!error){
try{
serverSocket=new ServerSocket(12345, 0, ip);
serverSocket.setSoTimeout(500);
}
catch(Exception e){}
}
Thread irThread=new Thread(ir);
irThread.start();
while(!done && !error){
String input=ir.getSubmitted();
if(input.startsWith(":quit")){
done=true;
System.out.println("Quitting");
continue;
}
try {
socket = serverSocket.accept();
skip = false;
} catch (Exception e) {
skip = true;
}
if (!skip) {
ServerThread s=new ServerThread();
tcp=new TCP();
tcp.initiator = false;
tcp.socket = socket;
socket=null;
tcp.active = true;
tcp.tr.setSocket(socket);
t = new Thread(tcp.tr);
t.start();
s.setTCP(tcp);
new Thread(s).start();
}
try {
Thread.sleep(10);
} catch (Exception e) {}
}
System.out.println("Hit enter to finish quitting");
tcp.stop();
ir.stop();
System.out.println("If quitting does not occur please make sure there are no connections to the server");
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/SplitLongWays.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/SplitLongWays.java
index cba3fc8b..0f8bda22 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/SplitLongWays.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/SplitLongWays.java
@@ -1,80 +1,81 @@
/**
* This file is part of OSM2GpsMid
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* Copyright (C) 2007 Harald Mueller
*
*/
package de.ueller.osmToGpsMid;
import java.util.LinkedList;
import de.ueller.osmToGpsMid.model.Bounds;
import de.ueller.osmToGpsMid.model.Way;
public class SplitLongWays {
OsmParser parser;
LinkedList<Way> added=new LinkedList<Way>();
public SplitLongWays(OsmParser parser) {
super();
int count = 0;
this.parser = parser;
for (Way way : parser.getWays()) {
testAndSplit(way);
count++;
if (count % 500 == 0) {
System.err.println("Tested " + count
+ " ways for splitting");
}
}
for (Way w : added) {
parser.addWay(w);
}
count = 0;
for (Way way : parser.getWays()) {
if (way.isArea()) {
if (way.triangles == null) {
way.triangulate();
}
if (way.triangles != null && way.triangles.size() > 0) {
+ count++;
if (count % 500 == 0) {
System.err.println("Did " + count
+ " recreatePath()s");
}
way.recreatePathAvoidDuplicates();
}
}
}
added=null;
}
private void testAndSplit(Way way) {
// if (nonCont && way.getSegmentCount() == 1) return;
// if w way is an Area, it's now also splitable
// if ( way.isArea()) return;
// TODO: Length of one longitude degree gets smallen when aproaching the poles.
Bounds b=way.getBounds();
if ((b.maxLat-b.minLat) > 0.09f
|| (b.maxLon-b.minLon) > 0.09f ){
Way newWay=way.split();
if (newWay != null){
added.add(newWay);
// if (way.isArea()){
// DebugViewer v=DebugViewer.getInstanz(new ArrayList<Triangle>(way.triangles));
// v.alt=new ArrayList<Triangle>(newWay.triangles);
// v.recalcView();
// v.repaint();
// }
testAndSplit(way);
testAndSplit(newWay);
}
}
}
}
| true | true | public SplitLongWays(OsmParser parser) {
super();
int count = 0;
this.parser = parser;
for (Way way : parser.getWays()) {
testAndSplit(way);
count++;
if (count % 500 == 0) {
System.err.println("Tested " + count
+ " ways for splitting");
}
}
for (Way w : added) {
parser.addWay(w);
}
count = 0;
for (Way way : parser.getWays()) {
if (way.isArea()) {
if (way.triangles == null) {
way.triangulate();
}
if (way.triangles != null && way.triangles.size() > 0) {
if (count % 500 == 0) {
System.err.println("Did " + count
+ " recreatePath()s");
}
way.recreatePathAvoidDuplicates();
}
}
}
added=null;
}
| public SplitLongWays(OsmParser parser) {
super();
int count = 0;
this.parser = parser;
for (Way way : parser.getWays()) {
testAndSplit(way);
count++;
if (count % 500 == 0) {
System.err.println("Tested " + count
+ " ways for splitting");
}
}
for (Way w : added) {
parser.addWay(w);
}
count = 0;
for (Way way : parser.getWays()) {
if (way.isArea()) {
if (way.triangles == null) {
way.triangulate();
}
if (way.triangles != null && way.triangles.size() > 0) {
count++;
if (count % 500 == 0) {
System.err.println("Did " + count
+ " recreatePath()s");
}
way.recreatePathAvoidDuplicates();
}
}
}
added=null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.