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/eclipse/net.vtst.eclipse.easyxtext.ui/src/net/vtst/eclipse/easyxtext/ui/launching/attributes/WorkspaceFileLaunchAttribute.java b/src/eclipse/net.vtst.eclipse.easyxtext.ui/src/net/vtst/eclipse/easyxtext/ui/launching/attributes/WorkspaceFileLaunchAttribute.java
index 9ec770d..1f2367f 100644
--- a/src/eclipse/net.vtst.eclipse.easyxtext.ui/src/net/vtst/eclipse/easyxtext/ui/launching/attributes/WorkspaceFileLaunchAttribute.java
+++ b/src/eclipse/net.vtst.eclipse.easyxtext.ui/src/net/vtst/eclipse/easyxtext/ui/launching/attributes/WorkspaceFileLaunchAttribute.java
@@ -1,159 +1,167 @@
// EasyXtext
// (c) Vincent Simonet, 2011
package net.vtst.eclipse.easyxtext.ui.launching.attributes;
import java.util.regex.Pattern;
import net.vtst.eclipse.easyxtext.ui.launching.tab.IEasyLaunchConfigurationTab;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.internal.ui.SWTFactory;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* Launch attribute which designates a file in the workspace. It is internally stored as
* a string, and is represented in launch configuration by a text box with a "browse" button
* opening a file picker. Files in the file picker are filtered by a pattern and/or a content type.
* @author Vincent Simonet
*
*/
public class WorkspaceFileLaunchAttribute extends AbstractStringLaunchAttribute {
private Pattern pattern; // May be null
private IContentType contentType; // May be null
public WorkspaceFileLaunchAttribute(String defaultValue, Pattern pattern, IContentType contentType) {
super(defaultValue);
this.pattern = pattern;
this.contentType = contentType;
}
public WorkspaceFileLaunchAttribute(String defaultValue, Pattern pattern) {
this(defaultValue, pattern, null);
}
public WorkspaceFileLaunchAttribute(String defaultValue, IContentType contentType) {
this(defaultValue, null, contentType);
}
public Control createControl(IEasyLaunchConfigurationTab tab, Composite parent, int hspan) {
return new Control(parent, hspan, tab);
}
public IFile getFileValue(ILaunchConfiguration config) {
String value = getValue(config);
try {
return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(value));
} catch (IllegalArgumentException exn) {
return null;
}
}
public void setFileValue(ILaunchConfigurationWorkingCopy config, IFile selectedFile) {
setValue(config, selectedFile.getFullPath().toString());
}
public class Control extends AbstractLaunchAttribute<String>.Control {
private Text text;
private Button button;
private String labelKey = getLabelKey();
@SuppressWarnings("restriction")
public Control(Composite parent, int hspan, IEasyLaunchConfigurationTab tab) {
super(tab, parent, hspan);
if (hspan < 3) return;
addWidget(SWTFactory.createLabel(parent, tab.getString(labelKey), 1));
text = SWTFactory.createSingleText(parent, hspan - 2);
text.addModifyListener(tab.getUpdateListener());
addWidget(text);
button = SWTFactory.createPushButton(parent, tab.getString(labelKey + "_browse"), null);
addWidget(button);
button.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent arg0) {
selectFile();
}
public void widgetDefaultSelected(SelectionEvent arg0) {}
});
tab.registerControl(this);
}
private void selectFile() {
// See http://eclipse-tips.com/how-to-guides/5-selection-dialogs-in-eclipse
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
null,
new WorkbenchLabelProvider(),
new BaseWorkbenchContentProvider());
dialog.setAllowMultiple(false);
dialog.setTitle(tab.getString(labelKey + "_title"));
dialog.setMessage(tab.getString(labelKey + "_message"));
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parent, Object element) {
if (element instanceof IFile) {
IFile file = (IFile) element;
if (pattern != null && pattern.matcher(file.getName()).matches()) return true;
- try { if (contentType != null && file.getContentDescription().getContentType().isKindOf(contentType)) return true; }
+ try {
+ if (file.getContentDescription() != null) {
+ IContentType fileContentType = file.getContentDescription().getContentType();
+ if (contentType != null &&
+ fileContentType != null &&
+ fileContentType.isKindOf(contentType))
+ return true;
+ }
+ }
catch (CoreException e) {}
return false;
} else {
return true;
}
}});
try {
IPath path = new Path(text.getText());
dialog.setInitialSelection(ResourcesPlugin.getWorkspace().getRoot().getFile(path));
} catch (IllegalArgumentException exn) {} // Raised by new Path(...)
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] result) {
if (result.length != 1 ||
!(result[0] instanceof IFile)) {
return new Status(IStatus.ERROR, WorkspaceFileLaunchAttribute.class.getName(), tab.getString(labelKey + "_error"));
}
return new Status(IStatus.OK, WorkspaceFileLaunchAttribute.class.getName(), "");
}});
dialog.open();
Object[] result = dialog.getResult();
if (result == null || result.length != 1) return;
if (!(result[0] instanceof IFile)) return;
IFile selectedFile = (IFile) result[0];
text.setText(selectedFile.getFullPath().toString());
}
public String getControlValue() {
return text.getText();
}
public void setControlValue(String value) {
text.setText(value);
}
public void addModifyListener(ModifyListener listener) {
text.addModifyListener(listener);
}
}
}
| true | true | private void selectFile() {
// See http://eclipse-tips.com/how-to-guides/5-selection-dialogs-in-eclipse
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
null,
new WorkbenchLabelProvider(),
new BaseWorkbenchContentProvider());
dialog.setAllowMultiple(false);
dialog.setTitle(tab.getString(labelKey + "_title"));
dialog.setMessage(tab.getString(labelKey + "_message"));
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parent, Object element) {
if (element instanceof IFile) {
IFile file = (IFile) element;
if (pattern != null && pattern.matcher(file.getName()).matches()) return true;
try { if (contentType != null && file.getContentDescription().getContentType().isKindOf(contentType)) return true; }
catch (CoreException e) {}
return false;
} else {
return true;
}
}});
try {
IPath path = new Path(text.getText());
dialog.setInitialSelection(ResourcesPlugin.getWorkspace().getRoot().getFile(path));
} catch (IllegalArgumentException exn) {} // Raised by new Path(...)
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] result) {
if (result.length != 1 ||
!(result[0] instanceof IFile)) {
return new Status(IStatus.ERROR, WorkspaceFileLaunchAttribute.class.getName(), tab.getString(labelKey + "_error"));
}
return new Status(IStatus.OK, WorkspaceFileLaunchAttribute.class.getName(), "");
}});
dialog.open();
Object[] result = dialog.getResult();
if (result == null || result.length != 1) return;
if (!(result[0] instanceof IFile)) return;
IFile selectedFile = (IFile) result[0];
text.setText(selectedFile.getFullPath().toString());
}
| private void selectFile() {
// See http://eclipse-tips.com/how-to-guides/5-selection-dialogs-in-eclipse
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
null,
new WorkbenchLabelProvider(),
new BaseWorkbenchContentProvider());
dialog.setAllowMultiple(false);
dialog.setTitle(tab.getString(labelKey + "_title"));
dialog.setMessage(tab.getString(labelKey + "_message"));
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parent, Object element) {
if (element instanceof IFile) {
IFile file = (IFile) element;
if (pattern != null && pattern.matcher(file.getName()).matches()) return true;
try {
if (file.getContentDescription() != null) {
IContentType fileContentType = file.getContentDescription().getContentType();
if (contentType != null &&
fileContentType != null &&
fileContentType.isKindOf(contentType))
return true;
}
}
catch (CoreException e) {}
return false;
} else {
return true;
}
}});
try {
IPath path = new Path(text.getText());
dialog.setInitialSelection(ResourcesPlugin.getWorkspace().getRoot().getFile(path));
} catch (IllegalArgumentException exn) {} // Raised by new Path(...)
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] result) {
if (result.length != 1 ||
!(result[0] instanceof IFile)) {
return new Status(IStatus.ERROR, WorkspaceFileLaunchAttribute.class.getName(), tab.getString(labelKey + "_error"));
}
return new Status(IStatus.OK, WorkspaceFileLaunchAttribute.class.getName(), "");
}});
dialog.open();
Object[] result = dialog.getResult();
if (result == null || result.length != 1) return;
if (!(result[0] instanceof IFile)) return;
IFile selectedFile = (IFile) result[0];
text.setText(selectedFile.getFullPath().toString());
}
|
diff --git a/kernel/src/main/java/org/vosao/service/back/impl/PageServiceImpl.java b/kernel/src/main/java/org/vosao/service/back/impl/PageServiceImpl.java
index 86f8bec..7110984 100644
--- a/kernel/src/main/java/org/vosao/service/back/impl/PageServiceImpl.java
+++ b/kernel/src/main/java/org/vosao/service/back/impl/PageServiceImpl.java
@@ -1,340 +1,339 @@
/**
* Vosao CMS. Simple CMS for Google App Engine.
* Copyright (C) 2009 Vosao development team
*
* 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.
*
* email: [email protected]
*/
package org.vosao.service.back.impl;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.datanucleus.util.StringUtils;
import org.vosao.business.CurrentUser;
import org.vosao.business.decorators.TreeItemDecorator;
import org.vosao.entity.ContentEntity;
import org.vosao.entity.ContentPermissionEntity;
import org.vosao.entity.PageEntity;
import org.vosao.entity.StructureEntity;
import org.vosao.entity.UserEntity;
import org.vosao.enums.PageState;
import org.vosao.enums.PageType;
import org.vosao.service.ServiceResponse;
import org.vosao.service.back.CommentService;
import org.vosao.service.back.ContentPermissionService;
import org.vosao.service.back.GroupService;
import org.vosao.service.back.LanguageService;
import org.vosao.service.back.PageService;
import org.vosao.service.back.TemplateService;
import org.vosao.service.impl.AbstractServiceImpl;
import org.vosao.service.vo.PageRequestVO;
import org.vosao.service.vo.PageVO;
import org.vosao.utils.DateUtil;
/**
* @author Alexander Oleynik
*/
public class PageServiceImpl extends AbstractServiceImpl
implements PageService {
private static Log logger = LogFactory.getLog(PageServiceImpl.class);
private CommentService commentService;
private TemplateService templateService;
private LanguageService languageService;
private ContentPermissionService contentPermissionService;
private GroupService groupService;
@Override
public ServiceResponse updateContent(String pageId, String content,
String languageCode, boolean approve) {
PageEntity page = getBusiness().getPageBusiness().getById(pageId);
if (page != null) {
if (!getBusiness().getPageBusiness().canChangeContent(
page.getFriendlyURL(), languageCode)) {
return ServiceResponse.createErrorResponse("Access denied");
}
UserEntity user = CurrentUser.getInstance();
ContentPermissionEntity perm = getBusiness()
.getContentPermissionBusiness().getPermission(
page.getFriendlyURL(), user);
if (approve && perm.isPublishGranted()) {
page.setState(PageState.APPROVED);
}
else {
page.setState(PageState.EDIT);
}
page.setModDate(new Date());
page.setModUserEmail(user.getEmail());
getDao().getPageDao().save(page);
getDao().getPageDao().setContent(pageId, languageCode, content);
return ServiceResponse.createSuccessResponse(
"Page content was successfully updated");
}
else {
return ServiceResponse.createErrorResponse("Page not found "
+ pageId);
}
}
@Override
public TreeItemDecorator<PageVO> getTree() {
List<PageVO> pages = PageVO.create(getBusiness().getPageBusiness()
.select());
Map<String, TreeItemDecorator<PageVO>> buf =
new HashMap<String, TreeItemDecorator<PageVO>>();
for (PageVO page : pages) {
buf.put(page.getFriendlyURL(),
new TreeItemDecorator<PageVO>(page, null));
}
TreeItemDecorator<PageVO> root = null;
for (String id : buf.keySet()) {
TreeItemDecorator<PageVO> page = buf.get(id);
if (StringUtils.isEmpty(page.getEntity().getParentUrl())) {
root = page;
}
else {
TreeItemDecorator<PageVO> parent = buf.get(page.getEntity()
.getParentUrl());
if (parent != null) {
parent.getChildren().add(page);
page.setParent(parent);
}
}
}
return root;
}
@Override
public PageEntity getPage(String id) {
if (StringUtils.isEmpty(id)) {
return null;
}
return getBusiness().getPageBusiness().getById(id);
}
@Override
public PageEntity getPageByUrl(String url) {
return getBusiness().getPageBusiness().getByUrl(url);
}
@Override
public ServiceResponse savePage(Map<String, String> vo) {
UserEntity user = CurrentUser.getInstance();
PageEntity page = getPage(vo.get("id"));
if (page == null) {
page = new PageEntity();
page.setCreateUserEmail(user.getEmail());
}
page.setModDate(new Date());
page.setModUserEmail(user.getEmail());
page.setCommentsEnabled(Boolean.valueOf(vo.get("commentsEnabled")));
page.setFriendlyURL(vo.get("friendlyUrl"));
ContentPermissionEntity perm = getBusiness()
.getContentPermissionBusiness().getPermission(
page.getFriendlyURL(), CurrentUser.getInstance());
boolean approve = Boolean.valueOf(vo.get("approve"));
if (approve && perm.isPublishGranted()) {
page.setState(PageState.APPROVED);
}
else {
page.setState(PageState.EDIT);
}
if (!perm.isChangeGranted()) {
return ServiceResponse.createErrorResponse("Access denied");
}
try {
page.setPublishDate(DateUtil.toDate(vo.get("publishDate")));
}
catch (ParseException e) {
return ServiceResponse.createErrorResponse("Date is in wrong format");
}
page.setTemplate(vo.get("template"));
page.setTitle(vo.get("title"));
page.setPageType(PageType.valueOf(vo.get("pageType")));
page.setStructureId(vo.get("structureId"));
page.setStructureTemplateId(vo.get("structureTemplateId"));
List<String> errors = getBusiness().getPageBusiness()
.validateBeforeUpdate(page);
if (errors.isEmpty()) {
getDao().getPageDao().save(page);
getDao().getPageDao().setContent(page.getId(),
vo.get("languageCode"), vo.get("content"));
- return ServiceResponse.createSuccessResponse(
- "Page was successfully saved.");
+ return ServiceResponse.createSuccessResponse(page.getId());
}
else {
return ServiceResponse.createErrorResponse(
"Errors occured during saving page.", errors);
}
}
@Override
public List<PageVO> getChildren(String url) {
return PageVO.create(getBusiness().getPageBusiness().getByParent(url));
}
@Override
public ServiceResponse deletePages(List<String> ids) {
getBusiness().getPageBusiness().remove(ids);
return ServiceResponse.createSuccessResponse(
"Pages were successfully deleted");
}
@Override
public List<ContentEntity> getContents(String pageId) {
return getBusiness().getPageBusiness().getContents(pageId);
}
@Override
public List<PageVO> getPageVersions(String url) {
return PageVO.create(getBusiness().getPageBusiness().selectByUrl(url));
}
@Override
public ServiceResponse addVersion(String url, String versionTitle) {
if (!getBusiness().getContentPermissionBusiness().getPermission(
url, CurrentUser.getInstance()).isChangeGranted()) {
return ServiceResponse.createErrorResponse("Access denied");
}
List<PageEntity> list = getBusiness().getPageBusiness().selectByUrl(url);
if (list.size() > 0) {
PageEntity lastPage = list.get(list.size() - 1);
return ServiceResponse.createSuccessResponse(
getBusiness().getPageBusiness().addVersion(
lastPage, lastPage.getVersion() + 1, versionTitle,
CurrentUser.getInstance()).getId());
}
return ServiceResponse.createErrorResponse("Page not found");
}
@Override
public ServiceResponse approve(String pageId) {
if (pageId == null) {
return ServiceResponse.createErrorResponse("Page not found");
}
PageEntity page = getDao().getPageDao().getById(pageId);
if (page == null) {
return ServiceResponse.createErrorResponse("Page not found");
}
if (!getBusiness().getContentPermissionBusiness().getPermission(
page.getFriendlyURL(), CurrentUser.getInstance())
.isPublishGranted()) {
return ServiceResponse.createErrorResponse("Access denied");
}
page.setState(PageState.APPROVED);
getDao().getPageDao().save(page);
return ServiceResponse.createSuccessResponse(
"Page was successfully approved.");
}
@Override
public PageRequestVO getPageRequest(final String id,
final String parentUrl) {
try {
PageRequestVO result = new PageRequestVO();
result.setPage(getPage(id));
String permUrl = parentUrl;
if (result.getPage() != null) {
String url = result.getPage().getFriendlyURL();
result.setVersions(getPageVersions(url));
result.setChildren(getChildren(url));
result.setComments(getCommentService().getByPage(url));
result.setContents(getContents(id));
result.setPermissions(getContentPermissionService().selectByUrl(
url));
permUrl = result.getPage().getFriendlyURL();
if (result.getPage().isStructured()) {
StructureEntity structure = getDao().getStructureDao().getById(
result.getPage().getStructureId());
if (structure != null) {
result.setStructureFields(structure.getFields());
}
}
}
result.setTemplates(getTemplateService().getTemplates());
result.setLanguages(getLanguageService().select());
result.setGroups(getGroupService().select());
result.setPagePermission(getContentPermissionService().getPermission(
permUrl));
result.setStructures(getDao().getStructureDao().select());
return result;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public CommentService getCommentService() {
return commentService;
}
@Override
public void setCommentService(CommentService bean) {
commentService = bean;
}
@Override
public LanguageService getLanguageService() {
return languageService;
}
@Override
public TemplateService getTemplateService() {
return templateService;
}
@Override
public void setLanguageService(LanguageService bean) {
languageService = bean;
}
@Override
public void setTemplateService(TemplateService bean) {
templateService = bean;
}
@Override
public ContentPermissionService getContentPermissionService() {
return contentPermissionService;
}
@Override
public void setContentPermissionService(ContentPermissionService bean) {
contentPermissionService = bean;
}
@Override
public GroupService getGroupService() {
return groupService;
}
@Override
public void setGroupService(GroupService bean) {
groupService = bean;
}
}
| true | true | public ServiceResponse savePage(Map<String, String> vo) {
UserEntity user = CurrentUser.getInstance();
PageEntity page = getPage(vo.get("id"));
if (page == null) {
page = new PageEntity();
page.setCreateUserEmail(user.getEmail());
}
page.setModDate(new Date());
page.setModUserEmail(user.getEmail());
page.setCommentsEnabled(Boolean.valueOf(vo.get("commentsEnabled")));
page.setFriendlyURL(vo.get("friendlyUrl"));
ContentPermissionEntity perm = getBusiness()
.getContentPermissionBusiness().getPermission(
page.getFriendlyURL(), CurrentUser.getInstance());
boolean approve = Boolean.valueOf(vo.get("approve"));
if (approve && perm.isPublishGranted()) {
page.setState(PageState.APPROVED);
}
else {
page.setState(PageState.EDIT);
}
if (!perm.isChangeGranted()) {
return ServiceResponse.createErrorResponse("Access denied");
}
try {
page.setPublishDate(DateUtil.toDate(vo.get("publishDate")));
}
catch (ParseException e) {
return ServiceResponse.createErrorResponse("Date is in wrong format");
}
page.setTemplate(vo.get("template"));
page.setTitle(vo.get("title"));
page.setPageType(PageType.valueOf(vo.get("pageType")));
page.setStructureId(vo.get("structureId"));
page.setStructureTemplateId(vo.get("structureTemplateId"));
List<String> errors = getBusiness().getPageBusiness()
.validateBeforeUpdate(page);
if (errors.isEmpty()) {
getDao().getPageDao().save(page);
getDao().getPageDao().setContent(page.getId(),
vo.get("languageCode"), vo.get("content"));
return ServiceResponse.createSuccessResponse(
"Page was successfully saved.");
}
else {
return ServiceResponse.createErrorResponse(
"Errors occured during saving page.", errors);
}
}
| public ServiceResponse savePage(Map<String, String> vo) {
UserEntity user = CurrentUser.getInstance();
PageEntity page = getPage(vo.get("id"));
if (page == null) {
page = new PageEntity();
page.setCreateUserEmail(user.getEmail());
}
page.setModDate(new Date());
page.setModUserEmail(user.getEmail());
page.setCommentsEnabled(Boolean.valueOf(vo.get("commentsEnabled")));
page.setFriendlyURL(vo.get("friendlyUrl"));
ContentPermissionEntity perm = getBusiness()
.getContentPermissionBusiness().getPermission(
page.getFriendlyURL(), CurrentUser.getInstance());
boolean approve = Boolean.valueOf(vo.get("approve"));
if (approve && perm.isPublishGranted()) {
page.setState(PageState.APPROVED);
}
else {
page.setState(PageState.EDIT);
}
if (!perm.isChangeGranted()) {
return ServiceResponse.createErrorResponse("Access denied");
}
try {
page.setPublishDate(DateUtil.toDate(vo.get("publishDate")));
}
catch (ParseException e) {
return ServiceResponse.createErrorResponse("Date is in wrong format");
}
page.setTemplate(vo.get("template"));
page.setTitle(vo.get("title"));
page.setPageType(PageType.valueOf(vo.get("pageType")));
page.setStructureId(vo.get("structureId"));
page.setStructureTemplateId(vo.get("structureTemplateId"));
List<String> errors = getBusiness().getPageBusiness()
.validateBeforeUpdate(page);
if (errors.isEmpty()) {
getDao().getPageDao().save(page);
getDao().getPageDao().setContent(page.getId(),
vo.get("languageCode"), vo.get("content"));
return ServiceResponse.createSuccessResponse(page.getId());
}
else {
return ServiceResponse.createErrorResponse(
"Errors occured during saving page.", errors);
}
}
|
diff --git a/src/main/java/net/toxbank/client/resource/AbstractToxBankResource.java b/src/main/java/net/toxbank/client/resource/AbstractToxBankResource.java
index 12ae804..a7273ed 100644
--- a/src/main/java/net/toxbank/client/resource/AbstractToxBankResource.java
+++ b/src/main/java/net/toxbank/client/resource/AbstractToxBankResource.java
@@ -1,47 +1,48 @@
package net.toxbank.client.resource;
import java.net.URL;
public abstract class AbstractToxBankResource implements IToxBankResource {
/**
*
*/
private static final long serialVersionUID = -8819428763217419573L;
private URL resourceURL;
private String title;
public AbstractToxBankResource(URL resourceURL) {
setResourceURL(resourceURL);
}
public AbstractToxBankResource() {
this(null);
}
public void setResourceURL(URL resourceURL) {
this.resourceURL = resourceURL;
}
public URL getResourceURL() {
return resourceURL;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String toString() {
return getResourceURL()==null?super.toString():getResourceURL().toString();
}
@Override
public boolean equals(Object obj) {
if ((obj!=null) && (obj instanceof IToxBankResource)) {
+ if (resourceURL==null) return this == obj;
return resourceURL.equals(((IToxBankResource)obj).getResourceURL());
} else return false;
}
}
| true | true | public boolean equals(Object obj) {
if ((obj!=null) && (obj instanceof IToxBankResource)) {
return resourceURL.equals(((IToxBankResource)obj).getResourceURL());
} else return false;
}
| public boolean equals(Object obj) {
if ((obj!=null) && (obj instanceof IToxBankResource)) {
if (resourceURL==null) return this == obj;
return resourceURL.equals(((IToxBankResource)obj).getResourceURL());
} else return false;
}
|
diff --git a/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java b/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
index cf854310..65a25385 100644
--- a/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
+++ b/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
@@ -1,664 +1,664 @@
/*******************************************************************************
* Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams. All rights reserved.
* This program and the accompanying materials are made available under the terms of the new BSD license which
* accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html Contributors:
* Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams - initial API and implementation
******************************************************************************/
package org.vivoweb.harvester.fetch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vivoweb.harvester.util.InitLog;
import org.vivoweb.harvester.util.SpecialEntities;
import org.vivoweb.harvester.util.args.ArgDef;
import org.vivoweb.harvester.util.args.ArgList;
import org.vivoweb.harvester.util.args.ArgParser;
import org.vivoweb.harvester.util.repo.RecordHandler;
/**
* Fetches rdf data from a JDBC database placing the data in the supplied record handler.
* @author Christopher Haines ([email protected])
*/
public class JDBCFetch {
/**
* SLF4J Logger
*/
private static Logger log = LoggerFactory.getLogger(JDBCFetch.class);
/**
* Record Handler to write records to
*/
private RecordHandler rh;
/**
* Statement processor for the database
*/
private Statement cursor;
/**
* Mapping of tablename to idField name
*/
private Map<String, List<String>> idFields = null;
/**
* Mapping of tablename to mapping of fieldname to tablename
*/
private Map<String, Map<String, String>> fkRelations = null;
/**
* Mapping of tablename to list of datafields
*/
private Map<String, List<String>> dataFields = null;
/**
* Set of table names
*/
private Set<String> tableNames = null;
/**
* List of conditions
*/
private Map<String, List<String>> whereClauses;
/**
* Mapping of extra tables for the from section
*/
private Map<String, String> fromClauses;
/**
* Namespace for RDF made from this database
*/
private String uriNS;
/**
* Prefix each field in query with this
*/
private String queryPre;
/**
* Suffix each field in query with this
*/
private String querySuf;
/**
* The user defined SQL Query string
*/
private Map<String,String> queryStrings;
/**
* Constructor
* @param dbConn connection to the database
* @param output RecordHandler to write data to
* @param uriNameSpace namespace base for rdf records
* @throws SQLException error talking with database
*/
public JDBCFetch(Connection dbConn, RecordHandler output, String uriNameSpace) throws SQLException {
this(dbConn, output, uriNameSpace, null, null, null, null, null, null, null, null, null);
}
/**
* Perform post-construction data prep and validation
* Prevents null pointer exceptions
*/
private void prep() {
if(this.tableNames == null) {
this.tableNames = new TreeSet<String>();
}
if(this.fromClauses != null) {
this.tableNames.addAll(this.fromClauses.keySet());
}
if(this.dataFields != null) {
this.tableNames.addAll(this.dataFields.keySet());
}
if(this.idFields != null) {
this.tableNames.addAll(this.idFields.keySet());
}
if(this.whereClauses != null) {
this.tableNames.addAll(this.whereClauses.keySet());
}
if(this.fkRelations != null) {
this.tableNames.addAll(this.fkRelations.keySet());
}
if(this.queryStrings != null) {
this.tableNames.addAll(this.queryStrings.keySet());
}
}
/**
* Get the ArgParser for this task
* @return the ArgParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("JDBCFetch");
parser.addArgument(new ArgDef().setShortOption('d').setLongOpt("driver").withParameter(true, "JDBC_DRIVER").setDescription("jdbc driver class").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('c').setLongOpt("connection").withParameter(true, "JDBC_CONN").setDescription("jdbc connection string").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('u').setLongOpt("username").withParameter(true, "USERNAME").setDescription("database username").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("password").withParameter(true, "PASSWORD").setDescription("database password").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("output").withParameter(true, "CONFIG_FILE").setDescription("RecordHandler config file path").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('t').setLongOpt("tableName").withParameters(true, "TABLE_NAME").setDescription("a single database table name [have multiple -t for more table names]").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('Q').setLongOpt("query").withParameterValueMap("TABLE_NAME", "SQL_QUERY").setDescription("use SQL_QUERY to select from TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("id").withParameterValueMap("TABLE_NAME", "ID_FIELD_LIST").setDescription("use columns in ID_FIELD_LIST[comma separated] as identifier for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('F').setLongOpt("fields").withParameterValueMap("TABLE_NAME", "FIELD_LIST").setDescription("fetch columns in FIELD_LIST[comma separated] for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('R').setLongOpt("relations").withParameterValueMap("TABLE_NAME", "RELATION_PAIR_LIST").setDescription("fetch columns in RELATION_PAIR_LIST[comma separated] for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('W').setLongOpt("whereClause").withParameterValueMap("TABLE_NAME", "CLAUSE_LIST").setDescription("filter TABLE_NAME records based on conditions in CLAUSE_LIST[comma separated]").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('T').setLongOpt("tableFromClause").withParameterValueMap("TABLE_NAME", "TABLE_LIST").setDescription("add tables to use in from clasuse for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('O').setLongOpt("outputOverride").withParameterValueMap("RH_PARAM", "VALUE").setDescription("override the RH_PARAM of output recordhandler using VALUE").setRequired(false));
parser.addArgument(new ArgDef().setLongOpt("delimiterPrefix").withParameter(true, "DELIMITER").setDescription("Prefix each field in the query with this character").setDefaultValue("").setRequired(false));
parser.addArgument(new ArgDef().setLongOpt("delimiterSuffix").withParameter(true, "DELIMITER").setDescription("Suffix each field in the query with this character").setDefaultValue("").setRequired(false));
return parser;
}
/**
* Command line Constructor
* @param args commandline arguments
* @throws IOException error creating task
*/
public JDBCFetch(String[] args) throws IOException {
this(new ArgList(getParser(), args));
}
/**
* Arglist Constructor
* @param opts option set of parsed args
* @throws IOException error creating task
*/
public JDBCFetch(ArgList opts) throws IOException {
String jdbcDriverClass = opts.get("d");
try {
Class.forName(jdbcDriverClass);
} catch(ClassNotFoundException e) {
throw new IOException(e.getMessage(), e);
}
// Setting the database connection parameters
String connLine = opts.get("c");
String username = opts.get("u");
String password = opts.get("p");
this.queryPre = opts.get("delimiterPrefix");
this.querySuf = opts.get("delimiterSuffix");
this.tableNames = new TreeSet<String>();
this.tableNames.addAll(opts.getAll("t"));
if(opts.has("T")) {
this.fromClauses = opts.getValueMap("T");
}
// Set the data fields map according to the command line -F values
if(opts.has("F")) {
this.dataFields = new HashMap<String, List<String>>();
Map<String,String> fields = opts.getValueMap("F");
for(String tableName : fields.keySet()) {
this.dataFields.put(tableName, Arrays.asList(fields.get(tableName).split("\\s?,\\s?")));
}
}
// Set the ID fields map according to the command line -I values
if(opts.has("I")) {
this.idFields = new HashMap<String, List<String>>();
Map<String,String> ids = opts.getValueMap("I");
for(String tableName : ids.keySet()) {
this.idFields.put(tableName, Arrays.asList(ids.get(tableName).split("\\s?,\\s?")));
}
}
// Sets a map of the SQL Where clauses to be applied
if(opts.has("W")) {
this.whereClauses = new HashMap<String, List<String>>();
Map<String,String> wheres = opts.getValueMap("W");
for(String tableName : wheres.keySet()) {
this.whereClauses.put(tableName, Arrays.asList(wheres.get(tableName).split("\\s?,\\s?")));
}
}
// settign manual foriegn key relations
if(opts.has("R")) {
this.fkRelations = new HashMap<String, Map<String, String>>();
Map<String,String> rels = opts.getValueMap("R");
for(String tableName : rels.keySet()) {
if(!this.fkRelations.containsKey(tableName)) {
this.fkRelations.put(tableName, new HashMap<String, String>());
}
for(String relLine : rels.get(tableName).split("\\s?,\\s?")) {
String[] relPair = relLine.split("\\s?~\\s?", 2);
if(relPair.length != 2) {
throw new IllegalArgumentException("Bad Relation Line: " + relLine);
}
this.fkRelations.get(tableName).put(relPair[0], relPair[1]);
}
}
}
// Set SQl style query string from -Q value
if(opts.has("Q")) {
this.queryStrings = opts.getValueMap("Q");
}
// Establishing the database connection with provided parameters.
Connection dbConn;
try {
dbConn = DriverManager.getConnection(connLine, username, password);
this.cursor = dbConn.createStatement();
this.rh = RecordHandler.parseConfig(opts.get("o"), opts.getValueMap("O"));
} catch(SQLException e) {
throw new IOException(e.getMessage(), e);
}
this.uriNS = connLine + "/";
prep();
}
/**
* Library style Constructor
* @param dbConn The database Connection
* @param rh Record Handler to write records to
* @param uriNS the uri namespace to use
* @param queryPre Query prefix often "["
* @param querySuf Query suffix often "]"
* @param tableNames set of the table names
* @param fromClauses Mapping of extra tables for the from section
* @param dataFields Mapping of tablename to list of datafields
* @param idFields Mapping of tablename to idField name
* @param whereClauses List of conditions
* @param relations Mapping of tablename to mapping of fieldname to tablename
* @param queryStrings Mapping of tablename to query
* @throws SQLException error accessing database
*/
public JDBCFetch(Connection dbConn, RecordHandler rh, String uriNS, String queryPre, String querySuf, Set<String> tableNames, Map<String, String> fromClauses, Map<String, List<String>> dataFields, Map<String, List<String>> idFields, Map<String, List<String>> whereClauses, Map<String, Map<String, String>> relations, Map<String, String> queryStrings) throws SQLException {
this.cursor = dbConn.createStatement();
this.rh = rh;
this.tableNames = tableNames;
this.fromClauses = fromClauses;
this.dataFields = dataFields;
this.idFields = idFields;
this.whereClauses = whereClauses;
this.fkRelations = relations;
this.uriNS = uriNS;
this.queryPre = queryPre;
this.querySuf = querySuf;
this.queryStrings = queryStrings;
prep();
}
/**
* Get the field prefix
* @return the field prefix
*/
private String getFieldPrefix() {
if(this.queryPre == null) {
this.queryPre = getParser().getOptMap().get("delimiterPrefix").getDefaultValue();
}
return this.queryPre;
}
/**
* Set the field prefix
* @param fieldPrefix the field prefix to use
*/
public void setFieldPrefix(String fieldPrefix) {
this.queryPre = fieldPrefix;
}
/**
* Get the field suffix
* @return the field suffix
*/
private String getFieldSuffix() {
if(this.querySuf == null) {
this.querySuf = getParser().getOptMap().get("delimiterSuffix").getDefaultValue();
}
return this.querySuf;
}
/**
* Set the field suffix
* @param fieldSuffix the field suffix to use
*/
public void setFieldSuffix(String fieldSuffix) {
this.querySuf = fieldSuffix;
}
/**
* Get the data field information for a table from the database
* @param tableName the table to get the data field information for
* @return the data field list
* @throws SQLException error connecting to DB
*/
private List<String> getDataFields(String tableName) throws SQLException {
if(this.dataFields == null || (this.queryStrings != null && this.queryStrings.containsKey(tableName))) {
this.dataFields = new HashMap<String, List<String>>();
}
if(!this.dataFields.containsKey(tableName)) {
this.dataFields.put(tableName, new LinkedList<String>());
if(this.queryStrings == null || !this.queryStrings.containsKey(tableName)) {
ResultSet columnData = this.cursor.getConnection().getMetaData().getColumns(this.cursor.getConnection().getCatalog(), null, tableName, "%");
while(columnData.next()) {
String colName = columnData.getString("COLUMN_NAME");
if((getIDFields(tableName).size() > 1 || !getIDFields(tableName).contains(colName)) && !getFkRelationFields(tableName).containsKey(colName)) {
this.dataFields.get(tableName).add(colName);
}
}
}
}
return this.dataFields.get(tableName);
}
/**
* Get the relation field information for a table from the database
* @param tableName the table to get the relation field information for
* @return the relation field mapping
* @throws SQLException error connecting to DB
*/
private Map<String, String> getFkRelationFields(String tableName) throws SQLException {
if(this.fkRelations == null || (this.queryStrings != null && this.queryStrings.containsKey(tableName))) {
this.fkRelations = new HashMap<String, Map<String, String>>();
}
if(!this.fkRelations.containsKey(tableName)) {
this.fkRelations.put(tableName, new HashMap<String, String>());
if(this.queryStrings == null || !this.queryStrings.containsKey(tableName)) {
ResultSet foreignKeys = this.cursor.getConnection().getMetaData().getImportedKeys(this.cursor.getConnection().getCatalog(), null, tableName);
while(foreignKeys.next()) {
this.fkRelations.get(tableName).put(foreignKeys.getString("FKCOLUMN_NAME"), foreignKeys.getString("PKTABLE_NAME"));
}
}
}
return this.fkRelations.get(tableName);
}
/**
* Get the where clauses for a table from the database
* @param tableName the table to get the where clauses for
* @return the where clauses
*/
private List<String> getWhereClauses(String tableName) {
if(this.whereClauses == null) {
this.whereClauses = new HashMap<String, List<String>>();
}
if(!this.whereClauses.containsKey(tableName)) {
this.whereClauses.put(tableName, new LinkedList<String>());
}
return this.whereClauses.get(tableName);
}
/**
* Get the id field list for a table from the database
* @param tableName the table to get the id field list for
* @return the id field list
* @throws SQLException error connecting to DB
*/
private List<String> getIDFields(String tableName) throws SQLException {
if(this.idFields == null) {
this.idFields = new HashMap<String, List<String>>();
}
if(!this.idFields.containsKey(tableName)) {
this.idFields.put(tableName, new LinkedList<String>());
ResultSet primaryKeys = this.cursor.getConnection().getMetaData().getPrimaryKeys(this.cursor.getConnection().getCatalog(), null, tableName);
while(primaryKeys.next()) {
this.idFields.get(tableName).add(primaryKeys.getString("COLUMN_NAME"));
}
}
if(this.idFields.get(tableName).isEmpty()) {
throw new IllegalArgumentException("ID fields for table '" + tableName + "' were not provided and no primary keys are present... please provide an ID field set for this table");
}
return this.idFields.get(tableName);
}
/**
* Gets the tablenames in database
* @return set of tablenames
* @throws SQLException error connecting to DB
*/
private Set<String> getTableNames() throws SQLException {
if(this.tableNames.isEmpty()) {
String[] tableTypes = {"TABLE"};
ResultSet tableData = this.cursor.getConnection().getMetaData().getTables(this.cursor.getConnection().getCatalog(), null, "%", tableTypes);
while(tableData.next()) {
this.tableNames.add(tableData.getString("TABLE_NAME"));
}
}
return this.tableNames;
}
/**
* Builds a select statement against the table using configured fields
* @param tableName the table to build the select statement for
* @return the select statement
* @throws SQLException error connecting to db
*/
private String buildSelect(String tableName) throws SQLException {
if(this.queryStrings != null && this.queryStrings.containsKey(tableName) ){
String query = this.queryStrings.get(tableName);
log.debug("User defined SQL Query:\n" + query);
return query;
}
boolean multiTable = this.fromClauses != null && this.fromClauses.containsKey(tableName);
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
for(String dataField : getDataFields(tableName)) {
sb.append(getFieldPrefix());
if(multiTable && dataField.split("\\.").length <= 1) {
sb.append(tableName);
sb.append(".");
}
sb.append(dataField);
sb.append(getFieldSuffix());
sb.append(", ");
}
for(String relField : getFkRelationFields(tableName).keySet()) {
sb.append(getFieldPrefix());
if(multiTable && relField.split("\\.").length <= 1) {
sb.append(tableName);
sb.append(".");
}
sb.append(relField);
sb.append(getFieldSuffix());
sb.append(", ");
}
for(String idField : getIDFields(tableName)) {
sb.append(getFieldPrefix());
if(multiTable && idField.split("\\.").length <= 1) {
sb.append(tableName);
sb.append(".");
}
sb.append(idField);
sb.append(getFieldSuffix());
sb.append(", ");
}
sb.delete(sb.lastIndexOf(", "), sb.length());
sb.append(" FROM ");
sb.append(tableName);
if(multiTable) {
sb.append(", ");
sb.append(this.fromClauses.get(tableName));
}
if(getWhereClauses(tableName).size() > 0) {
sb.append(" WHERE ");
sb.append(StringUtils.join(getWhereClauses(tableName), " AND "));
}
log.debug("Generated SQL Query:\n" + sb.toString());
return sb.toString();
}
/**
* Builds a table's record namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableRecordNS(String tableName) {
return this.uriNS + tableName;
}
/**
* Builds a table's field description namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableFieldNS(String tableName) {
return this.uriNS + "fields/" + tableName + "/";
}
/**
* Builds a table's type description namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableType(String tableName) {
return this.uriNS + "types#" + tableName;
}
/**
* Executes the task
* @throws IOException error processing record handler or jdbc connection
*/
public void execute() throws IOException {
// For each Table
try {
for(String tableName : getTableNames()) {
StringBuilder sb = new StringBuilder();
// For each Record
ResultSet rs = this.cursor.executeQuery(buildSelect(tableName));
// ResultSetMetaData rsmd = rs.getMetaData();
// int ColumnCount = rsmd.getColumnCount();
// Map<String,String> columnData = new HashMap<String,String>();
while(rs.next()) {
StringBuilder recID = new StringBuilder();
recID.append("id");
for(String idField : getIDFields(tableName)) {
recID.append("_-_");
String id = rs.getString(idField);
if(id != null) {
id = id.trim();
}
id = SpecialEntities.xmlEncode(id);
recID.append(id);
}
// log.trace("Creating RDF for "+tableName+": "+recID);
// Build RDF BEGIN
// Header info
String tableNS = "db-" + tableName;
sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>\n");
sb.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
sb.append(" xmlns:");
sb.append(tableNS);
sb.append("=\"");
sb.append(buildTableFieldNS(tableName));
sb.append("\"\n");
sb.append(" xml:base=\"");
sb.append(buildTableRecordNS(tableName));
sb.append("\">\n");
// Record info BEGIN
sb.append(" <rdf:Description rdf:ID=\"");
sb.append(recID);
sb.append("\">\n");
// insert type value
sb.append(" <rdf:type rdf:resource=\"");
sb.append(buildTableType(tableName));
sb.append("\"/>\n");
// DataFields
List<String> dataFieldList;
if(this.queryStrings != null && this.queryStrings.containsKey(tableName)) {
dataFieldList = getResultSetFields(rs);
} else {
dataFieldList = getDataFields(tableName);
}
for(String dataField : dataFieldList) {
// Field BEGIN
String field = tableNS + ":" + dataField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">");
// insert field value
if(rs.getString(dataField) != null) {
sb.append(SpecialEntities.xmlEncode(rs.getString(dataField).trim()));
}
// Field END
sb.append("</");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">\n");
}
// Relation Fields
for(String relationField : getFkRelationFields(tableName).keySet()) {
// Field BEGIN
String field = tableNS+":"+relationField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(" rdf:resource=\"");
sb.append(this.buildTableRecordNS(getFkRelationFields(tableName).get(relationField)));
// insert field value
- sb.append("#id-" + rs.getString(relationField).trim());
+ sb.append("#id_-_" + rs.getString(relationField).trim());
// Field END
sb.append("\"/>\n");
}
// Record info END
sb.append(" </rdf:Description>\n");
// Footer info
sb.append("</rdf:RDF>");
// Build RDF END
// Write RDF to RecordHandler
log.trace("Adding record: " + tableName + "_" + recID);
this.rh.addRecord(tableName + "_" + recID, sb.toString(), this.getClass());
}
}
} catch(SQLException e) {
throw new IOException(e.getMessage(), e);
}
}
/**
* Get the fields from a result set
* @param rs the resultset
* @return the list of fields
* @throws SQLException error reading resultset
*/
private List<String> getResultSetFields(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
List<String> fields = new ArrayList<String>(count);
for(int x = 1; x <= count; x++) {
fields.add(rsmd.getColumnName(x));
}
return fields;
}
/**
* Main method
* @param args commandline arguments
*/
public static void main(String... args) {
InitLog.initLogger(JDBCFetch.class);
log.info(getParser().getAppName()+": Start");
try {
new JDBCFetch(args).execute();
} catch(IllegalArgumentException e) {
log.debug(e.getMessage(), e);
System.out.println(getParser().getUsage());
} catch(Exception e) {
log.error(e.getMessage(), e);
}
log.info(getParser().getAppName()+": End");
}
}
| true | true | public void execute() throws IOException {
// For each Table
try {
for(String tableName : getTableNames()) {
StringBuilder sb = new StringBuilder();
// For each Record
ResultSet rs = this.cursor.executeQuery(buildSelect(tableName));
// ResultSetMetaData rsmd = rs.getMetaData();
// int ColumnCount = rsmd.getColumnCount();
// Map<String,String> columnData = new HashMap<String,String>();
while(rs.next()) {
StringBuilder recID = new StringBuilder();
recID.append("id");
for(String idField : getIDFields(tableName)) {
recID.append("_-_");
String id = rs.getString(idField);
if(id != null) {
id = id.trim();
}
id = SpecialEntities.xmlEncode(id);
recID.append(id);
}
// log.trace("Creating RDF for "+tableName+": "+recID);
// Build RDF BEGIN
// Header info
String tableNS = "db-" + tableName;
sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>\n");
sb.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
sb.append(" xmlns:");
sb.append(tableNS);
sb.append("=\"");
sb.append(buildTableFieldNS(tableName));
sb.append("\"\n");
sb.append(" xml:base=\"");
sb.append(buildTableRecordNS(tableName));
sb.append("\">\n");
// Record info BEGIN
sb.append(" <rdf:Description rdf:ID=\"");
sb.append(recID);
sb.append("\">\n");
// insert type value
sb.append(" <rdf:type rdf:resource=\"");
sb.append(buildTableType(tableName));
sb.append("\"/>\n");
// DataFields
List<String> dataFieldList;
if(this.queryStrings != null && this.queryStrings.containsKey(tableName)) {
dataFieldList = getResultSetFields(rs);
} else {
dataFieldList = getDataFields(tableName);
}
for(String dataField : dataFieldList) {
// Field BEGIN
String field = tableNS + ":" + dataField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">");
// insert field value
if(rs.getString(dataField) != null) {
sb.append(SpecialEntities.xmlEncode(rs.getString(dataField).trim()));
}
// Field END
sb.append("</");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">\n");
}
// Relation Fields
for(String relationField : getFkRelationFields(tableName).keySet()) {
// Field BEGIN
String field = tableNS+":"+relationField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(" rdf:resource=\"");
sb.append(this.buildTableRecordNS(getFkRelationFields(tableName).get(relationField)));
// insert field value
sb.append("#id-" + rs.getString(relationField).trim());
// Field END
sb.append("\"/>\n");
}
// Record info END
sb.append(" </rdf:Description>\n");
// Footer info
sb.append("</rdf:RDF>");
// Build RDF END
// Write RDF to RecordHandler
log.trace("Adding record: " + tableName + "_" + recID);
this.rh.addRecord(tableName + "_" + recID, sb.toString(), this.getClass());
}
}
} catch(SQLException e) {
throw new IOException(e.getMessage(), e);
}
}
| public void execute() throws IOException {
// For each Table
try {
for(String tableName : getTableNames()) {
StringBuilder sb = new StringBuilder();
// For each Record
ResultSet rs = this.cursor.executeQuery(buildSelect(tableName));
// ResultSetMetaData rsmd = rs.getMetaData();
// int ColumnCount = rsmd.getColumnCount();
// Map<String,String> columnData = new HashMap<String,String>();
while(rs.next()) {
StringBuilder recID = new StringBuilder();
recID.append("id");
for(String idField : getIDFields(tableName)) {
recID.append("_-_");
String id = rs.getString(idField);
if(id != null) {
id = id.trim();
}
id = SpecialEntities.xmlEncode(id);
recID.append(id);
}
// log.trace("Creating RDF for "+tableName+": "+recID);
// Build RDF BEGIN
// Header info
String tableNS = "db-" + tableName;
sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>\n");
sb.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
sb.append(" xmlns:");
sb.append(tableNS);
sb.append("=\"");
sb.append(buildTableFieldNS(tableName));
sb.append("\"\n");
sb.append(" xml:base=\"");
sb.append(buildTableRecordNS(tableName));
sb.append("\">\n");
// Record info BEGIN
sb.append(" <rdf:Description rdf:ID=\"");
sb.append(recID);
sb.append("\">\n");
// insert type value
sb.append(" <rdf:type rdf:resource=\"");
sb.append(buildTableType(tableName));
sb.append("\"/>\n");
// DataFields
List<String> dataFieldList;
if(this.queryStrings != null && this.queryStrings.containsKey(tableName)) {
dataFieldList = getResultSetFields(rs);
} else {
dataFieldList = getDataFields(tableName);
}
for(String dataField : dataFieldList) {
// Field BEGIN
String field = tableNS + ":" + dataField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">");
// insert field value
if(rs.getString(dataField) != null) {
sb.append(SpecialEntities.xmlEncode(rs.getString(dataField).trim()));
}
// Field END
sb.append("</");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">\n");
}
// Relation Fields
for(String relationField : getFkRelationFields(tableName).keySet()) {
// Field BEGIN
String field = tableNS+":"+relationField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(" rdf:resource=\"");
sb.append(this.buildTableRecordNS(getFkRelationFields(tableName).get(relationField)));
// insert field value
sb.append("#id_-_" + rs.getString(relationField).trim());
// Field END
sb.append("\"/>\n");
}
// Record info END
sb.append(" </rdf:Description>\n");
// Footer info
sb.append("</rdf:RDF>");
// Build RDF END
// Write RDF to RecordHandler
log.trace("Adding record: " + tableName + "_" + recID);
this.rh.addRecord(tableName + "_" + recID, sb.toString(), this.getClass());
}
}
} catch(SQLException e) {
throw new IOException(e.getMessage(), e);
}
}
|
diff --git a/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/actions/save/SaveComparisonModelAction.java b/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/actions/save/SaveComparisonModelAction.java
index 53a71ade3..5359a2361 100644
--- a/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/actions/save/SaveComparisonModelAction.java
+++ b/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/actions/save/SaveComparisonModelAction.java
@@ -1,98 +1,102 @@
/*******************************************************************************
* Copyright (c) 2012 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.compare.ide.ui.internal.actions.save;
import static com.google.common.collect.Maps.newHashMap;
import com.google.common.collect.ImmutableList;
import java.io.File;
import java.io.IOException;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.ide.ui.internal.EMFCompareConstants;
import org.eclipse.emf.compare.ide.ui.internal.EMFCompareIDEUIPlugin;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil.Copier;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* @author <a href="mailto:[email protected]">Mikael Barbero</a>
*/
public class SaveComparisonModelAction extends Action {
/**
*
*/
private static final ImmutableList<String> DIALOG_BUTTON_LABELS = ImmutableList.of("Replace", "Cancel");
private CompareConfiguration configuration;
/**
* @param parent
*/
public SaveComparisonModelAction(CompareConfiguration configuration) {
this.configuration = configuration;
setToolTipText("Save Comparison Model");
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(EMFCompareIDEUIPlugin.PLUGIN_ID,
"icons/full/toolb16/saveas_edit.gif")); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
Shell parent = configuration.getContainer().getWorkbenchPart().getSite().getShell();
FileDialog fileDialog = new FileDialog(parent, SWT.SAVE);
- File file = new File(fileDialog.open());
- if (file.exists()) {
- MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \""
- + file.toString() + "\" already exists. Do you want to replace the existing one?",
- MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1);
- int open = messageDialog.open();
- if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) {
+ String filePath = fileDialog.open();
+ if (filePath != null) {
+ File file = new File(filePath);
+ if (file.exists()) {
+ MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null,
+ "File \"" + file.toString()
+ + "\" already exists. Do you want to replace the existing one?",
+ MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1);
+ int open = messageDialog.open();
+ if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) {
+ saveComparison(file);
+ } // else do nothing
+ } else {
saveComparison(file);
- } // else do nothing
- } else {
- saveComparison(file);
+ }
}
super.run();
}
private void saveComparison(File file) {
Comparison comparison = (Comparison)configuration.getProperty(EMFCompareConstants.COMPARE_RESULT);
Resource resource = new XMIResourceImpl(URI.createFileURI(file.getAbsolutePath()));
Copier copier = new Copier(false);
EObject comparisonCopy = copier.copy(comparison);
copier.copyReferences();
resource.getContents().add(comparisonCopy);
try {
resource.save(newHashMap());
} catch (IOException e) {
EMFCompareIDEUIPlugin.getDefault().log(e);
}
}
}
| false | true | public void run() {
Shell parent = configuration.getContainer().getWorkbenchPart().getSite().getShell();
FileDialog fileDialog = new FileDialog(parent, SWT.SAVE);
File file = new File(fileDialog.open());
if (file.exists()) {
MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \""
+ file.toString() + "\" already exists. Do you want to replace the existing one?",
MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1);
int open = messageDialog.open();
if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) {
saveComparison(file);
} // else do nothing
} else {
saveComparison(file);
}
super.run();
}
| public void run() {
Shell parent = configuration.getContainer().getWorkbenchPart().getSite().getShell();
FileDialog fileDialog = new FileDialog(parent, SWT.SAVE);
String filePath = fileDialog.open();
if (filePath != null) {
File file = new File(filePath);
if (file.exists()) {
MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null,
"File \"" + file.toString()
+ "\" already exists. Do you want to replace the existing one?",
MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[0]), 1);
int open = messageDialog.open();
if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) {
saveComparison(file);
} // else do nothing
} else {
saveComparison(file);
}
}
super.run();
}
|
diff --git a/src/com/arcao/geocaching4locus/service/AbstractService.java b/src/com/arcao/geocaching4locus/service/AbstractService.java
index f6d0ed71..5be7ba8b 100644
--- a/src/com/arcao/geocaching4locus/service/AbstractService.java
+++ b/src/com/arcao/geocaching4locus/service/AbstractService.java
@@ -1,293 +1,294 @@
package com.arcao.geocaching4locus.service;
import java.util.Date;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.arcao.geocaching.api.exception.InvalidCredentialsException;
import com.arcao.geocaching.api.exception.NetworkException;
import com.arcao.geocaching4locus.ErrorActivity;
import com.arcao.geocaching4locus.R;
public abstract class AbstractService extends IntentService {
protected String TAG;
public static final String ACTION_PROGRESS_UPDATE = "com.arcao.geocaching4locus.intent.action.PROGRESS_UPDATE";
public static final String ACTION_PROGRESS_COMPLETE = "com.arcao.geocaching4locus.intent.action.PROGRESS_COMPLETE";
public static final String PARAM_COUNT = "COUNT";
public static final String PARAM_CURRENT = "CURRENT";
private boolean canceled;
protected NotificationManager notificationManager;
protected int notificationId;
protected int actionTextId;
public AbstractService(String tag, int notificationId, int actionTextId) {
super(tag);
this.TAG = tag;
this.notificationId = notificationId;
this.actionTextId = actionTextId;
}
protected abstract void setInstance();
protected abstract void removeInstance();
protected abstract Intent createOngoingEventIntent();
protected abstract void run(Intent intent) throws Exception;
@Override
public void onCreate() {
super.onCreate();
setInstance();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
canceled = false;
startForeground(notificationId, createProgressNotification(0, 0));
}
protected Notification createProgressNotification(int count, int current) {
Intent intent = createOngoingEventIntent();
if (intent != null)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setOngoing(true);
+ nb.setWhen(0); // this fix redraw issue while refreshing
int percent = 0;
if (count > 0)
percent = ((current * 100) / count);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// extract colors and text sizes for notification
extractColors();
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_download);
contentView.setTextViewText(R.id.progress_title, getText(actionTextId));
// correct size and color
contentView.setTextColor(R.id.progress_title, notification_title_color);
contentView.setFloat(R.id.progress_title, "setTextSize", notification_title_size);
contentView.setTextColor(R.id.progress_text, notification_text_color);
if (count <= 0) {
contentView.setProgressBar(R.id.progress_bar, 0, 0, true);
} else {
contentView.setProgressBar(R.id.progress_bar, count, current, false);
}
contentView.setTextViewText(R.id.progress_text, percent + "%");
nb.setContent(contentView);
} else {
if (count <= 0) {
nb.setProgress(0, 0, true);
} else {
nb.setProgress(count, current, false);
nb.setContentText(String.format("%d / %d (%d%%)", current, count, percent));
}
nb.setContentTitle(getText(actionTextId));
}
nb.setContentIntent(PendingIntent.getActivity(getBaseContext(), 0, intent, 0));
return nb.build();
}
protected Notification createErrorNotification(int resErrorId, String errorText, boolean openPreference, Throwable exception) {
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setOngoing(false);
nb.setWhen(new Date().getTime());
nb.setTicker(getText(R.string.error_title));
nb.setContentTitle(getText(R.string.error_title));
nb.setContentText(Html.fromHtml(getString(resErrorId, errorText)));
Intent intent = new Intent(this, ErrorActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(ErrorActivity.ACTION_ERROR);
intent.putExtra(ErrorActivity.PARAM_RESOURCE_ID, resErrorId);
intent.putExtra(ErrorActivity.PARAM_ADDITIONAL_MESSAGE, errorText);
intent.putExtra(ErrorActivity.PARAM_OPEN_PREFERENCE, openPreference);
if (exception != null)
intent.putExtra(ErrorActivity.PARAM_EXCEPTION, exception);
nb.setContentIntent(PendingIntent.getActivity(getBaseContext(), 0, intent, 0));
return nb.build();
}
@Override
protected void onHandleIntent(Intent intent) {
loadConfiguration(PreferenceManager.getDefaultSharedPreferences(this));
try {
run(intent);
} catch (InvalidCredentialsException e) {
Log.e(TAG, e.getMessage(), e);
sendError(R.string.error_credentials, null, true, null);
} catch (NetworkException e) {
Log.e(TAG, e.getMessage(), e);
sendError(R.string.error_network, null, false, null);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
String message = e.getMessage();
if (message == null)
message = "";
sendError(R.string.error, String.format("%s<br>Exception: %s", message, e.getClass().getSimpleName()), false, e);
}
}
@Override
public void onDestroy() {
canceled = true;
removeInstance();
stopForeground(true);
super.onDestroy();
}
public boolean isCanceled() {
return canceled;
}
protected abstract void loadConfiguration(SharedPreferences prefs);
public void sendProgressUpdate(int current, int count) {
if (canceled)
return;
notificationManager.notify(notificationId, createProgressNotification(count, current));
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_PROGRESS_UPDATE);
//broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_COUNT, count);
broadcastIntent.putExtra(PARAM_CURRENT, current);
sendBroadcast(broadcastIntent);
}
protected void sendProgressComplete(int count) {
if (!canceled) {
notificationManager.notify(notificationId, createProgressNotification(count, count));
}
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_PROGRESS_COMPLETE);
//broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_COUNT, count);
broadcastIntent.putExtra(PARAM_CURRENT, count);
sendBroadcast(broadcastIntent);
}
protected void sendError(int error, String additionalMessage, boolean openPreference, Throwable exception) {
// error notification
notificationManager.notify(error, createErrorNotification(error, additionalMessage, openPreference, exception));
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ErrorActivity.ACTION_ERROR);
broadcastIntent.putExtra(ErrorActivity.PARAM_RESOURCE_ID, error);
if (additionalMessage != null)
broadcastIntent.putExtra(ErrorActivity.PARAM_ADDITIONAL_MESSAGE, additionalMessage);
broadcastIntent.putExtra(ErrorActivity.PARAM_OPEN_PREFERENCE, openPreference);
if (exception != null)
broadcastIntent.putExtra(ErrorActivity.PARAM_EXCEPTION, exception);
sendBroadcast(broadcastIntent);
}
// --------------------- Methods to get right color and text size for title and text for notification ------------------
protected Integer notification_title_color = null;
protected float notification_title_size = 11;
protected Integer notification_text_color = null;
protected float notification_text_size = 11;
private final String COLOR_SEARCH_RECURSE_TITLE_TIP = "SOME_SAMPLE_TITLE";
private final String COLOR_SEARCH_RECURSE_TEXT_TIP = "SOME_SAMPLE_TEXT";
protected boolean recurseGroup(ViewGroup gp) {
final int count = gp.getChildCount();
for (int i = 0; i < count; ++i) {
if (gp.getChildAt(i) instanceof TextView) {
final TextView text = (TextView) gp.getChildAt(i);
final String szText = text.getText().toString();
if (COLOR_SEARCH_RECURSE_TITLE_TIP.equals(szText)) {
notification_title_color = text.getTextColors().getDefaultColor();
notification_title_size = text.getTextSize();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager systemWM = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
systemWM.getDefaultDisplay().getMetrics(metrics);
notification_title_size /= metrics.scaledDensity;
if (notification_title_color != null && notification_text_color != null)
return true;
} else if (COLOR_SEARCH_RECURSE_TEXT_TIP.equals(szText)) {
notification_text_color = text.getTextColors().getDefaultColor();
notification_text_size = text.getTextSize();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager systemWM = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
systemWM.getDefaultDisplay().getMetrics(metrics);
notification_text_size /= metrics.scaledDensity;
if (notification_title_color != null && notification_text_color != null)
return true;
}
} else if (gp.getChildAt(i) instanceof ViewGroup) {
if (recurseGroup((ViewGroup) gp.getChildAt(i)))
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
protected void extractColors() {
if (notification_title_color != null && notification_text_color != null)
return;
try {
Notification ntf = new Notification();
ntf.setLatestEventInfo(this, COLOR_SEARCH_RECURSE_TITLE_TIP, COLOR_SEARCH_RECURSE_TEXT_TIP, null);
LinearLayout group = new LinearLayout(this);
ViewGroup event = (ViewGroup) ntf.contentView.apply(this, group);
recurseGroup(event);
group.removeAllViews();
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
if (notification_title_color == null)
notification_title_color = android.R.color.black;
if (notification_text_color == null)
notification_text_color = android.R.color.black;
}
}
| true | true | protected Notification createProgressNotification(int count, int current) {
Intent intent = createOngoingEventIntent();
if (intent != null)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setOngoing(true);
int percent = 0;
if (count > 0)
percent = ((current * 100) / count);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// extract colors and text sizes for notification
extractColors();
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_download);
contentView.setTextViewText(R.id.progress_title, getText(actionTextId));
// correct size and color
contentView.setTextColor(R.id.progress_title, notification_title_color);
contentView.setFloat(R.id.progress_title, "setTextSize", notification_title_size);
contentView.setTextColor(R.id.progress_text, notification_text_color);
if (count <= 0) {
contentView.setProgressBar(R.id.progress_bar, 0, 0, true);
} else {
contentView.setProgressBar(R.id.progress_bar, count, current, false);
}
contentView.setTextViewText(R.id.progress_text, percent + "%");
nb.setContent(contentView);
} else {
if (count <= 0) {
nb.setProgress(0, 0, true);
} else {
nb.setProgress(count, current, false);
nb.setContentText(String.format("%d / %d (%d%%)", current, count, percent));
}
nb.setContentTitle(getText(actionTextId));
}
nb.setContentIntent(PendingIntent.getActivity(getBaseContext(), 0, intent, 0));
return nb.build();
}
| protected Notification createProgressNotification(int count, int current) {
Intent intent = createOngoingEventIntent();
if (intent != null)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setOngoing(true);
nb.setWhen(0); // this fix redraw issue while refreshing
int percent = 0;
if (count > 0)
percent = ((current * 100) / count);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// extract colors and text sizes for notification
extractColors();
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_download);
contentView.setTextViewText(R.id.progress_title, getText(actionTextId));
// correct size and color
contentView.setTextColor(R.id.progress_title, notification_title_color);
contentView.setFloat(R.id.progress_title, "setTextSize", notification_title_size);
contentView.setTextColor(R.id.progress_text, notification_text_color);
if (count <= 0) {
contentView.setProgressBar(R.id.progress_bar, 0, 0, true);
} else {
contentView.setProgressBar(R.id.progress_bar, count, current, false);
}
contentView.setTextViewText(R.id.progress_text, percent + "%");
nb.setContent(contentView);
} else {
if (count <= 0) {
nb.setProgress(0, 0, true);
} else {
nb.setProgress(count, current, false);
nb.setContentText(String.format("%d / %d (%d%%)", current, count, percent));
}
nb.setContentTitle(getText(actionTextId));
}
nb.setContentIntent(PendingIntent.getActivity(getBaseContext(), 0, intent, 0));
return nb.build();
}
|
diff --git a/src/nl/nikhef/jgridstart/gui/util/GUIScreenshotsTest.java b/src/nl/nikhef/jgridstart/gui/util/GUIScreenshotsTest.java
index e39a75c..cee6611 100644
--- a/src/nl/nikhef/jgridstart/gui/util/GUIScreenshotsTest.java
+++ b/src/nl/nikhef/jgridstart/gui/util/GUIScreenshotsTest.java
@@ -1,516 +1,516 @@
package nl.nikhef.jgridstart.gui.util;
import java.awt.AWTException;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
import junit.framework.TestCase;
import org.bouncycastle.util.encoders.Base64;
import org.junit.Test;
import nl.nikhef.jgridstart.logging.LogHelper;
import nl.nikhef.jgridstart.util.FileUtils;
import nl.nikhef.jgridstart.util.PasswordCache;
import abbot.finder.BasicFinder;
import abbot.finder.ComponentNotFoundException;
import abbot.finder.Matcher;
import abbot.finder.MultipleComponentsFoundException;
import abbot.tester.ComponentTester;
import abbot.util.AWT;
/** Generate screenshots the for documentation of jGridstart */
public class GUIScreenshotsTest extends TestCase {
static private Logger logger = Logger.getLogger("nl.nikhef.jgridstart.gui.util");
protected static ComponentTester tester = new ComponentTester();
/** password used for test certificate */
protected static String password = "test123pass";
/** replacement characters for {@link #keyString} */
protected static HashMap<Character, Character> replacemap = null;
/** Make screenshot taking part of unit tests */
@Test
public static void testScreenshots() throws Exception {
File shotdir = FileUtils.createTempDir("jgridstart-screenshots-");
try {
doScreenshots(shotdir);
} catch(Throwable e) {
// on error, output final screenshot as base64 on debug log
File errorshot = new File(shotdir, "error.png");
saveScreenshot(errorshot);
Thread.sleep(500);
FileInputStream in = new FileInputStream(errorshot);
byte[] data = new byte[(int)errorshot.length()];
in.read(data, 0, data.length);
// need to log in chunks because logger doesn't seem to be able to support >4096 chars
String basedata = new String(Base64.encode(data));
logger.finest("Interactive UI testing failed, last screenshot (base64 encoded):");
logger.finest("=== BEGIN PNG ===");
int pos = 0;
while (pos < basedata.length()) {
int len = 1024;
if (pos+len < basedata.length())
logger.finest(basedata.substring(pos, pos+len));
else
logger.finest(basedata.substring(pos));
pos += len;
}
logger.finest("=== END PNG ===");
// destroy window
Window mainwnd = AWT.getActiveWindow();
if (mainwnd!=null && mainwnd.isVisible()) mainwnd.dispose();
// pass on error
if (e instanceof Exception) throw (Exception)e;
else if (e instanceof Error) throw (Error)e;
else throw new Exception("Unknown throwable: ", e);
} finally {
// remove screenshot directory again
FileUtils.recursiveDelete(shotdir);
}
}
/** User-callable screenshot taking program */
public static void main(String[] args) throws Exception {
// screenshot output directory
if (args.length!=1) {
System.err.println("please give screenshot dir as argument");
return;
}
doScreenshots(new File(args[0]));
System.exit(0);
}
public static void doScreenshots(File shotdir) throws Exception {
shotdir.mkdirs();
String prefix = "jgridstart-screenshot-";
// setup temporary environment
logger.info("Setting up jGridstart interactive screenshot and testing environment");
File tmphome = FileUtils.createTempDir("jgridstart-home");
Window mainwnd = null;
try {
System.setProperty("jgridstart.ca.provider", "LocalCA");
System.setProperty("jgridstart.ca.local.hold", "true");
System.setProperty("user.home", tmphome.getCanonicalPath());
// create standard gui
nl.nikhef.jgridstart.gui.Main.main(new String[]{});
LogHelper.setupLogging(true);
// move mouse here since closing window may give up focus later
Thread.sleep(2000); guiSleep();
mainwnd = AWT.getActiveWindow();
assertNotNull(mainwnd);
tester.mouseMove(mainwnd.getComponents()[0]);
assertWindowname("jgridstart-main-window");
/*
* Request new
*/
logger.info("Interactive testing scenario: Request New");
// start screen
saveScreenshot(new File(shotdir, prefix+"newrequest01.png"));
// new request wizard
guiSleep(); tester.key(new Integer('N'), InputEvent.CTRL_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest02.png"));
// enter details
guiSleep();
assertWindowname("jgridstart-requestwizard-0");
focusByName("givenname");
keyString("John\t");
keyString("Doe\t");
keyString("[email protected]\t");
keyString("N\t");
keyString(" \t\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest03.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// verification form
System.setProperty("wizard.show.help1", "true"); // simulate help btn1 pressed
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest04.png"));
assertWindowname("jgridstart-requestwizard-2");
// form display
JButton btn = (JButton) new BasicFinder().find(new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals("display form");
}
});
btn.doClick();
waitEnabled(JButton.class, "Close");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest05.png"));
assertWindowname("jgridstart-verification-form");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// close wizard
guiSleep();
assertWindowname("jgridstart-requestwizard-2");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest09.png"));
assertWindowname("jgridstart-requestwizard-3");
// show final screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest10.png"));
assertWindowname("jgridstart-requestwizard-4");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest11.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Renewal
*/
logger.info("Interactive testing scenario: Renewal");
System.setProperty("jgridstart.ca.local.hold", "true");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// start screen
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew01.png"));
assertWindowname("jgridstart-main-window");
// personal details
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('W');
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew02.png"));
assertWindowname("jgridstart-requestwizard-0");
focusByName("email");
keyString("\t");
keyString(password+"\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
// renew03.png used to be a password dialog, which was removed
// submit page
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew04.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// wait for approval page
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew05.png"));
assertWindowname("jgridstart-requestwizard-2");
// close wizard
guiSleep();
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
waitEnabled(JButton.class, "Next");
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew09.png"));
assertWindowname("jgridstart-requestwizard-3");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew10.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Import/export
*/
logger.info("Interactive testing scenario: Import/Export");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// starting screenshot (multiple certificates)
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport01.png"));
assertWindowname("jgridstart-main-window");
// export dialog
tester.key(new Integer('E'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Export");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport02.png"));
assertWindowname("jgridstart-export-file-dialog");
// enter name and do export
tester.keyString("my_certificate.p12\n");
Thread.sleep(2000);
saveScreenshot(new File(shotdir, prefix+"importexport03.png"));
assertWindowname("jgridstart-password-entry-decrypt");
tester.keyString(password+"\n");
guiSleep();
assertWindowname("jgridstart-main-window");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// import dialog
tester.key(new Integer('I'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Import");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport04.png"));
assertWindowname("jgridstart-import-file-dialog");
guiSleep();
// enter name and do import
tester.keyString("my_certificate.p12\n");
Thread.sleep(1000);
saveScreenshot(new File(shotdir, prefix+"importexport05.png"));
assertWindowname("jgridstart-password-entry-decrypt");
keyString(password+"\n");
guiSleep();
/*
* Certificate details
*/
logger.info("Interactive testing scenario: Certificate details");
// certificate details view
mainwnd.setSize(750, 480);
System.setProperty("view.showdetails", "true");
- URLLauncherCertificate.performAction("viewlist(false)", tester.findFocusOwner());
+ URLLauncherCertificate.performAction("viewlist(false)", mainwnd);
tester.key(KeyEvent.VK_F5);
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"viewdetails01.png"));
assertWindowname("jgridstart-main-window");
/*
* Exit!
*/
logger.info("Interactive testing finished");
/* Quit does a {@link System.exit}, which JUnit doesn't like. The
* error it gives is something like:
* [junit] Test <testclass> FAILED (crashed)
* So we leave it to the calling function to dispose of the window.
*/
//tester.key(new Integer('Q'), InputEvent.CTRL_MASK);
} finally {
guiSleep(); Thread.sleep(500); // for screenshot to complete ...
FileUtils.recursiveDelete(tmphome);
}
// exit!
return;
}
/** Write screenshot of current window to specified file as png.
* <p>
* Assumes a single screen. */
protected static void saveScreenshot(final File dst) throws AWTException, IOException, InterruptedException, InvocationTargetException {
final Robot robot = new Robot();
guiSleep(); guiSleep(); guiSleep();
// capture screen
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
logger.info("Saving screenshot: "+dst);
try {
// find active window area, or full desktop if that fails
Window w = AWT.getActiveWindow();
Rectangle captureSize = w != null ? w.getBounds() :
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
// take image
BufferedImage img = robot.createScreenCapture(captureSize);
img.flush();
ImageIO.write(img, "png", dst);
} catch(IOException e) {
System.err.println(e);
}
}
});
}
protected static void guiSleep() {
// process gui events
tester.waitForIdle();
}
/** Like {@link ComponentTester#keyString}, but correcting some characters.
* <p>
* While Abbot has features to deal with different locales, I have experienced
* problems where at {@code @} appeared to be typed as {@code "}. This can result,
* for example, in an invalid email address. This method tries to work around the
* blocking issues I've encountered here (very crude method though).
* @throws InterruptedException
*/
protected static void keyString(String s) throws AWTException, InterruptedException {
char[] c = s.toCharArray();
// initialize when needed
if (replacemap==null) {
logger.fine("Detecting robot keymapping");
replacemap = new HashMap<Character, Character>();
// create textbox, type in each character, store result
final String chars = "1234567890";
JFrame frame = new JFrame("Detecting key mapping (don't type yourself!)");
JTextField field = new JTextField("", 10);
frame.add(field);
frame.setSize(200, 100);
frame.setVisible(true);
for (int i=0; i<chars.length(); i++) {
try {
field.setText("");
tester.setModifiers(InputEvent.SHIFT_MASK, true);
tester.keyStroke(chars.charAt(i));
tester.setModifiers(InputEvent.SHIFT_MASK, false);
guiSleep();
replacemap.put(field.getText().charAt(0), chars.charAt(i));
} catch (Exception e) { }
}
frame.setVisible(false);
frame.dispose();
}
for (int i=0; i<c.length; i++) {
if (replacemap.containsKey(c[i])) {
guiSleep();
tester.setModifiers(InputEvent.SHIFT_MASK, true);
tester.keyStroke(replacemap.get(c[i]));
tester.setModifiers(InputEvent.SHIFT_MASK, false);
guiSleep();
} else {
tester.keyStroke(c[i]);
}
}
}
/** Assert the currently active window has the specified name */
protected static void assertWindowname(String name) throws InterruptedException, ComponentNotFoundException {
logger.fine("Expecting window name: "+name);
Window w = null;
for (int i=0; i<10; i++) {
guiSleep();
w = AWT.getActiveWindow();
if (w==null) continue;
if (name.equals(w.getName())) return;
Thread.sleep(100);
}
throw new ComponentNotFoundException("Window name not found: "+name + (w!=null ? (" (currently focused: "+w.getName()+")") : ""));
}
/** Wait for a component to be present and enabled.
* <p>
* @param klass Component descendant, like {@linkplain JLabel}
* @param text What text the component contains, or {@code null} for any
*/
protected static void waitEnabled(final Class<?> klass, final String text) throws MultipleComponentsFoundException, InterruptedException, ComponentNotFoundException {
Component c = null;
long timeout = 40000;
long start = System.currentTimeMillis();
while ( System.currentTimeMillis() - start < timeout ) {
try {
c = (Component)new BasicFinder().find(new Matcher() {
public boolean matches(Component c) {
return klass.isInstance(c) && (text==null || text.equals(getComponentText(c))) && c.isEnabled();
}
});
return;
} catch (Exception e) { }
guiSleep();
}
if (c==null) throw new ComponentNotFoundException("Component not found or enabled: "+text);
}
/** Return the text of a component, or {@code null} if not supported. */
protected static String getComponentText(final Component c) {
if (c instanceof JButton)
return ((JButton)c).getText();
if (c instanceof JLabel)
return ((JLabel)c).getText();
if (c instanceof JTextComponent)
return ((JTextComponent)c).getText();
// TODO when needed, add others
return null;
}
/** Gives focus to a {@linkplain Component} by its name */
protected static boolean focusByName(final String name) throws ComponentNotFoundException, MultipleComponentsFoundException {
Component c = findByName(name);
if (c.hasFocus()) return true;
// try ordinary method
if (c.requestFocusInWindow()) {
while (!c.hasFocus()) guiSleep();
return true;
}
// press tab until we have the correct focus
for (int i=0; i<25 /* TODO proper number */; i++) {
tester.keyStroke('\t');
guiSleep();
if (name.equals(AWT.getActiveWindow().getFocusOwner().getName())) return true;
}
// failed ...
logger.warning("Could not give focus to component: "+name);
return true;
}
/** Finds a {@linkplain Component} by its name */
protected static Component findByName(final String name) throws ComponentNotFoundException, MultipleComponentsFoundException {
return new BasicFinder().find(new Matcher() {
public boolean matches(Component c) {
return name.equals(c.getName());
}
});
}
}
| true | true | public static void doScreenshots(File shotdir) throws Exception {
shotdir.mkdirs();
String prefix = "jgridstart-screenshot-";
// setup temporary environment
logger.info("Setting up jGridstart interactive screenshot and testing environment");
File tmphome = FileUtils.createTempDir("jgridstart-home");
Window mainwnd = null;
try {
System.setProperty("jgridstart.ca.provider", "LocalCA");
System.setProperty("jgridstart.ca.local.hold", "true");
System.setProperty("user.home", tmphome.getCanonicalPath());
// create standard gui
nl.nikhef.jgridstart.gui.Main.main(new String[]{});
LogHelper.setupLogging(true);
// move mouse here since closing window may give up focus later
Thread.sleep(2000); guiSleep();
mainwnd = AWT.getActiveWindow();
assertNotNull(mainwnd);
tester.mouseMove(mainwnd.getComponents()[0]);
assertWindowname("jgridstart-main-window");
/*
* Request new
*/
logger.info("Interactive testing scenario: Request New");
// start screen
saveScreenshot(new File(shotdir, prefix+"newrequest01.png"));
// new request wizard
guiSleep(); tester.key(new Integer('N'), InputEvent.CTRL_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest02.png"));
// enter details
guiSleep();
assertWindowname("jgridstart-requestwizard-0");
focusByName("givenname");
keyString("John\t");
keyString("Doe\t");
keyString("[email protected]\t");
keyString("N\t");
keyString(" \t\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest03.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// verification form
System.setProperty("wizard.show.help1", "true"); // simulate help btn1 pressed
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest04.png"));
assertWindowname("jgridstart-requestwizard-2");
// form display
JButton btn = (JButton) new BasicFinder().find(new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals("display form");
}
});
btn.doClick();
waitEnabled(JButton.class, "Close");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest05.png"));
assertWindowname("jgridstart-verification-form");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// close wizard
guiSleep();
assertWindowname("jgridstart-requestwizard-2");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest09.png"));
assertWindowname("jgridstart-requestwizard-3");
// show final screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest10.png"));
assertWindowname("jgridstart-requestwizard-4");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest11.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Renewal
*/
logger.info("Interactive testing scenario: Renewal");
System.setProperty("jgridstart.ca.local.hold", "true");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// start screen
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew01.png"));
assertWindowname("jgridstart-main-window");
// personal details
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('W');
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew02.png"));
assertWindowname("jgridstart-requestwizard-0");
focusByName("email");
keyString("\t");
keyString(password+"\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
// renew03.png used to be a password dialog, which was removed
// submit page
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew04.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// wait for approval page
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew05.png"));
assertWindowname("jgridstart-requestwizard-2");
// close wizard
guiSleep();
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
waitEnabled(JButton.class, "Next");
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew09.png"));
assertWindowname("jgridstart-requestwizard-3");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew10.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Import/export
*/
logger.info("Interactive testing scenario: Import/Export");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// starting screenshot (multiple certificates)
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport01.png"));
assertWindowname("jgridstart-main-window");
// export dialog
tester.key(new Integer('E'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Export");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport02.png"));
assertWindowname("jgridstart-export-file-dialog");
// enter name and do export
tester.keyString("my_certificate.p12\n");
Thread.sleep(2000);
saveScreenshot(new File(shotdir, prefix+"importexport03.png"));
assertWindowname("jgridstart-password-entry-decrypt");
tester.keyString(password+"\n");
guiSleep();
assertWindowname("jgridstart-main-window");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// import dialog
tester.key(new Integer('I'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Import");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport04.png"));
assertWindowname("jgridstart-import-file-dialog");
guiSleep();
// enter name and do import
tester.keyString("my_certificate.p12\n");
Thread.sleep(1000);
saveScreenshot(new File(shotdir, prefix+"importexport05.png"));
assertWindowname("jgridstart-password-entry-decrypt");
keyString(password+"\n");
guiSleep();
/*
* Certificate details
*/
logger.info("Interactive testing scenario: Certificate details");
// certificate details view
mainwnd.setSize(750, 480);
System.setProperty("view.showdetails", "true");
URLLauncherCertificate.performAction("viewlist(false)", tester.findFocusOwner());
tester.key(KeyEvent.VK_F5);
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"viewdetails01.png"));
assertWindowname("jgridstart-main-window");
/*
* Exit!
*/
logger.info("Interactive testing finished");
/* Quit does a {@link System.exit}, which JUnit doesn't like. The
* error it gives is something like:
* [junit] Test <testclass> FAILED (crashed)
* So we leave it to the calling function to dispose of the window.
*/
//tester.key(new Integer('Q'), InputEvent.CTRL_MASK);
} finally {
guiSleep(); Thread.sleep(500); // for screenshot to complete ...
FileUtils.recursiveDelete(tmphome);
}
// exit!
return;
}
| public static void doScreenshots(File shotdir) throws Exception {
shotdir.mkdirs();
String prefix = "jgridstart-screenshot-";
// setup temporary environment
logger.info("Setting up jGridstart interactive screenshot and testing environment");
File tmphome = FileUtils.createTempDir("jgridstart-home");
Window mainwnd = null;
try {
System.setProperty("jgridstart.ca.provider", "LocalCA");
System.setProperty("jgridstart.ca.local.hold", "true");
System.setProperty("user.home", tmphome.getCanonicalPath());
// create standard gui
nl.nikhef.jgridstart.gui.Main.main(new String[]{});
LogHelper.setupLogging(true);
// move mouse here since closing window may give up focus later
Thread.sleep(2000); guiSleep();
mainwnd = AWT.getActiveWindow();
assertNotNull(mainwnd);
tester.mouseMove(mainwnd.getComponents()[0]);
assertWindowname("jgridstart-main-window");
/*
* Request new
*/
logger.info("Interactive testing scenario: Request New");
// start screen
saveScreenshot(new File(shotdir, prefix+"newrequest01.png"));
// new request wizard
guiSleep(); tester.key(new Integer('N'), InputEvent.CTRL_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest02.png"));
// enter details
guiSleep();
assertWindowname("jgridstart-requestwizard-0");
focusByName("givenname");
keyString("John\t");
keyString("Doe\t");
keyString("[email protected]\t");
keyString("N\t");
keyString(" \t\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest03.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// verification form
System.setProperty("wizard.show.help1", "true"); // simulate help btn1 pressed
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest04.png"));
assertWindowname("jgridstart-requestwizard-2");
// form display
JButton btn = (JButton) new BasicFinder().find(new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals("display form");
}
});
btn.doClick();
waitEnabled(JButton.class, "Close");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest05.png"));
assertWindowname("jgridstart-verification-form");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// close wizard
guiSleep();
assertWindowname("jgridstart-requestwizard-2");
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
guiSleep();
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest09.png"));
assertWindowname("jgridstart-requestwizard-3");
// show final screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest10.png"));
assertWindowname("jgridstart-requestwizard-4");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"newrequest11.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Renewal
*/
logger.info("Interactive testing scenario: Renewal");
System.setProperty("jgridstart.ca.local.hold", "true");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// start screen
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew01.png"));
assertWindowname("jgridstart-main-window");
// personal details
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('W');
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew02.png"));
assertWindowname("jgridstart-requestwizard-0");
focusByName("email");
keyString("\t");
keyString(password+"\t");
keyString(password+"\t");
keyString(password+"\t");
// wait for submission screen
tester.key(new Integer('N'), InputEvent.ALT_MASK);
// renew03.png used to be a password dialog, which was removed
// submit page
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew04.png"));
assertWindowname("jgridstart-requestwizard-1");
waitEnabled(JButton.class, "Next");
// wait for approval page
tester.key(new Integer('N'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew05.png"));
assertWindowname("jgridstart-requestwizard-2");
// close wizard
guiSleep();
tester.key(new Integer('C'), InputEvent.ALT_MASK);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew06.png"));
assertWindowname("jgridstart-main-window");
// enable certificate in LocalCA and refresh pane
System.setProperty("jgridstart.ca.local.hold", "false");
tester.key(KeyEvent.VK_F5);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew07.png"));
assertWindowname("jgridstart-main-window");
// show request wizard again
tester.key(new Integer('A'), InputEvent.ALT_MASK);
tester.key('R');
waitEnabled(JButton.class, "Next");
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew08.png"));
assertWindowname("jgridstart-requestwizard-2");
// install step
tester.key(new Integer('N'), InputEvent.ALT_MASK);
Thread.sleep(1000);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew09.png"));
assertWindowname("jgridstart-requestwizard-3");
// exit wizard
tester.key(new Integer('C'), InputEvent.ALT_MASK);
// save final screenshot
guiSleep();
saveScreenshot(new File(shotdir, prefix+"renew10.png"));
assertWindowname("jgridstart-main-window");
guiSleep();
/*
* Import/export
*/
logger.info("Interactive testing scenario: Import/Export");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// starting screenshot (multiple certificates)
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport01.png"));
assertWindowname("jgridstart-main-window");
// export dialog
tester.key(new Integer('E'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Export");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport02.png"));
assertWindowname("jgridstart-export-file-dialog");
// enter name and do export
tester.keyString("my_certificate.p12\n");
Thread.sleep(2000);
saveScreenshot(new File(shotdir, prefix+"importexport03.png"));
assertWindowname("jgridstart-password-entry-decrypt");
tester.keyString(password+"\n");
guiSleep();
assertWindowname("jgridstart-main-window");
// forget password so we certainly get the password dialog
PasswordCache.getInstance().clear();
// import dialog
tester.key(new Integer('I'), InputEvent.CTRL_MASK);
waitEnabled(JButton.class, "Import");
guiSleep();
saveScreenshot(new File(shotdir, prefix+"importexport04.png"));
assertWindowname("jgridstart-import-file-dialog");
guiSleep();
// enter name and do import
tester.keyString("my_certificate.p12\n");
Thread.sleep(1000);
saveScreenshot(new File(shotdir, prefix+"importexport05.png"));
assertWindowname("jgridstart-password-entry-decrypt");
keyString(password+"\n");
guiSleep();
/*
* Certificate details
*/
logger.info("Interactive testing scenario: Certificate details");
// certificate details view
mainwnd.setSize(750, 480);
System.setProperty("view.showdetails", "true");
URLLauncherCertificate.performAction("viewlist(false)", mainwnd);
tester.key(KeyEvent.VK_F5);
Thread.sleep(500);
guiSleep();
saveScreenshot(new File(shotdir, prefix+"viewdetails01.png"));
assertWindowname("jgridstart-main-window");
/*
* Exit!
*/
logger.info("Interactive testing finished");
/* Quit does a {@link System.exit}, which JUnit doesn't like. The
* error it gives is something like:
* [junit] Test <testclass> FAILED (crashed)
* So we leave it to the calling function to dispose of the window.
*/
//tester.key(new Integer('Q'), InputEvent.CTRL_MASK);
} finally {
guiSleep(); Thread.sleep(500); // for screenshot to complete ...
FileUtils.recursiveDelete(tmphome);
}
// exit!
return;
}
|
diff --git a/jython/src/org/python/modules/types.java b/jython/src/org/python/modules/types.java
index 4864d0cf..6a3a04f5 100644
--- a/jython/src/org/python/modules/types.java
+++ b/jython/src/org/python/modules/types.java
@@ -1,60 +1,60 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.modules;
import org.python.core.*;
public class types implements ClassDictInit {
public static PyString __doc__ = new PyString(
"Define names for all type symbols known in the standard "+
"interpreter.\n"+
"\n"+
"Types that are part of optional modules (e.g. array) "+
"are not listed.\n"
);
// xxx change some of these
public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
- dict.__setitem__("UnicodeType", PyType.fromClass(PyString.class));
+ dict.__setitem__("UnicodeType", PyType.fromClass(PyUnicode.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
}
| true | true | public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("UnicodeType", PyType.fromClass(PyString.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
| public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("UnicodeType", PyType.fromClass(PyUnicode.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
|
diff --git a/src/com/sonyericsson/chkbugreport/LineReader.java b/src/com/sonyericsson/chkbugreport/LineReader.java
index b924e37..1506e3a 100644
--- a/src/com/sonyericsson/chkbugreport/LineReader.java
+++ b/src/com/sonyericsson/chkbugreport/LineReader.java
@@ -1,62 +1,67 @@
/*
* Copyright (C) 2011 Sony Ericsson Mobile Communications AB
*
* This file is part of ChkBugReport.
*
* ChkBugReport 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.
*
* ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sonyericsson.chkbugreport;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LineReader {
private InputStream mIs;
public LineReader(InputStream is) {
mIs = new BufferedInputStream(is);
}
public String readLine() {
StringBuffer sb = new StringBuffer();
+ boolean firstWarning = false;
try {
while (true) {
int b = mIs.read();
if (b < 0) {
if (sb.length() == 0) return null;
break; // EOF
}
- if (b == 0xd) continue; // Skip ungly windows line ending
+ if (b == 0xd) {
+ if (firstWarning) break;
+ firstWarning = true;
+ continue; // Skip ungly windows line ending
+ }
if (b == 0xa) break; // EOL
sb.append((char)b);
}
} catch (IOException e) {
// Ignore exception
e.printStackTrace();
return null;
}
return sb.toString();
}
public void close() {
try {
mIs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | true | public String readLine() {
StringBuffer sb = new StringBuffer();
try {
while (true) {
int b = mIs.read();
if (b < 0) {
if (sb.length() == 0) return null;
break; // EOF
}
if (b == 0xd) continue; // Skip ungly windows line ending
if (b == 0xa) break; // EOL
sb.append((char)b);
}
} catch (IOException e) {
// Ignore exception
e.printStackTrace();
return null;
}
return sb.toString();
}
| public String readLine() {
StringBuffer sb = new StringBuffer();
boolean firstWarning = false;
try {
while (true) {
int b = mIs.read();
if (b < 0) {
if (sb.length() == 0) return null;
break; // EOF
}
if (b == 0xd) {
if (firstWarning) break;
firstWarning = true;
continue; // Skip ungly windows line ending
}
if (b == 0xa) break; // EOL
sb.append((char)b);
}
} catch (IOException e) {
// Ignore exception
e.printStackTrace();
return null;
}
return sb.toString();
}
|
diff --git a/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java b/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java
index 9ff469b..d571067 100644
--- a/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java
+++ b/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java
@@ -1,99 +1,104 @@
package de.hydrox.bukkit.DroxPerms;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class DroxPlayerCommands implements CommandExecutor {
private DroxPerms plugin;
public DroxPlayerCommands(DroxPerms plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
if (!(sender.hasPermission("droxperms.players"))) {
sender.sendMessage("You don't have permission to modify Players.");
return true;
}
Player caller = null;
if (sender instanceof Player) {
caller = (Player) sender;
}
boolean result = false;
if (split.length == 0) {
return false;
} else if (caller != null && caller.getName().equalsIgnoreCase(split[1])
&& !(sender.hasPermission("droxperms.players.self"))) {
sender.sendMessage("You don't have permission to modify your Permissions.");
return true;
}
// add permission
if (split[0].equalsIgnoreCase("addperm")) {
if (split.length == 3) {
// add global permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// add world permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove permission
if (split[0].equalsIgnoreCase("remperm")) {
if (split.length == 3) {
// remove global permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// remove world permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// add subgroup
if (split[0].equalsIgnoreCase("addsub")) {
if (split.length == 3) {
result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove subgroup
if (split[0].equalsIgnoreCase("remsub")) {
if (split.length == 3) {
result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("setgroup")) {
if (split.length == 3) {
result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("has")) {
if (split.length == 3) {
- result = plugin.getServer().getPlayer(split[1]).hasPermission(split[2]);
- if (result) {
- sender.sendMessage(split[1] + " has permission for " + split[2]);
+ Player player = plugin.getServer().getPlayer(split[1]);
+ if (player == null) {
+ sender.sendMessage(split[1] + " is not online");
} else {
- sender.sendMessage(split[1] + " doesn't have permission for " + split[2]);
+ result = player.hasPermission(split[2]);
+ if (result) {
+ sender.sendMessage(split[1] + " has permission for " + split[2]);
+ } else {
+ sender.sendMessage(split[1] + " doesn't have permission for " + split[2]);
+ }
}
}
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
if (!(sender.hasPermission("droxperms.players"))) {
sender.sendMessage("You don't have permission to modify Players.");
return true;
}
Player caller = null;
if (sender instanceof Player) {
caller = (Player) sender;
}
boolean result = false;
if (split.length == 0) {
return false;
} else if (caller != null && caller.getName().equalsIgnoreCase(split[1])
&& !(sender.hasPermission("droxperms.players.self"))) {
sender.sendMessage("You don't have permission to modify your Permissions.");
return true;
}
// add permission
if (split[0].equalsIgnoreCase("addperm")) {
if (split.length == 3) {
// add global permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// add world permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove permission
if (split[0].equalsIgnoreCase("remperm")) {
if (split.length == 3) {
// remove global permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// remove world permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// add subgroup
if (split[0].equalsIgnoreCase("addsub")) {
if (split.length == 3) {
result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove subgroup
if (split[0].equalsIgnoreCase("remsub")) {
if (split.length == 3) {
result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("setgroup")) {
if (split.length == 3) {
result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("has")) {
if (split.length == 3) {
result = plugin.getServer().getPlayer(split[1]).hasPermission(split[2]);
if (result) {
sender.sendMessage(split[1] + " has permission for " + split[2]);
} else {
sender.sendMessage(split[1] + " doesn't have permission for " + split[2]);
}
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
if (!(sender.hasPermission("droxperms.players"))) {
sender.sendMessage("You don't have permission to modify Players.");
return true;
}
Player caller = null;
if (sender instanceof Player) {
caller = (Player) sender;
}
boolean result = false;
if (split.length == 0) {
return false;
} else if (caller != null && caller.getName().equalsIgnoreCase(split[1])
&& !(sender.hasPermission("droxperms.players.self"))) {
sender.sendMessage("You don't have permission to modify your Permissions.");
return true;
}
// add permission
if (split[0].equalsIgnoreCase("addperm")) {
if (split.length == 3) {
// add global permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// add world permission
result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove permission
if (split[0].equalsIgnoreCase("remperm")) {
if (split.length == 3) {
// remove global permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]);
} else if (split.length == 4) {
// remove world permission
result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// add subgroup
if (split[0].equalsIgnoreCase("addsub")) {
if (split.length == 3) {
result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// remove subgroup
if (split[0].equalsIgnoreCase("remsub")) {
if (split.length == 3) {
result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("setgroup")) {
if (split.length == 3) {
result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]);
}
plugin.refreshPlayer(plugin.getServer().getPlayer(split[1]));
return result;
}
// set group
if (split[0].equalsIgnoreCase("has")) {
if (split.length == 3) {
Player player = plugin.getServer().getPlayer(split[1]);
if (player == null) {
sender.sendMessage(split[1] + " is not online");
} else {
result = player.hasPermission(split[2]);
if (result) {
sender.sendMessage(split[1] + " has permission for " + split[2]);
} else {
sender.sendMessage(split[1] + " doesn't have permission for " + split[2]);
}
}
}
}
return true;
}
|
diff --git a/jsf-ri/test/com/sun/faces/context/TestPartialResponseWriter.java b/jsf-ri/test/com/sun/faces/context/TestPartialResponseWriter.java
index 60c1e886e..035175112 100644
--- a/jsf-ri/test/com/sun/faces/context/TestPartialResponseWriter.java
+++ b/jsf-ri/test/com/sun/faces/context/TestPartialResponseWriter.java
@@ -1,134 +1,134 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 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 com.sun.faces.context;
import javax.faces.FactoryFinder;
import javax.faces.component.UIInput;
import javax.faces.component.UIOutput;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import com.sun.faces.cactus.ServletFacesTestCase;
/**
* <B>TestPartialResponseWriter.java</B> is a class ...
* <p/>
* <B>Lifetime And Scope</B> <P>
*/
public class TestPartialResponseWriter extends ServletFacesTestCase // ServletTestCase
{
//
// Protected Constants
//
// Class Variables
//
//
// Instance Variables
//
private ResponseWriter writer = null;
private PartialResponseWriter pWriter = null;
private RenderKit renderKit = null;
private StringWriter sw = null;
// Attribute Instance Variables
// Relationship Instance Variables
//
// Constructors and Initializers
//
public TestPartialResponseWriter() {
super("TestPartialResponseWriter.java");
}
public TestPartialResponseWriter(String name) {
super(name);
}
//
// Class methods
//
//
// General Methods
//
public void setUp() {
super.setUp();
RenderKitFactory renderKitFactory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
renderKit = renderKitFactory.getRenderKit(getFacesContext(),
RenderKitFactory.HTML_BASIC_RENDER_KIT);
sw = new StringWriter();
writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1");
pWriter = new PartialResponseWriter(writer);
}
// Tests that the <extension> element is placed correctly in the partial response output
public void testExtension() {
try {
pWriter.startDocument();
pWriter.startUpdate(PartialResponseWriter.VIEW_STATE_MARKER);
pWriter.write("foo");
pWriter.endUpdate();
pWriter.startExtension(Collections.<String, String>emptyMap());
pWriter.startElement("data", null);
pWriter.endElement("data");
pWriter.endExtension();
pWriter.endDocument();
- assertTrue(sw.toString().indexOf("</upe><extension><data></data></extension></changes></partial-response>") >= 0);
+ assertTrue(sw.toString().indexOf("</update><extension><data></data></extension></changes></partial-response>") >= 0);
} catch (IOException e) {
assertTrue(false);
}
}
}
| true | true | public void testExtension() {
try {
pWriter.startDocument();
pWriter.startUpdate(PartialResponseWriter.VIEW_STATE_MARKER);
pWriter.write("foo");
pWriter.endUpdate();
pWriter.startExtension(Collections.<String, String>emptyMap());
pWriter.startElement("data", null);
pWriter.endElement("data");
pWriter.endExtension();
pWriter.endDocument();
assertTrue(sw.toString().indexOf("</upe><extension><data></data></extension></changes></partial-response>") >= 0);
} catch (IOException e) {
assertTrue(false);
}
}
| public void testExtension() {
try {
pWriter.startDocument();
pWriter.startUpdate(PartialResponseWriter.VIEW_STATE_MARKER);
pWriter.write("foo");
pWriter.endUpdate();
pWriter.startExtension(Collections.<String, String>emptyMap());
pWriter.startElement("data", null);
pWriter.endElement("data");
pWriter.endExtension();
pWriter.endDocument();
assertTrue(sw.toString().indexOf("</update><extension><data></data></extension></changes></partial-response>") >= 0);
} catch (IOException e) {
assertTrue(false);
}
}
|
diff --git a/src/net/sf/gogui/gogui/GoGuiActions.java b/src/net/sf/gogui/gogui/GoGuiActions.java
index 99f1f5cd..03c64735 100644
--- a/src/net/sf/gogui/gogui/GoGuiActions.java
+++ b/src/net/sf/gogui/gogui/GoGuiActions.java
@@ -1,305 +1,305 @@
//----------------------------------------------------------------------------
// $Id$
//----------------------------------------------------------------------------
package net.sf.gogui.gogui;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URL;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.KeyStroke;
import net.sf.gogui.game.ConstNode;
import net.sf.gogui.game.NodeUtil;
import net.sf.gogui.gui.GuiUtil;
import net.sf.gogui.util.Platform;
/** Actions used in the GoGui tool bar and menu bar.
This class has a cyclic dependency with class GoGui, however the
dependency has a simple structure. The class contains actions that wrap a
call to public functions of GoGui and associate a name, icon, description
and accelerator key. There are also update functions that are used to
enable actions or add additional information to their descriptions
depending on the state of GoGui as far as it is accessible through public
functions.
*/
public class GoGuiActions
{
public final AbstractAction m_actionAbout;
public final AbstractAction m_actionAttachProgram;
public final AbstractAction m_actionBackward;
public final AbstractAction m_actionBackwardTen;
public final AbstractAction m_actionBeginning;
public final AbstractAction m_actionDetachProgram;
public final AbstractAction m_actionDocumentation;
public final AbstractAction m_actionEnd;
public final AbstractAction m_actionForward;
public final AbstractAction m_actionForwardTen;
public final AbstractAction m_actionInterrupt;
public final AbstractAction m_actionNextVariation;
public final AbstractAction m_actionNewGame;
public final AbstractAction m_actionOpen;
public final AbstractAction m_actionPass;
public final AbstractAction m_actionPlay;
public final AbstractAction m_actionPreviousVariation;
public final AbstractAction m_actionPrint;
public final AbstractAction m_actionSave;
public final AbstractAction m_actionSaveAs;
public final AbstractAction m_actionQuit;
public GoGuiActions(GoGui goGui)
{
m_goGui = goGui;
m_actionAbout = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAbout(); } };
init(m_actionAbout, "About",
"Show information about GoGui, Go program and Java environment");
m_actionAttachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAttachProgram(); } };
init(m_actionAttachProgram, "Attach Program...",
"Attach Go program to current game", KeyEvent.VK_A, null);
m_actionBackward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(1); } };
init(m_actionBackward, "Backward", "Go one move backward",
KeyEvent.VK_LEFT, "gogui-previous");
m_actionBackwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(10); } };
init(m_actionBackwardTen, "Backward 10", "Go ten moves backward",
KeyEvent.VK_LEFT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionBeginning = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBeginning(); } };
init(m_actionBeginning, "Beginning", "Go to beginning of game",
KeyEvent.VK_HOME, "gogui-first");
m_actionDetachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDetachProgram(); } };
init(m_actionDetachProgram, "Detach Program...",
"Detach Go program from current game and terminate it");
m_actionDocumentation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDocumentation(); } };
- init(m_actionAbout, "GoGui Documentation", "Browse GoGui manual",
- KeyEvent.VK_F1, getFunctionKeyShortcut());
+ init(m_actionDocumentation, "GoGui Documentation",
+ "Open GoGui manual", KeyEvent.VK_F1, getFunctionKeyShortcut());
m_actionEnd = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionEnd(); } };
init(m_actionEnd, "End", "Go to end of game",
KeyEvent.VK_END, "gogui-last");
m_actionForward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(1); } };
init(m_actionForward, "Forward", "Go one move forward",
KeyEvent.VK_RIGHT, "gogui-next");
m_actionForwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(10); } };
init(m_actionForwardTen, "Forward 10", "Go ten moves forward",
KeyEvent.VK_RIGHT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionInterrupt = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionInterrupt(); } };
init(m_actionInterrupt, "Interrupt", "Interrupt program",
KeyEvent.VK_ESCAPE, 0, "gogui-interrupt");
m_actionNextVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNextVariation(); } };
init(m_actionNextVariation, "Next Variation", "Go to next variation",
KeyEvent.VK_DOWN, "gogui-down");
m_actionNewGame = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNewGame(); } };
init(m_actionNewGame, "New Game", "Clear board and begin new game",
"gogui-newgame");
m_actionOpen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionOpen(); } };
init(m_actionOpen, "Open...", "Open game", KeyEvent.VK_O,
"document-open");
m_actionPass = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPass(); } };
init(m_actionPass, "Pass", "Play a pass", KeyEvent.VK_F2,
getFunctionKeyShortcut(), "gogui-pass");
m_actionPlay = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPlay(false); } };
init(m_actionPlay, "Play", "Make computer play", KeyEvent.VK_F5,
getFunctionKeyShortcut(), "gogui-play");
m_actionPreviousVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPreviousVariation(); } };
init(m_actionPreviousVariation, "Previous Variation",
"Go to previous variation", KeyEvent.VK_UP, "gogui-up");
m_actionPrint = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPrint(); } };
init(m_actionPrint, "Print...", "Print current position",
KeyEvent.VK_P, null);
m_actionSave = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSave(); } };
init(m_actionSave, "Save", "Save game", KeyEvent.VK_S,
"document-save");
m_actionSaveAs = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSaveAs(); } };
init(m_actionSaveAs, "Save As...", "Save game", "document-save-as");
m_actionQuit = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionQuit(); } };
init(m_actionQuit, "Quit", "Quit GoGui", KeyEvent.VK_Q, null);
}
public void update()
{
ConstNode node = m_goGui.getGame().getCurrentNode();
boolean hasFather = (node.getFatherConst() != null);
boolean hasChildren = (node.getNumberChildren() > 0);
boolean hasNextVariation = (NodeUtil.getNextVariation(node) != null);
boolean hasPreviousVariation =
(NodeUtil.getPreviousVariation(node) != null);
boolean isProgramAttached = m_goGui.isProgramAttached();
m_actionBackward.setEnabled(hasFather);
m_actionBackwardTen.setEnabled(hasFather);
m_actionBeginning.setEnabled(hasFather);
m_actionDetachProgram.setEnabled(isProgramAttached);
m_actionEnd.setEnabled(hasChildren);
m_actionForward.setEnabled(hasChildren);
m_actionForwardTen.setEnabled(hasChildren);
m_actionInterrupt.setEnabled(isProgramAttached);
m_actionNextVariation.setEnabled(hasNextVariation);
m_actionPlay.setEnabled(isProgramAttached);
m_actionPreviousVariation.setEnabled(hasPreviousVariation);
updateFile(m_goGui.getFile());
}
private final GoGui m_goGui;
private void init(AbstractAction action, String name, String desc)
{
init(action, name, desc, null, 0, null);
}
private void init(AbstractAction action, String name, String desc,
String icon)
{
init(action, name, desc, null, 0, icon);
}
private void init(AbstractAction action, String name, String desc,
int accel, String icon)
{
init(action, name, desc, new Integer(accel), getShortcut(), icon);
}
private void init(AbstractAction action, String name, String desc,
int accel, int modifier, String icon)
{
init(action, name, desc, new Integer(accel), modifier, icon);
}
private void init(AbstractAction action, String name, String desc,
int accel, int modifier)
{
init(action, name, desc, new Integer(accel), modifier, null);
}
private void init(AbstractAction action, String name, String desc,
Integer accel, int modifier, String icon)
{
action.putValue(AbstractAction.NAME, name);
setDescription(action, desc);
if (accel != null)
{
KeyStroke keyStroke = getKeyStroke(accel.intValue(), modifier);
action.putValue(AbstractAction.ACCELERATOR_KEY, keyStroke);
}
if (icon != null)
action.putValue(AbstractAction.SMALL_ICON,
GuiUtil.getIcon(icon, name));
}
private void setDescription(AbstractAction action, String desc)
{
action.putValue(AbstractAction.SHORT_DESCRIPTION, desc);
}
/** Get shortcut modifier for function keys.
Returns 0, unless platform is Mac.
*/
private static int getFunctionKeyShortcut()
{
if (Platform.isMac())
return getShortcut();
return 0;
}
private static KeyStroke getKeyStroke(int keyCode, int modifier)
{
return KeyStroke.getKeyStroke(keyCode, modifier);
}
private static int getShortcut()
{
return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
}
private void updateFile(File file)
{
String desc = "Save game";
if (file != null)
desc = desc + " (" + file + ")";
setDescription(m_actionSave, desc);
m_actionSave.setEnabled(file != null && m_goGui.isModified());
}
}
| true | true | public GoGuiActions(GoGui goGui)
{
m_goGui = goGui;
m_actionAbout = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAbout(); } };
init(m_actionAbout, "About",
"Show information about GoGui, Go program and Java environment");
m_actionAttachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAttachProgram(); } };
init(m_actionAttachProgram, "Attach Program...",
"Attach Go program to current game", KeyEvent.VK_A, null);
m_actionBackward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(1); } };
init(m_actionBackward, "Backward", "Go one move backward",
KeyEvent.VK_LEFT, "gogui-previous");
m_actionBackwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(10); } };
init(m_actionBackwardTen, "Backward 10", "Go ten moves backward",
KeyEvent.VK_LEFT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionBeginning = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBeginning(); } };
init(m_actionBeginning, "Beginning", "Go to beginning of game",
KeyEvent.VK_HOME, "gogui-first");
m_actionDetachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDetachProgram(); } };
init(m_actionDetachProgram, "Detach Program...",
"Detach Go program from current game and terminate it");
m_actionDocumentation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDocumentation(); } };
init(m_actionAbout, "GoGui Documentation", "Browse GoGui manual",
KeyEvent.VK_F1, getFunctionKeyShortcut());
m_actionEnd = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionEnd(); } };
init(m_actionEnd, "End", "Go to end of game",
KeyEvent.VK_END, "gogui-last");
m_actionForward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(1); } };
init(m_actionForward, "Forward", "Go one move forward",
KeyEvent.VK_RIGHT, "gogui-next");
m_actionForwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(10); } };
init(m_actionForwardTen, "Forward 10", "Go ten moves forward",
KeyEvent.VK_RIGHT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionInterrupt = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionInterrupt(); } };
init(m_actionInterrupt, "Interrupt", "Interrupt program",
KeyEvent.VK_ESCAPE, 0, "gogui-interrupt");
m_actionNextVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNextVariation(); } };
init(m_actionNextVariation, "Next Variation", "Go to next variation",
KeyEvent.VK_DOWN, "gogui-down");
m_actionNewGame = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNewGame(); } };
init(m_actionNewGame, "New Game", "Clear board and begin new game",
"gogui-newgame");
m_actionOpen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionOpen(); } };
init(m_actionOpen, "Open...", "Open game", KeyEvent.VK_O,
"document-open");
m_actionPass = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPass(); } };
init(m_actionPass, "Pass", "Play a pass", KeyEvent.VK_F2,
getFunctionKeyShortcut(), "gogui-pass");
m_actionPlay = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPlay(false); } };
init(m_actionPlay, "Play", "Make computer play", KeyEvent.VK_F5,
getFunctionKeyShortcut(), "gogui-play");
m_actionPreviousVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPreviousVariation(); } };
init(m_actionPreviousVariation, "Previous Variation",
"Go to previous variation", KeyEvent.VK_UP, "gogui-up");
m_actionPrint = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPrint(); } };
init(m_actionPrint, "Print...", "Print current position",
KeyEvent.VK_P, null);
m_actionSave = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSave(); } };
init(m_actionSave, "Save", "Save game", KeyEvent.VK_S,
"document-save");
m_actionSaveAs = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSaveAs(); } };
init(m_actionSaveAs, "Save As...", "Save game", "document-save-as");
m_actionQuit = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionQuit(); } };
init(m_actionQuit, "Quit", "Quit GoGui", KeyEvent.VK_Q, null);
}
| public GoGuiActions(GoGui goGui)
{
m_goGui = goGui;
m_actionAbout = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAbout(); } };
init(m_actionAbout, "About",
"Show information about GoGui, Go program and Java environment");
m_actionAttachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionAttachProgram(); } };
init(m_actionAttachProgram, "Attach Program...",
"Attach Go program to current game", KeyEvent.VK_A, null);
m_actionBackward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(1); } };
init(m_actionBackward, "Backward", "Go one move backward",
KeyEvent.VK_LEFT, "gogui-previous");
m_actionBackwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBackward(10); } };
init(m_actionBackwardTen, "Backward 10", "Go ten moves backward",
KeyEvent.VK_LEFT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionBeginning = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionBeginning(); } };
init(m_actionBeginning, "Beginning", "Go to beginning of game",
KeyEvent.VK_HOME, "gogui-first");
m_actionDetachProgram = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDetachProgram(); } };
init(m_actionDetachProgram, "Detach Program...",
"Detach Go program from current game and terminate it");
m_actionDocumentation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionDocumentation(); } };
init(m_actionDocumentation, "GoGui Documentation",
"Open GoGui manual", KeyEvent.VK_F1, getFunctionKeyShortcut());
m_actionEnd = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionEnd(); } };
init(m_actionEnd, "End", "Go to end of game",
KeyEvent.VK_END, "gogui-last");
m_actionForward = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(1); } };
init(m_actionForward, "Forward", "Go one move forward",
KeyEvent.VK_RIGHT, "gogui-next");
m_actionForwardTen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionForward(10); } };
init(m_actionForwardTen, "Forward 10", "Go ten moves forward",
KeyEvent.VK_RIGHT, getShortcut() | ActionEvent.SHIFT_MASK, null);
m_actionInterrupt = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionInterrupt(); } };
init(m_actionInterrupt, "Interrupt", "Interrupt program",
KeyEvent.VK_ESCAPE, 0, "gogui-interrupt");
m_actionNextVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNextVariation(); } };
init(m_actionNextVariation, "Next Variation", "Go to next variation",
KeyEvent.VK_DOWN, "gogui-down");
m_actionNewGame = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionNewGame(); } };
init(m_actionNewGame, "New Game", "Clear board and begin new game",
"gogui-newgame");
m_actionOpen = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionOpen(); } };
init(m_actionOpen, "Open...", "Open game", KeyEvent.VK_O,
"document-open");
m_actionPass = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPass(); } };
init(m_actionPass, "Pass", "Play a pass", KeyEvent.VK_F2,
getFunctionKeyShortcut(), "gogui-pass");
m_actionPlay = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPlay(false); } };
init(m_actionPlay, "Play", "Make computer play", KeyEvent.VK_F5,
getFunctionKeyShortcut(), "gogui-play");
m_actionPreviousVariation = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPreviousVariation(); } };
init(m_actionPreviousVariation, "Previous Variation",
"Go to previous variation", KeyEvent.VK_UP, "gogui-up");
m_actionPrint = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionPrint(); } };
init(m_actionPrint, "Print...", "Print current position",
KeyEvent.VK_P, null);
m_actionSave = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSave(); } };
init(m_actionSave, "Save", "Save game", KeyEvent.VK_S,
"document-save");
m_actionSaveAs = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionSaveAs(); } };
init(m_actionSaveAs, "Save As...", "Save game", "document-save-as");
m_actionQuit = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
m_goGui.actionQuit(); } };
init(m_actionQuit, "Quit", "Quit GoGui", KeyEvent.VK_Q, null);
}
|
diff --git a/MCMCStructureLearning/src/MCMC.java b/MCMCStructureLearning/src/MCMC.java
index bbac5c1..d8eb9f4 100644
--- a/MCMCStructureLearning/src/MCMC.java
+++ b/MCMCStructureLearning/src/MCMC.java
@@ -1,171 +1,171 @@
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
public abstract class MCMC {
public static double CurrentScore;
public static void main(String[] args)
{
if(args.length < 7)
{
System.out.println("Arguments required: <scoring method> <mixing steps> <running steps> <number of disease states> <number of allele codes> <data files> <output file> <alpha>");
return;
}
//parse data
Parser p = new Parser();
String[] files = new String[args.length-7];
for(int i = 5; i < args.length-2;i++)
{
files[i-5] = args[i];
}
int[][] data = p.Parse(files);
if(data != null)
{
System.out.println("Number of snps: "+(data[0].length - 1));
int numSNPs = data[0].length - 1;
//parse integer arguments
int mixingSteps = 0;
int runningSteps = 0;
int diseaseStates = 0;
int alleleStates = 0;
double alpha = 0;
try{
mixingSteps = Integer.parseInt(args[1]);
runningSteps = Integer.parseInt(args[2]);
diseaseStates = Integer.parseInt(args[3]);
alleleStates = Integer.parseInt(args[4]);
}
catch(NumberFormatException e)
{
System.out.println("Can not parse integer arguments.");
return;
}
//parse score function argument
Scorer s = null;
if(args[0].equals("AIC"))
{
- s = new AIC(data, alleleStates, diseaseStates);
+ s = new AIC(data, alleleStates, diseaseStates, alpha);
}
else if(args[0].equals("BIC"))
{
- s = new BIC(data, alleleStates, diseaseStates);
+ s = new BIC(data, alleleStates, diseaseStates, alpha);
}
else if(args[0].equals("BDeu"))
{
s = new BDeu(data, alleleStates, diseaseStates, alpha);
}
else
{
System.out.println("Scoring method does not exist.");
return;
}
if(mixingSteps >= 0 && runningSteps > 0 && diseaseStates > 1)
{
//calculate posterior probability of each edge and print to output file
PrintWriter out;
try
{
out = new PrintWriter(new FileWriter(args[args.length-1]));
int[] snpCounts = RunMC(mixingSteps, runningSteps, s, numSNPs, diseaseStates);
for(int i = 0; i < snpCounts.length; i++)
{
//print out snps that have a posterior probability greater than 0
if(snpCounts[i] > 0)
{
out.println(Integer.toString(i) + ": " + Double.toString((double)snpCounts[i]/runningSteps));
}
}
out.close();
}
catch (IOException e)
{
System.out.println("Can not write to file.");
}
}
}
return;
}
public static int[] RunMC(int mixingSteps, int runningSteps, Scorer s, int numSNPs, int diseaseStates)
{
//mixingSteps is the number of steps before we start counting how many times each edge is seen.
//runningSteps is the number of steps in which we count how many times each edge is seen.
//returns an array indexed by snp index that gives the number of times each snp was a parent snp during the last runningSteps steps
ArrayList<Integer> parents = new ArrayList<Integer>();
CurrentScore = s.Score(parents);
for(int i = 0; i < mixingSteps; i++)
{
parents = MCMCstep(parents, s, numSNPs, diseaseStates);
}
int[] snpCounts = new int[numSNPs];
double averageParentSize = 0;
int maxParentSize =0;
for(int i=0; i < runningSteps; i++)
{
parents = MCMCstep(parents, s, numSNPs, diseaseStates);
averageParentSize += parents.size();
if(maxParentSize < parents.size())
{
maxParentSize = parents.size();
}
java.util.Iterator<Integer> itr = parents.iterator();
while(itr.hasNext())
{
snpCounts[itr.next().intValue()]++;
}
}
System.out.println("Average parent size: " + averageParentSize/runningSteps);
System.out.println("Max parent size: " + maxParentSize);
return snpCounts;
}
public static ArrayList<Integer> MCMCstep(ArrayList<Integer> parents, Scorer s, int numSNPs, int diseaseStates)
{
//proposes a uniformly random move from all possible moves from current BN
//accepts proposal with probability min{1,R} where R = P(D|proposal)/P(D|current BN)
//returns the BN generated by accepting (or not) the proposal
ArrayList<Integer> proposal = GenerateNeighborBN(parents, numSNPs);
double proposalScore = s.Score(proposal);
double R = Math.exp(proposalScore)/Math.exp(CurrentScore);
double testVal = Math.random();
if(testVal <= R)
{
CurrentScore = proposalScore;
return proposal;
}
else
{
return parents;
}
}
public static ArrayList<Integer> GenerateNeighborBN(ArrayList<Integer> parents, int numSNPs)
{
//returns a BN that is 1 move away from the given BN, where a move is the addition or removal of an edge (parent node)
//the BN returned is chosen uniformly at random from all such BNs.
ArrayList<Integer> neighbor = new ArrayList<Integer>();
neighbor.addAll(parents);
Random randomGenerator = new Random();
int i = randomGenerator.nextInt(numSNPs); //random number in [0,N-1]
Integer I = Integer.valueOf(i);
if(parents.contains(I))
{
neighbor.remove(I);
}
else
{
neighbor.add(I);
}
return neighbor;
}
}
| false | true | public static void main(String[] args)
{
if(args.length < 7)
{
System.out.println("Arguments required: <scoring method> <mixing steps> <running steps> <number of disease states> <number of allele codes> <data files> <output file> <alpha>");
return;
}
//parse data
Parser p = new Parser();
String[] files = new String[args.length-7];
for(int i = 5; i < args.length-2;i++)
{
files[i-5] = args[i];
}
int[][] data = p.Parse(files);
if(data != null)
{
System.out.println("Number of snps: "+(data[0].length - 1));
int numSNPs = data[0].length - 1;
//parse integer arguments
int mixingSteps = 0;
int runningSteps = 0;
int diseaseStates = 0;
int alleleStates = 0;
double alpha = 0;
try{
mixingSteps = Integer.parseInt(args[1]);
runningSteps = Integer.parseInt(args[2]);
diseaseStates = Integer.parseInt(args[3]);
alleleStates = Integer.parseInt(args[4]);
}
catch(NumberFormatException e)
{
System.out.println("Can not parse integer arguments.");
return;
}
//parse score function argument
Scorer s = null;
if(args[0].equals("AIC"))
{
s = new AIC(data, alleleStates, diseaseStates);
}
else if(args[0].equals("BIC"))
{
s = new BIC(data, alleleStates, diseaseStates);
}
else if(args[0].equals("BDeu"))
{
s = new BDeu(data, alleleStates, diseaseStates, alpha);
}
else
{
System.out.println("Scoring method does not exist.");
return;
}
if(mixingSteps >= 0 && runningSteps > 0 && diseaseStates > 1)
{
//calculate posterior probability of each edge and print to output file
PrintWriter out;
try
{
out = new PrintWriter(new FileWriter(args[args.length-1]));
int[] snpCounts = RunMC(mixingSteps, runningSteps, s, numSNPs, diseaseStates);
for(int i = 0; i < snpCounts.length; i++)
{
//print out snps that have a posterior probability greater than 0
if(snpCounts[i] > 0)
{
out.println(Integer.toString(i) + ": " + Double.toString((double)snpCounts[i]/runningSteps));
}
}
out.close();
}
catch (IOException e)
{
System.out.println("Can not write to file.");
}
}
}
return;
}
| public static void main(String[] args)
{
if(args.length < 7)
{
System.out.println("Arguments required: <scoring method> <mixing steps> <running steps> <number of disease states> <number of allele codes> <data files> <output file> <alpha>");
return;
}
//parse data
Parser p = new Parser();
String[] files = new String[args.length-7];
for(int i = 5; i < args.length-2;i++)
{
files[i-5] = args[i];
}
int[][] data = p.Parse(files);
if(data != null)
{
System.out.println("Number of snps: "+(data[0].length - 1));
int numSNPs = data[0].length - 1;
//parse integer arguments
int mixingSteps = 0;
int runningSteps = 0;
int diseaseStates = 0;
int alleleStates = 0;
double alpha = 0;
try{
mixingSteps = Integer.parseInt(args[1]);
runningSteps = Integer.parseInt(args[2]);
diseaseStates = Integer.parseInt(args[3]);
alleleStates = Integer.parseInt(args[4]);
}
catch(NumberFormatException e)
{
System.out.println("Can not parse integer arguments.");
return;
}
//parse score function argument
Scorer s = null;
if(args[0].equals("AIC"))
{
s = new AIC(data, alleleStates, diseaseStates, alpha);
}
else if(args[0].equals("BIC"))
{
s = new BIC(data, alleleStates, diseaseStates, alpha);
}
else if(args[0].equals("BDeu"))
{
s = new BDeu(data, alleleStates, diseaseStates, alpha);
}
else
{
System.out.println("Scoring method does not exist.");
return;
}
if(mixingSteps >= 0 && runningSteps > 0 && diseaseStates > 1)
{
//calculate posterior probability of each edge and print to output file
PrintWriter out;
try
{
out = new PrintWriter(new FileWriter(args[args.length-1]));
int[] snpCounts = RunMC(mixingSteps, runningSteps, s, numSNPs, diseaseStates);
for(int i = 0; i < snpCounts.length; i++)
{
//print out snps that have a posterior probability greater than 0
if(snpCounts[i] > 0)
{
out.println(Integer.toString(i) + ": " + Double.toString((double)snpCounts[i]/runningSteps));
}
}
out.close();
}
catch (IOException e)
{
System.out.println("Can not write to file.");
}
}
}
return;
}
|
diff --git a/src/SEG_Airport/src/Model/Test.java b/src/SEG_Airport/src/Model/Test.java
index b728c36..1b91a2b 100644
--- a/src/SEG_Airport/src/Model/Test.java
+++ b/src/SEG_Airport/src/Model/Test.java
@@ -1,141 +1,141 @@
package Model;
import java.util.ArrayList;
public class Test {
//Just a class to unit test functionality of the other classes
public static void main(String[] args) {
//create airport and 4 runways
Airport a = new Airport("Heathrow");
Runway r = new Runway("27R", 1, 2, 3, 4, 5);
Runway r1 = new Runway("09L", 6, 7, 8, 9, 10);
Runway r2 = new Runway("27L", 11, 12, 13, 14, 15);
Runway r3 = new Runway("09R", 16, 17, 18, 19, 20);
PhysicalRunway one = new PhysicalRunway("27R/09L", r, r1);
PhysicalRunway two = new PhysicalRunway("27L/09R", r2, r3);
//add physical runways to airport
a.addPhysicalRunway(one);
a.addPhysicalRunway(two);
//iterate over the runways in the airport and print all values
System.out.println("\n******************\nThis is the airport and its runways:\n" + a.getName());
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//remove runway with name "one"
a.removePhysicalRunway("27R/09L");
System.out.println("\nThis is the same airport with runway one removed:\n" + a.getName());
//iterate over the runways in the airport and print all values
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//save airport a to xml file
a.saveToXML();
//create a second airport and a loadxmlfile object
//load a file
Airport a2 = null;
LoadXMLFile lf = new LoadXMLFile();
try {
a2 = lf.loadAirport();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\nThis is the loaded airport:\n" + a2.getName());
//iterate over the runways in the loaded airport and print all values
for (Object o : a2.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
Obstacle obs = new Obstacle("boeing 747", 56.0);
obs.saveToXML();
LoadXMLFile lof = new LoadXMLFile();
Obstacle obs1 = null;
lof.silentLoadObstacle("/Users/oscarmariani/Desktop/obstacle.xml");
try {
obs1 = lof.loadObstacle();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(obs1.getName() +
obs1.getHeight() + obs1.getWidth() + obs1.getLength());
Contact cont1 = new Contact("oscar", "mariani", "[email protected]");
Contact cont2 = new Contact("bob", "squarepants", "[email protected]");
ArrayList<Contact> contactsList = new ArrayList<Contact>();
contactsList.add(cont1);
contactsList.add(cont2);
try {
- SaveToXMLFile saveTo = new SaveToXMLFile(contactsList);
+ SaveToXMLFile saveTo = new SaveToXMLFile(contactsList, false);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<Contact> conts = null;
LoadXMLFile lof1 = new LoadXMLFile();
try {
conts = lof1.loadContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(conts.get(0).getFirstName() + conts.get(0).getLastName() + conts.get(0).getEmail());
System.out.println(conts.get(1).getFirstName() + conts.get(1).getLastName() + conts.get(1).getEmail());
}
}
| true | true | public static void main(String[] args) {
//create airport and 4 runways
Airport a = new Airport("Heathrow");
Runway r = new Runway("27R", 1, 2, 3, 4, 5);
Runway r1 = new Runway("09L", 6, 7, 8, 9, 10);
Runway r2 = new Runway("27L", 11, 12, 13, 14, 15);
Runway r3 = new Runway("09R", 16, 17, 18, 19, 20);
PhysicalRunway one = new PhysicalRunway("27R/09L", r, r1);
PhysicalRunway two = new PhysicalRunway("27L/09R", r2, r3);
//add physical runways to airport
a.addPhysicalRunway(one);
a.addPhysicalRunway(two);
//iterate over the runways in the airport and print all values
System.out.println("\n******************\nThis is the airport and its runways:\n" + a.getName());
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//remove runway with name "one"
a.removePhysicalRunway("27R/09L");
System.out.println("\nThis is the same airport with runway one removed:\n" + a.getName());
//iterate over the runways in the airport and print all values
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//save airport a to xml file
a.saveToXML();
//create a second airport and a loadxmlfile object
//load a file
Airport a2 = null;
LoadXMLFile lf = new LoadXMLFile();
try {
a2 = lf.loadAirport();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\nThis is the loaded airport:\n" + a2.getName());
//iterate over the runways in the loaded airport and print all values
for (Object o : a2.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
Obstacle obs = new Obstacle("boeing 747", 56.0);
obs.saveToXML();
LoadXMLFile lof = new LoadXMLFile();
Obstacle obs1 = null;
lof.silentLoadObstacle("/Users/oscarmariani/Desktop/obstacle.xml");
try {
obs1 = lof.loadObstacle();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(obs1.getName() +
obs1.getHeight() + obs1.getWidth() + obs1.getLength());
Contact cont1 = new Contact("oscar", "mariani", "[email protected]");
Contact cont2 = new Contact("bob", "squarepants", "[email protected]");
ArrayList<Contact> contactsList = new ArrayList<Contact>();
contactsList.add(cont1);
contactsList.add(cont2);
try {
SaveToXMLFile saveTo = new SaveToXMLFile(contactsList);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<Contact> conts = null;
LoadXMLFile lof1 = new LoadXMLFile();
try {
conts = lof1.loadContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(conts.get(0).getFirstName() + conts.get(0).getLastName() + conts.get(0).getEmail());
System.out.println(conts.get(1).getFirstName() + conts.get(1).getLastName() + conts.get(1).getEmail());
}
| public static void main(String[] args) {
//create airport and 4 runways
Airport a = new Airport("Heathrow");
Runway r = new Runway("27R", 1, 2, 3, 4, 5);
Runway r1 = new Runway("09L", 6, 7, 8, 9, 10);
Runway r2 = new Runway("27L", 11, 12, 13, 14, 15);
Runway r3 = new Runway("09R", 16, 17, 18, 19, 20);
PhysicalRunway one = new PhysicalRunway("27R/09L", r, r1);
PhysicalRunway two = new PhysicalRunway("27L/09R", r2, r3);
//add physical runways to airport
a.addPhysicalRunway(one);
a.addPhysicalRunway(two);
//iterate over the runways in the airport and print all values
System.out.println("\n******************\nThis is the airport and its runways:\n" + a.getName());
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//remove runway with name "one"
a.removePhysicalRunway("27R/09L");
System.out.println("\nThis is the same airport with runway one removed:\n" + a.getName());
//iterate over the runways in the airport and print all values
for (Object o : a.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
//save airport a to xml file
a.saveToXML();
//create a second airport and a loadxmlfile object
//load a file
Airport a2 = null;
LoadXMLFile lf = new LoadXMLFile();
try {
a2 = lf.loadAirport();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\nThis is the loaded airport:\n" + a2.getName());
//iterate over the runways in the loaded airport and print all values
for (Object o : a2.getPhysicalRunways()) {
System.out.println(((PhysicalRunway) o).getId()
+" "+ ((PhysicalRunway) o).getRunway(0).getName()
+" "+ ((PhysicalRunway) o).getRunway(0).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(0).getLDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getName()
+" "+ ((PhysicalRunway) o).getRunway(1).getTORA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getASDA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getTODA(1)
+" "+ ((PhysicalRunway) o).getRunway(1).getLDA(1)
);
}
Obstacle obs = new Obstacle("boeing 747", 56.0);
obs.saveToXML();
LoadXMLFile lof = new LoadXMLFile();
Obstacle obs1 = null;
lof.silentLoadObstacle("/Users/oscarmariani/Desktop/obstacle.xml");
try {
obs1 = lof.loadObstacle();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(obs1.getName() +
obs1.getHeight() + obs1.getWidth() + obs1.getLength());
Contact cont1 = new Contact("oscar", "mariani", "[email protected]");
Contact cont2 = new Contact("bob", "squarepants", "[email protected]");
ArrayList<Contact> contactsList = new ArrayList<Contact>();
contactsList.add(cont1);
contactsList.add(cont2);
try {
SaveToXMLFile saveTo = new SaveToXMLFile(contactsList, false);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<Contact> conts = null;
LoadXMLFile lof1 = new LoadXMLFile();
try {
conts = lof1.loadContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(conts.get(0).getFirstName() + conts.get(0).getLastName() + conts.get(0).getEmail());
System.out.println(conts.get(1).getFirstName() + conts.get(1).getLastName() + conts.get(1).getEmail());
}
|
diff --git a/modules/org.restlet.example/src/org/restlet/example/book/restlet/ch8/resources/MailResource.java b/modules/org.restlet.example/src/org/restlet/example/book/restlet/ch8/resources/MailResource.java
index 59e60298b..bdd0d2941 100644
--- a/modules/org.restlet.example/src/org/restlet/example/book/restlet/ch8/resources/MailResource.java
+++ b/modules/org.restlet.example/src/org/restlet/example/book/restlet/ch8/resources/MailResource.java
@@ -1,223 +1,223 @@
/**
* Copyright 2005-2008 Noelios Technologies.
*
* The contents of this file are subject to the terms of the following open
* source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can
* select the license that you prefer but you may not use this file except in
* compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.sun.com/cddl/cddl.html
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royaltee free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.example.book.restlet.ch8.resources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Parameter;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.example.book.restlet.ch8.objects.Contact;
import org.restlet.example.book.restlet.ch8.objects.Mail;
import org.restlet.example.book.restlet.ch8.objects.Mailbox;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
/**
* Resource for a mail.
*/
public class MailResource extends BaseResource {
/** The mail represented by this resource. */
private Mail mail;
/** The parent mailbox. */
private Mailbox mailbox;
public MailResource(Context context, Request request, Response response) {
super(context, request, response);
if (getCurrentUser() != null) {
// Authenticated access.
setModifiable(true);
final String mailboxId = Reference.decode((String) request
.getAttributes().get("mailboxId"));
this.mailbox = getObjectsFacade().getMailboxById(mailboxId);
if (this.mailbox != null) {
final String mailId = (String) request.getAttributes().get(
"mailId");
this.mail = getObjectsFacade().getMailById(mailId);
if (this.mail != null) {
getVariants().add(new Variant(MediaType.TEXT_HTML));
}
}
} else {
// Anonymous access
setModifiable(false);
}
}
/**
* Remove this resource.
*/
@Override
public void removeRepresentations() throws ResourceException {
getObjectsFacade().deleteMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef().getParentRef());
}
/**
* Generate the HTML representation of this resource.
*/
@Override
public Representation represent(Variant variant) throws ResourceException {
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
final List<Contact> contacts = new ArrayList<Contact>();
contacts.addAll(this.mailbox.getContacts());
if (this.mail.getRecipients() != null) {
for (final Contact contact : this.mail.getRecipients()) {
if (contact.getId() == null) {
contacts.add(contact);
}
}
}
dataModel.put("contacts", contacts);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
return getHTMLTemplateRepresentation("mail_" + this.mail.getStatus()
+ ".html", dataModel);
}
/**
* Update the underlying mail according to the given representation. If the
* mail is intended to be sent, send it to all of its recipients.
*/
@Override
public void storeRepresentation(Representation entity)
throws ResourceException {
final Form form = new Form(entity);
final List<String> mailAddresses = new ArrayList<String>();
for (final Parameter parameter : form.subList("recipients")) {
mailAddresses.add(parameter.getValue());
}
List<String> tags = null;
if (form.getFirstValue("tags") != null) {
tags = new ArrayList<String>(Arrays.asList(form.getFirstValue(
"tags").split(" ")));
}
getObjectsFacade().updateMail(this.mailbox, this.mail,
form.getFirstValue("status"), form.getFirstValue("subject"),
form.getFirstValue("message"), mailAddresses, tags);
// Detect if the mail is to be sent.
if (Mail.STATUS_SENDING.equalsIgnoreCase(this.mail.getStatus())) {
this.mail.setSendingDate(new Date());
// Loop on the list of recipients and post to their mailbox.
boolean success = true;
if (this.mail.getRecipients() != null) {
final Client client = new Client(Protocol.HTTP);
final Form form2 = new Form();
form2.add("status", Mail.STATUS_RECEIVING);
form2.add("senderAddress", getRequest().getRootRef()
+ "/mailboxes/" + this.mailbox.getId());
form2.add("senderName", this.mailbox.getSenderName());
form2.add("subject", this.mail.getSubject());
form2.add("message", this.mail.getMessage());
form2.add("sendingDate", this.mail.getSendingDate().toString());
for (final Contact recipient : this.mail.getRecipients()) {
form2.add("recipient", recipient.getMailAddress() + "$"
+ recipient.getName());
}
// Send the mail to every recipient
final StringBuilder builder = new StringBuilder();
Response response;
final Request request = new Request();
request.setMethod(Method.POST);
- request.setEntity(form2.getWebRepresentation());
for (final Contact contact : this.mail.getRecipients()) {
request.setResourceRef(contact.getMailAddress());
+ request.setEntity(form2.getWebRepresentation());
response = client.handle(request);
// Error when sending the mail.
if (!response.getStatus().isSuccess()) {
success = false;
builder.append(contact.getName());
builder.append("\t");
builder.append(response.getStatus());
}
}
if (success) {
// if the mail has been successfully sent to every
// recipient.
this.mail.setStatus(Mail.STATUS_SENT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef());
} else {
// At least one error has been encountered.
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
dataModel.put("message", builder.toString());
getResponse().setEntity(
getHTMLTemplateRepresentation("mail_"
+ this.mail.getStatus() + ".html",
dataModel));
}
} else {
// Still a draft
this.mail.setStatus(Mail.STATUS_DRAFT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
} else {
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
}
}
| false | true | public void storeRepresentation(Representation entity)
throws ResourceException {
final Form form = new Form(entity);
final List<String> mailAddresses = new ArrayList<String>();
for (final Parameter parameter : form.subList("recipients")) {
mailAddresses.add(parameter.getValue());
}
List<String> tags = null;
if (form.getFirstValue("tags") != null) {
tags = new ArrayList<String>(Arrays.asList(form.getFirstValue(
"tags").split(" ")));
}
getObjectsFacade().updateMail(this.mailbox, this.mail,
form.getFirstValue("status"), form.getFirstValue("subject"),
form.getFirstValue("message"), mailAddresses, tags);
// Detect if the mail is to be sent.
if (Mail.STATUS_SENDING.equalsIgnoreCase(this.mail.getStatus())) {
this.mail.setSendingDate(new Date());
// Loop on the list of recipients and post to their mailbox.
boolean success = true;
if (this.mail.getRecipients() != null) {
final Client client = new Client(Protocol.HTTP);
final Form form2 = new Form();
form2.add("status", Mail.STATUS_RECEIVING);
form2.add("senderAddress", getRequest().getRootRef()
+ "/mailboxes/" + this.mailbox.getId());
form2.add("senderName", this.mailbox.getSenderName());
form2.add("subject", this.mail.getSubject());
form2.add("message", this.mail.getMessage());
form2.add("sendingDate", this.mail.getSendingDate().toString());
for (final Contact recipient : this.mail.getRecipients()) {
form2.add("recipient", recipient.getMailAddress() + "$"
+ recipient.getName());
}
// Send the mail to every recipient
final StringBuilder builder = new StringBuilder();
Response response;
final Request request = new Request();
request.setMethod(Method.POST);
request.setEntity(form2.getWebRepresentation());
for (final Contact contact : this.mail.getRecipients()) {
request.setResourceRef(contact.getMailAddress());
response = client.handle(request);
// Error when sending the mail.
if (!response.getStatus().isSuccess()) {
success = false;
builder.append(contact.getName());
builder.append("\t");
builder.append(response.getStatus());
}
}
if (success) {
// if the mail has been successfully sent to every
// recipient.
this.mail.setStatus(Mail.STATUS_SENT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef());
} else {
// At least one error has been encountered.
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
dataModel.put("message", builder.toString());
getResponse().setEntity(
getHTMLTemplateRepresentation("mail_"
+ this.mail.getStatus() + ".html",
dataModel));
}
} else {
// Still a draft
this.mail.setStatus(Mail.STATUS_DRAFT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
} else {
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
}
| public void storeRepresentation(Representation entity)
throws ResourceException {
final Form form = new Form(entity);
final List<String> mailAddresses = new ArrayList<String>();
for (final Parameter parameter : form.subList("recipients")) {
mailAddresses.add(parameter.getValue());
}
List<String> tags = null;
if (form.getFirstValue("tags") != null) {
tags = new ArrayList<String>(Arrays.asList(form.getFirstValue(
"tags").split(" ")));
}
getObjectsFacade().updateMail(this.mailbox, this.mail,
form.getFirstValue("status"), form.getFirstValue("subject"),
form.getFirstValue("message"), mailAddresses, tags);
// Detect if the mail is to be sent.
if (Mail.STATUS_SENDING.equalsIgnoreCase(this.mail.getStatus())) {
this.mail.setSendingDate(new Date());
// Loop on the list of recipients and post to their mailbox.
boolean success = true;
if (this.mail.getRecipients() != null) {
final Client client = new Client(Protocol.HTTP);
final Form form2 = new Form();
form2.add("status", Mail.STATUS_RECEIVING);
form2.add("senderAddress", getRequest().getRootRef()
+ "/mailboxes/" + this.mailbox.getId());
form2.add("senderName", this.mailbox.getSenderName());
form2.add("subject", this.mail.getSubject());
form2.add("message", this.mail.getMessage());
form2.add("sendingDate", this.mail.getSendingDate().toString());
for (final Contact recipient : this.mail.getRecipients()) {
form2.add("recipient", recipient.getMailAddress() + "$"
+ recipient.getName());
}
// Send the mail to every recipient
final StringBuilder builder = new StringBuilder();
Response response;
final Request request = new Request();
request.setMethod(Method.POST);
for (final Contact contact : this.mail.getRecipients()) {
request.setResourceRef(contact.getMailAddress());
request.setEntity(form2.getWebRepresentation());
response = client.handle(request);
// Error when sending the mail.
if (!response.getStatus().isSuccess()) {
success = false;
builder.append(contact.getName());
builder.append("\t");
builder.append(response.getStatus());
}
}
if (success) {
// if the mail has been successfully sent to every
// recipient.
this.mail.setStatus(Mail.STATUS_SENT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef());
} else {
// At least one error has been encountered.
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
dataModel.put("message", builder.toString());
getResponse().setEntity(
getHTMLTemplateRepresentation("mail_"
+ this.mail.getStatus() + ".html",
dataModel));
}
} else {
// Still a draft
this.mail.setStatus(Mail.STATUS_DRAFT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
} else {
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
}
|
diff --git a/jogl-utils/src/com/mbien/engine/glsl/GLSLException.java b/jogl-utils/src/com/mbien/engine/glsl/GLSLException.java
index 918f2a0..6a07eca 100644
--- a/jogl-utils/src/com/mbien/engine/glsl/GLSLException.java
+++ b/jogl-utils/src/com/mbien/engine/glsl/GLSLException.java
@@ -1,64 +1,64 @@
package com.mbien.engine.glsl;
/**
* Created on 29. March 2007, 15:33
* @author Michael Bien
*/
public class GLSLException extends Exception {
public final Object source;
/** Creates a new instance of GLSLException */
public GLSLException(Object source, String message) {
super(message);
this.source = source;
}
protected static String format(GLSLShader shader, String massages[]) {
StringBuilder sb = new StringBuilder();
- sb.append(shader.getName());
+// sb.append(shader.getName());
if(shader.getFragments() != null) {
CodeFragment[] fragments = shader.getFragments();
for (int i = 0; i < fragments.length; i++) {
sb.append(fragments[i].name);
if(i < fragments.length-1)
sb.append(", ");
}
}
sb.append("\n");
for (int i = 0; i < massages.length; i++) {
sb.append(" ");
sb.append(massages[i]);
if(i < massages.length-1)
sb.append("\n");
}
return sb.toString();
}
protected static String format(GLSLProgram program, String massages[]) {
StringBuilder sb = new StringBuilder();
// sb.append(program.getName());
// if(program.fragments != null) {
// for (int i = 0; i < program.fragments.length; i++) {
// sb.append(program.fragments[i].name);
// if(i < program.fragments.length-1)
// sb.append(", ");
// }
// }
sb.append("\n");
for (int i = 0; i < massages.length; i++) {
sb.append(" ");
sb.append(massages[i]);
if(i < massages.length-1)
sb.append("\n");
}
return sb.toString();
}
}
| true | true | protected static String format(GLSLShader shader, String massages[]) {
StringBuilder sb = new StringBuilder();
sb.append(shader.getName());
if(shader.getFragments() != null) {
CodeFragment[] fragments = shader.getFragments();
for (int i = 0; i < fragments.length; i++) {
sb.append(fragments[i].name);
if(i < fragments.length-1)
sb.append(", ");
}
}
sb.append("\n");
for (int i = 0; i < massages.length; i++) {
sb.append(" ");
sb.append(massages[i]);
if(i < massages.length-1)
sb.append("\n");
}
return sb.toString();
}
| protected static String format(GLSLShader shader, String massages[]) {
StringBuilder sb = new StringBuilder();
// sb.append(shader.getName());
if(shader.getFragments() != null) {
CodeFragment[] fragments = shader.getFragments();
for (int i = 0; i < fragments.length; i++) {
sb.append(fragments[i].name);
if(i < fragments.length-1)
sb.append(", ");
}
}
sb.append("\n");
for (int i = 0; i < massages.length; i++) {
sb.append(" ");
sb.append(massages[i]);
if(i < massages.length-1)
sb.append("\n");
}
return sb.toString();
}
|
diff --git a/tds/src/main/java/thredds/servlet/HtmlWriter.java b/tds/src/main/java/thredds/servlet/HtmlWriter.java
index 39643bcca..15b6dfe11 100644
--- a/tds/src/main/java/thredds/servlet/HtmlWriter.java
+++ b/tds/src/main/java/thredds/servlet/HtmlWriter.java
@@ -1,799 +1,804 @@
package thredds.servlet;
import thredds.catalog.*;
import thredds.datatype.DateType;
import ucar.unidata.util.StringUtil;
import ucar.unidata.util.Format;
import ucar.nc2.dataset.AxisType;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.VariableEnhanced;
import ucar.nc2.dt.grid.GridDataset;
import ucar.nc2.dt.GridDatatype;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.*;
/**
* _more_
*
* @author edavis
* @since Feb 24, 2006 3:18:50 PM
*/
public class HtmlWriter
{
static private org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger( HtmlWriter.class );
private static HtmlWriter singleton;
private String contextPath;
private String contextName;
private String contextVersion;
private String userCssPath; // relative to context path
private String contextLogoPath; // relative to context path
private String contextLogoAlt; // Alternate text for logo
private String instituteLogoPath; // relative to context path
private String instituteLogoAlt; // Alternate text for logo
private String docsPath; // relative to context path
private ucar.nc2.units.DateFormatter formatter = new ucar.nc2.units.DateFormatter();
/*
* <li>Context path: "/thredds"</li>
* <li>Servlet name: "THREDDS Data Server"</li>
* <li>Documentation location: "/thredds/docs/"</li>
* <li>Version information: ThreddsDefault.version</li>
* <li>Catalog reference URL: "/thredds/catalogServices?catalog="</li>
*/
public static void init( String contextPath, String contextName, String contextVersion,
String docsPath, String userCssPath,
String contextLogoPath, String instituteLogoPath )
{
if ( singleton != null )
{
log.warn( "init(): this method has already been called; it should only be called once." );
return;
//throw new IllegalStateException( "HtmlWriter.init() has already been called.");
}
singleton = new HtmlWriter( contextPath, contextName, contextVersion,
docsPath, userCssPath,
contextLogoPath, instituteLogoPath );
}
public static HtmlWriter getInstance()
{
if ( singleton == null )
{
log.warn( "getInstance(): init() has not been called.");
return null;
//throw new IllegalStateException( "HtmlWriter.init() has not been called." );
}
return singleton;
}
/** @noinspection UNUSED_SYMBOL*/
private HtmlWriter() {}
private HtmlWriter( String contextPath, String contextName, String contextVersion,
String docsPath, String userCssPath,
String contextLogoPath, String instituteLogoPath )
{
this.contextPath = contextPath;
this.contextName = contextName;
this.contextVersion = contextVersion;
this.docsPath = docsPath;
this.userCssPath = userCssPath;
this.contextLogoPath = contextLogoPath;
this.contextLogoAlt = "";
this.instituteLogoPath = instituteLogoPath;
this.instituteLogoAlt = "";
}
public String getContextPath() { return contextPath; }
public String getContextName() { return contextName; }
public String getContextVersion() { return contextVersion; }
public String getContextLogoPath() { return contextLogoPath; }
//public String getUserCssPath() { return userCssPath; }
//public String getInstituteLogoPath() { return instituteLogoPath; }
public String getDocsPath() { return docsPath; }
public String getHtmlDoctypeAndOpenTag()
{
return new StringBuffer()
.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n")
.append( " \"http://www.w3.org/TR/html4/loose.dtd\">\n")
.append( "<html>\n")
.toString();
}
public String getXHtmlDoctypeAndOpenTag()
{
return new StringBuffer()
// .append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n")
.append( " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n")
.append( "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">")
.toString();
}
// public static final String UNIDATA_CSS
public String getUserCSS()
{
return new StringBuffer()
.append( "<link rel='stylesheet' href='")
.append( this.contextPath)
.append( "/").append( userCssPath).append("' type='text/css' >").toString();
}
// public static final String UNIDATA_HEAD
public String getUserHead()
{
return new StringBuffer()
.append( "<table width=\"100%\">\n")
.append( " <tr>\n" )
.append( " <td width=\"95\" height=\"95\" align=\"left\"><img src=\"").append( contextPath).append("/").append( instituteLogoPath ).append("\" alt=\"").append( instituteLogoAlt).append("\" width=\"95\" height=\"93\"> </td>\n")
.append( " <td width=\"701\" align=\"left\" valign=\"top\">\n")
.append( " <table width=\"303\">\n" )
.append( " <tr>\n" )
.append( " <td width=\"295\" height=\"22\" align=\"left\" valign=\"top\"><h3><strong>").append( contextName).append("</strong></h3></td>\n" )
.append( " </tr>\n" )
.append( " </table>\n" )
.append( " </td>\n" )
.append( " </tr>\n" )
.append( "</table>")
.toString();
}
// private static final String TOMCAT_CSS
private String getTomcatCSS()
{
return new StringBuffer()
.append( "H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} " )
.append( "H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} " )
.append( "H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} " )
.append( "BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} " )
.append( "B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} " )
.append( "P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}" )
.append( "A {color : black;}" )
.append( "A.name {color : black;}" )
.append( "HR {color : #525D76;}")
.toString();
}
/**
* Write a file directory.
*
* @param dir directory
* @param path the URL path reletive to the base
*/
public void writeDirectory( HttpServletResponse res, File dir, String path )
throws IOException
{
// error checking
if ( dir == null )
{
res.sendError( HttpServletResponse.SC_NOT_FOUND );
ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 );
return;
}
if ( !dir.exists() || !dir.isDirectory() )
{
res.sendError( HttpServletResponse.SC_NOT_FOUND );
ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 );
return;
}
// Get directory as HTML
String dirHtmlString = getDirectory( path, dir );
res.setContentLength( dirHtmlString.length() );
res.setContentType( "text/html; charset=iso-8859-1" );
// LOOK faster to use PrintStream instead of PrintWriter
// Return an input stream to the underlying bytes
// Prepare a writer
OutputStreamWriter osWriter;
try
{
osWriter = new OutputStreamWriter( res.getOutputStream(), "UTF8" );
}
catch ( java.io.UnsupportedEncodingException e )
{
// Should never happen
osWriter = new OutputStreamWriter( res.getOutputStream() );
}
PrintWriter writer = new PrintWriter( osWriter );
writer.write( dirHtmlString );
writer.flush();
ServletUtil.logServerAccess( HttpServletResponse.SC_OK, dirHtmlString.length() );
}
private String getDirectory( String path, File dir )
{
StringBuffer sb = new StringBuffer();
// Render the page header
sb.append( getHtmlDoctypeAndOpenTag() ); // "<html>\n" );
sb.append( "<head>\r\n" );
sb.append( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" );
sb.append( "<title>" );
sb.append( "Directory listing for " ).append( path );
sb.append( "</title>\r\n" );
sb.append( "<STYLE type='text/css'><!--" );
sb.append( this.getTomcatCSS() );
sb.append( "--></STYLE>\r\n" );
sb.append( "</head>\r\n" );
sb.append( "<body>\r\n" );
sb.append( "<h1>" );
sb.append( "Directory listing for " ).append( path );
// Render the link to our parent (if required)
String parentDirectory = path;
if ( parentDirectory.endsWith( "/" ) )
{
parentDirectory =
parentDirectory.substring( 0, parentDirectory.length() - 1 );
}
int slash = parentDirectory.lastIndexOf( '/' );
if ( slash >= 0 )
{
String parent = parentDirectory.substring( 0, slash );
sb.append( " - <a href=\"" );
if ( parent.equals( "" ) )
{
parent = "/";
}
sb.append( "../" ); // sb.append(encode(parent));
//if (!parent.endsWith("/"))
// sb.append("/");
sb.append( "\">" );
sb.append( "<b>" );
sb.append( "Up to " ).append( parent );
sb.append( "</b>" );
sb.append( "</a>" );
}
sb.append( "</h1>\r\n" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<table width=\"100%\" cellspacing=\"0\"" +
" cellpadding=\"5\" align=\"center\">\r\n" );
// Render the column headings
sb.append( "<tr>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Filename" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"center\"><font size=\"+1\"><strong>" );
sb.append( "Size" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"right\"><font size=\"+1\"><strong>" );
sb.append( "Last Modified" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "</tr>" );
// Render the directory entries within this directory
boolean shade = false;
File[] children = dir.listFiles();
List fileList = Arrays.asList( children );
Collections.sort( fileList );
for ( int i = 0; i < fileList.size(); i++ )
{
File child = (File) fileList.get( i );
String childname = child.getName();
if ( childname.equalsIgnoreCase( "WEB-INF" ) ||
childname.equalsIgnoreCase( "META-INF" ) )
{
continue;
}
if ( child.isDirectory() ) childname = childname + "/";
//if (!endsWithSlash) childname = path + "/" + childname; // client removes last path if no slash
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\"> \r\n" );
sb.append( "<a href=\"" );
//sb.append( encode(contextPath));
// resourceName = encode(path + resourceName);
sb.append( childname );
sb.append( "\"><tt>" );
sb.append( childname );
sb.append( "</tt></a></td>\r\n" );
sb.append( "<td align=\"right\"><tt>" );
if ( child.isDirectory() )
{
sb.append( " " );
}
else
{
sb.append( renderSize( child.length() ) );
}
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"right\"><tt>" );
sb.append( formatter.toDateTimeString( new Date( child.lastModified() ) ) );
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
}
// Render the page footer
sb.append( "</table>\r\n" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<h3>" ).append( this.contextVersion );
sb.append( " <a href='").append(this.contextPath).append(this.docsPath).append("'> Documentation</a></h3>\r\n" );
sb.append( "</body>\r\n" );
sb.append( "</html>\r\n" );
return sb.toString();
}
private String renderSize( long size )
{
long leftSide = size / 1024;
long rightSide = ( size % 1024 ) / 103; // Makes 1 digit
if ( ( leftSide == 0 ) && ( rightSide == 0 ) && ( size > 0 ) )
{
rightSide = 1;
}
return ( "" + leftSide + "." + rightSide + " kb" );
}
public void writeCatalog( HttpServletResponse res, InvCatalogImpl cat, boolean isLocalCatalog )
throws IOException
{
String catHtmlAsString = convertCatalogToHtml( cat, isLocalCatalog );
res.setContentLength( catHtmlAsString.length() );
res.setContentType( "text/html; charset=iso-8859-1" );
// Write it out
OutputStreamWriter osWriter;
try
{
osWriter = new OutputStreamWriter( res.getOutputStream(), "UTF8" );
}
catch ( java.io.UnsupportedEncodingException e )
{
// Should never happen
osWriter = new OutputStreamWriter( res.getOutputStream() );
}
PrintWriter writer = new PrintWriter( osWriter );
writer.write( catHtmlAsString );
writer.flush();
ServletUtil.logServerAccess( HttpServletResponse.SC_OK, catHtmlAsString.length() );
}
/**
* Write a catalog in HTML, make it look like a file directory.
*
* @param cat catalog to write
*/
private String convertCatalogToHtml( InvCatalogImpl cat, boolean isLocalCatalog )
{
StringBuffer sb = new StringBuffer( 10000 );
String catname = StringUtil.quoteHtmlContent( cat.getUriString() );
// Render the page header
sb.append( getHtmlDoctypeAndOpenTag() ); // "<html>\n" );
sb.append( "<head>\r\n" );
sb.append( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" );
sb.append( "<title>" );
sb.append( "Catalog " ).append( catname );
sb.append( "</title>\r\n" );
sb.append( "<STYLE type='text/css'><!--" );
sb.append( this.getTomcatCSS() );
sb.append( "--></STYLE> " );
sb.append( "</head>\r\n" );
sb.append( "<body>" );
sb.append( "<h1>" );
sb.append( "Catalog " ).append( catname );
sb.append( "</h1>" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<table width=\"100%\" cellspacing=\"0\"" +
" cellpadding=\"5\" align=\"center\">\r\n" );
// Render the column headings
sb.append( "<tr>\r\n" );
sb.append( "<th align=\"left\"><font size=\"+1\">" );
sb.append( "Dataset" );
sb.append( "</font></th>\r\n" );
sb.append( "<th align=\"center\"><font size=\"+1\">" );
sb.append( "Size" );
sb.append( "</font></th>\r\n" );
sb.append( "<th align=\"right\"><font size=\"+1\">" );
sb.append( "Last Modified" );
sb.append( "</font></th>\r\n" );
sb.append( "</tr>" );
// Recursively render the datasets
boolean shade = false;
shade = doDatasets( cat, cat.getDatasets(), sb, shade, 0, isLocalCatalog );
// Render the page footer
sb.append( "</table>\r\n" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<h3>" ).append( this.contextVersion );
sb.append( " <a href='" ).append( contextPath ).append( "/").append(this.docsPath).append("'> Documentation</a></h3>\r\n" );
sb.append( "</body>\r\n" );
sb.append( "</html>\r\n" );
return ( sb.toString() );
}
private boolean doDatasets( InvCatalogImpl cat, List datasets, StringBuffer sb, boolean shade, int level, boolean isLocalCatalog )
{
URI catURI = cat.getBaseURI();
String catHtml;
if ( !isLocalCatalog )
{
// Setup HREF url to link to HTML dataset page (more below).
catHtml = contextPath + "/catalog.html?cmd=subset&catalog=" + cat.getUriString() + "&";
}
else
{ // replace xml with html
catHtml = cat.getUriString();
int pos = catHtml.lastIndexOf( '.' );
if (pos < 0)
catHtml = catHtml + "catalog.html?";
else
catHtml = catHtml.substring( 0, pos ) + ".html?";
}
for ( int i = 0; i < datasets.size(); i++ )
{
InvDatasetImpl ds = (InvDatasetImpl) datasets.get( i );
String name = StringUtil.quoteHtmlContent( ds.getName() );
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\">" );
for ( int j = 0; j <= level; j++ )
{
sb.append( " " );
}
sb.append( "\r\n" );
if ( ds instanceof InvCatalogRef )
{
InvCatalogRef catref = (InvCatalogRef) ds;
String href = catref.getXlinkHref();
+ if ( ! isLocalCatalog )
+ {
+ URI hrefUri = cat.getBaseURI().resolve( href);
+ href = hrefUri.toString();
+ }
try {
URI uri = new URI(href);
if (uri.isAbsolute()) {
href = contextPath + "/catalogServices?catalog=" + href;
} else {
int pos = href.lastIndexOf('.');
href = href.substring(0, pos) + ".html";
}
} catch (URISyntaxException e) {
log.error(href, e);
}
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( href ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "/</tt></a></td>\r\n" );
}
else // Not an InvCatalogRef
{
if (ds.hasNestedDatasets())
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
// Check if dataset has single resolver service.
if ( ds.getAccess().size() == 1 &&
( (InvAccess) ds.getAccess().get( 0)).getService().getServiceType().equals( ServiceType.RESOLVER ) )
{
InvAccess access = (InvAccess) ds.getAccess().get( 0);
String accessUrlName = access.getUnresolvedUrlName();
int pos = accessUrlName.lastIndexOf( ".xml");
if ( pos != -1 )
accessUrlName = accessUrlName.substring( 0, pos ) + ".html";
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( accessUrlName ) );
sb.append( "\"><tt>" );
String tmpName = name;
if ( tmpName.endsWith( ".xml"))
{
tmpName = tmpName.substring( 0, tmpName.lastIndexOf( '.' ) );
}
sb.append( tmpName );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset with an ID.
else if ( ds.getID() != null )
{
// Write link to HTML dataset page.
sb.append( "<a href=\"" );
// sb.append("catalog.html?cmd=subset&catalog=");
sb.append( StringUtil.quoteHtmlContent( catHtml ) );
sb.append( "dataset=" );
sb.append( StringUtil.quoteHtmlContent( ds.getID() ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset without an ID.
else
{
sb.append( "<tt>" );
sb.append( name );
sb.append( "</tt></td>\r\n" );
}
}
sb.append( "<td align=\"right\"><tt>" );
double size = ds.getDataSize();
if ( ( size != 0.0 ) && !Double.isNaN( size ) )
{
sb.append( Format.formatByteSize( size ) );
}
else
{
sb.append( " " );
}
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"right\"><tt>" );
// Get last modified time.
DateType lastModDateType = ds.getLastModifiedDate();
if ( lastModDateType == null )
{
if ( ! ds.hasAccess())
sb.append( "--");// "");
else
sb.append( "--");// "Unknown");
}
else
{
if ( lastModDateType.isPresent() )
sb.append( formatter.toDateTimeString( new Date() ) );
if ( lastModDateType.getDate() != null )
sb.append( formatter.toDateTimeString( lastModDateType.getDate() ) );
}
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
if ( !( ds instanceof InvCatalogRef ) )
{
shade = doDatasets( cat, ds.getDatasets(), sb, shade, level + 1, isLocalCatalog );
}
}
return shade;
}
/**
* Show CDM compliance (ccordinate systems, etc) of a NetcdfDataset.
*
* @param ds dataset to write
*/
public void showCDM( HttpServletResponse res , NetcdfDataset ds )
throws IOException
{
String cdmAsString = getCDM( ds);
res.setContentLength( cdmAsString.length() );
res.setContentType( "text/html; charset=iso-8859-1" );
// Write it out
OutputStreamWriter osWriter;
try
{
osWriter = new OutputStreamWriter( res.getOutputStream(), "UTF8" );
}
catch ( UnsupportedEncodingException e )
{
// Should never happen
osWriter = new OutputStreamWriter( res.getOutputStream() );
}
PrintWriter writer = new PrintWriter( osWriter );
writer.write( cdmAsString );
writer.flush();
ServletUtil.logServerAccess( HttpServletResponse.SC_OK, cdmAsString.length() );
}
private String getCDM( NetcdfDataset ds )
{
StringBuffer sb = new StringBuffer( 10000 );
String name = StringUtil.quoteHtmlContent( ds.getLocation() );
// Render the page header
sb.append( getHtmlDoctypeAndOpenTag() ); // "<html>\n" );
sb.append( "<head>\r\n" );
sb.append( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" );
sb.append( "<title>" );
sb.append( "Common Data Model" );
sb.append( "</title>\r\n" );
sb.append( "<STYLE type='text/css'><!--" );
sb.append( this.getTomcatCSS() );
sb.append( "--></STYLE> " );
sb.append( "</head>\r\n" );
sb.append( "<body>" );
sb.append( "<h1>" );
sb.append( "Dataset ").append( name );
sb.append( "</h1>" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<table width=\"100%\" cellspacing=\"0\"" +
" cellpadding=\"5\" align=\"center\">\r\n" );
//////// Axis
sb.append( "<tr>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Axis" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Type" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Units" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "</tr>" );
// Show the coordinate axes
boolean shade = false;
List axes = ds.getCoordinateAxes();
for ( int i = 0; i < axes.size(); i++ )
{
CoordinateAxis axis = (CoordinateAxis) axes.get( i );
showAxis( axis, sb, shade );
shade = !shade;
}
///////////// Grid
GridDataset gds = new GridDataset( ds );
// look for projections
//List gridsets = gds.getGridsets();
sb.append( "<tr>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "GeoGrid" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Description" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "<td align=\"left\"><font size=\"+1\"><strong>" );
sb.append( "Units" );
sb.append( "</strong></font></td>\r\n" );
sb.append( "</tr>" );
// Show the grids
shade = false;
List grids = gds.getGrids();
for ( int i = 0; i < grids.size(); i++ )
{
GridDatatype grid = (GridDatatype) grids.get( i );
showGrid( grid, sb, shade );
shade = !shade;
}
// Render the page footer
sb.append( "</table>\r\n" );
sb.append( "<HR size=\"1\" noshade=\"noshade\">" );
sb.append( "<h3>" ).append( this.contextVersion );
sb.append( " <a href='" ).append( contextPath ).append( "/" ).append( this.docsPath ).append( "'> Documentation</a></h3>\r\n" );
sb.append( "</body>\r\n" );
sb.append( "</html>\r\n" );
return( sb.toString());
}
private void showAxis( CoordinateAxis axis, StringBuffer sb, boolean shade )
{
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\">" );
sb.append( "\r\n" );
StringBuffer sbuff = new StringBuffer();
axis.getNameAndDimensions( sbuff, false, true );
String name = StringUtil.quoteHtmlContent( sbuff.toString() );
sb.append( " " );
sb.append( name );
sb.append( "</tt></a></td>\r\n" );
sb.append( "<td align=\"left\"><tt>" );
AxisType type = axis.getAxisType();
String stype = ( type == null ) ? "" : StringUtil.quoteHtmlContent( type.toString() );
sb.append( stype );
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"left\"><tt>" );
String units = axis.getUnitsString();
String sunits = ( units == null ) ? "" : units;
sb.append( sunits );
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
}
private void showGrid( GridDatatype grid, StringBuffer sb, boolean shade )
{
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\">" );
sb.append( "\r\n" );
VariableEnhanced ve = grid.getVariable();
StringBuffer sbuff = new StringBuffer();
ve.getNameAndDimensions( sbuff, false, true );
String name = StringUtil.quoteHtmlContent( sbuff.toString() );
sb.append( " " );
sb.append( name );
sb.append( "</tt></a></td>\r\n" );
sb.append( "<td align=\"left\"><tt>" );
String desc = ve.getDescription();
String sdesc = ( desc == null ) ? "" : StringUtil.quoteHtmlContent( desc );
sb.append( sdesc );
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"left\"><tt>" );
String units = ve.getUnitsString();
String sunits = ( units == null ) ? "" : units;
sb.append( sunits );
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
}
}
| true | true | private boolean doDatasets( InvCatalogImpl cat, List datasets, StringBuffer sb, boolean shade, int level, boolean isLocalCatalog )
{
URI catURI = cat.getBaseURI();
String catHtml;
if ( !isLocalCatalog )
{
// Setup HREF url to link to HTML dataset page (more below).
catHtml = contextPath + "/catalog.html?cmd=subset&catalog=" + cat.getUriString() + "&";
}
else
{ // replace xml with html
catHtml = cat.getUriString();
int pos = catHtml.lastIndexOf( '.' );
if (pos < 0)
catHtml = catHtml + "catalog.html?";
else
catHtml = catHtml.substring( 0, pos ) + ".html?";
}
for ( int i = 0; i < datasets.size(); i++ )
{
InvDatasetImpl ds = (InvDatasetImpl) datasets.get( i );
String name = StringUtil.quoteHtmlContent( ds.getName() );
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\">" );
for ( int j = 0; j <= level; j++ )
{
sb.append( " " );
}
sb.append( "\r\n" );
if ( ds instanceof InvCatalogRef )
{
InvCatalogRef catref = (InvCatalogRef) ds;
String href = catref.getXlinkHref();
try {
URI uri = new URI(href);
if (uri.isAbsolute()) {
href = contextPath + "/catalogServices?catalog=" + href;
} else {
int pos = href.lastIndexOf('.');
href = href.substring(0, pos) + ".html";
}
} catch (URISyntaxException e) {
log.error(href, e);
}
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( href ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "/</tt></a></td>\r\n" );
}
else // Not an InvCatalogRef
{
if (ds.hasNestedDatasets())
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
// Check if dataset has single resolver service.
if ( ds.getAccess().size() == 1 &&
( (InvAccess) ds.getAccess().get( 0)).getService().getServiceType().equals( ServiceType.RESOLVER ) )
{
InvAccess access = (InvAccess) ds.getAccess().get( 0);
String accessUrlName = access.getUnresolvedUrlName();
int pos = accessUrlName.lastIndexOf( ".xml");
if ( pos != -1 )
accessUrlName = accessUrlName.substring( 0, pos ) + ".html";
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( accessUrlName ) );
sb.append( "\"><tt>" );
String tmpName = name;
if ( tmpName.endsWith( ".xml"))
{
tmpName = tmpName.substring( 0, tmpName.lastIndexOf( '.' ) );
}
sb.append( tmpName );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset with an ID.
else if ( ds.getID() != null )
{
// Write link to HTML dataset page.
sb.append( "<a href=\"" );
// sb.append("catalog.html?cmd=subset&catalog=");
sb.append( StringUtil.quoteHtmlContent( catHtml ) );
sb.append( "dataset=" );
sb.append( StringUtil.quoteHtmlContent( ds.getID() ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset without an ID.
else
{
sb.append( "<tt>" );
sb.append( name );
sb.append( "</tt></td>\r\n" );
}
}
sb.append( "<td align=\"right\"><tt>" );
double size = ds.getDataSize();
if ( ( size != 0.0 ) && !Double.isNaN( size ) )
{
sb.append( Format.formatByteSize( size ) );
}
else
{
sb.append( " " );
}
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"right\"><tt>" );
// Get last modified time.
DateType lastModDateType = ds.getLastModifiedDate();
if ( lastModDateType == null )
{
if ( ! ds.hasAccess())
sb.append( "--");// "");
else
sb.append( "--");// "Unknown");
}
else
{
if ( lastModDateType.isPresent() )
sb.append( formatter.toDateTimeString( new Date() ) );
if ( lastModDateType.getDate() != null )
sb.append( formatter.toDateTimeString( lastModDateType.getDate() ) );
}
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
if ( !( ds instanceof InvCatalogRef ) )
{
shade = doDatasets( cat, ds.getDatasets(), sb, shade, level + 1, isLocalCatalog );
}
}
return shade;
}
| private boolean doDatasets( InvCatalogImpl cat, List datasets, StringBuffer sb, boolean shade, int level, boolean isLocalCatalog )
{
URI catURI = cat.getBaseURI();
String catHtml;
if ( !isLocalCatalog )
{
// Setup HREF url to link to HTML dataset page (more below).
catHtml = contextPath + "/catalog.html?cmd=subset&catalog=" + cat.getUriString() + "&";
}
else
{ // replace xml with html
catHtml = cat.getUriString();
int pos = catHtml.lastIndexOf( '.' );
if (pos < 0)
catHtml = catHtml + "catalog.html?";
else
catHtml = catHtml.substring( 0, pos ) + ".html?";
}
for ( int i = 0; i < datasets.size(); i++ )
{
InvDatasetImpl ds = (InvDatasetImpl) datasets.get( i );
String name = StringUtil.quoteHtmlContent( ds.getName() );
sb.append( "<tr" );
if ( shade )
{
sb.append( " bgcolor=\"#eeeeee\"" );
}
sb.append( ">\r\n" );
shade = !shade;
sb.append( "<td align=\"left\">" );
for ( int j = 0; j <= level; j++ )
{
sb.append( " " );
}
sb.append( "\r\n" );
if ( ds instanceof InvCatalogRef )
{
InvCatalogRef catref = (InvCatalogRef) ds;
String href = catref.getXlinkHref();
if ( ! isLocalCatalog )
{
URI hrefUri = cat.getBaseURI().resolve( href);
href = hrefUri.toString();
}
try {
URI uri = new URI(href);
if (uri.isAbsolute()) {
href = contextPath + "/catalogServices?catalog=" + href;
} else {
int pos = href.lastIndexOf('.');
href = href.substring(0, pos) + ".html";
}
} catch (URISyntaxException e) {
log.error(href, e);
}
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( href ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "/</tt></a></td>\r\n" );
}
else // Not an InvCatalogRef
{
if (ds.hasNestedDatasets())
sb.append( "<img src='/thredds/folder.gif' alt='folder' width='20' height='22'> ");
// Check if dataset has single resolver service.
if ( ds.getAccess().size() == 1 &&
( (InvAccess) ds.getAccess().get( 0)).getService().getServiceType().equals( ServiceType.RESOLVER ) )
{
InvAccess access = (InvAccess) ds.getAccess().get( 0);
String accessUrlName = access.getUnresolvedUrlName();
int pos = accessUrlName.lastIndexOf( ".xml");
if ( pos != -1 )
accessUrlName = accessUrlName.substring( 0, pos ) + ".html";
sb.append( "<a href=\"" );
sb.append( StringUtil.quoteHtmlContent( accessUrlName ) );
sb.append( "\"><tt>" );
String tmpName = name;
if ( tmpName.endsWith( ".xml"))
{
tmpName = tmpName.substring( 0, tmpName.lastIndexOf( '.' ) );
}
sb.append( tmpName );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset with an ID.
else if ( ds.getID() != null )
{
// Write link to HTML dataset page.
sb.append( "<a href=\"" );
// sb.append("catalog.html?cmd=subset&catalog=");
sb.append( StringUtil.quoteHtmlContent( catHtml ) );
sb.append( "dataset=" );
sb.append( StringUtil.quoteHtmlContent( ds.getID() ) );
sb.append( "\"><tt>" );
sb.append( name );
sb.append( "</tt></a></td>\r\n" );
}
// Dataset without an ID.
else
{
sb.append( "<tt>" );
sb.append( name );
sb.append( "</tt></td>\r\n" );
}
}
sb.append( "<td align=\"right\"><tt>" );
double size = ds.getDataSize();
if ( ( size != 0.0 ) && !Double.isNaN( size ) )
{
sb.append( Format.formatByteSize( size ) );
}
else
{
sb.append( " " );
}
sb.append( "</tt></td>\r\n" );
sb.append( "<td align=\"right\"><tt>" );
// Get last modified time.
DateType lastModDateType = ds.getLastModifiedDate();
if ( lastModDateType == null )
{
if ( ! ds.hasAccess())
sb.append( "--");// "");
else
sb.append( "--");// "Unknown");
}
else
{
if ( lastModDateType.isPresent() )
sb.append( formatter.toDateTimeString( new Date() ) );
if ( lastModDateType.getDate() != null )
sb.append( formatter.toDateTimeString( lastModDateType.getDate() ) );
}
sb.append( "</tt></td>\r\n" );
sb.append( "</tr>\r\n" );
if ( !( ds instanceof InvCatalogRef ) )
{
shade = doDatasets( cat, ds.getDatasets(), sb, shade, level + 1, isLocalCatalog );
}
}
return shade;
}
|
diff --git a/src/main/java/org/fotap/heysync/ClassCreatingClassloader.java b/src/main/java/org/fotap/heysync/ClassCreatingClassloader.java
index 275da40..5779ad5 100644
--- a/src/main/java/org/fotap/heysync/ClassCreatingClassloader.java
+++ b/src/main/java/org/fotap/heysync/ClassCreatingClassloader.java
@@ -1,77 +1,77 @@
package org.fotap.heysync;
import org.jetlang.channels.Publisher;
import org.jetlang.core.Callback;
import org.objectweb.asm.Type;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">peter royal</a>
*/
class ClassCreatingClassloader extends ClassLoader {
<T> T publisherFor(Class<T> type, Map<Method, ? extends Publisher<?>> publishers) {
List<Method> methods = new ArrayList<Method>(publishers.keySet());
Type outputType = publisherTypeFor(type);
return newInstance(loadOrDefine(outputType, new PublisherCreator<T>(type, outputType, methods)),
publisherArguments(publishers, methods));
}
private static Type publisherTypeFor(Class<?> type) {
return Type.getType("L" + Type.getInternalName(type) + "$Publisher;");
}
<T, R> Callback<R> callbackFor(Method method, T receiver) {
Type outputType = callbackTypeFor(method);
Class<? extends Callback<R>> type = loadOrDefine(outputType, new CallbackCreator<R>(outputType, method));
return newInstance(type, receiver);
}
private Object[] publisherArguments(Map<Method, ? extends Publisher<?>> publishers, List<Method> methods) {
List<Publisher<?>> arguments = new ArrayList<Publisher<?>>();
for (Method method : methods) {
arguments.add(publishers.get(method));
}
return arguments.toArray();
}
private <T> T newInstance(Class<? extends T> type, Object... initargs) {
return new Instantiator<T>(type, initargs).newInstance();
}
private <T> Class<? extends T> defineClass(ClassCreator<T> creator) {
byte[] bytes = creator.bytes();
// new ClassReader(bytes).accept(new ASMifierClassVisitor(new PrintWriter(System.out)), ClassReader.SKIP_DEBUG );
Class<?> type = defineClass(creator.outputType().getClassName(), bytes, 0, bytes.length);
resolveClass(type);
return type.asSubclass(creator.type());
}
private <T> Class<? extends T> loadOrDefine(Type outputType, ClassCreator<T> creator) {
Class<?> callbackClass = findLoadedClass(outputType.getClassName());
if (null != callbackClass) {
return Cast.as(callbackClass);
}
return defineClass(creator);
}
private Type callbackTypeFor(Method method) {
StringBuilder builder = new StringBuilder()
.append("L")
.append(Type.getInternalName(method.getDeclaringClass()))
.append("$Callback$")
.append(method.getName());
for (Class<?> type : method.getParameterTypes()) {
- builder.append("$").append(type.getName().replace('.', '$'));
+ builder.append("$").append(type.getName().replace('.', '$').replace(':', '$').replace('[', '$').replace(']', '$'));
}
builder.append(";");
return Type.getType(builder.toString());
}
}
| true | true | private Type callbackTypeFor(Method method) {
StringBuilder builder = new StringBuilder()
.append("L")
.append(Type.getInternalName(method.getDeclaringClass()))
.append("$Callback$")
.append(method.getName());
for (Class<?> type : method.getParameterTypes()) {
builder.append("$").append(type.getName().replace('.', '$'));
}
builder.append(";");
return Type.getType(builder.toString());
}
| private Type callbackTypeFor(Method method) {
StringBuilder builder = new StringBuilder()
.append("L")
.append(Type.getInternalName(method.getDeclaringClass()))
.append("$Callback$")
.append(method.getName());
for (Class<?> type : method.getParameterTypes()) {
builder.append("$").append(type.getName().replace('.', '$').replace(':', '$').replace('[', '$').replace(']', '$'));
}
builder.append(";");
return Type.getType(builder.toString());
}
|
diff --git a/src/br/com/anteater/main/Main.java b/src/br/com/anteater/main/Main.java
index d68b236..5803d79 100644
--- a/src/br/com/anteater/main/Main.java
+++ b/src/br/com/anteater/main/Main.java
@@ -1,16 +1,19 @@
package br.com.anteater.main;
import br.com.anteater.script.BuildScript;
import br.com.anteater.script.InteractiveScript;
import br.com.anteater.script.ScriptBase;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ScriptBase script = args.length > 0 ? new BuildScript() : new InteractiveScript();
- script.execute(args);
+ int exitCode = script.execute(args);
+ if (exitCode != 0) {
+ System.exit(exitCode);
+ }
}
}
| true | true | public static void main(String[] args) {
ScriptBase script = args.length > 0 ? new BuildScript() : new InteractiveScript();
script.execute(args);
}
| public static void main(String[] args) {
ScriptBase script = args.length > 0 ? new BuildScript() : new InteractiveScript();
int exitCode = script.execute(args);
if (exitCode != 0) {
System.exit(exitCode);
}
}
|
diff --git a/src/main/java/org/codinjutsu/tools/jenkins/view/JenkinsPanel.java b/src/main/java/org/codinjutsu/tools/jenkins/view/JenkinsPanel.java
index 6036179..2591cdc 100644
--- a/src/main/java/org/codinjutsu/tools/jenkins/view/JenkinsPanel.java
+++ b/src/main/java/org/codinjutsu/tools/jenkins/view/JenkinsPanel.java
@@ -1,47 +1,48 @@
/*
* Copyright (c) 2012 David Boissier
*
* 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.codinjutsu.tools.jenkins.view;
import javax.swing.*;
import java.awt.*;
public class JenkinsPanel extends JPanel {
public static JenkinsPanel onePanel(JenkinsBrowserPanel jenkinsBrowserPanel, RssLatestBuildPanel rssLatestJobPanel) {
return new JenkinsPanel(jenkinsBrowserPanel, rssLatestJobPanel);
}
// public static JenkinsPanel browserOnly(JenkinsBrowserPanel jenkinsBrowserPanel) {
// return new JenkinsPanel(jenkinsBrowserPanel);
// }
//
// private JenkinsPanel(JenkinsBrowserPanel jenkinsBrowserPanel) {
// setLayout(new BorderLayout());
// add(jenkinsBrowserPanel, BorderLayout.CENTER);
// }
private JenkinsPanel(JenkinsBrowserPanel jenkinsBrowserPanel, RssLatestBuildPanel rssLatestJobPanel) {
setLayout(new BorderLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+ splitPane.setOneTouchExpandable(true);
splitPane.setTopComponent(jenkinsBrowserPanel);
splitPane.setBottomComponent(rssLatestJobPanel);
splitPane.setDividerLocation(600);
add(splitPane, BorderLayout.CENTER);
}
}
| true | true | private JenkinsPanel(JenkinsBrowserPanel jenkinsBrowserPanel, RssLatestBuildPanel rssLatestJobPanel) {
setLayout(new BorderLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(jenkinsBrowserPanel);
splitPane.setBottomComponent(rssLatestJobPanel);
splitPane.setDividerLocation(600);
add(splitPane, BorderLayout.CENTER);
}
| private JenkinsPanel(JenkinsBrowserPanel jenkinsBrowserPanel, RssLatestBuildPanel rssLatestJobPanel) {
setLayout(new BorderLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setTopComponent(jenkinsBrowserPanel);
splitPane.setBottomComponent(rssLatestJobPanel);
splitPane.setDividerLocation(600);
add(splitPane, BorderLayout.CENTER);
}
|
diff --git a/src/main/java/hudson/plugins/sonar/template/SonarPomGenerator.java b/src/main/java/hudson/plugins/sonar/template/SonarPomGenerator.java
index cf8e1fc..fef17f3 100644
--- a/src/main/java/hudson/plugins/sonar/template/SonarPomGenerator.java
+++ b/src/main/java/hudson/plugins/sonar/template/SonarPomGenerator.java
@@ -1,79 +1,79 @@
package hudson.plugins.sonar.template;
import hudson.FilePath;
import hudson.plugins.sonar.model.LightProjectConfig;
import hudson.plugins.sonar.model.ReportsConfig;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* @author Evgeny Mandrikov
* @since 1.2
*/
public final class SonarPomGenerator {
public static void generatePomForNonMavenProject(LightProjectConfig project, FilePath root, String pomName) throws IOException, InterruptedException {
SimpleTemplate pomTemplate = new SimpleTemplate("hudson/plugins/sonar/sonar-light-pom.template");
pomTemplate.setAttribute("groupId", project.getGroupId());
pomTemplate.setAttribute("artifactId", project.getArtifactId());
pomTemplate.setAttribute("projectName", project.getProjectName()); // FIXME Godin: env.expand because projectName can be "${JOB_NAME}"
pomTemplate.setAttribute("projectVersion", StringUtils.isEmpty(project.getProjectVersion()) ? "1.0" : project.getProjectVersion());
pomTemplate.setAttribute("javaVersion", StringUtils.isEmpty(project.getJavaVersion()) ? "1.5" : project.getJavaVersion());
List<String> srcDirs = getProjectSrcDirsList(project.getProjectSrcDir());
boolean multiSources = srcDirs.size() > 1;
- setPomElement("sourceDirectory", srcDirs.get(0), pomTemplate);
+ setPomElement("sourceDirectory", srcDirs.size() == 0 ? "src" : srcDirs.get(0), pomTemplate);
pomTemplate.setAttribute("srcDirsPlugin", multiSources ? generateSrcDirsPluginTemplate(srcDirs).toString() : "");
setPomElement("project.build.sourceEncoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("encoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("description", project.getProjectDescription(), pomTemplate);
setPomElement("sonar.phase", multiSources ? "generate-sources" : "", pomTemplate);
setPomElement("outputDirectory", project.getProjectBinDir(), pomTemplate);
ReportsConfig reports = project.isReuseReports() ? project.getReports() : new ReportsConfig();
setPomElement("sonar.dynamicAnalysis", project.isReuseReports() ? "reuseReports" : "false", true, pomTemplate);
setPomElement("sonar.surefire.reportsPath", reports.getSurefireReportsPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.cobertura.reportPath", reports.getCoberturaReportPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.clover.reportPath", reports.getCloverReportPath(), project.isReuseReports(), pomTemplate);
pomTemplate.write(root, pomName);
}
private static SimpleTemplate generateSrcDirsPluginTemplate(List<String> srcDirs) throws IOException, InterruptedException {
SimpleTemplate srcTemplate = new SimpleTemplate("hudson/plugins/sonar/sonar-multi-sources.template");
StringBuffer sourcesXml = new StringBuffer();
for (int i = 1; i < srcDirs.size(); i++) {
sourcesXml.append("<source><![CDATA[").append(StringUtils.trim(srcDirs.get(i))).append("]]></source>\n");
}
srcTemplate.setAttribute("sources", sourcesXml.toString());
return srcTemplate;
}
private static void setPomElement(String tagName, String tagValue, SimpleTemplate template) {
setPomElement(tagName, tagValue, true, template);
}
private static void setPomElement(String tagName, String tagValue, boolean enabled, SimpleTemplate template) {
String tagContent;
if (enabled && StringUtils.isNotBlank(tagValue)) {
tagContent = "<" + tagName + "><![CDATA[" + tagValue + "]]></" + tagName + ">";
} else {
tagContent = "";
}
template.setAttribute(tagName, tagContent);
}
private static List<String> getProjectSrcDirsList(String src) {
String[] dirs = StringUtils.split(src, ',');
return Arrays.asList(dirs);
}
/**
* Hide utility-class constructor.
*/
private SonarPomGenerator() {
}
}
| true | true | public static void generatePomForNonMavenProject(LightProjectConfig project, FilePath root, String pomName) throws IOException, InterruptedException {
SimpleTemplate pomTemplate = new SimpleTemplate("hudson/plugins/sonar/sonar-light-pom.template");
pomTemplate.setAttribute("groupId", project.getGroupId());
pomTemplate.setAttribute("artifactId", project.getArtifactId());
pomTemplate.setAttribute("projectName", project.getProjectName()); // FIXME Godin: env.expand because projectName can be "${JOB_NAME}"
pomTemplate.setAttribute("projectVersion", StringUtils.isEmpty(project.getProjectVersion()) ? "1.0" : project.getProjectVersion());
pomTemplate.setAttribute("javaVersion", StringUtils.isEmpty(project.getJavaVersion()) ? "1.5" : project.getJavaVersion());
List<String> srcDirs = getProjectSrcDirsList(project.getProjectSrcDir());
boolean multiSources = srcDirs.size() > 1;
setPomElement("sourceDirectory", srcDirs.get(0), pomTemplate);
pomTemplate.setAttribute("srcDirsPlugin", multiSources ? generateSrcDirsPluginTemplate(srcDirs).toString() : "");
setPomElement("project.build.sourceEncoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("encoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("description", project.getProjectDescription(), pomTemplate);
setPomElement("sonar.phase", multiSources ? "generate-sources" : "", pomTemplate);
setPomElement("outputDirectory", project.getProjectBinDir(), pomTemplate);
ReportsConfig reports = project.isReuseReports() ? project.getReports() : new ReportsConfig();
setPomElement("sonar.dynamicAnalysis", project.isReuseReports() ? "reuseReports" : "false", true, pomTemplate);
setPomElement("sonar.surefire.reportsPath", reports.getSurefireReportsPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.cobertura.reportPath", reports.getCoberturaReportPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.clover.reportPath", reports.getCloverReportPath(), project.isReuseReports(), pomTemplate);
pomTemplate.write(root, pomName);
}
| public static void generatePomForNonMavenProject(LightProjectConfig project, FilePath root, String pomName) throws IOException, InterruptedException {
SimpleTemplate pomTemplate = new SimpleTemplate("hudson/plugins/sonar/sonar-light-pom.template");
pomTemplate.setAttribute("groupId", project.getGroupId());
pomTemplate.setAttribute("artifactId", project.getArtifactId());
pomTemplate.setAttribute("projectName", project.getProjectName()); // FIXME Godin: env.expand because projectName can be "${JOB_NAME}"
pomTemplate.setAttribute("projectVersion", StringUtils.isEmpty(project.getProjectVersion()) ? "1.0" : project.getProjectVersion());
pomTemplate.setAttribute("javaVersion", StringUtils.isEmpty(project.getJavaVersion()) ? "1.5" : project.getJavaVersion());
List<String> srcDirs = getProjectSrcDirsList(project.getProjectSrcDir());
boolean multiSources = srcDirs.size() > 1;
setPomElement("sourceDirectory", srcDirs.size() == 0 ? "src" : srcDirs.get(0), pomTemplate);
pomTemplate.setAttribute("srcDirsPlugin", multiSources ? generateSrcDirsPluginTemplate(srcDirs).toString() : "");
setPomElement("project.build.sourceEncoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("encoding", project.getProjectSrcEncoding(), pomTemplate);
setPomElement("description", project.getProjectDescription(), pomTemplate);
setPomElement("sonar.phase", multiSources ? "generate-sources" : "", pomTemplate);
setPomElement("outputDirectory", project.getProjectBinDir(), pomTemplate);
ReportsConfig reports = project.isReuseReports() ? project.getReports() : new ReportsConfig();
setPomElement("sonar.dynamicAnalysis", project.isReuseReports() ? "reuseReports" : "false", true, pomTemplate);
setPomElement("sonar.surefire.reportsPath", reports.getSurefireReportsPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.cobertura.reportPath", reports.getCoberturaReportPath(), project.isReuseReports(), pomTemplate);
setPomElement("sonar.clover.reportPath", reports.getCloverReportPath(), project.isReuseReports(), pomTemplate);
pomTemplate.write(root, pomName);
}
|
diff --git a/src/rules/RageRule.java b/src/rules/RageRule.java
index 7d8feb1..1983956 100644
--- a/src/rules/RageRule.java
+++ b/src/rules/RageRule.java
@@ -1,117 +1,117 @@
package rules;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import ballmer.BallmerBot;
public class RageRule implements BotRule {
private enum RageEnum {
DEVELOPERS(30,30),
CHAIR_THROW(10,20);
private int min;
private int variable;
RageEnum(int min, int variable) {
this.min = min;
this.variable = variable;
}
public int getMin() {
return min;
}
public int getVariable() {
return variable;
}
}
private BallmerBot bot;
private String channel;
private RageEnum currentRage;
private Random random;
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private Runnable rageRunnable = new Runnable() {
public void run() {
rage();
scheduleNextRage();
};
};
public RageRule(BallmerBot bot, String channel) {
this.bot = bot;
this.channel = channel;
random = new Random();
scheduleNextRage();
}
private void scheduleNextRage() {
currentRage = getRage();
int nextTime = random.nextInt(currentRage.getVariable()) + currentRage.getMin();
executor.schedule(rageRunnable, nextTime, TimeUnit.MINUTES);
System.out.println("next rage scheduled in " + nextTime + " minutes with rage " + currentRage);
}
private void rage() {
List<String> rageText = getRageTextFor(currentRage);
for (String rage : rageText) {
if (rage.startsWith("/me ")) {
rage = rage.substring(4);
bot.sendAction(channel, rage);
} else {
bot.sendMessage(channel, rage);
}
}
}
/**
* Gets the next rage that ballmer should do.
* @return
*/
private RageEnum getRage() {
RageEnum tempEnum;
do {
int next = random.nextInt(RageEnum.values().length);
tempEnum = RageEnum.values()[next];
} while (tempEnum == currentRage);
return tempEnum;
}
private List<String> getRageTextFor(RageEnum rage) {
List<String> rv = new ArrayList<String>();
switch(rage) {
case DEVELOPERS:
double chance = 1.0;
- while (chance < random.nextDouble() && rv.size() <= 4) {
+ while (chance > random.nextDouble() && rv.size() <= 4) {
rv.add("DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS");
chance /= 2.0;
}
break;
case CHAIR_THROW:
rv.add("/me throws a chair at " + getRandNick());
break;
}
return rv;
}
private String getRandNick() {
User[] nicks = bot.getUsers(channel);
return nicks[random.nextInt(nicks.length)].getNick();
}
@Override
public boolean processMessage(String channel, String sender, String login, String hostname, String message, PircBot callback) {
return false;
}
}
| true | true | private List<String> getRageTextFor(RageEnum rage) {
List<String> rv = new ArrayList<String>();
switch(rage) {
case DEVELOPERS:
double chance = 1.0;
while (chance < random.nextDouble() && rv.size() <= 4) {
rv.add("DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS");
chance /= 2.0;
}
break;
case CHAIR_THROW:
rv.add("/me throws a chair at " + getRandNick());
break;
}
return rv;
}
| private List<String> getRageTextFor(RageEnum rage) {
List<String> rv = new ArrayList<String>();
switch(rage) {
case DEVELOPERS:
double chance = 1.0;
while (chance > random.nextDouble() && rv.size() <= 4) {
rv.add("DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS");
chance /= 2.0;
}
break;
case CHAIR_THROW:
rv.add("/me throws a chair at " + getRandNick());
break;
}
return rv;
}
|
diff --git a/src/main/java/org/mozilla/android/sync/repositories/bookmarks/LocalBookmarkSynchronizer.java b/src/main/java/org/mozilla/android/sync/repositories/bookmarks/LocalBookmarkSynchronizer.java
index 70e50635a..fa4f18ddf 100644
--- a/src/main/java/org/mozilla/android/sync/repositories/bookmarks/LocalBookmarkSynchronizer.java
+++ b/src/main/java/org/mozilla/android/sync/repositories/bookmarks/LocalBookmarkSynchronizer.java
@@ -1,240 +1,240 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Android Sync Client.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Jason Voll <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.android.sync.repositories.bookmarks;
import java.util.ArrayList;
import java.util.Iterator;
import org.mozilla.android.sync.repositories.domain.BookmarkRecord;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Browser;
public class LocalBookmarkSynchronizer {
/*
* This class carries out a local sync which is used to
* keep Mozilla's Bookmark sync database in sync with
* Android's stock bookmark database.
*/
// TODO eventually make this a thread or integrate it
// into some sort of service.
public static final String MOBILE_PARENT_ID = "mobile";
public static final String MOBILE_PARENT_NAME = "mobile";
public static final String BOOKMARK_TYPE = "bookmark";
private Context context;
private BookmarksDatabaseHelper dbHelper;
private ArrayList<Long> visitedDroidIds = new ArrayList<Long>();
public LocalBookmarkSynchronizer(Context context) {
this.context = context;
this.dbHelper = new BookmarksDatabaseHelper(context);
}
/*
* This sync must happen before performing each sync from device
* to sync server. This pulls all changes from the stock bookmarks
* db to the local Moz bookmark db.
*/
public void syncStockToMoz() {
// Get all bookmarks from Moz table (which will reflect last
// known state of stock bookmarks - i.e. a snapshot)
Cursor curMoz = dbHelper.fetchAllBookmarksOrderByAndroidId();
curMoz.moveToFirst();
while (curMoz.isAfterLast() == false) {
// Find bookmark in android store
- int androidId = curMoz.getInt(curMoz.getColumnIndex(BookmarksDatabaseHelper.COL_ANDROID_ID));
+ long androidId = DBUtils.getLongFromCursor(curMoz, BookmarksDatabaseHelper.COL_ANDROID_ID);
String where = Browser.BookmarkColumns._ID + "=" + androidId;
Cursor curDroid = context.getContentResolver().query(Browser.BOOKMARKS_URI, null, where, null, null);
curDroid.moveToFirst();
String guid = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_GUID);
// Check if bookmark has been deleted or modified
if (curDroid.isAfterLast()) {
dbHelper.markDeleted(guid);
} else if (!bookmarksSame(curMoz, curDroid)) {
dbHelper.updateTitleUri(guid,
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.TITLE),
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.URL));
}
visitedDroidIds.add(androidId);
curDroid.close();
}
curMoz.close();
// Find any bookmarks in the local store that we didn't visit
// and add them to our local snapshot
String[] columns = new String[] {
Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.URL,
Browser.BookmarkColumns.TITLE
};
Iterator<Long> it = visitedDroidIds.listIterator();
String where = Browser.BookmarkColumns._ID + " NOT IN (";
while (it.hasNext()) {
long id = it.next();
where = where + id + ", ";
}
where = where.substring(0, where.length() -2) + ")";
Cursor curNew = context.getContentResolver().query(Browser.BOOKMARKS_URI, columns, where, null, null);
curNew.moveToFirst();
while (!curNew.isAfterLast()) {
dbHelper.insertBookmark(
createBookmark(curNew));
}
curNew.close();
}
// Apply changes from local snapshot to stock bookmarks db
// Must provide a list of guids modified in the last sync
public void syncMozToStock(String[] guids) {
// Fetch records for guids
Cursor curMoz = dbHelper.fetch(guids);
curMoz.moveToFirst();
while (!curMoz.isAfterLast()) {
long androidId = DBUtils.getLongFromCursor(curMoz, BookmarksDatabaseHelper.COL_ANDROID_ID);
// Handle deletions
boolean deleted = DBUtils.getLongFromCursor(curMoz, BookmarksDatabaseHelper.COL_DELETED) == 1 ? true:false;
if (deleted) {
context.getContentResolver().delete(Browser.BOOKMARKS_URI, Browser.BookmarkColumns._ID + "=" + androidId, null);
} else {
// Check if a record with the given android Id already exists
Cursor curDroid = context.getContentResolver().query(Browser.BOOKMARKS_URI, null, Browser.BookmarkColumns._ID + "=" + androidId, null, null);
curDroid.moveToFirst();
String title = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_TITLE);
String uri = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_BMK_URI);
ContentValues cv = getContentValuesStock(title, uri);
if (curDroid.isAfterLast()) {
// Handle insertions
Uri newRecord = context.getContentResolver().insert(Browser.BOOKMARKS_URI , cv);
// TODO figure out how to get id from Uri and write it out to the moz snapshotted record
} else {
// Handle updates
int rows = context.getContentResolver().update(
Browser.BOOKMARKS_URI, cv, Browser.BookmarkColumns._ID + "=" + androidId, null);
// TODO check that number of rows modified is 1, if not, scream bloody murder!
}
curDroid.close();
}
curMoz.moveToNext();
}
curMoz.close();
}
// Check if two bookmarks are the same
private boolean bookmarksSame(Cursor curMoz, Cursor curDroid) {
String mozTitle = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_TITLE);
String droidTitle = DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.TITLE);
if (!mozTitle.equals(droidTitle)) return false;
String mozUri = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_BMK_URI);
String droidUri = DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.URL);
if (!mozUri.equals(droidUri)) return false;
return true;
}
// Create new moz bookmark from droid cursor
// containing title, url, id
private BookmarkRecord createBookmark(Cursor curDroid) {
String title = DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.TITLE);
String uri = DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.URL);
long droidId = DBUtils.getLongFromCursor(curDroid, Browser.BookmarkColumns._ID);
BookmarkRecord rec = new BookmarkRecord();
rec.androidID = droidId;
rec.loadInSidebar = false;
rec.title = title;
rec.bookmarkURI = uri;
rec.description = "";
rec.tags = "";
rec.keyword = "";
rec.parentID = MOBILE_PARENT_ID;
rec.parentName = MOBILE_PARENT_NAME;
rec.type = BOOKMARK_TYPE;
rec.generatorURI = "";
rec.staticTitle = "";
rec.folderName = "";
rec.queryID = "";
rec.siteURI = "";
rec.feedURI = "";
rec.pos = "";
rec.children = "";
return rec;
}
// Create content values object for insertion into android db
private ContentValues getContentValuesStock(String title, String uri) {
ContentValues cv = new ContentValues();
cv.put(Browser.BookmarkColumns.BOOKMARK, 1);
cv.put(Browser.BookmarkColumns.TITLE, title);
cv.put(Browser.BookmarkColumns.URL, uri);
// Making assumption that android's db has defaults for the other fields
return cv;
}
}
| true | true | public void syncStockToMoz() {
// Get all bookmarks from Moz table (which will reflect last
// known state of stock bookmarks - i.e. a snapshot)
Cursor curMoz = dbHelper.fetchAllBookmarksOrderByAndroidId();
curMoz.moveToFirst();
while (curMoz.isAfterLast() == false) {
// Find bookmark in android store
int androidId = curMoz.getInt(curMoz.getColumnIndex(BookmarksDatabaseHelper.COL_ANDROID_ID));
String where = Browser.BookmarkColumns._ID + "=" + androidId;
Cursor curDroid = context.getContentResolver().query(Browser.BOOKMARKS_URI, null, where, null, null);
curDroid.moveToFirst();
String guid = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_GUID);
// Check if bookmark has been deleted or modified
if (curDroid.isAfterLast()) {
dbHelper.markDeleted(guid);
} else if (!bookmarksSame(curMoz, curDroid)) {
dbHelper.updateTitleUri(guid,
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.TITLE),
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.URL));
}
visitedDroidIds.add(androidId);
curDroid.close();
}
curMoz.close();
// Find any bookmarks in the local store that we didn't visit
// and add them to our local snapshot
String[] columns = new String[] {
Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.URL,
Browser.BookmarkColumns.TITLE
};
Iterator<Long> it = visitedDroidIds.listIterator();
String where = Browser.BookmarkColumns._ID + " NOT IN (";
while (it.hasNext()) {
long id = it.next();
where = where + id + ", ";
}
where = where.substring(0, where.length() -2) + ")";
Cursor curNew = context.getContentResolver().query(Browser.BOOKMARKS_URI, columns, where, null, null);
curNew.moveToFirst();
while (!curNew.isAfterLast()) {
dbHelper.insertBookmark(
createBookmark(curNew));
}
curNew.close();
}
| public void syncStockToMoz() {
// Get all bookmarks from Moz table (which will reflect last
// known state of stock bookmarks - i.e. a snapshot)
Cursor curMoz = dbHelper.fetchAllBookmarksOrderByAndroidId();
curMoz.moveToFirst();
while (curMoz.isAfterLast() == false) {
// Find bookmark in android store
long androidId = DBUtils.getLongFromCursor(curMoz, BookmarksDatabaseHelper.COL_ANDROID_ID);
String where = Browser.BookmarkColumns._ID + "=" + androidId;
Cursor curDroid = context.getContentResolver().query(Browser.BOOKMARKS_URI, null, where, null, null);
curDroid.moveToFirst();
String guid = DBUtils.getStringFromCursor(curMoz, BookmarksDatabaseHelper.COL_GUID);
// Check if bookmark has been deleted or modified
if (curDroid.isAfterLast()) {
dbHelper.markDeleted(guid);
} else if (!bookmarksSame(curMoz, curDroid)) {
dbHelper.updateTitleUri(guid,
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.TITLE),
DBUtils.getStringFromCursor(curDroid, Browser.BookmarkColumns.URL));
}
visitedDroidIds.add(androidId);
curDroid.close();
}
curMoz.close();
// Find any bookmarks in the local store that we didn't visit
// and add them to our local snapshot
String[] columns = new String[] {
Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.URL,
Browser.BookmarkColumns.TITLE
};
Iterator<Long> it = visitedDroidIds.listIterator();
String where = Browser.BookmarkColumns._ID + " NOT IN (";
while (it.hasNext()) {
long id = it.next();
where = where + id + ", ";
}
where = where.substring(0, where.length() -2) + ")";
Cursor curNew = context.getContentResolver().query(Browser.BOOKMARKS_URI, columns, where, null, null);
curNew.moveToFirst();
while (!curNew.isAfterLast()) {
dbHelper.insertBookmark(
createBookmark(curNew));
}
curNew.close();
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
index 22dd353f0..326407f30 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
@@ -1,1296 +1,1297 @@
/*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.imageio.spi.ServiceRegistry;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.sip.SipErrorEvent;
import javax.servlet.sip.SipErrorListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.ar.SipApplicationRouter;
import javax.servlet.sip.ar.SipApplicationRouterInfo;
import javax.servlet.sip.ar.SipApplicationRoutingRegion;
import javax.servlet.sip.ar.SipRouteModifier;
import javax.servlet.sip.ar.spi.SipApplicationRouterProvider;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.ListeningPoint;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipProvider;
import javax.sip.TimeoutEvent;
import javax.sip.Transaction;
import javax.sip.TransactionAlreadyExistsException;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.TransactionUnavailableException;
import javax.sip.address.Address;
import javax.sip.header.CSeqHeader;
import javax.sip.header.Header;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.Parameters;
import javax.sip.header.RouteHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.catalina.LifecycleException;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.modeler.Registry;
import org.mobicents.servlet.sip.GenericUtils;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.address.AddressImpl;
import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode;
import org.mobicents.servlet.sip.core.dispatchers.DispatcherException;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcherFactory;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.message.SipServletResponseImpl;
import org.mobicents.servlet.sip.message.TransactionApplicationData;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.router.ManageableApplicationRouter;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* Implementation of the SipApplicationDispatcher interface.
* Central point getting the sip messages from the different stacks for a Tomcat Service(Engine),
* translating jain sip SIP messages to sip servlets SIP messages, creating a MessageRouter responsible
* for choosing which Dispatcher will be used for routing the message and
* dispatches the messages.
* @author Jean Deruelle
*/
public class SipApplicationDispatcherImpl implements SipApplicationDispatcher, MBeanRegistration {
/**
* Timer task that will gather information about congestion control
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*/
public class CongestionControlTimerTask implements Runnable {
public void run() {
if(logger.isDebugEnabled()) {
logger.debug("CongestionControlTimerTask now running ");
}
analyzeQueueCongestionState();
analyzeMemory();
//TODO wait for JDK 6 new OperatingSystemMXBean
// analyzeCPU();
}
}
//the logger
private static transient Logger logger = Logger.getLogger(SipApplicationDispatcherImpl.class);
//the sip factory implementation, it is not clear if the sip factory should be the same instance
//for all applications
private SipFactoryImpl sipFactoryImpl = null;
//the sip application router responsible for the routing logic of sip messages to
//sip servlet applications
private SipApplicationRouter sipApplicationRouter = null;
//map of applications deployed
private Map<String, SipContext> applicationDeployed = null;
//map hashes to app names
private Map<String, String> mdToApplicationName = null;
//map app names to hashes
private Map<String, String> applicationNameToMd = null;
//List of host names managed by the container
private Set<String> hostNames = null;
//30 sec
private long congestionControlCheckingInterval;
protected transient CongestionControlTimerTask congestionControlTimerTask;
protected transient ScheduledFuture congestionControlTimerFuture;
private Boolean started = Boolean.FALSE;
private SipNetworkInterfaceManager sipNetworkInterfaceManager;
private ConcurrencyControlMode concurrencyControlMode;
private AtomicLong requestsProcessed = new AtomicLong(0);
private AtomicLong responsesProcessed = new AtomicLong(0);
private boolean rejectSipMessages = false;
private boolean bypassResponseExecutor = false;
private boolean bypassRequestExecutor = false;
private boolean memoryToHigh = false;
private double maxMemory;
private int memoryThreshold;
private CongestionControlPolicy congestionControlPolicy;
int queueSize;
private int numberOfMessagesInQueue;
private double percentageOfMemoryUsed;
// This executor is used for async things that don't need to wait on session executors, like CANCEL requests
// or when the container is configured to execute every request ASAP without waiting on locks (no concurrency control)
private ThreadPoolExecutor asynchronousExecutor = new ThreadPoolExecutor(4, 32, 90, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
//used for the congestion control mechanism
private ScheduledThreadPoolExecutor congestionControlThreadPool = null;
// fatcory for dispatching SIP messages
private MessageDispatcherFactory messageDispatcherFactory;
/**
*
*/
public SipApplicationDispatcherImpl() {
applicationDeployed = new ConcurrentHashMap<String, SipContext>();
mdToApplicationName = new ConcurrentHashMap<String, String>();
applicationNameToMd = new ConcurrentHashMap<String, String>();
sipFactoryImpl = new SipFactoryImpl(this);
hostNames = new CopyOnWriteArraySet<String>();
sipNetworkInterfaceManager = new SipNetworkInterfaceManager(this);
maxMemory = Runtime.getRuntime().maxMemory() / 1024;
congestionControlPolicy = CongestionControlPolicy.ErrorResponse;
congestionControlThreadPool = new ScheduledThreadPoolExecutor(2,
new ThreadPoolExecutor.CallerRunsPolicy());
congestionControlThreadPool.prestartAllCoreThreads();
}
/**
* {@inheritDoc}
*/
public void init() throws LifecycleException {
//load the sip application router from the javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property
//and initializes it if present
String sipApplicationRouterProviderClassName = System.getProperty("javax.servlet.sip.ar.spi.SipApplicationRouterProvider");
if(sipApplicationRouterProviderClassName != null && sipApplicationRouterProviderClassName.length() > 0) {
if(logger.isInfoEnabled()) {
logger.info("Using the javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property to load the application router provider");
}
try {
sipApplicationRouter = ((SipApplicationRouterProvider)
Class.forName(sipApplicationRouterProviderClassName).newInstance()).getSipApplicationRouter();
} catch (InstantiationException e) {
throw new LifecycleException("Impossible to load the Sip Application Router",e);
} catch (IllegalAccessException e) {
throw new LifecycleException("Impossible to load the Sip Application Router",e);
} catch (ClassNotFoundException e) {
throw new LifecycleException("Impossible to load the Sip Application Router",e);
} catch (ClassCastException e) {
throw new LifecycleException("Sip Application Router defined does not implement " + SipApplicationRouter.class.getName(),e);
}
} else {
if(logger.isInfoEnabled()) {
logger.info("Using the Service Provider Framework to load the application router provider");
}
//TODO when moving to JDK 6, use the official http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html instead
//http://grep.codeconsult.ch/2007/10/31/the-java-service-provider-spec-and-sunmiscservice/
Iterator<SipApplicationRouterProvider> providers = ServiceRegistry.lookupProviders(SipApplicationRouterProvider.class);
if(providers.hasNext()) {
sipApplicationRouter = providers.next().getSipApplicationRouter();
}
}
if(sipApplicationRouter == null) {
throw new LifecycleException("No Sip Application Router Provider could be loaded. " +
"No jar compliant with JSR 289 Section Section 15.4.2 could be found on the classpath " +
"and no javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property set");
}
if(logger.isInfoEnabled()) {
logger.info("Using the following Application Router : " + sipApplicationRouter.getClass().getName());
}
sipApplicationRouter.init();
sipApplicationRouter.applicationDeployed(new ArrayList<String>(applicationDeployed.keySet()));
if( oname == null ) {
try {
oname=new ObjectName(domain + ":type=SipApplicationDispatcher");
Registry.getRegistry(null, null)
.registerComponent(this, oname, null);
if(logger.isInfoEnabled()) {
logger.info("Sip Application dispatcher registered under following name " + oname);
}
} catch (Exception e) {
logger.error("Impossible to register the Sip Application dispatcher in domain" + domain, e);
}
}
if(logger.isInfoEnabled()) {
logger.info("bypassRequestExecutor ? " + bypassRequestExecutor);
logger.info("bypassResponseExecutor ? " + bypassResponseExecutor);
}
messageDispatcherFactory = new MessageDispatcherFactory(this);
}
/**
* {@inheritDoc}
*/
public void start() {
synchronized (started) {
if(started) {
return;
}
started = Boolean.TRUE;
}
congestionControlTimerTask = new CongestionControlTimerTask();
if(congestionControlTimerFuture == null && congestionControlCheckingInterval > 0) {
congestionControlTimerFuture = congestionControlThreadPool.scheduleWithFixedDelay(congestionControlTimerTask, congestionControlCheckingInterval, congestionControlCheckingInterval, TimeUnit.MILLISECONDS);
if(logger.isInfoEnabled()) {
logger.info("Congestion control background task started and checking every " + congestionControlCheckingInterval + " milliseconds.");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("No Congestion control background task started since the checking interval is equals to " + congestionControlCheckingInterval + " milliseconds.");
}
}
if(logger.isDebugEnabled()) {
logger.debug("Sip Application Dispatcher started");
}
// outbound interfaces set here and not in sipstandardcontext because
// depending on jboss or tomcat context can be started before or after
// connectors
resetOutboundInterfaces();
//JSR 289 Section 2.1.1 Step 4.If present invoke SipServletListener.servletInitialized() on each of initialized Servlet's listeners.
for (SipContext sipContext : applicationDeployed.values()) {
sipContext.notifySipServletsListeners();
}
}
/**
* {@inheritDoc}
*/
public void stop() {
synchronized (started) {
if(!started) {
return;
}
started = Boolean.FALSE;
}
sipApplicationRouter.destroy();
if(oname != null) {
Registry.getRegistry(null, null).unregisterComponent(oname);
}
}
/**
* {@inheritDoc}
*/
public void addSipApplication(String sipApplicationName, SipContext sipApplication) {
if(logger.isDebugEnabled()) {
logger.debug("Adding the following sip servlet application " + sipApplicationName + ", SipContext=" + sipApplication);
}
if(sipApplicationName == null) {
throw new IllegalArgumentException("Something when wrong while initializing a sip servlets or converged application ");
}
if(sipApplication == null) {
throw new IllegalArgumentException("Something when wrong while initializing the following application " + sipApplicationName);
}
//if the application has not set any concurrency control mode, we default to the container wide one
if(sipApplication.getConcurrencyControlMode() == null) {
sipApplication.setConcurrencyControlMode(concurrencyControlMode);
if(logger.isInfoEnabled()) {
logger.info("No concurrency control mode for application " + sipApplicationName + " , defaulting to the container wide one : " + concurrencyControlMode);
}
} else {
if(logger.isInfoEnabled()) {
logger.info("Concurrency control mode for application " + sipApplicationName + " is " + sipApplication.getConcurrencyControlMode());
}
}
sipApplication.getServletContext().setAttribute(ConcurrencyControlMode.class.getCanonicalName(), sipApplication.getConcurrencyControlMode());
applicationDeployed.put(sipApplicationName, sipApplication);
String hash = GenericUtils.hashString(sipApplicationName);
mdToApplicationName.put(hash, sipApplicationName);
applicationNameToMd.put(sipApplicationName, hash);
List<String> newlyApplicationsDeployed = new ArrayList<String>();
newlyApplicationsDeployed.add(sipApplicationName);
sipApplicationRouter.applicationDeployed(newlyApplicationsDeployed);
//if the ApplicationDispatcher is started, notification is sent that the servlets are ready for service
//otherwise the notification will be delayed until the ApplicationDispatcher has started
synchronized (started) {
if(started) {
sipApplication.notifySipServletsListeners();
}
}
if(logger.isInfoEnabled()) {
logger.info("the following sip servlet application has been added : " + sipApplicationName);
}
if(logger.isInfoEnabled()) {
logger.info("It contains the following Sip Servlets : ");
for(String servletName : sipApplication.getChildrenMap().keySet()) {
logger.info("SipApplicationName : " + sipApplicationName + "/ServletName : " + servletName);
}
if(sipApplication.getSipRubyController() != null) {
logger.info("It contains the following Sip Ruby Controller : " + sipApplication.getSipRubyController());
}
}
}
/**
* {@inheritDoc}
*/
public SipContext removeSipApplication(String sipApplicationName) {
SipContext sipContext = applicationDeployed.remove(sipApplicationName);
List<String> applicationsUndeployed = new ArrayList<String>();
applicationsUndeployed.add(sipApplicationName);
sipApplicationRouter.applicationUndeployed(applicationsUndeployed);
if(sipContext != null) {
((SipManager)sipContext.getManager()).removeAllSessions();
}
String hash = GenericUtils.hashString(sipApplicationName);
mdToApplicationName.remove(hash);
applicationNameToMd.remove(sipApplicationName);
if(logger.isInfoEnabled()) {
logger.info("the following sip servlet application has been removed : " + sipApplicationName);
}
return sipContext;
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processIOException(javax.sip.IOExceptionEvent)
*/
public void processIOException(IOExceptionEvent event) {
logger.error("An IOException occured on " + event.getHost() + ":" + event.getPort() + "/" + event.getTransport() + " for provider " + event.getSource());
}
/*
* Gives the number of pending messages in all queues for all concurrency control modes.
*/
public int getNumberOfPendingMessages() {
return this.asynchronousExecutor.getQueue().size();
// int size = 0;
// Iterator<SipContext> applicationsIterator = this.applicationDeployed
// .values().iterator();
// boolean noneModeAlreadyCounted = false;
// while (applicationsIterator.hasNext()) {
// SipContext context = applicationsIterator.next();
// SipManager manager = (SipManager) context
// .getManager();
// if(context.getConcurrencyControlMode().equals(
// ConcurrencyControlMode.None) && !noneModeAlreadyCounted) {
// size = this.asynchronousExecutor.getQueue().size();
// noneModeAlreadyCounted = true;
// } else if (context.getConcurrencyControlMode().equals(
// ConcurrencyControlMode.SipApplicationSession)) {
// Iterator<MobicentsSipApplicationSession> sessionIterator = manager
// .getAllSipApplicationSessions();
// while (sessionIterator.hasNext()) {
// size += sessionIterator.next().getExecutorService()
// .getQueue().size();
// }
// } else if (context.getConcurrencyControlMode().equals(
// ConcurrencyControlMode.SipSession)) {
// Iterator<MobicentsSipSession> sessionIterator = manager
// .getAllSipSessions();
// while (sessionIterator.hasNext()) {
// size += sessionIterator.next().getExecutorService()
// .getQueue().size();
// }
// }
// }
//
// return size;
}
private void analyzeQueueCongestionState() {
this.numberOfMessagesInQueue = getNumberOfPendingMessages();
if(rejectSipMessages) {
if(numberOfMessagesInQueue <queueSize) {
logger.warn("number of pending messages in the queues : " + numberOfMessagesInQueue + " < to the queue Size : " + queueSize + " => stopping to reject requests");
rejectSipMessages = false;
}
} else {
if(numberOfMessagesInQueue > queueSize) {
logger.warn("number of pending messages in the queues : " + numberOfMessagesInQueue + " > to the queue Size : " + queueSize + " => starting to reject requests");
rejectSipMessages = true;
}
}
}
private void analyzeMemory() {
Runtime runtime = Runtime.getRuntime();
double allocatedMemory = runtime.totalMemory() / 1024;
double freeMemory = runtime.freeMemory() / 1024;
double totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
this.percentageOfMemoryUsed= (100 - ((totalFreeMemory / maxMemory) * 100));
if(memoryToHigh) {
if(percentageOfMemoryUsed < memoryThreshold) {
logger.warn("Memory used: " + percentageOfMemoryUsed + "% < to the memory threshold : " + memoryThreshold + " => stopping to reject requests");
memoryToHigh = false;
}
} else {
if(percentageOfMemoryUsed > memoryThreshold) {
logger.warn("Memory used: " + percentageOfMemoryUsed + "% > to the memory threshold : " + memoryThreshold + " => starting to reject requests");
memoryToHigh = true;
}
}
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processRequest(javax.sip.RequestEvent)
*/
public void processRequest(RequestEvent requestEvent) {
if((rejectSipMessages || memoryToHigh) && CongestionControlPolicy.DropMessage.equals(congestionControlPolicy)) {
logger.error("dropping request, memory is too high or too many messages present in queues");
return;
}
final SipProvider sipProvider = (SipProvider)requestEvent.getSource();
ServerTransaction requestTransaction = requestEvent.getServerTransaction();
final Dialog dialog = requestEvent.getDialog();
final Request request = requestEvent.getRequest();
final String requestMethod = request.getMethod();
try {
if(logger.isDebugEnabled()) {
logger.debug("Got a request event " + request.toString());
}
if (!Request.ACK.equals(requestMethod) && requestTransaction == null ) {
try {
//folsson fix : Workaround broken Cisco 7940/7912
if(request.getHeader(MaxForwardsHeader.NAME) == null){
request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70));
}
requestTransaction = sipProvider.getNewServerTransaction(request);
} catch ( TransactionUnavailableException tae) {
logger.error("cannot get a new Server transaction for this request " + request, tae);
// Sends a 500 Internal server error and stops processing.
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
return;
} catch ( TransactionAlreadyExistsException taex ) {
// Already processed this request so just return.
return;
}
}
final ServerTransaction transaction = requestTransaction;
if(logger.isDebugEnabled()) {
logger.debug("ServerTx ref " + transaction);
logger.debug("Dialog ref " + dialog);
}
final SipServletRequestImpl sipServletRequest = new SipServletRequestImpl(
request,
sipFactoryImpl,
null,
transaction,
dialog,
JainSipUtils.dialogCreatingMethods.contains(requestMethod));
requestsProcessed.incrementAndGet();
// Check if the request is meant for me. If so, strip the topmost
// Route header.
final RouteHeader routeHeader = (RouteHeader) request
.getHeader(RouteHeader.NAME);
//Popping the router header if it's for the container as
//specified in JSR 289 - Section 15.8
if(!isRouteExternal(routeHeader)) {
request.removeFirst(RouteHeader.NAME);
sipServletRequest.setPoppedRoute(routeHeader);
final Parameters poppedAddress = (Parameters)routeHeader.getAddress().getURI();
if(poppedAddress.getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) != null) {
if(logger.isDebugEnabled()) {
logger.debug("the request is for a proxy application, thus it is a subsequent request ");
}
sipServletRequest.setRoutingState(RoutingState.SUBSEQUENT);
}
if(transaction != null) {
TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData();
if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) {
transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false));
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("Routing State " + sipServletRequest.getRoutingState());
}
try {
if(rejectSipMessages || memoryToHigh) {
if(!Request.ACK.equals(requestMethod) && !Request.PRACK.equals(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVICE_UNAVAILABLE, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
+ return;
}
}
messageDispatcherFactory.getRequestDispatcher(sipServletRequest, this).
dispatchMessage(sipProvider, sipServletRequest);
} catch (DispatcherException e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(e.getErrorCode(), (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
}
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(request.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
}
return;
}
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent)
*/
public void processResponse(ResponseEvent responseEvent) {
if((rejectSipMessages || memoryToHigh) && CongestionControlPolicy.DropMessage.equals(congestionControlPolicy)) {
logger.error("dropping response, memory is too high or too many messages present in queues");
return;
}
if(logger.isInfoEnabled()) {
logger.info("Response " + responseEvent.getResponse().toString());
}
final Response response = responseEvent.getResponse();
final CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME);
//if this is a response to a cancel, the response is dropped
if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) {
if(logger.isDebugEnabled()) {
logger.debug("the response is dropped accordingly to JSR 289 " +
"since this a response to a CANCEL");
}
return;
}
responsesProcessed.incrementAndGet();
final ClientTransaction clientTransaction = responseEvent.getClientTransaction();
final Dialog dialog = responseEvent.getDialog();
// Transate the response to SipServletResponse
final SipServletResponseImpl sipServletResponse = new SipServletResponseImpl(
response,
sipFactoryImpl,
clientTransaction,
null,
dialog);
try {
messageDispatcherFactory.getResponseDispatcher(sipServletResponse, this).
dispatchMessage(null, sipServletResponse);
} catch (Throwable e) {
logger.error("An unexpected exception happened while routing the response " + sipServletResponse, e);
return;
}
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processDialogTerminated(javax.sip.DialogTerminatedEvent)
*/
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
if(logger.isInfoEnabled()) {
logger.info("Dialog Terminated => " + dialogTerminatedEvent.getDialog().getCallId().getCallId());
}
Dialog dialog = dialogTerminatedEvent.getDialog();
TransactionApplicationData tad = (TransactionApplicationData) dialog.getApplicationData();
if(tad != null) {
SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage();
MobicentsSipSession sipSessionImpl = sipServletMessageImpl.getSipSession();
tryToInvalidateSession(sipSessionImpl);
} else {
logger.warn("no application data for this dialog " + dialogTerminatedEvent.getDialog().getDialogId());
}
}
/**
* @param sipSessionImpl
*/
private void tryToInvalidateSession(MobicentsSipSession sipSessionImpl) {
//the key can be null if the application already invalidated the session
if(sipSessionImpl.getKey() != null) {
SipContext sipContext = findSipApplication(sipSessionImpl.getKey().getApplicationName());
//the context can be null if the server is being shutdown
if(sipContext != null) {
sipContext.enterSipApp(null, null, null, true, false);
try {
if(logger.isInfoEnabled()) {
logger.info("session " + sipSessionImpl.getId() + " is valid ? :" + sipSessionImpl.isValid());
if(sipSessionImpl.isValid()) {
logger.info("Sip session " + sipSessionImpl.getId() + " is ready to be invalidated ? :" + sipSessionImpl.isReadyToInvalidate());
}
}
if(sipSessionImpl.isValid() && sipSessionImpl.isReadyToInvalidate()) {
sipSessionImpl.onTerminatedState();
}
MobicentsSipApplicationSession sipApplicationSession = sipSessionImpl.getSipApplicationSession();
if(sipApplicationSession != null && sipApplicationSession.isValid() && sipApplicationSession.isReadyToInvalidate()) {
sipApplicationSession.tryToInvalidate();
}
} finally {
sipContext.exitSipApp(null, null);
}
}
}
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processTimeout(javax.sip.TimeoutEvent)
*/
public void processTimeout(TimeoutEvent timeoutEvent) {
Transaction transaction = null;
if(timeoutEvent.isServerTransaction()) {
transaction = timeoutEvent.getServerTransaction();
} else {
transaction = timeoutEvent.getClientTransaction();
}
if(logger.isInfoEnabled()) {
logger.info("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
}
TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
if(tad != null) {
SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
MobicentsSipSession sipSession = sipServletMessage.getSipSession();
if(sipSession != null) {
sipSession.removeOngoingTransaction(transaction);
//notifying SipErrorListener that no ACK has been received for a UAS only
SipServletResponseImpl lastFinalResponse = (SipServletResponseImpl)
((SipServletRequestImpl)sipServletMessage).getLastInformationalResponse();
if(logger.isInfoEnabled()) {
logger.info("last Final Response" + lastFinalResponse);
}
ProxyImpl proxy = sipSession.getProxy();
if(sipServletMessage instanceof SipServletRequestImpl &&
proxy == null &&
lastFinalResponse != null) {
List<SipErrorListener> sipErrorListeners =
sipSession.getSipApplicationSession().getSipContext().getListeners().getSipErrorListeners();
SipErrorEvent sipErrorEvent = new SipErrorEvent(
(SipServletRequest)sipServletMessage,
lastFinalResponse);
for (SipErrorListener sipErrorListener : sipErrorListeners) {
try {
sipErrorListener.noAckReceived(sipErrorEvent);
} catch (Throwable t) {
logger.error("SipErrorListener threw exception", t);
}
}
}
SipServletResponseImpl lastInfoResponse = (SipServletResponseImpl)
((SipServletRequestImpl)sipServletMessage).getLastInformationalResponse();
if(logger.isInfoEnabled()) {
logger.info("last Informational Response" + lastInfoResponse);
}
if(sipServletMessage instanceof SipServletRequestImpl &&
proxy == null &&
lastInfoResponse != null) {
List<SipErrorListener> sipErrorListeners =
sipSession.getSipApplicationSession().getSipContext().getListeners().getSipErrorListeners();
SipErrorEvent sipErrorEvent = new SipErrorEvent(
(SipServletRequest)sipServletMessage,
lastInfoResponse);
for (SipErrorListener sipErrorListener : sipErrorListeners) {
try {
sipErrorListener.noPrackReceived(sipErrorEvent);
} catch (Throwable t) {
logger.error("SipErrorListener threw exception", t);
}
}
}
tryToInvalidateSession(sipSession);
}
}
}
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processTransactionTerminated(javax.sip.TransactionTerminatedEvent)
*/
public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
Transaction transaction = null;
if(transactionTerminatedEvent.isServerTransaction()) {
transaction = transactionTerminatedEvent.getServerTransaction();
} else {
transaction = transactionTerminatedEvent.getClientTransaction();
}
if(logger.isInfoEnabled()) {
logger.info("transaction " + transaction + " terminated => " + transaction.getRequest().toString());
}
TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
if(tad != null) {
SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage();
MobicentsSipSession sipSessionImpl = sipServletMessageImpl.getSipSession();
if(sipSessionImpl == null) {
// if(logger.isInfoEnabled()) {
logger.warn("no sip session were returned for this transaction " + transaction + " and message " + sipServletMessageImpl);
// }
} else {
if(sipSessionImpl.getKey() != null) {
if(logger.isInfoEnabled()) {
logger.info("sip session " + sipSessionImpl.getId() + " returned for this transaction " + transaction);
}
tryToInvalidateSession(sipSessionImpl);
} else {
if(logger.isInfoEnabled()) {
logger.info("sip session already invalidate by the app for message " + sipServletMessageImpl);
}
}
// sipSessionImpl.removeOngoingTransaction(transaction);
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("TransactionApplicationData not available on the following request " + transaction.getRequest().toString());
}
}
}
public String getApplicationNameFromHash(String hash) {
return mdToApplicationName.get(hash);
}
public String getHashFromApplicationName(String appName) {
return applicationNameToMd.get(appName);
}
/**
* Check if the route is external
* @param routeHeader the route to check
* @return true if the route is external, false otherwise
*/
public final boolean isRouteExternal(RouteHeader routeHeader) {
if (routeHeader != null) {
javax.sip.address.SipURI routeUri = (javax.sip.address.SipURI) routeHeader.getAddress().getURI();
String routeTransport = routeUri.getTransportParam();
if(routeTransport == null) {
routeTransport = ListeningPoint.UDP;
}
return isExternal(routeUri.getHost(), routeUri.getPort(), routeTransport);
}
return true;
}
/**
* Check if the via header is external
* @param viaHeader the via header to check
* @return true if the via header is external, false otherwise
*/
public final boolean isViaHeaderExternal(ViaHeader viaHeader) {
if (viaHeader != null) {
return isExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport());
}
return true;
}
/**
* Check whether or not the triplet host, port and transport are corresponding to an interface
* @param host can be hostname or ipaddress
* @param port port number
* @param transport transport used
* @return true if the triplet host, port and transport are corresponding to an interface
* false otherwise
*/
public final boolean isExternal(String host, int port, String transport) {
boolean isExternal = true;
ExtendedListeningPoint listeningPoint = sipNetworkInterfaceManager.findMatchingListeningPoint(host, port, transport);
if((hostNames.contains(host) || listeningPoint != null)) {
if(logger.isDebugEnabled()) {
logger.debug("hostNames.contains(host)=" +
hostNames.contains(host) +
" | listeningPoint found = " +
listeningPoint);
}
isExternal = false;
}
if(logger.isDebugEnabled()) {
logger.debug("the triplet host/port/transport : " +
host + "/" +
port + "/" +
transport + " is external : " + isExternal);
}
return isExternal;
}
/**
* @return the sipApplicationRouter
*/
public SipApplicationRouter getSipApplicationRouter() {
return sipApplicationRouter;
}
/**
* @param sipApplicationRouter the sipApplicationRouter to set
*/
public void setSipApplicationRouter(SipApplicationRouter sipApplicationRouter) {
this.sipApplicationRouter = sipApplicationRouter;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipNetworkInterfaceManager()
*/
public SipNetworkInterfaceManager getSipNetworkInterfaceManager() {
return this.sipNetworkInterfaceManager;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipFactory()
*/
public SipFactoryImpl getSipFactory() {
return sipFactoryImpl;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getOutboundInterfaces()
*/
public List<SipURI> getOutboundInterfaces() {
return sipNetworkInterfaceManager.getOutboundInterfaces();
}
/**
* set the outbound interfaces on all servlet context of applications deployed
*/
private void resetOutboundInterfaces() {
List<SipURI> outboundInterfaces = sipNetworkInterfaceManager.getOutboundInterfaces();
for (SipContext sipContext : applicationDeployed.values()) {
sipContext.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES,
outboundInterfaces);
}
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#addHostName(java.lang.String)
*/
public void addHostName(String hostName) {
if(logger.isDebugEnabled()) {
logger.debug(this);
logger.debug("Adding hostname "+ hostName);
}
hostNames.add(hostName);
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findHostNames()
*/
public Set<String> findHostNames() {
return hostNames;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#removeHostName(java.lang.String)
*/
public void removeHostName(String hostName) {
if(logger.isDebugEnabled()) {
logger.debug("Removing hostname "+ hostName);
}
hostNames.remove(hostName);
}
/**
*
*/
public SipApplicationRouterInfo getNextInterestedApplication(
SipServletRequestImpl sipServletRequest) {
SipApplicationRoutingRegion routingRegion = null;
Serializable stateInfo = null;
if(sipServletRequest.getSipSession() != null) {
routingRegion = sipServletRequest.getSipSession().getRegionInternal();
stateInfo = sipServletRequest.getSipSession().getStateInfo();
}
final Request request = (Request) sipServletRequest.getMessage();
sipServletRequest.setReadOnly(true);
SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication(
sipServletRequest,
routingRegion,
sipServletRequest.getRoutingDirective(),
null,
stateInfo);
sipServletRequest.setReadOnly(false);
// 15.4.1 Procedure : point 2
final SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier();
final String[] routes = applicationRouterInfo.getRoutes();
try {
// ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route,
// it is up to container to decide whether it is external or internal.
if(SipRouteModifier.ROUTE.equals(sipRouteModifier)) {
final Address routeAddress = SipFactories.addressFactory.createAddress(routes[0]);
final RouteHeader applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress);
if(isRouteExternal(applicationRouterInfoRouteHeader)) {
// push all of the routes on the Route header stack of the request and
// send the request externally
for (int i = routes.length-1 ; i >= 0; i--) {
Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]);
request.addHeader(routeHeader);
}
}
} else if (SipRouteModifier.ROUTE_BACK.equals(sipRouteModifier)) {
// Push container Route, pick up the first outbound interface
final SipURI sipURI = getOutboundInterfaces().get(0);
sipURI.setParameter("modifier", "route_back");
Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString());
request.addHeader(routeHeader);
// push all of the routes on the Route header stack of the request and
// send the request externally
for (int i = routes.length-1 ; i >= 0; i--) {
routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]);
request.addHeader(routeHeader);
}
}
} catch (ParseException e) {
logger.error("Impossible to parse the route returned by the application router " +
"into a compliant address",e);
}
return applicationRouterInfo;
}
public ThreadPoolExecutor getAsynchronousExecutor() {
return asynchronousExecutor;
}
/**
* Serialize the state info in memory and deserialize it and return the new object.
* Since there is no clone method this is the only way to get the same object with a new reference
* @param stateInfo the state info to serialize
* @return the state info serialized and deserialized
*/
private Serializable serializeStateInfo(Serializable stateInfo) {
ByteArrayOutputStream baos = null;
ObjectOutputStream out = null;
ByteArrayInputStream bais = null;
ObjectInputStream in = null;
try{
baos = new ByteArrayOutputStream();
out = new ObjectOutputStream(baos);
out.writeObject(stateInfo);
bais = new ByteArrayInputStream(baos.toByteArray());
in =new ObjectInputStream(bais);
return (Serializable)in.readObject();
} catch (IOException e) {
logger.error("Impossible to serialize the state info", e);
return stateInfo;
} catch (ClassNotFoundException e) {
logger.error("Impossible to serialize the state info", e);
return stateInfo;
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
if(baos != null) {
baos.close();
}
if(bais != null) {
bais.close();
}
} catch (IOException e) {
logger.error("Impossible to close the streams after serializing state info", e);
}
}
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplications()
*/
public Iterator<SipContext> findSipApplications() {
return applicationDeployed.values().iterator();
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplication(java.lang.String)
*/
public SipContext findSipApplication(String applicationName) {
return applicationDeployed.get(applicationName);
}
// -------------------- JMX and Registration --------------------
protected String domain;
protected ObjectName oname;
protected MBeanServer mserver;
public ObjectName getObjectName() {
return oname;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
/*
* (non-Javadoc)
* @see javax.management.MBeanRegistration#postDeregister()
*/
public void postDeregister() {}
/*
* (non-Javadoc)
* @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
*/
public void postRegister(Boolean registrationDone) {}
/*
* (non-Javadoc)
* @see javax.management.MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {}
/*
* (non-Javadoc)
* @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
oname=name;
mserver=server;
domain=name.getDomain();
return name;
}
/* Exposed methods for the management console. Some of these duplicate existing methods, but
* with JMX friendly types.
*/
public String[] findInstalledSipApplications() {
Iterator<SipContext> apps = findSipApplications();
ArrayList<String> appList = new ArrayList<String>();
while(apps.hasNext()){
SipContext ctx = apps.next();
appList.add(ctx.getApplicationName());
}
String[] ret = new String[appList.size()];
for(int q=0; q<appList.size(); q++) ret[q] = appList.get(q);
return ret;
}
public Object retrieveApplicationRouterConfiguration() {
if(this.sipApplicationRouter instanceof ManageableApplicationRouter) {
ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter;
return router.getCurrentConfiguration();
} else {
throw new RuntimeException("This application router is not manageable");
}
}
public void updateApplicationRouterConfiguration(Object configuration) {
if(this.sipApplicationRouter instanceof ManageableApplicationRouter) {
ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter;
router.configure(configuration);
} else {
throw new RuntimeException("This application router is not manageable");
}
}
public ConcurrencyControlMode getConcurrencyControlMode() {
return concurrencyControlMode;
}
public void setConcurrencyControlMode(ConcurrencyControlMode concurrencyControlMode) {
this.concurrencyControlMode = concurrencyControlMode;
if(logger.isInfoEnabled()) {
logger.info("Container wide Concurrency Control set to " + concurrencyControlMode.toString());
}
}
public int getQueueSize() {
return queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public void setConcurrencyControlModeByName(String concurrencyControlMode) {
this.concurrencyControlMode = ConcurrencyControlMode.valueOf(concurrencyControlMode);
}
/**
* @return the requestsProcessed
*/
public long getRequestsProcessed() {
return requestsProcessed.get();
}
/**
* @return the requestsProcessed
*/
public long getResponsesProcessed() {
return responsesProcessed.get();
}
/**
* @param congestionControlCheckingInterval the congestionControlCheckingInterval to set
*/
public void setCongestionControlCheckingInterval(
long congestionControlCheckingInterval) {
this.congestionControlCheckingInterval = congestionControlCheckingInterval;
if(started) {
if(congestionControlTimerFuture != null) {
congestionControlTimerFuture.cancel(false);
}
if(congestionControlCheckingInterval > 0) {
congestionControlTimerFuture = congestionControlThreadPool.scheduleWithFixedDelay(congestionControlTimerTask, congestionControlCheckingInterval, congestionControlCheckingInterval, TimeUnit.MILLISECONDS);
if(logger.isInfoEnabled()) {
logger.info("Congestion control background task modified to check every " + congestionControlCheckingInterval + " milliseconds.");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("No Congestion control background task started since the checking interval is equals to " + congestionControlCheckingInterval + " milliseconds.");
}
}
}
}
/**
* @return the congestionControlCheckingInterval
*/
public long getCongestionControlCheckingInterval() {
return congestionControlCheckingInterval;
}
/**
* @param congestionControlPolicy the congestionControlPolicy to set
*/
public void setCongestionControlPolicy(CongestionControlPolicy congestionControlPolicy) {
this.congestionControlPolicy = congestionControlPolicy;
}
public void setCongestionControlPolicyByName(String congestionControlPolicy) {
this.congestionControlPolicy = CongestionControlPolicy.valueOf(congestionControlPolicy);
}
/**
* @return the congestionControlPolicy
*/
public CongestionControlPolicy getCongestionControlPolicy() {
return congestionControlPolicy;
}
/**
* @param memoryThreshold the memoryThreshold to set
*/
public void setMemoryThreshold(int memoryThreshold) {
this.memoryThreshold = memoryThreshold;
}
/**
* @return the memoryThreshold
*/
public int getMemoryThreshold() {
return memoryThreshold;
}
/**
* @return the numberOfMessagesInQueue
*/
public int getNumberOfMessagesInQueue() {
return numberOfMessagesInQueue;
}
/**
* @return the percentageOfMemoryUsed
*/
public double getPercentageOfMemoryUsed() {
return percentageOfMemoryUsed;
}
/**
* @param bypassRequestExecutor the bypassRequestExecutor to set
*/
public void setBypassRequestExecutor(boolean bypassRequestExecutor) {
this.bypassRequestExecutor = bypassRequestExecutor;
}
/**
* @return the bypassRequestExecutor
*/
public boolean isBypassRequestExecutor() {
return bypassRequestExecutor;
}
/**
* @param bypassResponseExecutor the bypassResponseExecutor to set
*/
public void setBypassResponseExecutor(boolean bypassResponseExecutor) {
this.bypassResponseExecutor = bypassResponseExecutor;
}
/**
* @return the bypassResponseExecutor
*/
public boolean isBypassResponseExecutor() {
return bypassResponseExecutor;
}
}
| true | true | public void processRequest(RequestEvent requestEvent) {
if((rejectSipMessages || memoryToHigh) && CongestionControlPolicy.DropMessage.equals(congestionControlPolicy)) {
logger.error("dropping request, memory is too high or too many messages present in queues");
return;
}
final SipProvider sipProvider = (SipProvider)requestEvent.getSource();
ServerTransaction requestTransaction = requestEvent.getServerTransaction();
final Dialog dialog = requestEvent.getDialog();
final Request request = requestEvent.getRequest();
final String requestMethod = request.getMethod();
try {
if(logger.isDebugEnabled()) {
logger.debug("Got a request event " + request.toString());
}
if (!Request.ACK.equals(requestMethod) && requestTransaction == null ) {
try {
//folsson fix : Workaround broken Cisco 7940/7912
if(request.getHeader(MaxForwardsHeader.NAME) == null){
request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70));
}
requestTransaction = sipProvider.getNewServerTransaction(request);
} catch ( TransactionUnavailableException tae) {
logger.error("cannot get a new Server transaction for this request " + request, tae);
// Sends a 500 Internal server error and stops processing.
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
return;
} catch ( TransactionAlreadyExistsException taex ) {
// Already processed this request so just return.
return;
}
}
final ServerTransaction transaction = requestTransaction;
if(logger.isDebugEnabled()) {
logger.debug("ServerTx ref " + transaction);
logger.debug("Dialog ref " + dialog);
}
final SipServletRequestImpl sipServletRequest = new SipServletRequestImpl(
request,
sipFactoryImpl,
null,
transaction,
dialog,
JainSipUtils.dialogCreatingMethods.contains(requestMethod));
requestsProcessed.incrementAndGet();
// Check if the request is meant for me. If so, strip the topmost
// Route header.
final RouteHeader routeHeader = (RouteHeader) request
.getHeader(RouteHeader.NAME);
//Popping the router header if it's for the container as
//specified in JSR 289 - Section 15.8
if(!isRouteExternal(routeHeader)) {
request.removeFirst(RouteHeader.NAME);
sipServletRequest.setPoppedRoute(routeHeader);
final Parameters poppedAddress = (Parameters)routeHeader.getAddress().getURI();
if(poppedAddress.getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) != null) {
if(logger.isDebugEnabled()) {
logger.debug("the request is for a proxy application, thus it is a subsequent request ");
}
sipServletRequest.setRoutingState(RoutingState.SUBSEQUENT);
}
if(transaction != null) {
TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData();
if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) {
transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false));
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("Routing State " + sipServletRequest.getRoutingState());
}
try {
if(rejectSipMessages || memoryToHigh) {
if(!Request.ACK.equals(requestMethod) && !Request.PRACK.equals(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVICE_UNAVAILABLE, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
}
messageDispatcherFactory.getRequestDispatcher(sipServletRequest, this).
dispatchMessage(sipProvider, sipServletRequest);
} catch (DispatcherException e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(e.getErrorCode(), (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
}
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(request.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
}
return;
}
}
| public void processRequest(RequestEvent requestEvent) {
if((rejectSipMessages || memoryToHigh) && CongestionControlPolicy.DropMessage.equals(congestionControlPolicy)) {
logger.error("dropping request, memory is too high or too many messages present in queues");
return;
}
final SipProvider sipProvider = (SipProvider)requestEvent.getSource();
ServerTransaction requestTransaction = requestEvent.getServerTransaction();
final Dialog dialog = requestEvent.getDialog();
final Request request = requestEvent.getRequest();
final String requestMethod = request.getMethod();
try {
if(logger.isDebugEnabled()) {
logger.debug("Got a request event " + request.toString());
}
if (!Request.ACK.equals(requestMethod) && requestTransaction == null ) {
try {
//folsson fix : Workaround broken Cisco 7940/7912
if(request.getHeader(MaxForwardsHeader.NAME) == null){
request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70));
}
requestTransaction = sipProvider.getNewServerTransaction(request);
} catch ( TransactionUnavailableException tae) {
logger.error("cannot get a new Server transaction for this request " + request, tae);
// Sends a 500 Internal server error and stops processing.
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
return;
} catch ( TransactionAlreadyExistsException taex ) {
// Already processed this request so just return.
return;
}
}
final ServerTransaction transaction = requestTransaction;
if(logger.isDebugEnabled()) {
logger.debug("ServerTx ref " + transaction);
logger.debug("Dialog ref " + dialog);
}
final SipServletRequestImpl sipServletRequest = new SipServletRequestImpl(
request,
sipFactoryImpl,
null,
transaction,
dialog,
JainSipUtils.dialogCreatingMethods.contains(requestMethod));
requestsProcessed.incrementAndGet();
// Check if the request is meant for me. If so, strip the topmost
// Route header.
final RouteHeader routeHeader = (RouteHeader) request
.getHeader(RouteHeader.NAME);
//Popping the router header if it's for the container as
//specified in JSR 289 - Section 15.8
if(!isRouteExternal(routeHeader)) {
request.removeFirst(RouteHeader.NAME);
sipServletRequest.setPoppedRoute(routeHeader);
final Parameters poppedAddress = (Parameters)routeHeader.getAddress().getURI();
if(poppedAddress.getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) != null) {
if(logger.isDebugEnabled()) {
logger.debug("the request is for a proxy application, thus it is a subsequent request ");
}
sipServletRequest.setRoutingState(RoutingState.SUBSEQUENT);
}
if(transaction != null) {
TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData();
if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) {
transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false));
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("Routing State " + sipServletRequest.getRoutingState());
}
try {
if(rejectSipMessages || memoryToHigh) {
if(!Request.ACK.equals(requestMethod) && !Request.PRACK.equals(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVICE_UNAVAILABLE, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
return;
}
}
messageDispatcherFactory.getRequestDispatcher(sipServletRequest, this).
dispatchMessage(sipProvider, sipServletRequest);
} catch (DispatcherException e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(e.getErrorCode(), (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
return;
}
} catch (Throwable e) {
logger.error("Unexpected exception while processing request " + request,e);
// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
if(!Request.ACK.equalsIgnoreCase(request.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
}
return;
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui.discovery/src/org/eclipse/equinox/internal/p2/ui/discovery/util/FilteredViewer.java b/bundles/org.eclipse.equinox.p2.ui.discovery/src/org/eclipse/equinox/internal/p2/ui/discovery/util/FilteredViewer.java
index b44c13b6a..6b78e3969 100644
--- a/bundles/org.eclipse.equinox.p2.ui.discovery/src/org/eclipse/equinox/internal/p2/ui/discovery/util/FilteredViewer.java
+++ b/bundles/org.eclipse.equinox.p2.ui.discovery/src/org/eclipse/equinox/internal/p2/ui/discovery/util/FilteredViewer.java
@@ -1,236 +1,245 @@
/*******************************************************************************
* Copyright (c) 2004, 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
* Jacek Pospychala - bug 187762
* Mohamed Tarief - [email protected] - IBM - Bug 174481
* Tasktop Technologies - generalized filter code for structured viewers
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.discovery.util;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.ui.discovery.wizards.Messages;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.progress.WorkbenchJob;
/**
* Based on {@link org.eclipse.ui.dialogs.FilteredTree}.
*
* @author Steffen Pingel
*/
public abstract class FilteredViewer {
private boolean automaticFind;
private Label clearFilterTextControl;
private Composite container;
TextSearchControl filterText;
private int minimumHeight;
String previousFilterText = ""; //$NON-NLS-1$
WorkbenchJob refreshJob;
private long refreshJobDelay = 200L;
private PatternFilter searchFilter;
protected StructuredViewer viewer;
private Composite header;
public FilteredViewer() {
setAutomaticFind(true);
}
void clearFilterText() {
filterText.getTextControl().setText(""); //$NON-NLS-1$
filterTextChanged();
}
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().margins(0, 0).applyTo(container);
container.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (refreshJob != null) {
refreshJob.cancel();
}
}
});
doCreateHeader();
viewer = doCreateViewer(container);
searchFilter = doCreateFilter();
viewer.addFilter(searchFilter);
GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, minimumHeight).applyTo(viewer.getControl());
}
protected PatternFilter doCreateFilter() {
return new PatternFilter() {
@Override
protected boolean isParentMatch(Viewer viewer, Object element) {
return false;
}
};
}
private void doCreateFindControl(Composite parent) {
Label label = new Label(parent, SWT.NONE);
label.setText(Messages.ConnectorDiscoveryWizardMainPage_filterLabel);
GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(label);
filterText = new TextSearchControl(parent, automaticFind);
if (automaticFind) {
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
filterTextChanged();
}
});
+ } else {
+ filterText.getTextControl().addTraverseListener(new TraverseListener() {
+ public void keyTraversed(TraverseEvent e) {
+ if (e.detail == SWT.TRAVERSE_RETURN) {
+ e.doit = false;
+ filterTextChanged();
+ }
+ }
+ });
}
filterText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.ICON_CANCEL) {
clearFilterText();
} else {
// search icon and enter
filterTextChanged();
}
}
});
GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.CENTER).applyTo(filterText);
}
private void doCreateHeader() {
header = new Composite(container, SWT.NONE);
GridLayoutFactory.fillDefaults().applyTo(header);
GridDataFactory.fillDefaults().grab(true, false).applyTo(header);
doCreateFindControl(header);
doCreateHeaderControls(header);
// arrange all header controls horizontally
GridLayoutFactory.fillDefaults().numColumns(header.getChildren().length).applyTo(header);
}
protected void doCreateHeaderControls(Composite parent) {
// ignore
}
public void setHeaderVisible(boolean visible) {
if (header != null && visible != header.getVisible()) {
header.setVisible(visible);
GridData headerLayout = (GridData) header.getLayoutData();
headerLayout.exclude = !visible;
container.layout(true, true);
}
}
public boolean isHeaderVisible() {
return header != null && header.getVisible();
}
protected WorkbenchJob doCreateRefreshJob() {
return new WorkbenchJob("filter") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
if (filterText.isDisposed()) {
return Status.CANCEL_STATUS;
}
String text = filterText.getTextControl().getText();
text = text.trim();
if (!previousFilterText.equals(text)) {
previousFilterText = text;
doFind(text);
}
return Status.OK_STATUS;
}
};
}
protected abstract StructuredViewer doCreateViewer(Composite parent);
protected void doFind(String text) {
searchFilter.setPattern(text);
if (clearFilterTextControl != null) {
clearFilterTextControl.setVisible(text != null && text.length() != 0);
}
viewer.refresh(true);
}
/**
* Invoked whenever the filter text is changed or the user otherwise causes the filter text to change.
*/
protected void filterTextChanged() {
if (refreshJob == null) {
refreshJob = doCreateRefreshJob();
} else {
refreshJob.cancel();
}
refreshJob.schedule(refreshJobDelay);
}
/**
* Provides the text string of the search widget.
*/
protected String getFilterText() {
return filterText == null ? null : filterText.getTextControl().getText();
}
public Control getControl() {
return container;
}
public int getMinimumHeight() {
return minimumHeight;
}
protected long getRefreshJobDelay() {
return refreshJobDelay;
}
public StructuredViewer getViewer() {
return viewer;
}
public void setMinimumHeight(int minimumHeight) {
this.minimumHeight = minimumHeight;
if (viewer != null) {
GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, minimumHeight).applyTo(viewer.getControl());
}
}
protected void setRefreshJobDelay(long refreshJobDelay) {
this.refreshJobDelay = refreshJobDelay;
}
public final void setAutomaticFind(boolean automaticFind) {
if (filterText != null) {
throw new IllegalStateException("setAutomaticFind() needs be invoked before controls are created"); //$NON-NLS-1$
}
this.automaticFind = automaticFind;
}
public final boolean isAutomaticFind() {
return automaticFind;
}
}
| true | true | private void doCreateFindControl(Composite parent) {
Label label = new Label(parent, SWT.NONE);
label.setText(Messages.ConnectorDiscoveryWizardMainPage_filterLabel);
GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(label);
filterText = new TextSearchControl(parent, automaticFind);
if (automaticFind) {
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
filterTextChanged();
}
});
}
filterText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.ICON_CANCEL) {
clearFilterText();
} else {
// search icon and enter
filterTextChanged();
}
}
});
GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.CENTER).applyTo(filterText);
}
| private void doCreateFindControl(Composite parent) {
Label label = new Label(parent, SWT.NONE);
label.setText(Messages.ConnectorDiscoveryWizardMainPage_filterLabel);
GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(label);
filterText = new TextSearchControl(parent, automaticFind);
if (automaticFind) {
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
filterTextChanged();
}
});
} else {
filterText.getTextControl().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN) {
e.doit = false;
filterTextChanged();
}
}
});
}
filterText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.ICON_CANCEL) {
clearFilterText();
} else {
// search icon and enter
filterTextChanged();
}
}
});
GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.CENTER).applyTo(filterText);
}
|
diff --git a/src/com/redhat/ceylon/compiler/codegen/CeylonModelLoader.java b/src/com/redhat/ceylon/compiler/codegen/CeylonModelLoader.java
index 28343f970..f3d48a4fa 100755
--- a/src/com/redhat/ceylon/compiler/codegen/CeylonModelLoader.java
+++ b/src/com/redhat/ceylon/compiler/codegen/CeylonModelLoader.java
@@ -1,604 +1,604 @@
package com.redhat.ceylon.compiler.codegen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.lang.model.type.TypeKind;
import javax.tools.JavaFileObject.Kind;
import com.redhat.ceylon.compiler.tools.LanguageCompiler;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.compiler.util.Util;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Attribute.Array;
import com.sun.tools.javac.code.Attribute.Compound;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.jvm.ClassReader;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Name.Table;
public class CeylonModelLoader implements ModelCompleter, ModelLoader {
private Symtab symtab;
private Table names;
private Map<String, Declaration> declarationsByName = new HashMap<String, Declaration>();
private ClassReader reader;
private PhasedUnits phasedUnits;
private com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext;
private TypeParser typeParser = new TypeParser();
private Log log;
public static CeylonModelLoader instance(Context context) {
CeylonModelLoader instance = context.get(CeylonModelLoader.class);
if (instance == null) {
instance = new CeylonModelLoader(context);
context.put(CeylonModelLoader.class, instance);
}
return instance;
}
public CeylonModelLoader(Context context) {
phasedUnits = LanguageCompiler.getPhasedUnitsInstance(context);
ceylonContext = LanguageCompiler.getCeylonContextInstance(context);
symtab = Symtab.instance(context);
names = Name.Table.instance(context);
reader = ClassReader.instance(context);
log = Log.instance(context);
}
public void loadRequiredModules(com.sun.tools.javac.util.List<JCCompilationUnit> trees) {
/*
* We start by loading java.lang and ceylon.language because we will need them no matter what.
*/
PackageSymbol ceylonPkg = reader.enterPackage(names.fromString("ceylon.language"));
ceylonPkg.complete();
PackageSymbol javaPkg = reader.enterPackage(names.fromString("java.lang"));
javaPkg.complete();
/*
* Eventually this will go away as we get a hook from the typechecker to load on demand, but
* for now the typechecker requires at least ceylon.language to be loaded
*/
for(Symbol m : ceylonPkg.members().getElements()){
convertToDeclaration(lookupClassSymbol(m.getQualifiedName().toString()));
}
for(final JCCompilationUnit tree : trees){
CompilationUnit ceylonTree = ((CeylonCompilationUnit)tree).ceylonTree;
final String pkgName = tree.getPackageName().toString();
ceylonTree.visit(new Visitor(){
@Override
public void visit(ClassDefinition that) {
String name = that.getIdentifier().getText();
String fqn = pkgName.isEmpty() ? name : pkgName+"."+name;
ClassSymbol classSymbol = reader.enterClass(names.fromString(fqn), tree.getSourceFile());
super.visit(that);
}
});
}
}
private Declaration convertToDeclaration(ClassSymbol classSymbol) {
String className = classSymbol.className();
if(declarationsByName.containsKey(className)){
return declarationsByName.get(className);
}
Declaration decl = makeDeclaration(classSymbol);
declarationsByName.put(className, decl);
decl.setShared((classSymbol.flags() & Flags.PUBLIC) != 0);
// find its module
String pkgName = classSymbol.packge().getQualifiedName().toString();
Module module = findOrCreateModule(pkgName);
Package pkg = findOrCreatePackage(module, pkgName);
// and add it there
pkg.getMembers().add(decl);
decl.setContainer(pkg);
return decl;
}
private Declaration makeDeclaration(ClassSymbol classSymbol) {
String name = classSymbol.getSimpleName().toString();
Declaration decl;
if(name.lastIndexOf('$') == 0){
decl = makeToplevelAttribute(classSymbol);
decl.setName(name.substring(1));
}else{
decl = makeLazyClassOrInterface(classSymbol);
decl.setName(name);
}
return decl;
}
private Declaration makeToplevelAttribute(ClassSymbol classSymbol) {
Value value = new LazyValue(classSymbol, this);
value.setVariable(true);
return value;
}
private ClassOrInterface makeLazyClassOrInterface(ClassSymbol classSymbol) {
if(!classSymbol.isInterface()){
Class klass = new LazyClass(classSymbol, this);
klass.setAbstract((classSymbol.flags() & Flags.ABSTRACT) != 0);
return klass;
}else{
return new LazyInterface(classSymbol, this);
}
}
private Declaration convertToDeclaration(Type type, Scope scope) {
String typeName;
switch(type.getKind()){
case VOID: typeName = "java.lang.Void"; break;
case BOOLEAN: typeName = "java.lang.Boolean"; break;
case BYTE: typeName = "java.lang.Byte"; break;
case CHAR: typeName = "java.lang.Character"; break;
case SHORT: typeName = "java.lang.Short"; break;
case INT: typeName = "java.lang.Integer"; break;
case LONG: typeName = "java.lang.Long"; break;
case FLOAT: typeName = "java.lang.Float"; break;
case DOUBLE: typeName = "java.lang.Double"; break;
case ARRAY:
Type componentType = ((Type.ArrayType)type).getComponentType();
//throw new RuntimeException("Array type not implemented");
//UnionType[Empty|Sequence<Natural>] casetypes
// producedtypes.typearguments: typeparam[element]->type[natural]
TypeDeclaration emptyDecl = (TypeDeclaration)convertToDeclaration("ceylon.language.Empty");
TypeDeclaration sequenceDecl = (TypeDeclaration)convertToDeclaration("ceylon.language.Sequence");
UnionType unionType = new UnionType();
List<ProducedType> caseTypes = new ArrayList<ProducedType>(2);
caseTypes.add(emptyDecl.getType());
List<ProducedType> typeArguments = new ArrayList<ProducedType>(1);
typeArguments.add(getType(componentType, scope));
caseTypes.add(sequenceDecl.getProducedType(null, typeArguments));
unionType.setCaseTypes(caseTypes);
return unionType;
case DECLARED:
typeName = type.tsym.getQualifiedName().toString();
break;
case TYPEVAR:
return safeLookupTypeParameter(scope, type.tsym.getQualifiedName().toString());
case WILDCARD:
// FIXME: wtf?
typeName = "ceylon.language.Nothing";
break;
default:
throw new RuntimeException("Failed to handle type "+type);
}
return convertToDeclaration(typeName);
}
private Declaration convertToDeclaration(String typeName) {
ClassSymbol classSymbol = lookupClassSymbol(typeName);
if(classSymbol == null)
throw new RuntimeException("Failed to resolve "+typeName);
return convertToDeclaration(classSymbol);
}
private TypeParameter safeLookupTypeParameter(Scope scope, String name) {
TypeParameter param = lookupTypeParameter(scope, name);
if(param == null)
throw new RuntimeException("Type param "+name+" not found in "+scope);
return param;
}
private TypeParameter lookupTypeParameter(Scope scope, String name) {
if(scope instanceof Method){
for(TypeParameter param : ((Method) scope).getTypeParameters()){
if(param.getName().equals(name))
return param;
}
// look it up in its class
return lookupTypeParameter(scope.getContainer(), name);
}else if(scope instanceof ClassOrInterface){
for(TypeParameter param : ((ClassOrInterface) scope).getTypeParameters()){
if(param.getName().equals(name))
return param;
}
// not found
return null;
}else
throw new RuntimeException("Type param "+name+" lookup not supported for scope "+scope);
}
private ClassSymbol lookupClassSymbol(String name) {
ClassSymbol classSymbol;
String outerName = name;
/*
* This madness here tries to look for a class, and if it fails, tries to resolve it
* from its parent class. This is required because a.b.C.D (where D is an inner class
* of C) is not found in symtab.classes but in C's ClassSymbol.enclosedElements.
*/
do{
classSymbol = symtab.classes.get(names.fromString(outerName));
if(classSymbol != null){
if(outerName.length() == name.length())
return classSymbol;
else
return lookupInnerClass(classSymbol, name.substring(outerName.length()+1).split("\\."));
}
int lastDot = outerName.lastIndexOf(".");
if(lastDot == -1 || lastDot == 0)
return null;
outerName = outerName.substring(0, lastDot);
}while(classSymbol == null);
return null;
}
private ClassSymbol lookupInnerClass(ClassSymbol classSymbol, String[] parts) {
PART:
for(String part : parts){
for(Symbol s : classSymbol.getEnclosedElements()){
if(s instanceof ClassSymbol
&& s.getSimpleName().toString().equals(part)){
classSymbol = (ClassSymbol) s;
continue PART;
}
}
// didn't find the inner class
return null;
}
return classSymbol;
}
public Package findOrCreatePackage(Module module, final String pkgName) {
for(Package pkg : module.getPackages()){
if(pkg.getNameAsString().equals(pkgName))
return pkg;
}
Package pkg = new Package(){
@Override
public Declaration getDirectMember(String name) {
// FIXME: some refactoring needed
String className = pkgName.isEmpty() ? name : pkgName + "." + name;
// we need its package ready first
PackageSymbol javaPkg = reader.enterPackage(names.fromString(pkgName));
javaPkg.complete();
ClassSymbol classSymbol = lookupClassSymbol(className);
// only get it from the classpath if we're not compiling it
if(classSymbol != null && classSymbol.classfile.getKind() != Kind.SOURCE)
return convertToDeclaration(className);
return super.getDirectMember(name);
}
@Override
public Declaration getDirectMemberOrParameter(String name) {
// FIXME: what's the difference?
return getDirectMember(name);
}
};
pkg.setModule(module);
// FIXME: some refactoring needed
pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\.")));
module.getPackages().add(pkg);
return pkg;
}
public Module findOrCreateModule(String pkgName) {
java.util.List<String> moduleName;
// FIXME: this is a rather simplistic view of the world
if(pkgName == null)
moduleName = Arrays.asList("<default module>");
else if(pkgName.startsWith("java."))
moduleName = Arrays.asList("java");
else if(pkgName.startsWith("sun."))
moduleName = Arrays.asList("sun");
else
moduleName = Arrays.asList(pkgName.split("\\."));
Module module = phasedUnits.getModuleBuilder().getOrCreateModule(moduleName);
// make sure that when we load the ceylon language module we set it to where
// the typechecker will look for it
if(pkgName != null
&& pkgName.startsWith("ceylon.language.")
&& ceylonContext.getModules().getLanguageModule() == null){
ceylonContext.getModules().setLanguageModule(module);
}
// FIXME: this can't be that easy.
module.setAvailable(true);
return module;
}
private ProducedType getType(Type type, Scope scope) {
TypeDeclaration declaration = (TypeDeclaration) convertToDeclaration(type, scope);
com.sun.tools.javac.util.List<Type> javacTypeArguments = type.getTypeArguments();
if(!javacTypeArguments.isEmpty()){
List<ProducedType> typeArguments = new ArrayList<ProducedType>(javacTypeArguments.size());
for(Type typeArgument : javacTypeArguments){
typeArguments.add((ProducedType) getType(typeArgument, scope));
}
return declaration.getProducedType(null, typeArguments);
}
return declaration.getType();
}
//
// ModelCompleter
@Override
public void complete(LazyInterface iface) {
complete(iface, iface.classSymbol);
}
@Override
public void complete(LazyClass klass) {
complete(klass, klass.classSymbol);
}
private void complete(ClassOrInterface klass, ClassSymbol classSymbol) {
// FIXME: deal with toplevel methods and attributes
// do its type parameters first
setTypeParameters(klass, classSymbol);
int constructorCount = 0;
// then its methods
for(Symbol member : classSymbol.members().getElements()){
// FIXME: deal with multiple constructors
// FIXME: could be an attribute
if(member instanceof MethodSymbol){
MethodSymbol methodSymbol = (MethodSymbol) member;
if(methodSymbol.isStatic()
/* FIXME: Temporary: if it's not public drop it. */
|| (methodSymbol.flags() & Flags.PUBLIC) == 0)
continue;
if(methodSymbol.isConstructor()){
constructorCount++;
// ignore the non-first ones
if(constructorCount > 1){
// only warn once
if(constructorCount == 2)
log.rawWarning(0, "Has multiple constructors: "+classSymbol.getQualifiedName());
continue;
}
setParameters((Class)klass, methodSymbol);
continue;
}
// normal method
Method method = new Method();
method.setShared((methodSymbol.flags() & Flags.PUBLIC) != 0);
method.setContainer(klass);
method.setName(methodSymbol.name.toString());
klass.getMembers().add(method);
// type params first
setTypeParameters(method, methodSymbol);
// now its parameters
setParameters(method, methodSymbol);
// FIXME: deal with type override by annotations
method.setType(getType(methodSymbol.getReturnType(), method));
}
}
if(klass instanceof Class && constructorCount == 0){
// must be a default constructor
((Class)klass).setParameterList(new ParameterList());
}
// FIXME: deal with type override by annotations
// look at its super type
Type superClass = classSymbol.getSuperclass();
// ceylon.language.Void has no super type. java.lang.Object neither
- if(!classSymbol.getQualifiedName().toString().equals("language.ceylon.Void")
+ if(!classSymbol.getQualifiedName().toString().equals("ceylon.language.Void")
&& superClass.getKind() != TypeKind.NONE)
klass.setExtendedType(getType(superClass, klass));
// interfaces need to have their superclass set to Object
else if(superClass.getKind() == TypeKind.NONE
&& klass instanceof Interface){
klass.setExtendedType(getType("ceylon.language.Object", klass));
}
setSatisfiedTypes(klass, classSymbol);
}
private void setParameters(Functional klass, MethodSymbol methodSymbol) {
ParameterList parameters = new ParameterList();
klass.addParameterList(parameters);
for(VarSymbol paramSymbol : methodSymbol.params()){
ValueParameter parameter = new ValueParameter();
parameter.setContainer((Scope) klass);
// FIXME: deal with type override by annotations
parameter.setType(getType(paramSymbol.type, (Scope) klass));
parameters.getParameters().add(parameter);
}
}
@Override
public void complete(LazyValue value) {
Type type = null;
for(Symbol member : value.classSymbol.members().getElements()){
if(member instanceof MethodSymbol){
MethodSymbol method = (MethodSymbol) member;
if(method.name.toString().equals(Util.getGetterName(value.getName()))
&& method.isStatic()
&& method.params().size() == 0){
type = method.getReturnType();
break;
}
}
}
if(type == null)
throw new RuntimeException("Failed to find type for toplevel attribute "+value.getName());
value.setType(getType(type, null));
}
//
// Utils for loading type info from the model
private Compound getAnnotation(Symbol classSymbol, String name) {
com.sun.tools.javac.util.List<Compound> annotations = classSymbol.getAnnotationMirrors();
for(Compound annotation : annotations){
if(annotation.type.tsym.getQualifiedName().toString().equals(name))
return annotation;
}
return null;
}
private Array getTypeInfoFromAnnotations(Symbol symbol, String name) {
Compound annotation = getAnnotation(symbol, name);
if(annotation != null)
return (Array)annotation.member(names.fromString("value"));
return null;
}
//
// Satisfied Types
private Array getSatisfiedTypesFromAnnotations(Symbol symbol) {
return getTypeInfoFromAnnotations(symbol, "com.redhat.ceylon.compiler.metadata.java.SatisfiedTypes");
}
private void setSatisfiedTypes(ClassOrInterface klass, ClassSymbol classSymbol) {
Array satisfiedTypes = getSatisfiedTypesFromAnnotations(classSymbol);
if(satisfiedTypes != null){
klass.getSatisfiedTypes().addAll(getSatisfiedTypes(satisfiedTypes, klass));
}else{
for(Type iface : classSymbol.getInterfaces()){
klass.getSatisfiedTypes().add(getType(iface, klass));
}
}
}
private Collection<? extends ProducedType> getSatisfiedTypes(Array satisfiedTypes, Scope scope) {
List<ProducedType> producedTypes = new LinkedList<ProducedType>();
for(Attribute type : satisfiedTypes.values){
producedTypes.add(decodeType((String) type.getValue(), scope));
}
return producedTypes;
}
//
// Type parameters loading
private Array getTypeParametersFromAnnotations(Symbol symbol) {
return getTypeInfoFromAnnotations(symbol, "com.redhat.ceylon.compiler.metadata.java.TypeParameters");
}
// from our annotation
private void setTypeParameters(Scope scope, List<TypeParameter> params, Array typeParameters) {
for(Attribute attribute : typeParameters.values){
Compound typeParam = (Compound) attribute;
TypeParameter param = new TypeParameter();
param.setContainer(scope);
param.setName((String)typeParam.member(names.fromString("value")).getValue());
params.add(param);
Attribute varianceAttribute = typeParam.member(names.fromString("variance"));
if(varianceAttribute != null){
VarSymbol variance = (VarSymbol) varianceAttribute.getValue();
String varianceName = variance.name.toString();
if(varianceName.equals("IN")){
param.setContravariant(true);
}else if(varianceName.equals("OUT"))
param.setCovariant(true);
}
// FIXME: I'm pretty sure we can have bounds that refer to method
// params, so we need to do this in two phases
Attribute satisfiesAttribute = typeParam.member(names.fromString("satisfies"));
if(satisfiesAttribute != null){
String satisfies = (String) satisfiesAttribute.getValue();
if(!satisfies.isEmpty()){
ProducedType satisfiesType = decodeType(satisfies, scope);
param.getSatisfiedTypes().add(satisfiesType);
}
}
}
}
// from java type info
private void setTypeParameters(Scope scope, List<TypeParameter> params, com.sun.tools.javac.util.List<TypeSymbol> typeParameters) {
for(TypeSymbol typeParam : typeParameters){
TypeParameter param = new TypeParameter();
param.setContainer(scope);
param.setName(typeParam.name.toString());
params.add(param);
// FIXME: I'm pretty sure we can have bounds that refer to method
// params, so we need to do this in two phases
if(!typeParam.getBounds().isEmpty()){
for(Type bound : typeParam.getBounds())
param.getSatisfiedTypes().add(getType(bound, scope));
}
}
}
// method
private void setTypeParameters(Method method, MethodSymbol methodSymbol) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
method.setTypeParameters(params);
Array typeParameters = getTypeParametersFromAnnotations(methodSymbol);
if(typeParameters != null)
setTypeParameters(method, params, typeParameters);
else
setTypeParameters(method, params, methodSymbol.getTypeParameters());
}
// class
private void setTypeParameters(ClassOrInterface klass, ClassSymbol classSymbol) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
klass.setTypeParameters(params);
Array typeParameters = getTypeParametersFromAnnotations(classSymbol);
if(typeParameters != null)
setTypeParameters(klass, params, typeParameters);
else
setTypeParameters(klass, params, classSymbol.getTypeParameters());
}
//
// TypeParsing and ModelLoader
private ProducedType decodeType(String value, Scope scope) {
return typeParser .decodeType(value, scope, this);
}
@Override
public ProducedType getType(String name, Scope scope) {
if(scope != null){
TypeParameter typeParameter = lookupTypeParameter(scope, name);
if(typeParameter != null)
return typeParameter.getType();
}
return ((TypeDeclaration)convertToDeclaration(name)).getType();
}
}
| true | true | private void complete(ClassOrInterface klass, ClassSymbol classSymbol) {
// FIXME: deal with toplevel methods and attributes
// do its type parameters first
setTypeParameters(klass, classSymbol);
int constructorCount = 0;
// then its methods
for(Symbol member : classSymbol.members().getElements()){
// FIXME: deal with multiple constructors
// FIXME: could be an attribute
if(member instanceof MethodSymbol){
MethodSymbol methodSymbol = (MethodSymbol) member;
if(methodSymbol.isStatic()
/* FIXME: Temporary: if it's not public drop it. */
|| (methodSymbol.flags() & Flags.PUBLIC) == 0)
continue;
if(methodSymbol.isConstructor()){
constructorCount++;
// ignore the non-first ones
if(constructorCount > 1){
// only warn once
if(constructorCount == 2)
log.rawWarning(0, "Has multiple constructors: "+classSymbol.getQualifiedName());
continue;
}
setParameters((Class)klass, methodSymbol);
continue;
}
// normal method
Method method = new Method();
method.setShared((methodSymbol.flags() & Flags.PUBLIC) != 0);
method.setContainer(klass);
method.setName(methodSymbol.name.toString());
klass.getMembers().add(method);
// type params first
setTypeParameters(method, methodSymbol);
// now its parameters
setParameters(method, methodSymbol);
// FIXME: deal with type override by annotations
method.setType(getType(methodSymbol.getReturnType(), method));
}
}
if(klass instanceof Class && constructorCount == 0){
// must be a default constructor
((Class)klass).setParameterList(new ParameterList());
}
// FIXME: deal with type override by annotations
// look at its super type
Type superClass = classSymbol.getSuperclass();
// ceylon.language.Void has no super type. java.lang.Object neither
if(!classSymbol.getQualifiedName().toString().equals("language.ceylon.Void")
&& superClass.getKind() != TypeKind.NONE)
klass.setExtendedType(getType(superClass, klass));
// interfaces need to have their superclass set to Object
else if(superClass.getKind() == TypeKind.NONE
&& klass instanceof Interface){
klass.setExtendedType(getType("ceylon.language.Object", klass));
}
setSatisfiedTypes(klass, classSymbol);
}
| private void complete(ClassOrInterface klass, ClassSymbol classSymbol) {
// FIXME: deal with toplevel methods and attributes
// do its type parameters first
setTypeParameters(klass, classSymbol);
int constructorCount = 0;
// then its methods
for(Symbol member : classSymbol.members().getElements()){
// FIXME: deal with multiple constructors
// FIXME: could be an attribute
if(member instanceof MethodSymbol){
MethodSymbol methodSymbol = (MethodSymbol) member;
if(methodSymbol.isStatic()
/* FIXME: Temporary: if it's not public drop it. */
|| (methodSymbol.flags() & Flags.PUBLIC) == 0)
continue;
if(methodSymbol.isConstructor()){
constructorCount++;
// ignore the non-first ones
if(constructorCount > 1){
// only warn once
if(constructorCount == 2)
log.rawWarning(0, "Has multiple constructors: "+classSymbol.getQualifiedName());
continue;
}
setParameters((Class)klass, methodSymbol);
continue;
}
// normal method
Method method = new Method();
method.setShared((methodSymbol.flags() & Flags.PUBLIC) != 0);
method.setContainer(klass);
method.setName(methodSymbol.name.toString());
klass.getMembers().add(method);
// type params first
setTypeParameters(method, methodSymbol);
// now its parameters
setParameters(method, methodSymbol);
// FIXME: deal with type override by annotations
method.setType(getType(methodSymbol.getReturnType(), method));
}
}
if(klass instanceof Class && constructorCount == 0){
// must be a default constructor
((Class)klass).setParameterList(new ParameterList());
}
// FIXME: deal with type override by annotations
// look at its super type
Type superClass = classSymbol.getSuperclass();
// ceylon.language.Void has no super type. java.lang.Object neither
if(!classSymbol.getQualifiedName().toString().equals("ceylon.language.Void")
&& superClass.getKind() != TypeKind.NONE)
klass.setExtendedType(getType(superClass, klass));
// interfaces need to have their superclass set to Object
else if(superClass.getKind() == TypeKind.NONE
&& klass instanceof Interface){
klass.setExtendedType(getType("ceylon.language.Object", klass));
}
setSatisfiedTypes(klass, classSymbol);
}
|
diff --git a/src/test/java/org/atlasapi/properties/PropertiesTest.java b/src/test/java/org/atlasapi/properties/PropertiesTest.java
index 6a577533f..6f85d6f22 100644
--- a/src/test/java/org/atlasapi/properties/PropertiesTest.java
+++ b/src/test/java/org/atlasapi/properties/PropertiesTest.java
@@ -1,12 +1,12 @@
package org.atlasapi.properties;
import junit.framework.TestCase;
import com.metabroadcast.common.properties.Configurer;
public class PropertiesTest extends TestCase {
public void testShouldTakeProdProperties() throws Exception {
Configurer.load("prod");
- assertEquals("10.228.167.143", Configurer.get("mongo.host").get());
+ assertEquals("10.235.57.61", Configurer.get("mongo.host").get());
}
}
| true | true | public void testShouldTakeProdProperties() throws Exception {
Configurer.load("prod");
assertEquals("10.228.167.143", Configurer.get("mongo.host").get());
}
| public void testShouldTakeProdProperties() throws Exception {
Configurer.load("prod");
assertEquals("10.235.57.61", Configurer.get("mongo.host").get());
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java
index 90d39cd9..6af40832 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java
@@ -1,374 +1,374 @@
package org.ngrinder.agent.service;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.infra.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.ngrinder.common.util.CollectionUtils.buildMap;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
import static org.ngrinder.common.util.CompressionUtils.*;
import static org.ngrinder.common.util.ExceptionUtils.processException;
/**
* Agent package service.
*
* @author Matt
* @since 3.3
*/
@Service
public class AgentPackageService {
protected static final Logger LOGGER = LoggerFactory.getLogger(AgentPackageService.class);
public static final int EXEC = 0x81ed;
@Autowired
private Config config;
/**
* Get package name
*
* @param moduleName nGrinder module name.
* @return String module full name.
*/
public String getPackageName(String moduleName) {
return moduleName + "-" + config.getVersion();
}
/**
* Get distributable package name with appropriate extension.
*
* @param moduleName nGrinder sub module name.
* @param connectionIP where it will connect to
* @param region region
* @param ownerName owner name
* @param forWindow if true, then package type is zip,if false, package type is tar.
* @return String module full name.
*/
public String getDistributionPackageName(String moduleName, String connectionIP, String region, String ownerName,
boolean forWindow) {
return getPackageName(moduleName) + getFilenameComponent(connectionIP) + getFilenameComponent(region) +
getFilenameComponent(ownerName) + (forWindow ? ".zip" : ".tar");
}
private String getFilenameComponent(String value) {
value = StringUtils.trimToEmpty(value);
if (StringUtils.isNotEmpty(value)) {
value = "-" + value;
}
return value;
}
/**
* Get the agent package containing folder.
*
* @return File agent package dir.
*/
public File getPackagesDir() {
return config.isClustered() ? config.getExHome().getSubFile("download") : config.getHome().getSubFile("download");
}
/**
* Create agent package.
*
* @return File agent package.
*/
public synchronized File createAgentPackage() {
return createAgentPackage(null, null, null);
}
/**
* Create agent package.
*
* @param connectionIP host ip.
* @param region region
* @param owner owner
* @return File agent package.
*/
public synchronized File createAgentPackage(String connectionIP, String region,
String owner) {
return createAgentPackage((URLClassLoader) getClass().getClassLoader(), connectionIP, region, owner);
}
- public File createMonitorPackage() {
+ public synchronized File createMonitorPackage() {
File monitorPackagesDir = getPackagesDir();
if (monitorPackagesDir.mkdirs()) {
LOGGER.info("{} is created", monitorPackagesDir.getPath());
}
final String packageName = getDistributionPackageName("ngrinder-monitor", "", "", "", false);
File monitorPackage = new File(monitorPackagesDir, packageName);
if (monitorPackage.exists()) {
return monitorPackage;
}
FileUtils.deleteQuietly(monitorPackage);
final String basePath = "ngrinder-monitor/";
final String libPath = basePath + "lib/";
TarArchiveOutputStream tarOutputStream = null;
try {
tarOutputStream = createTarArchiveStream(monitorPackage);
addFolderToTar(tarOutputStream, basePath);
addFolderToTar(tarOutputStream, libPath);
final URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader();
Set<String> libs = getDependentLibs(classLoader);
for (URL eachUrl : classLoader.getURLs()) {
File eachClassPath = new File(eachUrl.getFile());
if (!isJar(eachClassPath)) {
continue;
}
if (isAgentDependentLib(eachClassPath, "ngrinder-sh")) {
processJarEntries(eachClassPath, new TarArchivingZipEntryProcessor(tarOutputStream, new FilePredicate() {
@Override
public boolean evaluate(Object object) {
ZipEntry zipEntry = (ZipEntry) object;
final String name = zipEntry.getName();
return name.contains("monitor") && (zipEntry.getName().endsWith("sh") ||
zipEntry.getName().endsWith("bat"));
}
}, basePath, EXEC));
} else if (isAgentDependentLib(eachClassPath, libs)) {
addFileToTar(tarOutputStream, eachClassPath, libPath + eachClassPath.getName());
}
}
addMonitorConfToTar(tarOutputStream, basePath, config.getControllerProperties().getPropertyInt
(ControllerConstants.PROP_CONTROLLER_MONITOR_PORT));
} catch (IOException e) {
LOGGER.error("Error while generating an monitor package" + e.getMessage());
} finally {
IOUtils.closeQuietly(tarOutputStream);
}
return monitorPackage;
}
/**
* Create agent package
*
* @param classLoader URLClass Loader.
* @param connectionIP host ip.
* @param region region
* @param owner owner
* @return File
*/
synchronized File createAgentPackage(URLClassLoader classLoader, String connectionIP, String region,
String owner) {
File agentPackagesDir = getPackagesDir();
if (agentPackagesDir.mkdirs()) {
LOGGER.info("{} is created", agentPackagesDir.getPath());
}
final String packageName = getDistributionPackageName("ngrinder-core", connectionIP, region, owner, false);
File agentTar = new File(agentPackagesDir, packageName);
if (agentTar.exists()) {
return agentTar;
}
FileUtils.deleteQuietly(agentTar);
final String basePath = "ngrinder-agent/";
final String libPath = basePath + "lib/";
TarArchiveOutputStream tarOutputStream = null;
try {
tarOutputStream = createTarArchiveStream(agentTar);
addFolderToTar(tarOutputStream, basePath);
addFolderToTar(tarOutputStream, libPath);
Set<String> libs = getDependentLibs(classLoader);
for (URL eachUrl : classLoader.getURLs()) {
File eachClassPath = new File(eachUrl.getFile());
if (!isJar(eachClassPath)) {
continue;
}
if (isAgentDependentLib(eachClassPath, "ngrinder-sh")) {
processJarEntries(eachClassPath, new TarArchivingZipEntryProcessor(tarOutputStream, new FilePredicate() {
@Override
public boolean evaluate(Object object) {
ZipEntry zipEntry = (ZipEntry) object;
final String name = zipEntry.getName();
return name.contains("agent") && (zipEntry.getName().endsWith("sh") ||
zipEntry.getName().endsWith("bat"));
}
}, basePath, EXEC));
} else if (isAgentDependentLib(eachClassPath, libs)) {
addFileToTar(tarOutputStream, eachClassPath, libPath + eachClassPath.getName());
}
}
addAgentConfToTar(tarOutputStream, basePath, connectionIP, region, owner);
} catch (IOException e) {
LOGGER.error("Error while generating an agent package" + e.getMessage());
} finally {
IOUtils.closeQuietly(tarOutputStream);
}
return agentTar;
}
private TarArchiveOutputStream createTarArchiveStream(File agentTar) throws IOException {
FileOutputStream fos = new FileOutputStream(agentTar);
return new TarArchiveOutputStream(new BufferedOutputStream(fos));
}
private void addMonitorConfToTar(TarArchiveOutputStream tarOutputStream, String basePath,
Integer monitorPort) throws IOException {
final String config = getAgentConfigContent("agent_monitor.conf", buildMap("monitorPort",
(Object) String.valueOf(monitorPort)));
final byte[] bytes = config.getBytes();
addInputStreamToTar(tarOutputStream, new ByteArrayInputStream(bytes), basePath + "__agent.conf",
bytes.length, TarArchiveEntry.DEFAULT_FILE_MODE);
}
private void addAgentConfToTar(TarArchiveOutputStream tarOutputStream, String basePath, String connectingIP,
String region, String owner) throws IOException {
if (StringUtils.isNotEmpty(connectingIP)) {
final String config = getAgentConfigContent("agent_agent.conf", getAgentConfigParam(connectingIP, region,
owner));
final byte[] bytes = config.getBytes();
addInputStreamToTar(tarOutputStream, new ByteArrayInputStream(bytes), basePath + "__agent.conf",
bytes.length, TarArchiveEntry.DEFAULT_FILE_MODE);
}
}
private Set<String> getDependentLibs(URLClassLoader cl) throws IOException {
Set<String> libs = new HashSet<String>();
InputStream dependencyStream = null;
try {
dependencyStream = cl.getResourceAsStream("dependencies.txt");
final String dependencies = IOUtils.toString(dependencyStream);
for (String each : StringUtils.split(dependencies, ";")) {
libs.add(each.trim().replace(".jar", "").replace("-SNAPSHOT", ""));
}
libs.add(getPackageName("ngrinder-core").replace("-SNAPSHOT", ""));
} catch (Exception e) {
IOUtils.closeQuietly(dependencyStream);
LOGGER.error("Error while loading dependencies.txt", e);
}
return libs;
}
private Map<String, Object> getAgentConfigParam(String forServer, String region, String owner) {
Map<String, Object> confMap = newHashMap();
confMap.put("controllerIP", forServer);
final int port = config.getControllerProperties().getPropertyInt(ControllerConstants.PROP_CONTROLLER_CONTROLLER_PORT);
confMap.put("controllerPort", String.valueOf(port));
if (StringUtils.isEmpty(region)) {
region = "NONE";
}
if (StringUtils.isNotBlank(owner)) {
region = region + "_owned_" + owner;
}
confMap.put("controllerRegion", region);
return confMap;
}
/**
* Check if this given path is jar.
*
* @param libFile lib file
* @return true if it's jar
*/
public boolean isJar(File libFile) {
return StringUtils.endsWith(libFile.getName(), ".jar");
}
/**
* Check if this given lib file is the given library.
*
* @param libFile lib file
* @param libName desirable name
* @return true if dependent lib
*/
public boolean isAgentDependentLib(File libFile, String libName) {
return StringUtils.startsWith(libFile.getName(), libName);
}
/**
* Check if this given lib file in the given lib set.
*
* @param libFile lib file
* @param libs lib set
* @return true if dependent lib
*/
public boolean isAgentDependentLib(File libFile, Set<String> libs) {
String name = libFile.getName();
name = name.replace(".jar", "").replace("-SNAPSHOT", "");
return libs.contains(name);
}
/**
* Get the agent.config content replacing the variables with the given values.
*
* @param templateName template name.
* @param values map of configurations.
* @return generated string
*/
public String getAgentConfigContent(String templateName, Map<String, Object> values) {
StringWriter writer = null;
try {
Configuration config = new Configuration();
ClassPathResource cpr = new ClassPathResource("ngrinder_agent_home_template");
config.setDirectoryForTemplateLoading(cpr.getFile());
config.setObjectWrapper(new DefaultObjectWrapper());
Template template = config.getTemplate(templateName);
writer = new StringWriter();
template.process(values, writer);
return writer.toString();
} catch (Exception e) {
throw processException("Error while fetching the script template.", e);
} finally {
IOUtils.closeQuietly(writer);
}
}
static class TarArchivingZipEntryProcessor implements ZipEntryProcessor {
private TarArchiveOutputStream tao;
private FilePredicate filePredicate;
private String basePath;
private int mode;
TarArchivingZipEntryProcessor(TarArchiveOutputStream tao, FilePredicate filePredicate, String basePath, int mode) {
this.tao = tao;
this.filePredicate = filePredicate;
this.basePath = basePath;
this.mode = mode;
}
@Override
public void process(ZipFile file, ZipEntry entry) throws IOException {
InputStream inputStream = null;
try {
inputStream = file.getInputStream(entry);
if (filePredicate.evaluate(entry)) {
addInputStreamToTar(this.tao, inputStream, basePath + FilenameUtils.getName(entry.getName()),
entry.getSize(),
this.mode);
}
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
}
| true | true | public File createMonitorPackage() {
File monitorPackagesDir = getPackagesDir();
if (monitorPackagesDir.mkdirs()) {
LOGGER.info("{} is created", monitorPackagesDir.getPath());
}
final String packageName = getDistributionPackageName("ngrinder-monitor", "", "", "", false);
File monitorPackage = new File(monitorPackagesDir, packageName);
if (monitorPackage.exists()) {
return monitorPackage;
}
FileUtils.deleteQuietly(monitorPackage);
final String basePath = "ngrinder-monitor/";
final String libPath = basePath + "lib/";
TarArchiveOutputStream tarOutputStream = null;
try {
tarOutputStream = createTarArchiveStream(monitorPackage);
addFolderToTar(tarOutputStream, basePath);
addFolderToTar(tarOutputStream, libPath);
final URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader();
Set<String> libs = getDependentLibs(classLoader);
for (URL eachUrl : classLoader.getURLs()) {
File eachClassPath = new File(eachUrl.getFile());
if (!isJar(eachClassPath)) {
continue;
}
if (isAgentDependentLib(eachClassPath, "ngrinder-sh")) {
processJarEntries(eachClassPath, new TarArchivingZipEntryProcessor(tarOutputStream, new FilePredicate() {
@Override
public boolean evaluate(Object object) {
ZipEntry zipEntry = (ZipEntry) object;
final String name = zipEntry.getName();
return name.contains("monitor") && (zipEntry.getName().endsWith("sh") ||
zipEntry.getName().endsWith("bat"));
}
}, basePath, EXEC));
} else if (isAgentDependentLib(eachClassPath, libs)) {
addFileToTar(tarOutputStream, eachClassPath, libPath + eachClassPath.getName());
}
}
addMonitorConfToTar(tarOutputStream, basePath, config.getControllerProperties().getPropertyInt
(ControllerConstants.PROP_CONTROLLER_MONITOR_PORT));
} catch (IOException e) {
LOGGER.error("Error while generating an monitor package" + e.getMessage());
} finally {
IOUtils.closeQuietly(tarOutputStream);
}
return monitorPackage;
}
| public synchronized File createMonitorPackage() {
File monitorPackagesDir = getPackagesDir();
if (monitorPackagesDir.mkdirs()) {
LOGGER.info("{} is created", monitorPackagesDir.getPath());
}
final String packageName = getDistributionPackageName("ngrinder-monitor", "", "", "", false);
File monitorPackage = new File(monitorPackagesDir, packageName);
if (monitorPackage.exists()) {
return monitorPackage;
}
FileUtils.deleteQuietly(monitorPackage);
final String basePath = "ngrinder-monitor/";
final String libPath = basePath + "lib/";
TarArchiveOutputStream tarOutputStream = null;
try {
tarOutputStream = createTarArchiveStream(monitorPackage);
addFolderToTar(tarOutputStream, basePath);
addFolderToTar(tarOutputStream, libPath);
final URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader();
Set<String> libs = getDependentLibs(classLoader);
for (URL eachUrl : classLoader.getURLs()) {
File eachClassPath = new File(eachUrl.getFile());
if (!isJar(eachClassPath)) {
continue;
}
if (isAgentDependentLib(eachClassPath, "ngrinder-sh")) {
processJarEntries(eachClassPath, new TarArchivingZipEntryProcessor(tarOutputStream, new FilePredicate() {
@Override
public boolean evaluate(Object object) {
ZipEntry zipEntry = (ZipEntry) object;
final String name = zipEntry.getName();
return name.contains("monitor") && (zipEntry.getName().endsWith("sh") ||
zipEntry.getName().endsWith("bat"));
}
}, basePath, EXEC));
} else if (isAgentDependentLib(eachClassPath, libs)) {
addFileToTar(tarOutputStream, eachClassPath, libPath + eachClassPath.getName());
}
}
addMonitorConfToTar(tarOutputStream, basePath, config.getControllerProperties().getPropertyInt
(ControllerConstants.PROP_CONTROLLER_MONITOR_PORT));
} catch (IOException e) {
LOGGER.error("Error while generating an monitor package" + e.getMessage());
} finally {
IOUtils.closeQuietly(tarOutputStream);
}
return monitorPackage;
}
|
diff --git a/srcj/com/sun/electric/tool/logicaleffort/LENetlister.java b/srcj/com/sun/electric/tool/logicaleffort/LENetlister.java
index 6b49ad3d8..21d004fef 100644
--- a/srcj/com/sun/electric/tool/logicaleffort/LENetlister.java
+++ b/srcj/com/sun/electric/tool/logicaleffort/LENetlister.java
@@ -1,594 +1,595 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: LENetlister.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*
* Created on November 11, 2003, 3:56 PM
*/
package com.sun.electric.tool.logicaleffort;
import com.sun.electric.tool.logicaleffort.*;
import com.sun.electric.database.hierarchy.*;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.topology.*;
import com.sun.electric.database.prototype.*;
import com.sun.electric.database.variable.*;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.tool.Tool;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.user.ui.MessagesWindow;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.ErrorLogger;
import com.sun.electric.technology.PrimitiveNode;
import java.awt.geom.AffineTransform;
import java.awt.*;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.*;
/**
* Creates a logical effort netlist to be sized by LESizer.
* This is so the LESizer is independent of Electric's Database,
* and can match George Chen's C++ version being developed for
* PNP.
*
* @author gainsley
*/
public class LENetlister extends HierarchyEnumerator.Visitor {
// ALL GATES SAME DELAY
/** global step-up */ private float su;
/** wire to gate cap ratio */ private float wireRatio;
/** convergence criteron */ private float epsilon;
/** max number of iterations */ private int maxIterations;
/** gate cap, in fF/lambda */ private float gateCap;
/** ratio of diffusion to gate cap */ private float alpha;
/** ratio of keeper to driver size */ private float keeperRatio;
/** all networks */ private HashMap allNets;
/** all instances (LEGATES, not loads) */ private HashMap allInstances;
/** The algorithm to run */ private LESizer.Alg algorithm;
/** Sizer */ private LESizer sizer;
/** Job we are part of */ private Job job;
/** Where to direct output */ private PrintStream out;
/** Mapping between NodeInst and Instance */private HashMap instancesMap;
/** True if we got aborted */ private boolean aborted;
/** for logging errors */ private ErrorLogger errorLogger;
private static final boolean DEBUG = false;
/** Creates a new instance of LENetlister */
public LENetlister(LESizer.Alg algorithm, Job job) {
// get preferences for this package
Tool leTool = Tool.findTool("logical effort");
su = (float)LETool.getGlobalFanout();
epsilon = (float)LETool.getConvergenceEpsilon();
maxIterations = LETool.getMaxIterations();
gateCap = (float)LETool.getGateCapacitance();
wireRatio = (float)LETool.getWireRatio();
alpha = (float)LETool.getDiffAlpha();
keeperRatio = (float)LETool.getKeeperRatio();
allNets = new HashMap();
allInstances = new HashMap();
this.algorithm = algorithm;
this.job = job;
this.instancesMap = new HashMap();
this.out = new PrintStream((OutputStream)System.out);
errorLogger = null;
aborted = false;
}
// Entry point: This netlists the cell
protected void netlist(Cell cell, VarContext context) {
//ArrayList connectedPorts = new ArrayList();
//connectedPorts.add(Schematics.tech.resistorNode.getPortsList());
if (errorLogger != null) errorLogger.delete();
errorLogger = ErrorLogger.newInstance("LE Netlister");
Netlist netlist = cell.getNetlist(true);
// read schematic-specific sizing options
for (Iterator instIt = cell.getNodes(); instIt.hasNext();) {
NodeInst ni = (NodeInst)instIt.next();
if (ni.getVar("ATTR_LESETTINGS") != null) {
useLESettings(ni, context); // get settings from object
break;
}
}
HierarchyEnumerator.enumerateCell(cell, context, netlist, this);
}
/**
* Size the netlist.
* @return true on success, false otherwise.
*/
public boolean size() {
//lesizer.printDesign();
boolean verbose = false;
// create a new sizer
sizer = new LESizer(algorithm, this, job, errorLogger);
boolean success = sizer.optimizeLoops(epsilon, maxIterations, verbose, alpha, keeperRatio);
//out.println("---------After optimization:------------");
//lesizer.printDesign();
// get rid of the sizer
sizer = null;
return success;
}
/**
* Updates the size of all Logical Effort gates
*/
public void updateSizes() {
// iterator over all LEGATEs
Set allEntries = allInstances.entrySet();
for (Iterator it = allEntries.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Instance inst = (Instance)entry.getValue();
Nodable no = inst.getNodable();
NodeInst ni = no.getNodeInst();
if (ni != null) no = ni;
String varName = "LEDRIVE_" + inst.getName();
no.newVar(varName, new Float(inst.getLeX()));
if (inst.getLeX() < 1.0f) {
String msg = "WARNING: Instance "+ni.describe()+" has size "+TextUtils.formatDouble(inst.getLeX(), 3)+" less than 1 ("+inst.getName()+")";
System.out.println(msg);
if (ni != null) {
ErrorLogger.ErrorLog log = errorLogger.logError(msg, ni.getParent(), 2);
log.addGeom(ni, true, ni.getParent(), inst.getContext());
}
}
}
printStatistics();
done();
}
public void done() {
errorLogger.termLogging(true);
errorLogger = null;
}
/** NodeInst should be an LESettings instance */
private void useLESettings(NodeInst ni, VarContext context) {
Variable var;
if ((var = ni.getVar("ATTR_su")) != null) su = VarContext.objectToFloat(context.evalVar(var), su);
if ((var = ni.getVar("ATTR_wire_ratio")) != null) wireRatio = VarContext.objectToFloat(context.evalVar(var), wireRatio);
if ((var = ni.getVar("ATTR_epsilon")) != null) epsilon = VarContext.objectToFloat(context.evalVar(var), epsilon);
if ((var = ni.getVar("ATTR_max_iter")) != null) maxIterations = VarContext.objectToInt(context.evalVar(var), maxIterations);
if ((var = ni.getVar("ATTR_gate_cap")) != null) gateCap = VarContext.objectToFloat(context.evalVar(var), gateCap);
if ((var = ni.getVar("ATTR_alpha")) != null) alpha = VarContext.objectToFloat(context.evalVar(var), alpha);
if ((var = ni.getVar("ATTR_keeper_ratio")) != null) keeperRatio = VarContext.objectToFloat(context.evalVar(var), keeperRatio);
}
/**
* Add new instance to design
* @param name name of the instance
* param leGate true if this is an LEGate
* @param leX size
* @param pins list of pins on instance
*
* @return the new instance added, null if error
*/
protected Instance addInstance(String name, Instance.Type type, float leSU,
float leX, ArrayList pins, Nodable no)
{
if (allInstances.containsKey(name)) {
out.println("Error: Instance "+name+" already exists.");
return null;
}
// create instance
Instance instance = new Instance(name, type, leSU, leX, no);
// create each net if necessary, from pin.
Iterator iter = pins.iterator();
while (iter.hasNext()) {
Pin pin = (Pin)iter.next();
String netname = pin.getNetName();
// check to see if net had already been added to the design
Net net = (Net)allNets.get(netname);
if (net != null) {
pin.setNet(net);
pin.setInstance(instance);
net.addPin(pin);
} else {
// create new net
net = new Net(netname);
allNets.put(netname, net);
pin.setNet(net);
pin.setInstance(instance);
net.addPin(pin);
}
}
instance.setPins(pins);
allInstances.put(name, instance);
return instance;
}
//public HashMap getInstancesMap() { return instancesMap; }
protected HashMap getAllInstances() { return allInstances; }
protected HashMap getAllNets() { return allNets; }
/** return number of gates sized */
protected int getNumGates() { return allInstances.size(); }
protected LESizer getSizer() { return sizer; }
protected float getKeeperRatio() { return keeperRatio; }
// ======================= Hierarchy Enumerator ==============================
/**
* Override the default Cell info to pass along logical effort specific information
* @return a LECellInfo
*/
public HierarchyEnumerator.CellInfo newCellInfo() { return new LECellInfo(); }
/**
* Enter cell initializes the LECellInfo.
* @param info the LECellInfo
* @return true to process the cell, false to ignore.
*/
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
if (aborted) return false;
if (((LETool.AnalyzeCell)job).checkAbort(null)) {
aborted = true;
return false;
}
((LECellInfo)info).leInit();
return true;
}
/**
* Visit NodeInst creates a new Logical Effort instance from the
* parameters found on the Nodable, if that Nodable is an LEGATE.
* It also creates instances for wire models (LEWIREs).
* @param ni the Nodable being visited
* @param info the cell info
* @return true to push down into the Nodable, false to continue.
*/
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
float leX = (float)0.0;
boolean wire = false;
boolean primitiveTransistor = false;
// Check if this NodeInst is tagged as a logical effort node
Instance.Type type = null;
Variable var = null;
if ((var = getVar(ni, "ATTR_LEGATE")) != null) {
// assume it is LEGATE if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEGATE;
else
type = Instance.Type.STATICGATE;
}
else if ((var = getVar(ni, "ATTR_LEKEEPER")) != null) {
// assume it is LEKEEPER if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEKEEPER;
else
type = Instance.Type.STATICGATE;
}
else if (getVar(ni, "ATTR_LEWIRE") != null) {
type = Instance.Type.WIRE;
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = ni.getVar("ATTR_L");
float len = VarContext.objectToFloat(info.getContext().evalVar(var), 0.0f);
var = ni.getVar("ATTR_width");
float width = VarContext.objectToFloat(info.getContext().evalVar(var), 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
wire = true;
}
else if ((ni.getProto() != null) && (ni.getProto().getFunction().isTransistor())) {
// handle transistor loads
type = Instance.Type.STATICGATE;
var = ni.getVar("ATTR_width");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no width in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no width in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float width = VarContext.objectToFloat(info.getContext().evalVar(var), (float)3.0);
var = ni.getVar("ATTR_length");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no length in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float length = VarContext.objectToFloat(info.getContext().evalVar(var), (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
primitiveTransistor = true;
}
else if (ni.getVar("ATTR_LESETTINGS") != null)
return false;
if (type == null) return true; // descend into and process
if (DEBUG) System.out.println("------------------------------------");
// If got to this point, this is either an LEGATE or an LEWIRE
// Both require us to build an instance.
ArrayList pins = new ArrayList();
Netlist netlist = info.getNetlist();
for (Iterator ppIt = ni.getProto().getPorts(); ppIt.hasNext();) {
PortProto pp = (PortProto)ppIt.next();
var = pp.getVar("ATTR_le");
// Note default 'le' value should be one
float le = VarContext.objectToFloat(info.getContext().evalVar(var), (float)1.0);
String netName = info.getUniqueNetName(info.getNetID(netlist.getNetwork(ni,pp,0)), ".");
Pin.Dir dir = Pin.Dir.INPUT;
// if it's not an output, it doesn't really matter what it is.
if (pp.getCharacteristic() == PortProto.Characteristic.OUT) dir = Pin.Dir.OUTPUT;
if (primitiveTransistor) {
// primitive Electric Transistors have their source and drain set to BIDIR, we
// want them set to OUTPUT so that they count as diffusion capacitance
if (pp.getCharacteristic() == PortProto.Characteristic.BIDIR) dir = Pin.Dir.OUTPUT;
}
pins.add(new Pin(pp.getName(), dir, le, netName));
if (DEBUG) System.out.println(" Added "+dir+" pin "+pp.getName()+", le: "+le+", netName: "+netName+", JNetwork: "+netlist.getNetwork(ni,pp,0));
if (type == Instance.Type.WIRE) break; // this is LEWIRE, only add one pin of it
}
// see if passed-down step-up exists
float localsu = su;
if (((LECellInfo)info).getSU() != -1f)
localsu = ((LECellInfo)info).getSU();
// check for step-up on gate
var = ni.getVar("ATTR_su");
if (var != null) {
float nisu = VarContext.objectToFloat(info.getContext().evalVar(var), -1f);
if (nisu != -1f)
localsu = nisu;
}
// create new leGate instance
VarContext vc = info.getContext().push(ni); // to create unique flat name
Instance inst = addInstance(vc.getInstPath("."), type, localsu, leX, pins, ni);
+ inst.setContext(info.getContext());
// set instance parameters for sizeable gates
if (type == Instance.Type.LEGATE) {
var = ni.getVar("ATTR_LEPARALLGRP");
if (var != null) {
// set parallel group number
int g = VarContext.objectToInt(info.getContext().evalVar(var), 0);
inst.setParallelGroup(g);
}
}
// set mfactor
var = ni.getVar("ATTR_M");
if (var != null) {
// set mfactor
int m = VarContext.objectToInt(info.getContext().evalVar(var), 1);
inst.setMfactor(m * ((LECellInfo)info).getMFactor());
}
if (DEBUG) {
if (wire) System.out.println(" Added LEWire "+vc.getInstPath(".")+", X="+leX);
else System.out.println(" Added instance "+vc.getInstPath(".")+" of type "+type+", X="+leX);
}
instancesMap.put(ni, inst);
return false;
}
private Variable getVar(Nodable no, String name) {
Variable var = no.getVar(name);
if (var == null) var = no.getVarDefaultOwner().getVar(name);
return var;
}
/**
* Nothing to do for exitCell
*/
public void exitCell(HierarchyEnumerator.CellInfo info) {
}
/**
* Logical Effort Cell Info class. Keeps track of:
* <p>- M factors
*/
public class LECellInfo extends HierarchyEnumerator.CellInfo {
/** M-factor to be applied to size */ private float mFactor;
/** SU to be applied to gates in cell */ private float cellsu;
/** initialize LECellInfo: assumes CellInfo.init() has been called */
protected void leInit() {
HierarchyEnumerator.CellInfo parent = getParentInfo();
// check for M-Factor from parent
if (parent == null) mFactor = 1f;
else mFactor = ((LECellInfo)parent).getMFactor();
// check for su from parent
if (parent == null) cellsu = -1f;
else cellsu = ((LECellInfo)parent).getSU();
// get info from node we pushed into
Nodable ni = getContext().getNodable();
if (ni == null) return;
// get mfactor from instance we pushed into
Variable mvar = ni.getVar("ATTR_M");
if (mvar != null) {
Object mval = getContext().evalVar(mvar, null);
if (mval != null)
mFactor = mFactor * VarContext.objectToFloat(mval, 1f);
}
// get su from instance we pushed into
Variable suvar = ni.getVar("ATTR_su");
if (suvar != null) {
float su = VarContext.objectToFloat(getContext().evalVar(suvar, null), -1f);
if (su != -1f) cellsu = su;
}
}
/** get mFactor */
protected float getMFactor() { return mFactor; }
protected float getSU() { return cellsu; }
}
// =============================== Statistics ==================================
public void printStatistics() {
Collection instances = getAllInstances().values();
float totalsize = 0f;
float instsize = 0f;
int numLEGates = 0;
int numLEWires = 0;
for (Iterator it = instances.iterator(); it.hasNext();) {
Instance inst = (Instance)it.next();
totalsize += inst.getLeX();
if (inst.getType() == Instance.Type.LEGATE || inst.getType() == Instance.Type.LEKEEPER) {
numLEGates++;
instsize += inst.getLeX();
}
if (inst.getType() == Instance.Type.WIRE)
numLEWires++;
}
System.out.println("Number of LEGATEs: "+numLEGates);
System.out.println("Number of Wires: "+numLEWires);
System.out.println("Total size of all LEGATEs: "+instsize);
System.out.println("Total size of all instances (sized and loads): "+totalsize);
}
/**
* return total size of all instances of the specified type
* if type is null, uses all types
*/
public float getTotalSize(Instance.Type type) {
Collection instances = getAllInstances().values();
float totalsize = 0f;
for (Iterator it = instances.iterator(); it.hasNext();) {
Instance inst = (Instance)it.next();
if (type == null)
totalsize += inst.getLeX();
else if (inst.getType() == type)
totalsize += inst.getLeX();
}
return totalsize;
}
public boolean printResults(Nodable no) {
// if this is a NodeInst, convert to Nodable
if (no instanceof NodeInst) {
no = Netlist.getNodableFor((NodeInst)no, 0);
}
Instance inst = (Instance)instancesMap.get(no);
if (inst == null) return false; // failed
MessagesWindow msgs = TopLevel.getMessagesWindow();
//Font oldFont = msgs.getFont();
//msgs.setFont(new Font("Courier", Font.BOLD, oldFont.getSize()));
// print netlister info
System.out.println("Netlister: Gate Cap="+gateCap+", Alpha="+alpha);
// print instance info
inst.print();
// collect info about what is driven
Pin out = (Pin)inst.getOutputPins().get(0);
Net net = out.getNet();
ArrayList gatesDrivenPins = new ArrayList();
ArrayList loadsDrivenPins = new ArrayList();
ArrayList wiresDrivenPins = new ArrayList();
ArrayList gatesFightingPins = new ArrayList();
for (Iterator it = net.getAllPins().iterator(); it.hasNext(); ) {
Pin pin = (Pin)it.next();
Instance in = pin.getInstance();
if (pin.getDir() == Pin.Dir.INPUT) {
if (in.isGate()) gatesDrivenPins.add(pin);
//if (in.getType() == Instance.Type.STATICGATE) staticGatesDriven.add(in);
if (in.getType() == Instance.Type.LOAD) loadsDrivenPins.add(pin);
if (in.getType() == Instance.Type.WIRE) wiresDrivenPins.add(pin);
}
if (pin.getDir() == Pin.Dir.OUTPUT) {
if (in.isGate()) gatesFightingPins.add(pin);
}
}
System.out.println("Note: Load = Size * LE * M");
System.out.println("Note: Load = Size * LE * M * Alpha, for Gates Fighting");
float totalLoad = 0f;
System.out.println(" -------------------- Gates Driven ("+gatesDrivenPins.size()+") --------------------");
for (Iterator it = gatesDrivenPins.iterator(); it.hasNext(); ) {
Pin pin = (Pin)it.next(); totalLoad += pin.getInstance().printLoadInfo(pin, alpha);
}
System.out.println(" -------------------- Loads Driven ("+loadsDrivenPins.size()+") --------------------");
for (Iterator it = loadsDrivenPins.iterator(); it.hasNext(); ) {
Pin pin = (Pin)it.next(); totalLoad += pin.getInstance().printLoadInfo(pin, alpha);
}
System.out.println(" -------------------- Wires Driven ("+wiresDrivenPins.size()+") --------------------");
for (Iterator it = wiresDrivenPins.iterator(); it.hasNext(); ) {
Pin pin = (Pin)it.next(); totalLoad += pin.getInstance().printLoadInfo(pin, alpha);
}
System.out.println(" -------------------- Gates Fighting ("+gatesFightingPins.size()+") --------------------");
for (Iterator it = gatesFightingPins.iterator(); it.hasNext(); ) {
Pin pin = (Pin)it.next(); totalLoad += pin.getInstance().printLoadInfo(pin, alpha);
}
System.out.println("*** Total Load: "+TextUtils.formatDouble(totalLoad, 2));
//msgs.setFont(oldFont);
return true;
}
// ---- TEST STUFF ----- REMOVE LATER ----
public static void test1() {
LESizer.test1();
}
}
| true | true | public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
float leX = (float)0.0;
boolean wire = false;
boolean primitiveTransistor = false;
// Check if this NodeInst is tagged as a logical effort node
Instance.Type type = null;
Variable var = null;
if ((var = getVar(ni, "ATTR_LEGATE")) != null) {
// assume it is LEGATE if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEGATE;
else
type = Instance.Type.STATICGATE;
}
else if ((var = getVar(ni, "ATTR_LEKEEPER")) != null) {
// assume it is LEKEEPER if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEKEEPER;
else
type = Instance.Type.STATICGATE;
}
else if (getVar(ni, "ATTR_LEWIRE") != null) {
type = Instance.Type.WIRE;
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = ni.getVar("ATTR_L");
float len = VarContext.objectToFloat(info.getContext().evalVar(var), 0.0f);
var = ni.getVar("ATTR_width");
float width = VarContext.objectToFloat(info.getContext().evalVar(var), 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
wire = true;
}
else if ((ni.getProto() != null) && (ni.getProto().getFunction().isTransistor())) {
// handle transistor loads
type = Instance.Type.STATICGATE;
var = ni.getVar("ATTR_width");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no width in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no width in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float width = VarContext.objectToFloat(info.getContext().evalVar(var), (float)3.0);
var = ni.getVar("ATTR_length");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no length in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float length = VarContext.objectToFloat(info.getContext().evalVar(var), (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
primitiveTransistor = true;
}
else if (ni.getVar("ATTR_LESETTINGS") != null)
return false;
if (type == null) return true; // descend into and process
if (DEBUG) System.out.println("------------------------------------");
// If got to this point, this is either an LEGATE or an LEWIRE
// Both require us to build an instance.
ArrayList pins = new ArrayList();
Netlist netlist = info.getNetlist();
for (Iterator ppIt = ni.getProto().getPorts(); ppIt.hasNext();) {
PortProto pp = (PortProto)ppIt.next();
var = pp.getVar("ATTR_le");
// Note default 'le' value should be one
float le = VarContext.objectToFloat(info.getContext().evalVar(var), (float)1.0);
String netName = info.getUniqueNetName(info.getNetID(netlist.getNetwork(ni,pp,0)), ".");
Pin.Dir dir = Pin.Dir.INPUT;
// if it's not an output, it doesn't really matter what it is.
if (pp.getCharacteristic() == PortProto.Characteristic.OUT) dir = Pin.Dir.OUTPUT;
if (primitiveTransistor) {
// primitive Electric Transistors have their source and drain set to BIDIR, we
// want them set to OUTPUT so that they count as diffusion capacitance
if (pp.getCharacteristic() == PortProto.Characteristic.BIDIR) dir = Pin.Dir.OUTPUT;
}
pins.add(new Pin(pp.getName(), dir, le, netName));
if (DEBUG) System.out.println(" Added "+dir+" pin "+pp.getName()+", le: "+le+", netName: "+netName+", JNetwork: "+netlist.getNetwork(ni,pp,0));
if (type == Instance.Type.WIRE) break; // this is LEWIRE, only add one pin of it
}
// see if passed-down step-up exists
float localsu = su;
if (((LECellInfo)info).getSU() != -1f)
localsu = ((LECellInfo)info).getSU();
// check for step-up on gate
var = ni.getVar("ATTR_su");
if (var != null) {
float nisu = VarContext.objectToFloat(info.getContext().evalVar(var), -1f);
if (nisu != -1f)
localsu = nisu;
}
// create new leGate instance
VarContext vc = info.getContext().push(ni); // to create unique flat name
Instance inst = addInstance(vc.getInstPath("."), type, localsu, leX, pins, ni);
// set instance parameters for sizeable gates
if (type == Instance.Type.LEGATE) {
var = ni.getVar("ATTR_LEPARALLGRP");
if (var != null) {
// set parallel group number
int g = VarContext.objectToInt(info.getContext().evalVar(var), 0);
inst.setParallelGroup(g);
}
}
// set mfactor
var = ni.getVar("ATTR_M");
if (var != null) {
// set mfactor
int m = VarContext.objectToInt(info.getContext().evalVar(var), 1);
inst.setMfactor(m * ((LECellInfo)info).getMFactor());
}
if (DEBUG) {
if (wire) System.out.println(" Added LEWire "+vc.getInstPath(".")+", X="+leX);
else System.out.println(" Added instance "+vc.getInstPath(".")+" of type "+type+", X="+leX);
}
instancesMap.put(ni, inst);
return false;
}
| public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
float leX = (float)0.0;
boolean wire = false;
boolean primitiveTransistor = false;
// Check if this NodeInst is tagged as a logical effort node
Instance.Type type = null;
Variable var = null;
if ((var = getVar(ni, "ATTR_LEGATE")) != null) {
// assume it is LEGATE if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEGATE;
else
type = Instance.Type.STATICGATE;
}
else if ((var = getVar(ni, "ATTR_LEKEEPER")) != null) {
// assume it is LEKEEPER if can't resolve value
int gate = VarContext.objectToInt(info.getContext().evalVar(var), 1);
if (gate == 1)
type = Instance.Type.LEKEEPER;
else
type = Instance.Type.STATICGATE;
}
else if (getVar(ni, "ATTR_LEWIRE") != null) {
type = Instance.Type.WIRE;
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = ni.getVar("ATTR_L");
float len = VarContext.objectToFloat(info.getContext().evalVar(var), 0.0f);
var = ni.getVar("ATTR_width");
float width = VarContext.objectToFloat(info.getContext().evalVar(var), 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
wire = true;
}
else if ((ni.getProto() != null) && (ni.getProto().getFunction().isTransistor())) {
// handle transistor loads
type = Instance.Type.STATICGATE;
var = ni.getVar("ATTR_width");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no width in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no width in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float width = VarContext.objectToFloat(info.getContext().evalVar(var), (float)3.0);
var = ni.getVar("ATTR_length");
if (var == null) {
System.out.println("Error: transistor "+ni+" has no length in Cell "+info.getCell());
ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return false;
}
float length = VarContext.objectToFloat(info.getContext().evalVar(var), (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
primitiveTransistor = true;
}
else if (ni.getVar("ATTR_LESETTINGS") != null)
return false;
if (type == null) return true; // descend into and process
if (DEBUG) System.out.println("------------------------------------");
// If got to this point, this is either an LEGATE or an LEWIRE
// Both require us to build an instance.
ArrayList pins = new ArrayList();
Netlist netlist = info.getNetlist();
for (Iterator ppIt = ni.getProto().getPorts(); ppIt.hasNext();) {
PortProto pp = (PortProto)ppIt.next();
var = pp.getVar("ATTR_le");
// Note default 'le' value should be one
float le = VarContext.objectToFloat(info.getContext().evalVar(var), (float)1.0);
String netName = info.getUniqueNetName(info.getNetID(netlist.getNetwork(ni,pp,0)), ".");
Pin.Dir dir = Pin.Dir.INPUT;
// if it's not an output, it doesn't really matter what it is.
if (pp.getCharacteristic() == PortProto.Characteristic.OUT) dir = Pin.Dir.OUTPUT;
if (primitiveTransistor) {
// primitive Electric Transistors have their source and drain set to BIDIR, we
// want them set to OUTPUT so that they count as diffusion capacitance
if (pp.getCharacteristic() == PortProto.Characteristic.BIDIR) dir = Pin.Dir.OUTPUT;
}
pins.add(new Pin(pp.getName(), dir, le, netName));
if (DEBUG) System.out.println(" Added "+dir+" pin "+pp.getName()+", le: "+le+", netName: "+netName+", JNetwork: "+netlist.getNetwork(ni,pp,0));
if (type == Instance.Type.WIRE) break; // this is LEWIRE, only add one pin of it
}
// see if passed-down step-up exists
float localsu = su;
if (((LECellInfo)info).getSU() != -1f)
localsu = ((LECellInfo)info).getSU();
// check for step-up on gate
var = ni.getVar("ATTR_su");
if (var != null) {
float nisu = VarContext.objectToFloat(info.getContext().evalVar(var), -1f);
if (nisu != -1f)
localsu = nisu;
}
// create new leGate instance
VarContext vc = info.getContext().push(ni); // to create unique flat name
Instance inst = addInstance(vc.getInstPath("."), type, localsu, leX, pins, ni);
inst.setContext(info.getContext());
// set instance parameters for sizeable gates
if (type == Instance.Type.LEGATE) {
var = ni.getVar("ATTR_LEPARALLGRP");
if (var != null) {
// set parallel group number
int g = VarContext.objectToInt(info.getContext().evalVar(var), 0);
inst.setParallelGroup(g);
}
}
// set mfactor
var = ni.getVar("ATTR_M");
if (var != null) {
// set mfactor
int m = VarContext.objectToInt(info.getContext().evalVar(var), 1);
inst.setMfactor(m * ((LECellInfo)info).getMFactor());
}
if (DEBUG) {
if (wire) System.out.println(" Added LEWire "+vc.getInstPath(".")+", X="+leX);
else System.out.println(" Added instance "+vc.getInstPath(".")+" of type "+type+", X="+leX);
}
instancesMap.put(ni, inst);
return false;
}
|
diff --git a/src/main/java/org/spoutcraft/client/inventory/SimpleMaterialManager.java b/src/main/java/org/spoutcraft/client/inventory/SimpleMaterialManager.java
index 19869813..cdb5f427 100644
--- a/src/main/java/org/spoutcraft/client/inventory/SimpleMaterialManager.java
+++ b/src/main/java/org/spoutcraft/client/inventory/SimpleMaterialManager.java
@@ -1,296 +1,296 @@
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/>
* Spoutcraft is licensed under the GNU Lesser General Public License.
*
* Spoutcraft 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 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft 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/>.
*/
package org.spoutcraft.client.inventory;
import java.util.ArrayList;
import java.util.List;
import gnu.trove.map.hash.TIntByteHashMap;
import gnu.trove.map.hash.TIntIntHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.src.Item;
import org.spoutcraft.api.util.map.TIntPairFloatHashMap;
import org.spoutcraft.api.util.map.TIntPairObjectHashMap;
import org.spoutcraft.api.addon.Addon;
import org.spoutcraft.api.inventory.ItemStack;
import org.spoutcraft.api.inventory.MaterialManager;
import org.spoutcraft.api.inventory.Recipe;
import org.spoutcraft.api.inventory.ShapedRecipe;
import org.spoutcraft.api.inventory.ShapelessRecipe;
import org.spoutcraft.api.material.CustomBlock;
import org.spoutcraft.api.material.Material;
import org.spoutcraft.api.material.MaterialData;
public class SimpleMaterialManager implements MaterialManager {
private final TIntPairFloatHashMap originalHardness = new TIntPairFloatHashMap();
private final TIntPairFloatHashMap originalFriction = new TIntPairFloatHashMap();
private final TIntByteHashMap originalOpacity = new TIntByteHashMap();
private final TIntIntHashMap originalLight = new TIntIntHashMap();
private final TIntPairObjectHashMap<String> customNames = new TIntPairObjectHashMap<String>(100);
private final TIntPairObjectHashMap<String> customTextures = new TIntPairObjectHashMap<String>(100);
private final TIntPairObjectHashMap<String> customTexturesPlugin = new TIntPairObjectHashMap<String>(100);
public float getFriction(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
return net.minecraft.src.Block.blocksList[id].slipperiness;
}
public void setFriction(org.spoutcraft.api.material.Block block, float friction) {
int id = block.getRawId();
int data = block.getRawData();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (!originalFriction.containsKey(id, data)) {
originalFriction.put(id, data, getFriction(block));
}
net.minecraft.src.Block.blocksList[id].slipperiness = friction;
}
public void resetFriction(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
int data = block.getRawData();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (originalFriction.containsKey(id, data)) {
setFriction(block, originalFriction.get(id, data));
originalFriction.remove(id, data);
}
}
public float getHardness(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
return net.minecraft.src.Block.blocksList[id].getHardness();
}
public void setHardness(org.spoutcraft.api.material.Block block, float hardness) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
net.minecraft.src.Block.blocksList[id].blockHardness = hardness;
}
public void resetHardness(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
int data = block.getRawData();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (originalHardness.containsKey(id, data)) {
setHardness(block, originalHardness.get(id, data));
originalHardness.remove(id, data);
}
}
public boolean isOpaque(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
return net.minecraft.src.Block.opaqueCubeLookup[id];
}
public void setOpaque(org.spoutcraft.api.material.Block block, boolean opacity) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (!originalOpacity.containsKey(id)) {
originalOpacity.put(id, (byte) (isOpaque(block) ? 1 : 0));
}
net.minecraft.src.Block.opaqueCubeLookup[id] = opacity;
}
public void resetOpacity(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (originalOpacity.containsKey(id)) {
setOpaque(block, originalOpacity.get(id) != 0);
originalOpacity.remove(id);
}
}
public int getLightLevel(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
return net.minecraft.src.Block.lightValue[id];
}
public void setLightLevel(org.spoutcraft.api.material.Block block, int level) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (!originalLight.containsKey(id)) {
originalLight.put(id, getLightLevel(block));
}
net.minecraft.src.Block.lightValue[id] = level;
}
public void resetLightLevel(org.spoutcraft.api.material.Block block) {
int id = block.getRawId();
if (block instanceof CustomBlock) {
id = ((CustomBlock) block).getBlockId();
}
if (originalLight.containsKey(id)) {
setLightLevel(block, originalLight.get(id));
originalLight.remove(id);
}
}
public void setItemName(Material item, String name) {
customNames.put(item.getRawId(), item.getRawData(), name);
}
public void resetName(Material item) {
int id = item.getRawId();
int data = item.getRawData();
if (customNames.containsKey(id, data)) {
customNames.remove(id, data);
}
}
public void setItemTexture(Material item, Addon addon, String texture) {
int id = item.getRawId();
int data = item.getRawData();
String addonName;
if (addon == null) {
addonName = null;
} else {
addonName = addon.getDescription().getName();
}
customTextures.put(id, data, texture);
if (addonName == null) {
customTexturesPlugin.remove(id, data);
} else {
customTexturesPlugin.put(id, data, addonName);
}
}
public String getCustomItemTexture(Material item) {
if (item == null) return null;
int id = item.getRawId();
int data = item.getRawData();
if (customTextures.containsKey(id, data)) {
return (String) customTextures.get(id, data);
}
return null;
}
public String getCustomItemTextureAddon(Material item) {
if (item == null) return null;
int id = item.getRawId();
int data = item.getRawData();
if (customTexturesPlugin.containsKey(id, data)) {
return (String) customTexturesPlugin.get(id, data);
}
return null;
}
public void resetTexture(Material item) {
int id = item.getRawId();
int data = item.getRawData();
if (customTextures.containsKey(id, data)) {
customTextures.remove(id, data);
}
}
public void reset() {
for (Material next : MaterialData.getMaterials()) {
if (next instanceof org.spoutcraft.api.material.Block) {
org.spoutcraft.api.material.Block block = (org.spoutcraft.api.material.Block)next;
resetFriction(block);
resetHardness(block);
resetOpacity(block);
resetLightLevel(block);
}
}
}
public boolean registerRecipe(Recipe recipe) {
SpoutcraftRecipe toAdd;
if (recipe instanceof ShapedRecipe) {
toAdd = SimpleShapedRecipe.fromSpoutRecipe((ShapedRecipe) recipe);
} else if (recipe instanceof ShapelessRecipe) {
toAdd = SimpleShapelessRecipe.fromSpoutRecipe((ShapelessRecipe) recipe);
} else {
return false;
}
toAdd.addToCraftingManager();
return true;
}
@SuppressWarnings("unchecked")
@Override
public String getToolTip(ItemStack is) {
net.minecraft.src.ItemStack itemstack = new net.minecraft.src.ItemStack(is.getTypeId(), is.getAmount(), is.getDurability());
Item rawItem = Item.itemsList[itemstack.itemID];
List<String> list;
if (rawItem != null) {
list = itemstack.getTooltip(Minecraft.theMinecraft.thePlayer, Minecraft.theMinecraft.gameSettings.advancedItemTooltips);
} else {
list = new ArrayList<String>();
}
Material item = MaterialData.getMaterial(is.getTypeId(), is.getDurability());
String custom = item != null ? String.format(item.getName(), String.valueOf(is.getDurability())) : null;
if (custom != null && is.getTypeId() != Item.potion.shiftedIndex) {
if (list.size() > 0) {
list.set(0, custom);
} else {
list.add(custom);
}
}
if (list.size() > 0) {
String tooltip = "";
int lines = 0;
for (int i = 0; i < list.size(); i++) {
String s = (String)list.get(i);
- if (i == 0) {
+ if (i == 0 && rawItem!=null) {
s = (new StringBuilder()).append("\247").append(Integer.toHexString(itemstack.getRarity().rarityColor)).append(s).toString();
} else {
s = (new StringBuilder()).append("\2477").append(s).toString();
}
tooltip += s + "\n";
lines++;
}
tooltip = tooltip.trim();
return tooltip;
}
return "";
}
}
| true | true | public String getToolTip(ItemStack is) {
net.minecraft.src.ItemStack itemstack = new net.minecraft.src.ItemStack(is.getTypeId(), is.getAmount(), is.getDurability());
Item rawItem = Item.itemsList[itemstack.itemID];
List<String> list;
if (rawItem != null) {
list = itemstack.getTooltip(Minecraft.theMinecraft.thePlayer, Minecraft.theMinecraft.gameSettings.advancedItemTooltips);
} else {
list = new ArrayList<String>();
}
Material item = MaterialData.getMaterial(is.getTypeId(), is.getDurability());
String custom = item != null ? String.format(item.getName(), String.valueOf(is.getDurability())) : null;
if (custom != null && is.getTypeId() != Item.potion.shiftedIndex) {
if (list.size() > 0) {
list.set(0, custom);
} else {
list.add(custom);
}
}
if (list.size() > 0) {
String tooltip = "";
int lines = 0;
for (int i = 0; i < list.size(); i++) {
String s = (String)list.get(i);
if (i == 0) {
s = (new StringBuilder()).append("\247").append(Integer.toHexString(itemstack.getRarity().rarityColor)).append(s).toString();
} else {
s = (new StringBuilder()).append("\2477").append(s).toString();
}
tooltip += s + "\n";
lines++;
}
tooltip = tooltip.trim();
return tooltip;
}
return "";
}
| public String getToolTip(ItemStack is) {
net.minecraft.src.ItemStack itemstack = new net.minecraft.src.ItemStack(is.getTypeId(), is.getAmount(), is.getDurability());
Item rawItem = Item.itemsList[itemstack.itemID];
List<String> list;
if (rawItem != null) {
list = itemstack.getTooltip(Minecraft.theMinecraft.thePlayer, Minecraft.theMinecraft.gameSettings.advancedItemTooltips);
} else {
list = new ArrayList<String>();
}
Material item = MaterialData.getMaterial(is.getTypeId(), is.getDurability());
String custom = item != null ? String.format(item.getName(), String.valueOf(is.getDurability())) : null;
if (custom != null && is.getTypeId() != Item.potion.shiftedIndex) {
if (list.size() > 0) {
list.set(0, custom);
} else {
list.add(custom);
}
}
if (list.size() > 0) {
String tooltip = "";
int lines = 0;
for (int i = 0; i < list.size(); i++) {
String s = (String)list.get(i);
if (i == 0 && rawItem!=null) {
s = (new StringBuilder()).append("\247").append(Integer.toHexString(itemstack.getRarity().rarityColor)).append(s).toString();
} else {
s = (new StringBuilder()).append("\2477").append(s).toString();
}
tooltip += s + "\n";
lines++;
}
tooltip = tooltip.trim();
return tooltip;
}
return "";
}
|
diff --git a/src/main/java/com/metaweb/gridworks/operations/ReconMatchBestCandidatesOperation.java b/src/main/java/com/metaweb/gridworks/operations/ReconMatchBestCandidatesOperation.java
index 34f88636..a5760449 100644
--- a/src/main/java/com/metaweb/gridworks/operations/ReconMatchBestCandidatesOperation.java
+++ b/src/main/java/com/metaweb/gridworks/operations/ReconMatchBestCandidatesOperation.java
@@ -1,103 +1,103 @@
package com.metaweb.gridworks.operations;
import java.util.List;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.metaweb.gridworks.browsing.RowVisitor;
import com.metaweb.gridworks.history.Change;
import com.metaweb.gridworks.model.AbstractOperation;
import com.metaweb.gridworks.model.Cell;
import com.metaweb.gridworks.model.Column;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.ReconCandidate;
import com.metaweb.gridworks.model.Row;
import com.metaweb.gridworks.model.Recon.Judgment;
import com.metaweb.gridworks.model.changes.CellChange;
import com.metaweb.gridworks.model.changes.ReconChange;
public class ReconMatchBestCandidatesOperation extends EngineDependentMassCellOperation {
static public AbstractOperation reconstruct(Project project, JSONObject obj) throws Exception {
JSONObject engineConfig = obj.getJSONObject("engineConfig");
String columnName = obj.getString("columnName");
return new ReconMatchBestCandidatesOperation(
engineConfig,
columnName
);
}
public ReconMatchBestCandidatesOperation(JSONObject engineConfig, String columnName) {
super(engineConfig, columnName, false);
}
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("op"); writer.value(OperationRegistry.s_opClassToName.get(this.getClass()));
writer.key("description"); writer.value(getBriefDescription(null));
writer.key("engineConfig"); writer.value(getEngineConfig());
writer.key("columnName"); writer.value(_columnName);
writer.endObject();
}
protected String getBriefDescription(Project project) {
return "Match each cell to its best recon candidate in column " + _columnName;
}
protected String createDescription(Column column,
List<CellChange> cellChanges) {
return "Match each of " + cellChanges.size() +
" cells to its best candidate in column " + column.getName();
}
protected RowVisitor createRowVisitor(Project project, List<CellChange> cellChanges) throws Exception {
Column column = project.columnModel.getColumnByName(_columnName);
return new RowVisitor() {
int cellIndex;
List<CellChange> cellChanges;
public RowVisitor init(int cellIndex, List<CellChange> cellChanges) {
this.cellIndex = cellIndex;
this.cellChanges = cellChanges;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
if (cellIndex < row.cells.size()) {
Cell cell = row.cells.get(cellIndex);
- if (cell.recon != null) {
+ if (cell != null && cell.recon != null) {
ReconCandidate candidate = cell.recon.getBestCandidate();
if (candidate != null) {
Cell newCell = new Cell(
cell.value,
cell.recon.dup()
);
newCell.recon.match = candidate;
newCell.recon.judgment = Judgment.Matched;
CellChange cellChange = new CellChange(rowIndex, cellIndex, cell, newCell);
cellChanges.add(cellChange);
}
}
}
return false;
}
}.init(column.getCellIndex(), cellChanges);
}
protected Change createChange(Project project, Column column, List<CellChange> cellChanges) {
return new ReconChange(
cellChanges,
_columnName,
column.getReconConfig(),
null
);
}
}
| true | true | protected RowVisitor createRowVisitor(Project project, List<CellChange> cellChanges) throws Exception {
Column column = project.columnModel.getColumnByName(_columnName);
return new RowVisitor() {
int cellIndex;
List<CellChange> cellChanges;
public RowVisitor init(int cellIndex, List<CellChange> cellChanges) {
this.cellIndex = cellIndex;
this.cellChanges = cellChanges;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
if (cellIndex < row.cells.size()) {
Cell cell = row.cells.get(cellIndex);
if (cell.recon != null) {
ReconCandidate candidate = cell.recon.getBestCandidate();
if (candidate != null) {
Cell newCell = new Cell(
cell.value,
cell.recon.dup()
);
newCell.recon.match = candidate;
newCell.recon.judgment = Judgment.Matched;
CellChange cellChange = new CellChange(rowIndex, cellIndex, cell, newCell);
cellChanges.add(cellChange);
}
}
}
return false;
}
}.init(column.getCellIndex(), cellChanges);
}
| protected RowVisitor createRowVisitor(Project project, List<CellChange> cellChanges) throws Exception {
Column column = project.columnModel.getColumnByName(_columnName);
return new RowVisitor() {
int cellIndex;
List<CellChange> cellChanges;
public RowVisitor init(int cellIndex, List<CellChange> cellChanges) {
this.cellIndex = cellIndex;
this.cellChanges = cellChanges;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
if (cellIndex < row.cells.size()) {
Cell cell = row.cells.get(cellIndex);
if (cell != null && cell.recon != null) {
ReconCandidate candidate = cell.recon.getBestCandidate();
if (candidate != null) {
Cell newCell = new Cell(
cell.value,
cell.recon.dup()
);
newCell.recon.match = candidate;
newCell.recon.judgment = Judgment.Matched;
CellChange cellChange = new CellChange(rowIndex, cellIndex, cell, newCell);
cellChanges.add(cellChange);
}
}
}
return false;
}
}.init(column.getCellIndex(), cellChanges);
}
|
diff --git a/agile-apps/agile-app-builds/src/main/java/org/headsupdev/agile/app/ci/CI.java b/agile-apps/agile-app-builds/src/main/java/org/headsupdev/agile/app/ci/CI.java
index 1ff7d972..d1778ee6 100644
--- a/agile-apps/agile-app-builds/src/main/java/org/headsupdev/agile/app/ci/CI.java
+++ b/agile-apps/agile-app-builds/src/main/java/org/headsupdev/agile/app/ci/CI.java
@@ -1,468 +1,468 @@
/*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.ci;
import org.apache.wicket.markup.html.list.ListView;
import org.headsupdev.agile.api.PropertyTree;
import org.headsupdev.agile.app.ci.permission.BuildForcePermission;
import org.headsupdev.agile.app.ci.permission.BuildListPermission;
import org.headsupdev.agile.web.HeadsUpPage;
import org.headsupdev.agile.web.HeadsUpSession;
import org.headsupdev.agile.web.DynamicMenuLink;
import org.headsupdev.agile.web.components.FormattedDateModel;
import org.headsupdev.agile.web.components.FormattedDurationModel;
import org.headsupdev.agile.web.components.StripedListView;
import org.headsupdev.agile.web.components.ProjectTreeListView;
import org.headsupdev.agile.security.permission.ProjectListPermission;
import org.headsupdev.agile.storage.StoredProject;
import org.headsupdev.agile.storage.HibernateStorage;
import org.headsupdev.agile.storage.ci.Build;
import org.headsupdev.agile.api.Project;
import org.headsupdev.agile.api.Manager;
import org.headsupdev.agile.api.Permission;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.PageParameters;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.model.Model;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.*;
/**
* Continuous integration home page
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class CI
extends HeadsUpPage
{
public void layout() {
super.layout();
add( CSSPackageResource.getHeaderContribution( getClass(), "ci.css" ) );
final boolean projectList = getProject().equals( StoredProject.getDefault() );
if ( projectList )
{
requirePermission( new ProjectListPermission() );
}
renderTopLinks( projectList );
WebMarkupContainer builds = new WebMarkupContainer( "buildlist" );
if ( projectList )
{
builds.setVisible( false );
}
else
{
builds.add( new StripedListView<Build>( "builds", getApp().getBuildsForProject( getProject() ) )
{
protected void populateItem( ListItem<Build> listItem )
{
super.populateItem( listItem );
Build build = listItem.getModelObject();
renderBuild( build, build.getProject(), false, false, listItem );
}
} );
}
add( builds );
WebMarkupContainer projects = new WebMarkupContainer( "projectlist" );
projects.add( new ProjectTreeListView( "projects", getProject() )
{
protected void populateProjectItem( ListItem listItem, Project project )
{
renderBuild( getApp().getLatestBuildForProject( project ), project,
true, CIBuilder.isProjectQueued( project ), listItem );
}
} );
add( projects.setVisible( ( projectList || getProject().getChildProjects().size() > 0 ) &&
Manager.getSecurityInstance().userHasPermission( getSession().getUser(), new ProjectListPermission(),
getProject() ) ) );
}
@Override
public String getTitle()
{
return "Builds for project " + getProject().getAlias();
}
void renderTopLinks( boolean projectList )
{
if ( !projectList )
{
Build latest = getApp().getLatestBuildForProject( getProject() );
int status = Build.BUILD_SUCCEEDED;
if ( latest != null )
{
status = latest.getStatus();
}
WebMarkupContainer building = new WebMarkupContainer( "building" );
WebMarkupContainer queued = new WebMarkupContainer( "queued" );
add( building.setVisible( status == Build.BUILD_RUNNING ) );
add( queued.setVisible( CIBuilder.isProjectQueued( getProject() ) ) );
if ( userHasPermission( ( (HeadsUpSession) getPage().getSession() ).getUser(),
new BuildForcePermission(), getProject() ) && CIApplication.getHandlerFactory().supportsBuilding( getProject() ) )
{
if ( status != Build.BUILD_RUNNING && !CIBuilder.isProjectQueued( getProject() ) )
{
add( new Link( "build" )
{
public void onClick()
{
queueBuild( getProject() );
}
} );
addLink( new DynamicMenuLink( "build" )
{
public void onClick()
{
queueBuild( getProject() );
}
} );
final PropertyTree buildConfigs = Manager.getStorageInstance().getGlobalConfiguration().
getApplicationConfigurationForProject( CIApplication.ID, getProject() ).getSubTree( "schedule" );
List<String> configNames = new LinkedList<String>( buildConfigs.getSubTreeIds() );
configNames.remove( "default" );
Collections.sort( configNames );
add( new ListView<String>( "buildConfigs", configNames )
{
@Override
protected void populateItem( ListItem<String> listItem )
{
final String configId = listItem.getModelObject();
final PropertyTree config = buildConfigs.getSubTree( configId );
final String configName = config.getProperty( "name" );
if ( configName == null )
{
listItem.setVisible( false );
return;
}
Link build = new Link( "build" )
{
@Override
public void onClick()
{
queueBuild( getProject(), configId, config );
}
};
build.add( new Label( "name", configName ) );
listItem.add( build );
}
} );
}
else
{
add( new WebMarkupContainer( "build" ).setVisible( false ) );
add( new WebMarkupContainer( "buildConfigs" ).setVisible( false ) );
}
if ( status == Build.BUILD_RUNNING )
{
building.add( new Link( "cancel" )
{
public void onClick()
{
cancelBuild( getProject() );
}
} );
addLink( new DynamicMenuLink( "cancel" )
{
public void onClick()
{
cancelBuild( getProject() );
}
} );
}
else
{
add( new WebMarkupContainer( "cancel" ).setVisible( false ) );
}
if ( CIBuilder.isProjectQueued( getProject() ) )
{
queued.add( new Link( "remove" )
{
public void onClick()
{
dequeueBuild( getProject() );
}
} );
addLink( new DynamicMenuLink( "dequeue" )
{
public void onClick()
{
dequeueBuild( getProject() );
}
} );
}
else
{
add( new WebMarkupContainer( "remove" ).setVisible( false ) );
}
}
else
{
add( new WebMarkupContainer( "build" ).setVisible( false ) );
add( new WebMarkupContainer( "buildConfigs" ).setVisible( false ) );
building.add( new WebMarkupContainer( "cancel" ).setVisible( false ) );
queued.add( new WebMarkupContainer( "remove" ).setVisible( false ) );
}
}
else
{
add( new WebMarkupContainer( "building" ).setVisible( false ) );
add( new WebMarkupContainer( "queued" ).setVisible( false ) );
add( new WebMarkupContainer( "build" ).setVisible( false ) );
add( new WebMarkupContainer( "buildConfigs" ).setVisible( false ) );
}
}
private void renderBuild( final Build build, final Project project, final boolean projectList,
final boolean queued, final ListItem listItem )
{
if ( projectList ) {
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
- Link link = new BookmarkablePageLink( "project-link", getClass(), params );
+ Link link = new BookmarkablePageLink<CI>( "project-link", getClass(), params );
link.add( new Label( "name", project.getAlias() ) );
listItem.add( link );
}
else
{
listItem.add( new Label( "name", project.getAlias() ) );
}
- if ( build.getConfigName() == null )
+ if ( build == null || build.getConfigName() == null )
{
listItem.add( new Label( "config", "" ) );
}
else
{
listItem.add( new Label( "config", build.getConfigName() ) );
}
final boolean canForce = projectList && userHasPermission( ( (HeadsUpSession) getPage().getSession() ).getUser(),
new BuildForcePermission(), project ) && CIApplication.getHandlerFactory().supportsBuilding( project );
WebMarkupContainer statusLink = new Link( "status-link" )
{
public void onClick()
{
if ( queued )
{
dequeueBuild( project );
}
else if ( build != null && build.getStatus() == Build.BUILD_RUNNING )
{
cancelBuild( project );
}
else
{
queueBuild( project );
}
}
};
if ( build != null )
{
WebMarkupContainer status;
if ( canForce )
{
status = statusLink;
listItem.add( new WebMarkupContainer( "status-icon" ).setVisible( false ) );
}
else
{
status = new WebMarkupContainer( "status-icon" );
listItem.add( statusLink.setVisible( false ) );
}
status.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
if ( canForce )
{
return "status-queued status-remove";
}
return "status-queued";
}
else
{
switch ( build.getStatus() )
{
case Build.BUILD_SUCCEEDED:
if ( canForce )
{
return "status-passed status-force";
}
return "status-passed";
case Build.BUILD_FAILED:
case Build.BUILD_CANCELLED:
if ( canForce )
{
return "status-failed status-force";
}
return "status-failed";
default:
if ( canForce )
{
return "status-running status-remove";
}
return "status-running";
}
}
}
} ) );
listItem.add( status );
listItem.add( new Label( "start", new FormattedDateModel( build.getStartTime(),
getSession().getTimeZone() ) ) );
listItem.add( new Label( "duration", new FormattedDurationModel( build.getStartTime(),
build.getEndTime() )
{
public String getObject() {
if ( build.getEndTime() == null )
{
return super.getObject() + "...";
}
return super.getObject();
}
} ) );
listItem.add( new Label( "tests", String.valueOf( build.getTests() ) )
.add( new CITestStatusModifier( "tests", build, "tests" ) ) );
listItem.add( new Label( "failures", String.valueOf( build.getFailures() ) )
.add( new CITestStatusModifier( "failures", build, "failures" ) ) );
listItem.add( new Label( "errors", String.valueOf( build.getErrors() ) )
.add( new CITestStatusModifier( "errors", build, "errors" ) ) );
listItem.add( new Label( "warnings", String.valueOf( build.getWarnings() ) )
.add( new CITestStatusModifier( "warnings", build, "warnings" ) ) );
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
params.add( "id", String.valueOf( build.getId() ) );
- BookmarkablePageLink link = new BookmarkablePageLink( "buildId-link", View.class, params );
+ BookmarkablePageLink link = new BookmarkablePageLink<View>( "buildId-link", View.class, params );
link.add( new Label( "buildId-label", String.valueOf( build.getId() ) ) );
listItem.add( link );
}
else
{
statusLink.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued status-force";
}
return "status-force";
}
} ) );
WebMarkupContainer statusIcon = new WebMarkupContainer( "status-icon" );
statusIcon.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued";
}
return "";
}
} ) );
listItem.add( statusIcon.setVisible( !canForce ) );
listItem.add( statusLink.setVisible( canForce ) );
listItem.add( new Label( "start", "" ) );
listItem.add( new Label( "duration", "" ) );
listItem.add( new Label( "tests", "" ) );
listItem.add( new Label( "failures", "" ) );
listItem.add( new Label( "errors", "" ) );
listItem.add( new Label( "warnings", "" ) );
listItem.add( new WebMarkupContainer( "buildId-link" ).setVisible( false ) );
}
}
protected void queueBuild( Project project )
{
CIApplication.getBuilder().queueProject( project, false );
}
protected void queueBuild( Project project, String id, PropertyTree config )
{
CIApplication.getBuilder().queueProject( project, id, config, false );
}
protected void dequeueBuild( Project project )
{
CIApplication.getBuilder().dequeueProject( project );
}
protected void cancelBuild( Project project )
{
Build b = getApp().getLatestBuildForProject( project );
if ( b.getEndTime() == null )
{
b.setEndTime( new Date() );
b.setStatus( Build.BUILD_CANCELLED );
saveBuild( b );
// TODO actually cancel a build - if possible
}
}
public Permission getRequiredPermission() {
return new BuildListPermission();
}
CIApplication getApp()
{
return (CIApplication) getHeadsUpApplication();
}
private void saveBuild( Build build )
{
HibernateStorage storage = (HibernateStorage) Manager.getStorageInstance();
Session session = storage.getHibernateSession();
Transaction tx = session.beginTransaction();
session.update( build );
tx.commit();
storage.closeSession();
}
}
| false | true | private void renderBuild( final Build build, final Project project, final boolean projectList,
final boolean queued, final ListItem listItem )
{
if ( projectList ) {
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
Link link = new BookmarkablePageLink( "project-link", getClass(), params );
link.add( new Label( "name", project.getAlias() ) );
listItem.add( link );
}
else
{
listItem.add( new Label( "name", project.getAlias() ) );
}
if ( build.getConfigName() == null )
{
listItem.add( new Label( "config", "" ) );
}
else
{
listItem.add( new Label( "config", build.getConfigName() ) );
}
final boolean canForce = projectList && userHasPermission( ( (HeadsUpSession) getPage().getSession() ).getUser(),
new BuildForcePermission(), project ) && CIApplication.getHandlerFactory().supportsBuilding( project );
WebMarkupContainer statusLink = new Link( "status-link" )
{
public void onClick()
{
if ( queued )
{
dequeueBuild( project );
}
else if ( build != null && build.getStatus() == Build.BUILD_RUNNING )
{
cancelBuild( project );
}
else
{
queueBuild( project );
}
}
};
if ( build != null )
{
WebMarkupContainer status;
if ( canForce )
{
status = statusLink;
listItem.add( new WebMarkupContainer( "status-icon" ).setVisible( false ) );
}
else
{
status = new WebMarkupContainer( "status-icon" );
listItem.add( statusLink.setVisible( false ) );
}
status.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
if ( canForce )
{
return "status-queued status-remove";
}
return "status-queued";
}
else
{
switch ( build.getStatus() )
{
case Build.BUILD_SUCCEEDED:
if ( canForce )
{
return "status-passed status-force";
}
return "status-passed";
case Build.BUILD_FAILED:
case Build.BUILD_CANCELLED:
if ( canForce )
{
return "status-failed status-force";
}
return "status-failed";
default:
if ( canForce )
{
return "status-running status-remove";
}
return "status-running";
}
}
}
} ) );
listItem.add( status );
listItem.add( new Label( "start", new FormattedDateModel( build.getStartTime(),
getSession().getTimeZone() ) ) );
listItem.add( new Label( "duration", new FormattedDurationModel( build.getStartTime(),
build.getEndTime() )
{
public String getObject() {
if ( build.getEndTime() == null )
{
return super.getObject() + "...";
}
return super.getObject();
}
} ) );
listItem.add( new Label( "tests", String.valueOf( build.getTests() ) )
.add( new CITestStatusModifier( "tests", build, "tests" ) ) );
listItem.add( new Label( "failures", String.valueOf( build.getFailures() ) )
.add( new CITestStatusModifier( "failures", build, "failures" ) ) );
listItem.add( new Label( "errors", String.valueOf( build.getErrors() ) )
.add( new CITestStatusModifier( "errors", build, "errors" ) ) );
listItem.add( new Label( "warnings", String.valueOf( build.getWarnings() ) )
.add( new CITestStatusModifier( "warnings", build, "warnings" ) ) );
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
params.add( "id", String.valueOf( build.getId() ) );
BookmarkablePageLink link = new BookmarkablePageLink( "buildId-link", View.class, params );
link.add( new Label( "buildId-label", String.valueOf( build.getId() ) ) );
listItem.add( link );
}
else
{
statusLink.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued status-force";
}
return "status-force";
}
} ) );
WebMarkupContainer statusIcon = new WebMarkupContainer( "status-icon" );
statusIcon.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued";
}
return "";
}
} ) );
listItem.add( statusIcon.setVisible( !canForce ) );
listItem.add( statusLink.setVisible( canForce ) );
listItem.add( new Label( "start", "" ) );
listItem.add( new Label( "duration", "" ) );
listItem.add( new Label( "tests", "" ) );
listItem.add( new Label( "failures", "" ) );
listItem.add( new Label( "errors", "" ) );
listItem.add( new Label( "warnings", "" ) );
listItem.add( new WebMarkupContainer( "buildId-link" ).setVisible( false ) );
}
}
| private void renderBuild( final Build build, final Project project, final boolean projectList,
final boolean queued, final ListItem listItem )
{
if ( projectList ) {
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
Link link = new BookmarkablePageLink<CI>( "project-link", getClass(), params );
link.add( new Label( "name", project.getAlias() ) );
listItem.add( link );
}
else
{
listItem.add( new Label( "name", project.getAlias() ) );
}
if ( build == null || build.getConfigName() == null )
{
listItem.add( new Label( "config", "" ) );
}
else
{
listItem.add( new Label( "config", build.getConfigName() ) );
}
final boolean canForce = projectList && userHasPermission( ( (HeadsUpSession) getPage().getSession() ).getUser(),
new BuildForcePermission(), project ) && CIApplication.getHandlerFactory().supportsBuilding( project );
WebMarkupContainer statusLink = new Link( "status-link" )
{
public void onClick()
{
if ( queued )
{
dequeueBuild( project );
}
else if ( build != null && build.getStatus() == Build.BUILD_RUNNING )
{
cancelBuild( project );
}
else
{
queueBuild( project );
}
}
};
if ( build != null )
{
WebMarkupContainer status;
if ( canForce )
{
status = statusLink;
listItem.add( new WebMarkupContainer( "status-icon" ).setVisible( false ) );
}
else
{
status = new WebMarkupContainer( "status-icon" );
listItem.add( statusLink.setVisible( false ) );
}
status.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
if ( canForce )
{
return "status-queued status-remove";
}
return "status-queued";
}
else
{
switch ( build.getStatus() )
{
case Build.BUILD_SUCCEEDED:
if ( canForce )
{
return "status-passed status-force";
}
return "status-passed";
case Build.BUILD_FAILED:
case Build.BUILD_CANCELLED:
if ( canForce )
{
return "status-failed status-force";
}
return "status-failed";
default:
if ( canForce )
{
return "status-running status-remove";
}
return "status-running";
}
}
}
} ) );
listItem.add( status );
listItem.add( new Label( "start", new FormattedDateModel( build.getStartTime(),
getSession().getTimeZone() ) ) );
listItem.add( new Label( "duration", new FormattedDurationModel( build.getStartTime(),
build.getEndTime() )
{
public String getObject() {
if ( build.getEndTime() == null )
{
return super.getObject() + "...";
}
return super.getObject();
}
} ) );
listItem.add( new Label( "tests", String.valueOf( build.getTests() ) )
.add( new CITestStatusModifier( "tests", build, "tests" ) ) );
listItem.add( new Label( "failures", String.valueOf( build.getFailures() ) )
.add( new CITestStatusModifier( "failures", build, "failures" ) ) );
listItem.add( new Label( "errors", String.valueOf( build.getErrors() ) )
.add( new CITestStatusModifier( "errors", build, "errors" ) ) );
listItem.add( new Label( "warnings", String.valueOf( build.getWarnings() ) )
.add( new CITestStatusModifier( "warnings", build, "warnings" ) ) );
PageParameters params = new PageParameters();
params.add( "project", project.getId() );
params.add( "id", String.valueOf( build.getId() ) );
BookmarkablePageLink link = new BookmarkablePageLink<View>( "buildId-link", View.class, params );
link.add( new Label( "buildId-label", String.valueOf( build.getId() ) ) );
listItem.add( link );
}
else
{
statusLink.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued status-force";
}
return "status-force";
}
} ) );
WebMarkupContainer statusIcon = new WebMarkupContainer( "status-icon" );
statusIcon.add( new AttributeModifier( "class", new Model<String>()
{
public String getObject()
{
if ( queued )
{
return "status-queued";
}
return "";
}
} ) );
listItem.add( statusIcon.setVisible( !canForce ) );
listItem.add( statusLink.setVisible( canForce ) );
listItem.add( new Label( "start", "" ) );
listItem.add( new Label( "duration", "" ) );
listItem.add( new Label( "tests", "" ) );
listItem.add( new Label( "failures", "" ) );
listItem.add( new Label( "errors", "" ) );
listItem.add( new Label( "warnings", "" ) );
listItem.add( new WebMarkupContainer( "buildId-link" ).setVisible( false ) );
}
}
|
diff --git a/com.vogella.android.imagegrid/src/com/vogella/android/imagegrid/MainActivity.java b/com.vogella.android.imagegrid/src/com/vogella/android/imagegrid/MainActivity.java
index 23e722c..06bd764 100644
--- a/com.vogella.android.imagegrid/src/com/vogella/android/imagegrid/MainActivity.java
+++ b/com.vogella.android.imagegrid/src/com/vogella/android/imagegrid/MainActivity.java
@@ -1,26 +1,26 @@
package com.vogella.android.imagegrid;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getFragmentManager();
- if (manager.findFragmentByTag("list")== null){
+ if (manager.findFragmentById(R.id.fragment) == null) {
manager.beginTransaction().add(R.id.fragment, new MyListFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getFragmentManager();
if (manager.findFragmentByTag("list")== null){
manager.beginTransaction().add(R.id.fragment, new MyListFragment()).commit();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getFragmentManager();
if (manager.findFragmentById(R.id.fragment) == null) {
manager.beginTransaction().add(R.id.fragment, new MyListFragment()).commit();
}
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/JoinLinesCommand.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/JoinLinesCommand.java
index 42172eeb..a29f5ff2 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/JoinLinesCommand.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/JoinLinesCommand.java
@@ -1,80 +1,82 @@
package net.sourceforge.vrapper.vim.commands;
import net.sourceforge.vrapper.platform.TextContent;
import net.sourceforge.vrapper.utils.LineInformation;
import net.sourceforge.vrapper.vim.EditorAdaptor;
/* FIXME: In Vim, if line ends with dot, two spaces are inserted instead of one
* when joining lines. It's not implemented here.
* I (Krzysiek) don't like that feature anyway, so if you are going to implement it,
* please provide an option to turn if off ;-)
*/
/* There's an interesting article on why two spaces were used after a period here:
* http://www.writersdigest.com/online-editor/how-many-spaces-after-a-period
*
* The “two spaces after period” rule was instituted during the days of
* typewriters. Typewriters had only one font, so all the letters were
* monospaced, or took up the same amount of space.
*
* An on/off switch for .vrapperrc would be best -- BRD
*/
public class JoinLinesCommand extends CountAwareCommand {
public static final Command INSTANCE = new JoinLinesCommand(true);
public static final Command DUMB_INSTANCE = new JoinLinesCommand(false);
private final boolean isSmart;
private JoinLinesCommand(boolean isSmart) {
this.isSmart = isSmart;
}
@Override
public void execute(EditorAdaptor editorAdaptor, int count)
throws CommandExecutionException {
if (count == NO_COUNT_GIVEN)
count = 1;
try {
editorAdaptor.getHistory().beginCompoundChange();
doIt(editorAdaptor, count, isSmart);
} finally {
editorAdaptor.getHistory().endCompoundChange();
}
}
public static void doIt(EditorAdaptor editorAdaptor, int count, boolean isSmart)
throws CommandExecutionException {
TextContent modelContent = editorAdaptor.getModelContent();
for (int i = 0; i < count; i++) {
int modelOffset = editorAdaptor.getPosition().getModelOffset();
LineInformation firstLnInfo = modelContent.getLineInformationOfOffset(modelOffset);
if (firstLnInfo.getNumber() + 1 == modelContent.getNumberOfLines())
throw new CommandExecutionException("there is nothing to join below last line");
LineInformation secondLnInfo = modelContent.getLineInformation(firstLnInfo.getNumber() + 1);
int eolOffset = firstLnInfo.getEndOffset();
int bolOffset = secondLnInfo.getBeginOffset();
- String secondLine = modelContent.getText(bolOffset, secondLnInfo.getLength());
+ String secondLineText = modelContent.getText(bolOffset, secondLnInfo.getLength());
+ LineInformation lastLineInfo = modelContent.getLineInformation(modelContent.getNumberOfLines() - 1);
String glue;
if (isSmart) {
glue = " ";
if (firstLnInfo.getLength() > 0 && Character.isWhitespace(modelContent.getText(eolOffset - 1, 1).charAt(0)))
glue = "";
- for (int j = 0; j < secondLine.length() && Character.isWhitespace(secondLine.charAt(j)); j++)
+ for (int j = 0; j < secondLineText.length() && Character.isWhitespace(secondLineText.charAt(j)); j++)
bolOffset++;
- if(secondLine.length() == 0)
- glue = "";
+ // On last line of file, if it's a blank line, we don't want to append a space
+ if(secondLnInfo.getNumber() == lastLineInfo.getNumber() && secondLineText.length() == 0)
+ glue = "";
else if (modelContent.getText(bolOffset, 1).charAt(0) == ')')
glue = "";
} else
glue = "";
modelContent.replace(eolOffset, bolOffset - eolOffset, glue);
editorAdaptor.setPosition(editorAdaptor.getPosition().setModelOffset(eolOffset), true);
}
}
@Override
public CountAwareCommand repetition() {
return this;
}
}
| false | true | public static void doIt(EditorAdaptor editorAdaptor, int count, boolean isSmart)
throws CommandExecutionException {
TextContent modelContent = editorAdaptor.getModelContent();
for (int i = 0; i < count; i++) {
int modelOffset = editorAdaptor.getPosition().getModelOffset();
LineInformation firstLnInfo = modelContent.getLineInformationOfOffset(modelOffset);
if (firstLnInfo.getNumber() + 1 == modelContent.getNumberOfLines())
throw new CommandExecutionException("there is nothing to join below last line");
LineInformation secondLnInfo = modelContent.getLineInformation(firstLnInfo.getNumber() + 1);
int eolOffset = firstLnInfo.getEndOffset();
int bolOffset = secondLnInfo.getBeginOffset();
String secondLine = modelContent.getText(bolOffset, secondLnInfo.getLength());
String glue;
if (isSmart) {
glue = " ";
if (firstLnInfo.getLength() > 0 && Character.isWhitespace(modelContent.getText(eolOffset - 1, 1).charAt(0)))
glue = "";
for (int j = 0; j < secondLine.length() && Character.isWhitespace(secondLine.charAt(j)); j++)
bolOffset++;
if(secondLine.length() == 0)
glue = "";
else if (modelContent.getText(bolOffset, 1).charAt(0) == ')')
glue = "";
} else
glue = "";
modelContent.replace(eolOffset, bolOffset - eolOffset, glue);
editorAdaptor.setPosition(editorAdaptor.getPosition().setModelOffset(eolOffset), true);
}
}
| public static void doIt(EditorAdaptor editorAdaptor, int count, boolean isSmart)
throws CommandExecutionException {
TextContent modelContent = editorAdaptor.getModelContent();
for (int i = 0; i < count; i++) {
int modelOffset = editorAdaptor.getPosition().getModelOffset();
LineInformation firstLnInfo = modelContent.getLineInformationOfOffset(modelOffset);
if (firstLnInfo.getNumber() + 1 == modelContent.getNumberOfLines())
throw new CommandExecutionException("there is nothing to join below last line");
LineInformation secondLnInfo = modelContent.getLineInformation(firstLnInfo.getNumber() + 1);
int eolOffset = firstLnInfo.getEndOffset();
int bolOffset = secondLnInfo.getBeginOffset();
String secondLineText = modelContent.getText(bolOffset, secondLnInfo.getLength());
LineInformation lastLineInfo = modelContent.getLineInformation(modelContent.getNumberOfLines() - 1);
String glue;
if (isSmart) {
glue = " ";
if (firstLnInfo.getLength() > 0 && Character.isWhitespace(modelContent.getText(eolOffset - 1, 1).charAt(0)))
glue = "";
for (int j = 0; j < secondLineText.length() && Character.isWhitespace(secondLineText.charAt(j)); j++)
bolOffset++;
// On last line of file, if it's a blank line, we don't want to append a space
if(secondLnInfo.getNumber() == lastLineInfo.getNumber() && secondLineText.length() == 0)
glue = "";
else if (modelContent.getText(bolOffset, 1).charAt(0) == ')')
glue = "";
} else
glue = "";
modelContent.replace(eolOffset, bolOffset - eolOffset, glue);
editorAdaptor.setPosition(editorAdaptor.getPosition().setModelOffset(eolOffset), true);
}
}
|
diff --git a/src/java-common/org/xins/common/ant/UppercaseTask.java b/src/java-common/org/xins/common/ant/UppercaseTask.java
index b6d5897dc..6d886c428 100644
--- a/src/java-common/org/xins/common/ant/UppercaseTask.java
+++ b/src/java-common/org/xins/common/ant/UppercaseTask.java
@@ -1,85 +1,85 @@
/*
* $Id$
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.ant;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
/**
* Apache Ant task that uppercase a text. Note that hyphens '-' are
* translated to underscores '_'.
*
* @version $Revision$ $Date$
* @author <a href="mailto:[email protected]">Anthony Goubard</a>
*
* @since XINS 1.1.0
*/
public class UppercaseTask extends Task {
/**
* Name of the property to store the uppercase value in.
*/
private String _propertyName;
/**
* The text that has to be set in uppercase.
*/
private String _text;
/**
* Sets the name of the property.
*
* @param newPropertyName
* the name of the property to store the uppercase value.
*/
public void setProperty(String newPropertyName) {
_propertyName = newPropertyName;
}
/**
* Sets the text to be set in uppercase.
*
* @param text
* the text that has to be set in uppercase.
*/
public void setText(String text) {
_text = text;
}
/**
* Called by the project to let the task do its work.
*
* @throws BuildException
* if something goes wrong with the build.
*/
public void execute() throws BuildException {
if (_propertyName == null) {
throw new BuildException("A property value needs to be specified.");
}
if (_text == null) {
- throw new BuildException("A property value needs to be specified.");
+ throw new BuildException("A text value needs to be specified.");
}
if (getProject().getUserProperty(_propertyName) != null) {
String message = "Override ignored for property \""
+ _propertyName
+ "\".";
log(message, Project.MSG_VERBOSE);
return;
}
String uppercase = _text.toUpperCase();
uppercase = uppercase.replace('-', '_');
uppercase = uppercase.replace('.', '_');
getProject().setUserProperty(_propertyName, uppercase);
}
}
| true | true | public void execute() throws BuildException {
if (_propertyName == null) {
throw new BuildException("A property value needs to be specified.");
}
if (_text == null) {
throw new BuildException("A property value needs to be specified.");
}
if (getProject().getUserProperty(_propertyName) != null) {
String message = "Override ignored for property \""
+ _propertyName
+ "\".";
log(message, Project.MSG_VERBOSE);
return;
}
String uppercase = _text.toUpperCase();
uppercase = uppercase.replace('-', '_');
uppercase = uppercase.replace('.', '_');
getProject().setUserProperty(_propertyName, uppercase);
}
| public void execute() throws BuildException {
if (_propertyName == null) {
throw new BuildException("A property value needs to be specified.");
}
if (_text == null) {
throw new BuildException("A text value needs to be specified.");
}
if (getProject().getUserProperty(_propertyName) != null) {
String message = "Override ignored for property \""
+ _propertyName
+ "\".";
log(message, Project.MSG_VERBOSE);
return;
}
String uppercase = _text.toUpperCase();
uppercase = uppercase.replace('-', '_');
uppercase = uppercase.replace('.', '_');
getProject().setUserProperty(_propertyName, uppercase);
}
|
diff --git a/src/controller/UserController.java b/src/controller/UserController.java
index 96e7882..5ab7be8 100644
--- a/src/controller/UserController.java
+++ b/src/controller/UserController.java
@@ -1,170 +1,171 @@
package controller;
import hash.HashCalculator;
import infra.UserSession;
import java.util.ArrayList;
import interceptor.annotations.Admin;
import model.User;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.com.caelum.vraptor.validator.Validations;
import dao.UserDao;
@Resource
public class UserController {
private final Result result;
private final UserDao dao;
private final UserSession userSession;
private final Validator validator;
public UserController(Result result, Validator validator, UserDao dao, UserSession userSession) {
this.userSession = userSession;
this.result = result;
this.dao = dao;
this.validator = validator;
}
@Path("/usuarios/cadastrar/")
public void userForm() {
result.include("specialties", dao.listSpecialty());
}
@Path("/login/")
public void loginForm() {
}
@Path("/logout/")
public void logout() {
userSession.logout();
result.redirectTo(IndexController.class).index();
}
@Post
@Path("/login/autenticar/")
public void authenticate(String login, String password) {
User user = dao.getUser(login);
if (user != null) {
HashCalculator encryption = new HashCalculator(password);
password = encryption.getValue();
if (user.getPassword().equals(password) && user.isActive()) {
userSession.login(user);
result.redirectTo(IndexController.class).index();
} else if (!user.isActive()){
result.include("notAuthenticated", "Usuário com cadastro não confirmado. Verifique seu e-mail.");
result.redirectTo(UserController.class).loginForm();
}
else {
result.include("notAuthenticated", "Senha incorreta.");
result.redirectTo(UserController.class).loginForm();
}
} else {
result.include("notFound", "Usuário não cadastrado no sistema.");
result.redirectTo(UserController.class).loginForm();
}
}
@Path("/usuarios/salvar/")
public void save(User user, ArrayList<Long> specialties_ids) {
validateUser(user);
user.setActive(false);
user.setCertified(false);
user.setPasswordFromRawString(user.getPassword());
dao.save(user, specialties_ids);
result.redirectTo(EmailConfirmationController.class).createAndSendEmailConfirmation(user, null);
}
@Path("/usuarios/editar/{userId}/")
public void userEditForm(long userId){
result.include("user",dao.getUser(userId));
result.include("specialties", dao.listSpecialty());
}
@Path("/usuarios/atualizacao/")
public void saveEdit(User user, ArrayList<Long> specialties_ids) {
copyUnchangeableFields(user);
validateProfile(user);
User userByEmail = dao.getUserByEmail(user.getEmail());
- // o e-mail mudou e é novo
+ // o e-mail mudou e nao existia no bd
if (userByEmail == null) {
user.setActive(false);
dao.edit(user, specialties_ids);
userSession.logout();
result.redirectTo(EmailConfirmationController.class).
createAndSendEmailConfirmation(user, "Sua conta foi editada com sucesso," +
" verifique a sua caixa de mensagens para confirmar a mudança do seu email.");
}
else {
// o e-mail não mudou
if (userByEmail.getId() == user.getId()) {
+ user.setActive(true);
dao.edit(user, specialties_ids);
result.redirectTo(IndexController.class).index();
}
- // o e-mail mudou e não é novo
+ // o e-mail mudou e existia no bd
else {
validator.add(new ValidationMessage("user.email", "email.ja.existente"));
validator.onErrorRedirectTo(this).userEditForm(user.getId());
}
}
}
private void copyUnchangeableFields(User user) {
user.setPassword(userSession.getLoggedUser().getPassword());
user.setRole(userSession.getLoggedUser().getRole());
user.setLogin(userSession.getLoggedUser().getLogin());
user.setId(userSession.getLoggedUser().getId());
}
@Path("/usuarios/{userId}/")
public void detail(long userId) {
result.include("user", dao.getUser(userId));
}
@Path("/usuarios/listar/")
public void list(){
result.include("user",dao.listUser());
}
private void validateProfile(final User user) {
validator.checking(new Validations() {{
that(!user.getEmail().isEmpty(), "user.email", "email.obrigatorio");
that(user.getEmail().split("@").length == 2, "user.email", "email.invalido");
}});
validator.onErrorRedirectTo(this).userForm();
}
private void validateUser(final User user) {
validateProfile(user);
validator.checking(new Validations() {{
that(!user.getLogin().isEmpty(), "user", "login.obrigatorio");
that(!user.getPassword().isEmpty(), "user.password", "senha.obrigatoria");
that(user.getPassword().length() >= 6, "user.password", "senha.menor.que.6.caracteres");
that(dao.getUser(user.getLogin()) == null, "user.login", "usuario.ja.existente");
that(dao.getUserByEmail(user.getEmail()) == null, "user.email", "email.ja.existente");
}
});
validator.onErrorRedirectTo(this).userForm();
}
@Admin
@Path("/usuario/certificado/{userId}")
public void certify(Long userId) {
User user = dao.getUser(userId);
user.setCertified(!user.isCertified());
dao.updateUser(user);
result.redirectTo(UserController.class).detail(userId);
}
}
| false | true | public void saveEdit(User user, ArrayList<Long> specialties_ids) {
copyUnchangeableFields(user);
validateProfile(user);
User userByEmail = dao.getUserByEmail(user.getEmail());
// o e-mail mudou e é novo
if (userByEmail == null) {
user.setActive(false);
dao.edit(user, specialties_ids);
userSession.logout();
result.redirectTo(EmailConfirmationController.class).
createAndSendEmailConfirmation(user, "Sua conta foi editada com sucesso," +
" verifique a sua caixa de mensagens para confirmar a mudança do seu email.");
}
else {
// o e-mail não mudou
if (userByEmail.getId() == user.getId()) {
dao.edit(user, specialties_ids);
result.redirectTo(IndexController.class).index();
}
// o e-mail mudou e não é novo
else {
validator.add(new ValidationMessage("user.email", "email.ja.existente"));
validator.onErrorRedirectTo(this).userEditForm(user.getId());
}
}
}
| public void saveEdit(User user, ArrayList<Long> specialties_ids) {
copyUnchangeableFields(user);
validateProfile(user);
User userByEmail = dao.getUserByEmail(user.getEmail());
// o e-mail mudou e nao existia no bd
if (userByEmail == null) {
user.setActive(false);
dao.edit(user, specialties_ids);
userSession.logout();
result.redirectTo(EmailConfirmationController.class).
createAndSendEmailConfirmation(user, "Sua conta foi editada com sucesso," +
" verifique a sua caixa de mensagens para confirmar a mudança do seu email.");
}
else {
// o e-mail não mudou
if (userByEmail.getId() == user.getId()) {
user.setActive(true);
dao.edit(user, specialties_ids);
result.redirectTo(IndexController.class).index();
}
// o e-mail mudou e existia no bd
else {
validator.add(new ValidationMessage("user.email", "email.ja.existente"));
validator.onErrorRedirectTo(this).userEditForm(user.getId());
}
}
}
|
diff --git a/src/org/openstreetmap/josm/plugins/notes/NotesLayer.java b/src/org/openstreetmap/josm/plugins/notes/NotesLayer.java
index 2e3233c..a7ebd1a 100644
--- a/src/org/openstreetmap/josm/plugins/notes/NotesLayer.java
+++ b/src/org/openstreetmap/josm/plugins/notes/NotesLayer.java
@@ -1,287 +1,287 @@
/* Copyright (c) 2013, Ian Dees
* 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. Neither the name of the project 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 OWNER 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 org.openstreetmap.josm.plugins.notes;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.ImageObserver;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JToolTip;
import org.apache.commons.lang.StringEscapeUtils;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.RenameLayerAction;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
import org.openstreetmap.josm.gui.MapView;
import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.plugins.notes.Note.Comment;
import org.openstreetmap.josm.plugins.notes.gui.NotesDialog;
import org.openstreetmap.josm.tools.ColorHelper;
public class NotesLayer extends Layer implements MouseListener {
private List<Note> data;
private List<Note> selection = new ArrayList<Note>(1);
private JToolTip tooltip = new JToolTip();
private static ImageIcon iconError = NotesPlugin.loadIcon("open_note16.png");
private static ImageIcon iconValid = NotesPlugin.loadIcon("closed_note16.png");
private NotesDialog dialog;
public NotesLayer(List<Note> dataSet, String name, NotesDialog dialog) {
super(name);
this.data = dataSet;
this.dialog = dialog;
// if the map layer has been closed, while we are requesting the osb db,
// the mapframe is null, so we check that, before installing the mouse listener
if(Main.map != null && Main.map.mapView != null) {
Main.map.mapView.addMouseListener(this);
}
}
@Override
public Object getInfoComponent() {
return getToolTipText();
}
@Override
public Action[] getMenuEntries() {
return new Action[]{
LayerListDialog.getInstance().createShowHideLayerAction(),
LayerListDialog.getInstance().createDeleteLayerAction(),
SeparatorLayerAction.INSTANCE,
new RenameLayerAction(null, this),
SeparatorLayerAction.INSTANCE,
new LayerListPopup.InfoAction(this)};
}
@Override
public String getToolTipText() {
return tr("Displays OpenStreetMap notes");
}
@Override
public boolean isMergable(Layer other) {
return false;
}
@Override
public void mergeFrom(Layer from) {}
@Override
public void paint(Graphics2D g, MapView mv, Bounds bounds) {
// This loop renders all the bug icons
for (Note note : data) {
// don't paint deleted nodes
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconValid;
break;
case open:
icon = iconError;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.drawImage(icon.getImage(), p.x - (width / 2), p.y - height, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
return false;
}
});
}
if(selection == null)
return;
// This loop renders the selection border and tooltips so they get drawn
// on top of the bug icons
for (Note note : selection) {
// draw selection border
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconError;
break;
case open:
icon = iconValid;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.setColor(ColorHelper.html2color(Main.pref.get("color.selected")));
g.drawRect(p.x-(width/2), p.y-height, width-1, height-1);
// draw description
StringBuilder sb = new StringBuilder("<html>");
//sb.append(note.getFirstComment().getText());
List<Comment> comments = note.getComments();
String sep = "";
for(Comment comment: comments) {
String commentText = comment.getText();
//closing a note creates an empty comment that we don't want to show
if(commentText != null && commentText.trim().length() > 0) {
sb.append(sep);
String userName = comment.getUser().getName();
if(userName == null || userName.trim().length() == 0) {
userName = "<Anonymous>";
}
sb.append(userName);
sb.append(":<br/>");
String htmlText = StringEscapeUtils.escapeHtml(comment.getText());
htmlText = htmlText.replaceAll("\n", "<br/>");
sb.append(htmlText);
}
- sep = "<hr>";
+ sep = "<hr/>";
}
sb.append("</html>");
// draw description as a tooltip
tooltip.setTipText(sb.toString());
int tx = p.x + (width / 2) + 5;
int ty = p.y - height -1;
g.translate(tx, ty);
// This limits the width of the tooltip to 1/2 of the drawing
// area, which makes longer tooltips actually readable (they
// would disappear if scrolled too much to the right)
// Need to do this twice as otherwise getPreferredSize doesn't take
// the reduced width into account
for(int x = 0; x < 2; x++) {
Dimension d = tooltip.getUI().getPreferredSize(tooltip);
d.width = Math.min(d.width, (mv.getWidth()*1/2));
tooltip.setSize(d);
tooltip.paint(g);
}
g.translate(-tx, -ty);
}
}
@Override
public void visitBoundingBox(BoundingXYVisitor v) {}
@Override
public Icon getIcon() {
return NotesPlugin.loadIcon("open_note16.png");
}
private Note getNearestNode(Point p) {
double snapDistance = 10;
double minDistanceSq = Double.MAX_VALUE;
Note minPrimitive = null;
for (Note note : data) {
Point sp = Main.map.mapView.getPoint(note.getLatLon());
//move the hotpoint location up to the center of the displayed icon where people are likely to click
sp.setLocation(sp.getX(), sp.getY() - iconError.getIconHeight()/2);
double dist = p.distanceSq(sp);
if (minDistanceSq > dist && p.distance(sp) < snapDistance) {
minDistanceSq = p.distanceSq(sp);
minPrimitive = note;
}
// prefer already selected node when multiple nodes on one point
else if(minDistanceSq == dist && selection.contains(note) && !selection.contains(minPrimitive))
{
minPrimitive = note;
}
}
return minPrimitive;
}
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
Note n = getNearestNode(e.getPoint());
if(n != null && data.contains(n)) {
selection.add(n);
} else {
selection = new ArrayList<Note>();
}
dialog.setSelectedNote(n);
Main.map.mapView.repaint();
}
}
public void mousePressed(MouseEvent e) {
mayTriggerPopup(e);
}
public void mouseReleased(MouseEvent e) {
mayTriggerPopup(e);
}
private void mayTriggerPopup(MouseEvent e) {
if(e.isPopupTrigger()) {
Note n = getNearestNode(e.getPoint());
if(n != null && data.contains(n)) {
System.out.println("Popup goes here?");
//PopupFactory.createPopup(n, dialog).show(e.getComponent(), e.getX(), e.getY());
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public List<Note> getDataSet() {
return data;
}
public void replaceSelection(Note selected) {
selection.clear();
selection.add(selected);
Main.map.mapView.repaint();
}
}
| true | true | public void paint(Graphics2D g, MapView mv, Bounds bounds) {
// This loop renders all the bug icons
for (Note note : data) {
// don't paint deleted nodes
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconValid;
break;
case open:
icon = iconError;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.drawImage(icon.getImage(), p.x - (width / 2), p.y - height, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
return false;
}
});
}
if(selection == null)
return;
// This loop renders the selection border and tooltips so they get drawn
// on top of the bug icons
for (Note note : selection) {
// draw selection border
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconError;
break;
case open:
icon = iconValid;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.setColor(ColorHelper.html2color(Main.pref.get("color.selected")));
g.drawRect(p.x-(width/2), p.y-height, width-1, height-1);
// draw description
StringBuilder sb = new StringBuilder("<html>");
//sb.append(note.getFirstComment().getText());
List<Comment> comments = note.getComments();
String sep = "";
for(Comment comment: comments) {
String commentText = comment.getText();
//closing a note creates an empty comment that we don't want to show
if(commentText != null && commentText.trim().length() > 0) {
sb.append(sep);
String userName = comment.getUser().getName();
if(userName == null || userName.trim().length() == 0) {
userName = "<Anonymous>";
}
sb.append(userName);
sb.append(":<br/>");
String htmlText = StringEscapeUtils.escapeHtml(comment.getText());
htmlText = htmlText.replaceAll("\n", "<br/>");
sb.append(htmlText);
}
sep = "<hr>";
}
sb.append("</html>");
// draw description as a tooltip
tooltip.setTipText(sb.toString());
int tx = p.x + (width / 2) + 5;
int ty = p.y - height -1;
g.translate(tx, ty);
// This limits the width of the tooltip to 1/2 of the drawing
// area, which makes longer tooltips actually readable (they
// would disappear if scrolled too much to the right)
// Need to do this twice as otherwise getPreferredSize doesn't take
// the reduced width into account
for(int x = 0; x < 2; x++) {
Dimension d = tooltip.getUI().getPreferredSize(tooltip);
d.width = Math.min(d.width, (mv.getWidth()*1/2));
tooltip.setSize(d);
tooltip.paint(g);
}
g.translate(-tx, -ty);
}
}
| public void paint(Graphics2D g, MapView mv, Bounds bounds) {
// This loop renders all the bug icons
for (Note note : data) {
// don't paint deleted nodes
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconValid;
break;
case open:
icon = iconError;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.drawImage(icon.getImage(), p.x - (width / 2), p.y - height, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
return false;
}
});
}
if(selection == null)
return;
// This loop renders the selection border and tooltips so they get drawn
// on top of the bug icons
for (Note note : selection) {
// draw selection border
Point p = mv.getPoint(note.getLatLon());
ImageIcon icon = null;
switch(note.getState()) {
case closed:
icon = iconError;
break;
case open:
icon = iconValid;
break;
}
int width = icon.getIconWidth();
int height = icon.getIconHeight();
g.setColor(ColorHelper.html2color(Main.pref.get("color.selected")));
g.drawRect(p.x-(width/2), p.y-height, width-1, height-1);
// draw description
StringBuilder sb = new StringBuilder("<html>");
//sb.append(note.getFirstComment().getText());
List<Comment> comments = note.getComments();
String sep = "";
for(Comment comment: comments) {
String commentText = comment.getText();
//closing a note creates an empty comment that we don't want to show
if(commentText != null && commentText.trim().length() > 0) {
sb.append(sep);
String userName = comment.getUser().getName();
if(userName == null || userName.trim().length() == 0) {
userName = "<Anonymous>";
}
sb.append(userName);
sb.append(":<br/>");
String htmlText = StringEscapeUtils.escapeHtml(comment.getText());
htmlText = htmlText.replaceAll("\n", "<br/>");
sb.append(htmlText);
}
sep = "<hr/>";
}
sb.append("</html>");
// draw description as a tooltip
tooltip.setTipText(sb.toString());
int tx = p.x + (width / 2) + 5;
int ty = p.y - height -1;
g.translate(tx, ty);
// This limits the width of the tooltip to 1/2 of the drawing
// area, which makes longer tooltips actually readable (they
// would disappear if scrolled too much to the right)
// Need to do this twice as otherwise getPreferredSize doesn't take
// the reduced width into account
for(int x = 0; x < 2; x++) {
Dimension d = tooltip.getUI().getPreferredSize(tooltip);
d.width = Math.min(d.width, (mv.getWidth()*1/2));
tooltip.setSize(d);
tooltip.paint(g);
}
g.translate(-tx, -ty);
}
}
|
diff --git a/src/player/millitta/Generate/Generator.java b/src/player/millitta/Generate/Generator.java
index 38b9d1f..fa372d2 100644
--- a/src/player/millitta/Generate/Generator.java
+++ b/src/player/millitta/Generate/Generator.java
@@ -1,19 +1,19 @@
package player.millitta.Generate;
import player.millitta.Constants;
public class Generator implements Constants, algds.Constants {
private Generator() {
}
static public AbstractGenerator get(long board) {
if( (board & (1L << BIT_PHASE)) != 0 && (board & (1L << (BIT_PHASE+1))) != 0) { // Flugphase
- return new GeneratorMovingPhase(board);
+ return new GeneratorFlyingPhase(board);
} else if ((board & (1L << BIT_PHASE)) != 0) { // Setzphase
return new GeneratorPlacingPhase(board);
} else { // Zugphase
- return new GeneratorFlyingPhase(board);
+ return new GeneratorMovingPhase(board);
}
}
}
| false | true | static public AbstractGenerator get(long board) {
if( (board & (1L << BIT_PHASE)) != 0 && (board & (1L << (BIT_PHASE+1))) != 0) { // Flugphase
return new GeneratorMovingPhase(board);
} else if ((board & (1L << BIT_PHASE)) != 0) { // Setzphase
return new GeneratorPlacingPhase(board);
} else { // Zugphase
return new GeneratorFlyingPhase(board);
}
}
| static public AbstractGenerator get(long board) {
if( (board & (1L << BIT_PHASE)) != 0 && (board & (1L << (BIT_PHASE+1))) != 0) { // Flugphase
return new GeneratorFlyingPhase(board);
} else if ((board & (1L << BIT_PHASE)) != 0) { // Setzphase
return new GeneratorPlacingPhase(board);
} else { // Zugphase
return new GeneratorMovingPhase(board);
}
}
|
diff --git a/src-pos/com/openbravo/pos/forms/DataLogicSales.java b/src-pos/com/openbravo/pos/forms/DataLogicSales.java
index a49e6a8..3706c44 100644
--- a/src-pos/com/openbravo/pos/forms/DataLogicSales.java
+++ b/src-pos/com/openbravo/pos/forms/DataLogicSales.java
@@ -1,690 +1,690 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007 Openbravo, S.L.
// http://sourceforge.net/projects/openbravopos
//
// 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
package com.openbravo.pos.forms;
import com.openbravo.pos.ticket.CategoryInfo;
import com.openbravo.pos.ticket.ProductInfoExt;
import com.openbravo.pos.ticket.TaxInfo;
import com.openbravo.pos.ticket.TicketInfo;
import com.openbravo.pos.ticket.TicketLineInfo;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.openbravo.data.loader.*;
import com.openbravo.format.Formats;
import com.openbravo.basic.BasicException;
import com.openbravo.pos.customers.CustomerInfoExt;
import com.openbravo.pos.inventory.TaxCustCategoryInfo;
import com.openbravo.pos.inventory.LocationInfo;
import com.openbravo.pos.inventory.MovementReason;
import com.openbravo.pos.inventory.TaxCategoryInfo;
import com.openbravo.pos.mant.FloorsInfo;
import com.openbravo.pos.payment.PaymentInfo;
import com.openbravo.pos.payment.PaymentInfoTicket;
import com.openbravo.pos.ticket.TicketTaxInfo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
*
* @author adrianromero
*/
public abstract class DataLogicSales extends BeanFactoryDataSingle {
protected Session s;
protected Datas[] auxiliarDatas;
protected Datas[] stockdiaryDatas;
protected Datas[] productcatDatas;
protected Datas[] paymenttabledatas;
protected Datas[] stockdatas;
/** Creates a new instance of SentenceContainerGeneric */
public DataLogicSales() {
productcatDatas = new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING, Datas.BOOLEAN, Datas.BOOLEAN, Datas.DOUBLE, Datas.DOUBLE, Datas.STRING, Datas.STRING, Datas.IMAGE, Datas.DOUBLE, Datas.DOUBLE, Datas.BOOLEAN, Datas.INT, Datas.BYTES};
stockdiaryDatas = new Datas[] {Datas.STRING, Datas.TIMESTAMP, Datas.INT, Datas.STRING, Datas.STRING, Datas.DOUBLE, Datas.DOUBLE};
paymenttabledatas = new Datas[] {Datas.STRING, Datas.STRING, Datas.TIMESTAMP, Datas.STRING, Datas.STRING, Datas.DOUBLE};
stockdatas = new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING, Datas.DOUBLE, Datas.DOUBLE, Datas.DOUBLE};
auxiliarDatas = new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING};
}
public void init(Session s){
this.s = s;
}
// Utilidades de productos
public final ProductInfoExt getProductInfo(String id) throws BasicException {
return (ProductInfoExt) new PreparedSentence(s
, "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE P.ID = ?"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(ProductInfoExt.class)).find(id);
}
public final ProductInfoExt getProductInfoByCode(String sCode) throws BasicException {
return (ProductInfoExt) new PreparedSentence(s
, "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE P.CODE = ?"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(ProductInfoExt.class)).find(sCode);
}
public final ProductInfoExt getProductInfoByReference(String sReference) throws BasicException {
return (ProductInfoExt) new PreparedSentence(s
, "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE P.REFERENCE = ?"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(ProductInfoExt.class)).find(sReference);
}
// Catalogo de productos
public final List<CategoryInfo> getRootCategories() throws BasicException {
return new PreparedSentence(s
, "SELECT ID, NAME, IMAGE FROM CATEGORIES WHERE PARENTID IS NULL ORDER BY NAME"
, null
, new SerializerReadClass(CategoryInfo.class)).list();
}
public final List<CategoryInfo> getSubcategories(String category) throws BasicException {
return new PreparedSentence(s
, "SELECT ID, NAME, IMAGE FROM CATEGORIES WHERE PARENTID = ? ORDER BY NAME"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(CategoryInfo.class)).list(category);
}
public final List<ProductInfoExt> getProductCatalog(String category) throws BasicException {
return new PreparedSentence(s
, "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID LEFT OUTER JOIN CATEGORIES C ON P.CATEGORY = C.ID, PRODUCTS_CAT O WHERE P.ID = O.PRODUCT AND P.CATEGORY = ?" +
"ORDER BY C.NAME, O.CATORDER, P.REFERENCE"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(ProductInfoExt.class)).list(category);
}
public final List<ProductInfoExt> getProductComments(String id) throws BasicException {
return new PreparedSentence(s
, "SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID, PRODUCTS_CAT O, PRODUCTS_COM M WHERE P.ID = O.PRODUCT AND P.ID = M.PRODUCT2 AND M.PRODUCT = ? " +
"ORDER BY O.CATORDER, P.NAME"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(ProductInfoExt.class)).list(id);
}
// Products list
public final SentenceList getProductList() {
return new StaticSentence(s
, new QBFBuilder(
"SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE ?(QBF_FILTER) ORDER BY P.REFERENCE", new String[] {"P.NAME", "P.PRICEBUY", "P.PRICESELL", "P.CATEGORY", "P.CODE"})
, new SerializerWriteBasic(new Datas[] {Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.STRING})
, new SerializerReadClass(ProductInfoExt.class));
}
// Products list
public SentenceList getProductListNormal() {
return new StaticSentence(s
, new QBFBuilder(
"SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE P.ISCOM = FALSE AND ?(QBF_FILTER) ORDER BY P.REFERENCE", new String[] {"P.NAME", "P.PRICEBUY", "P.PRICESELL", "P.CATEGORY", "P.CODE"})
, new SerializerWriteBasic(new Datas[] {Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.STRING})
, new SerializerReadClass(ProductInfoExt.class));
}
//Auxiliar list for a filter
public SentenceList getProductListAuxiliar() {
return new StaticSentence(s
, new QBFBuilder(
"SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, TC.ID, TC.NAME, P.CATEGORY, P.IMAGE, P.ATTRIBUTES " +
"FROM PRODUCTS P LEFT OUTER JOIN TAXCATEGORIES TC ON P.TAXCAT = TC.ID WHERE P.ISCOM = TRUE AND ?(QBF_FILTER) ORDER BY P.REFERENCE", new String[] {"P.NAME", "P.PRICEBUY", "P.PRICESELL", "P.CATEGORY", "P.CODE"})
, new SerializerWriteBasic(new Datas[] {Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.STRING})
, new SerializerReadClass(ProductInfoExt.class));
}
// Listados para combo
public final SentenceList getTaxList() {
return new StaticSentence(s
, "SELECT ID, NAME, CATEGORY, CUSTCATEGORY, PARENTID, RATE, RATECASCADE, RATEORDER FROM TAXES ORDER BY NAME"
, null
, new SerializerReadClass(TaxInfo.class));
}
public final SentenceList getCategoriesList() {
return new StaticSentence(s
, "SELECT ID, NAME, IMAGE FROM CATEGORIES ORDER BY NAME"
, null
, new SerializerReadClass(CategoryInfo.class));
}
public final SentenceList getTaxCustCategoriesList() {
return new StaticSentence(s
, "SELECT ID, NAME FROM TAXCUSTCATEGORIES ORDER BY NAME"
, null
, new SerializerReadClass(TaxCustCategoryInfo.class));
}
public final SentenceList getTaxCategoriesList() {
return new StaticSentence(s
, "SELECT ID, NAME FROM TAXCATEGORIES ORDER BY NAME"
, null
, new SerializerReadClass(TaxCategoryInfo.class));
}
public final SentenceList getLocationsList() {
return new StaticSentence(s
, "SELECT ID, NAME, ADDRESS FROM LOCATIONS ORDER BY NAME"
, null
, new SerializerReadClass(LocationInfo.class));
}
public final SentenceList getFloorsList() {
return new StaticSentence(s
, "SELECT ID, NAME FROM FLOORS ORDER BY NAME"
, null
, new SerializerReadClass(FloorsInfo.class));
}
public CustomerInfoExt findCustomerExt(String card) throws BasicException {
return (CustomerInfoExt) new PreparedSentence(s
, "SELECT ID, TAXID, SEARCHKEY, NAME, CARD, TAXCATEGORY, NOTES, MAXDEBT, VISIBLE, CURDATE, CURDEBT" +
", FIRSTNAME, LASTNAME, EMAIL, PHONE, PHONE2, FAX" +
", ADDRESS, ADDRESS2, POSTAL, CITY, REGION, COUNTRY" +
" FROM CUSTOMERS WHERE CARD = ? AND VISIBLE = TRUE"
, SerializerWriteString.INSTANCE
, new CustomerExtRead()).find(card);
}
public CustomerInfoExt loadCustomerExt(String id) throws BasicException {
return (CustomerInfoExt) new PreparedSentence(s
, "SELECT ID, TAXID, SEARCHKEY, NAME, CARD, TAXCATEGORY, NOTES, MAXDEBT, VISIBLE, CURDATE, CURDEBT" +
", FIRSTNAME, LASTNAME, EMAIL, PHONE, PHONE2, FAX" +
", ADDRESS, ADDRESS2, POSTAL, CITY, REGION, COUNTRY" +
" FROM CUSTOMERS WHERE ID = ?"
, SerializerWriteString.INSTANCE
, new CustomerExtRead()).find(id);
}
public final boolean isCashActive(String id) throws BasicException {
return new PreparedSentence(s,
"SELECT MONEY FROM CLOSEDCASH WHERE DATEEND IS NULL AND MONEY = ?",
SerializerWriteString.INSTANCE,
SerializerReadString.INSTANCE).find(id)
!= null;
}
public final TicketInfo loadTicket(final int tickettype, final int ticketid) throws BasicException {
TicketInfo ticket = (TicketInfo) new PreparedSentence(s
, "SELECT T.ID, T.TICKETTYPE, T.TICKETID, R.DATENEW, R.MONEY, R.ATTRIBUTES, P.ID, P.NAME, T.CUSTOMER FROM RECEIPTS R JOIN TICKETS T ON R.ID = T.ID LEFT OUTER JOIN PEOPLE P ON T.PERSON = P.ID WHERE T.TICKETTYPE = ? AND T.TICKETID = ?"
, SerializerWriteParams.INSTANCE
, new SerializerReadClass(TicketInfo.class))
.find(new DataParams() { public void writeValues() throws BasicException {
setInt(1, tickettype);
setInt(2, ticketid);
}});
if (ticket != null) {
String customerid = ticket.getCustomerId();
ticket.setCustomer(customerid == null
? null
: loadCustomerExt(customerid));
ticket.setLines(new PreparedSentence(s
, "SELECT L.TICKET, L.LINE, L.PRODUCT, L.UNITS, L.PRICE, T.ID, T.NAME, T.CATEGORY, T.CUSTCATEGORY, T.PARENTID, T.RATE, T.RATECASCADE, T.RATEORDER, L.ATTRIBUTES " +
"FROM TICKETLINES L, TAXES T WHERE L.TAXID = T.ID AND L.TICKET = ? ORDER BY L.LINE"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(TicketLineInfo.class)).list(ticket.getId()));
ticket.setPayments(new PreparedSentence(s
, "SELECT PAYMENT, TOTAL, TRANSID FROM PAYMENTS WHERE RECEIPT = ?"
, SerializerWriteString.INSTANCE
, new SerializerReadClass(PaymentInfoTicket.class)).list(ticket.getId()));
}
return ticket;
}
public final void saveTicket(final TicketInfo ticket, final String location) throws BasicException {
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
// Set Receipt Id
if (ticket.getTicketId() == 0) {
switch (ticket.getTicketType()) {
case TicketInfo.RECEIPT_NORMAL:
ticket.setTicketId(getNextTicketIndex().intValue());
break;
case TicketInfo.RECEIPT_REFUND:
ticket.setTicketId(getNextTicketRefundIndex().intValue());
break;
case TicketInfo.RECEIPT_PAYMENT:
ticket.setTicketId(getNextTicketPaymentIndex().intValue());
break;
default:
throw new BasicException();
}
}
// new receipt
new PreparedSentence(s
, "INSERT INTO RECEIPTS (ID, MONEY, DATENEW, ATTRIBUTES) VALUES (?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setString(2, ticket.getActiveCash());
setTimestamp(3, ticket.getDate());
try {
ByteArrayOutputStream o = new ByteArrayOutputStream();
ticket.getProperties().storeToXML(o, AppLocal.APP_NAME, "UTF-8");
setBytes(4, o.toByteArray());
} catch (IOException e) {
setBytes(4, null);
}
}});
// new ticket
new PreparedSentence(s
, "INSERT INTO TICKETS (ID, TICKETTYPE, TICKETID, PERSON, CUSTOMER) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setInt(2, ticket.getTicketType());
setInt(3, ticket.getTicketId());
setString(4, ticket.getUser().getId());
setString(5, ticket.getCustomerId());
}});
SentenceExec ticketlineinsert = new PreparedSentence(s
, "INSERT INTO TICKETLINES (TICKET, LINE, PRODUCT, UNITS, PRICE, TAXID, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?)"
, SerializerWriteBuilder.INSTANCE);
for (TicketLineInfo l : ticket.getLines()) {
ticketlineinsert.exec(l);
if (l.getProductID() != null) {
// update the stock
getStockDiaryInsert().exec(new Object[] {
UUID.randomUUID().toString(),
ticket.getDate(),
l.getMultiply() < 0.0
? MovementReason.IN_REFUND.getKey()
: MovementReason.OUT_SALE.getKey(),
location,
l.getProductID(),
new Double(-l.getMultiply()),
new Double(l.getPrice())
});
}
}
SentenceExec paymentinsert = new PreparedSentence(s
, "INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL, TRANSID, RETURNMSG) VALUES (?, ?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
for (final PaymentInfo p : ticket.getPayments()) {
paymentinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, p.getName());
setDouble(4, p.getTotal());
setString(5, ticket.getTransactionID());
- setString(6, ticket.getReturnMessage());
+ setBytes(6, (byte[]) Formats.BYTEA.parseValue(ticket.getReturnMessage()));
}});
if ("debt".equals(p.getName()) || "debtpaid".equals(p.getName())) {
// udate customer fields...
ticket.getCustomer().updateCurDebt(p.getTotal(), ticket.getDate());
// save customer fields...
getDebtUpdate().exec(new DataParams() { public void writeValues() throws BasicException {
setDouble(1, ticket.getCustomer().getCurdebt());
setTimestamp(2, ticket.getCustomer().getCurdate());
setString(3, ticket.getCustomer().getId());
}});
}
}
SentenceExec taxlinesinsert = new PreparedSentence(s
, "INSERT INTO TAXLINES (ID, RECEIPT, TAXID, BASE, AMOUNT) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
if (ticket.getTaxes() != null) {
for (final TicketTaxInfo tickettax: ticket.getTaxes()) {
taxlinesinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, tickettax.getTaxInfo().getId());
setDouble(4, tickettax.getSubTotal());
setDouble(5, tickettax.getTax());
}});
}
}
return null;
}
};
t.execute();
}
public final void deleteTicket(final TicketInfo ticket, final String location) throws BasicException {
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
// update the inventory
Date d = new Date();
for (int i = 0; i < ticket.getLinesCount(); i++) {
if (ticket.getLine(i).getProductID() != null) {
// Hay que actualizar el stock si el hay producto
getStockDiaryInsert().exec( new Object[] {
UUID.randomUUID().toString(),
d,
ticket.getLine(i).getMultiply() >= 0.0
? MovementReason.IN_REFUND.getKey()
: MovementReason.OUT_SALE.getKey(),
location,
ticket.getLine(i).getProductID(),
new Double(ticket.getLine(i).getMultiply()),
new Double(ticket.getLine(i).getPrice())
});
}
}
// update customer debts
for (PaymentInfo p : ticket.getPayments()) {
if ("debt".equals(p.getName()) || "debtpaid".equals(p.getName())) {
// udate customer fields...
ticket.getCustomer().updateCurDebt(-p.getTotal(), ticket.getDate());
// save customer fields...
getDebtUpdate().exec(new DataParams() { public void writeValues() throws BasicException {
setDouble(1, ticket.getCustomer().getCurdebt());
setTimestamp(2, ticket.getCustomer().getCurdate());
setString(3, ticket.getCustomer().getId());
}});
}
}
// and delete the receipt
new StaticSentence(s
, "DELETE FROM PAYMENTS WHERE RECEIPT = ?"
, SerializerWriteString.INSTANCE).exec(ticket.getId());
new StaticSentence(s
, "DELETE FROM TICKETLINES WHERE TICKET = ?"
, SerializerWriteString.INSTANCE).exec(ticket.getId());
new StaticSentence(s
, "DELETE FROM TICKETS WHERE ID = ?"
, SerializerWriteString.INSTANCE).exec(ticket.getId());
new StaticSentence(s
, "DELETE FROM RECEIPTS WHERE ID = ?"
, SerializerWriteString.INSTANCE).exec(ticket.getId());
return null;
}
};
t.execute();
}
public abstract Integer getNextTicketIndex() throws BasicException;
public abstract Integer getNextTicketRefundIndex() throws BasicException;
public abstract Integer getNextTicketPaymentIndex() throws BasicException;
public abstract SentenceList getProductCatQBF();
public final SentenceExec getProductCatInsert() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
Object[] values = (Object[]) params;
int i = new PreparedSentence(s
, "INSERT INTO PRODUCTS (ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, CATEGORY, TAXCAT, IMAGE, STOCKCOST, STOCKVOLUME, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
, new SerializerWriteBasicExt(productcatDatas, new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15})).exec(params);
if (i > 0 && ((Boolean)values[13]).booleanValue()) {
return new PreparedSentence(s
, "INSERT INTO PRODUCTS_CAT (PRODUCT, CATORDER) VALUES (?, ?)"
, new SerializerWriteBasicExt(productcatDatas, new int[] {0, 14})).exec(params);
} else {
return i;
}
}
};
}
public final SentenceExec getProductCatUpdate() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
Object[] values = (Object[]) params;
int i = new PreparedSentence(s
, "UPDATE PRODUCTS SET ID = ?, REFERENCE = ?, CODE = ?, NAME = ?, ISCOM = ?, ISSCALE = ?, PRICEBUY = ?, PRICESELL = ?, CATEGORY = ?, TAXCAT = ?, IMAGE = ?, STOCKCOST = ?, STOCKVOLUME = ?, ATTRIBUTES = ? WHERE ID = ?"
, new SerializerWriteBasicExt(productcatDatas, new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 0})).exec(params);
if (i > 0) {
if (((Boolean)values[13]).booleanValue()) {
if (new PreparedSentence(s
, "UPDATE PRODUCTS_CAT SET CATORDER = ? WHERE PRODUCT = ?"
, new SerializerWriteBasicExt(productcatDatas, new int[] {14, 0})).exec(params) == 0) {
new PreparedSentence(s
, "INSERT INTO PRODUCTS_CAT (PRODUCT, CATORDER) VALUES (?, ?)"
, new SerializerWriteBasicExt(productcatDatas, new int[] {0, 14})).exec(params);
}
} else {
new PreparedSentence(s
, "DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ?"
, new SerializerWriteBasicExt(productcatDatas, new int[] {0})).exec(params);
}
}
return i;
}
};
}
public final SentenceExec getProductCatDelete() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
new PreparedSentence(s
, "DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ?"
, new SerializerWriteBasicExt(productcatDatas, new int[] {0})).exec(params);
return new PreparedSentence(s
, "DELETE FROM PRODUCTS WHERE ID = ?"
, new SerializerWriteBasicExt(productcatDatas, new int[] {0})).exec(params);
}
};
}
public final SentenceExec getDebtUpdate() {
return new PreparedSentence(s
, "UPDATE CUSTOMERS SET CURDEBT = ?, CURDATE = ? WHERE ID = ?"
, SerializerWriteParams.INSTANCE);
}
public final SentenceExec getStockDiaryInsert() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
if (new PreparedSentence(s
, "UPDATE STOCKCURRENT SET UNITS = (UNITS + ?) WHERE LOCATION = ? AND PRODUCT = ?"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {5, 3, 4})).exec(params) == 0) {
new PreparedSentence(s
, "INSERT INTO STOCKCURRENT (LOCATION, PRODUCT, UNITS) VALUES (?, ?, ?)"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {3, 4, 5})).exec(params);
}
return new PreparedSentence(s
, "INSERT INTO STOCKDIARY (ID, DATENEW, REASON, LOCATION, PRODUCT, UNITS, PRICE) VALUES (?, ?, ?, ?, ?, ?, ?)"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {0, 1, 2, 3, 4, 5, 6})).exec(params);
}
};
}
public final SentenceExec getStockDiaryDelete() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
if (new PreparedSentence(s
, "UPDATE STOCKCURRENT SET UNITS = (UNITS - ?) WHERE LOCATION = ? AND PRODUCT = ?"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {5, 3, 4})).exec(params) == 0) {
new PreparedSentence(s
, "INSERT INTO STOCKCURRENT (LOCATION, PRODUCT, UNITS) VALUES (?, ?, -(?))"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {3, 4, 5})).exec(params);
}
return new PreparedSentence(s
, "DELETE FROM STOCKDIARY WHERE ID = ?"
, new SerializerWriteBasicExt(stockdiaryDatas, new int[] {0})).exec(params);
}
};
}
public final SentenceExec getPaymentMovementInsert() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
new PreparedSentence(s
, "INSERT INTO RECEIPTS (ID, MONEY, DATENEW) VALUES (?, ?, ?)"
, new SerializerWriteBasicExt(paymenttabledatas, new int[] {0, 1, 2})).exec(params);
return new PreparedSentence(s
, "INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL) VALUES (?, ?, ?, ?)"
, new SerializerWriteBasicExt(paymenttabledatas, new int[] {3, 0, 4, 5})).exec(params);
}
};
}
public final SentenceExec getPaymentMovementDelete() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
new PreparedSentence(s
, "DELETE FROM PAYMENTS WHERE ID = ?"
, new SerializerWriteBasicExt(paymenttabledatas, new int[] {3})).exec(params);
return new PreparedSentence(s
, "DELETE FROM RECEIPTS WHERE ID = ?"
, new SerializerWriteBasicExt(paymenttabledatas, new int[] {0})).exec(params);
}
};
}
public final double findProductStock(String id, String warehouse) throws BasicException {
PreparedSentence p = new PreparedSentence(s, "SELECT UNITS FROM STOCKCURRENT WHERE PRODUCT=? AND LOCATION=?"
, new SerializerWriteBasic(new Datas[]{ Datas.STRING, Datas.STRING})
, SerializerReadDouble.INSTANCE);
Double d = (Double) p.find(new Object[]{id, warehouse});
return d == null ? 0.0 : d.doubleValue();
}
public final SentenceList getProductStock() {
return new PreparedSentence (s
, "SELECT L.ID, L.NAME, ?, COALESCE(S.UNITS, 0.0), S.STOCKSECURITY, S.STOCKMAXIMUM " +
"FROM LOCATIONS L LEFT OUTER JOIN (" +
"SELECT PRODUCT, LOCATION, STOCKSECURITY, STOCKMAXIMUM, UNITS FROM STOCKCURRENT WHERE PRODUCT = ?) S " +
"ON L.ID = S.LOCATION"
, new SerializerWriteBasicExt(productcatDatas, new int[]{0, 0})
, new SerializerReadBasic(stockdatas));
}
public final SentenceExec getStockUpdate() {
return new SentenceExecTransaction(s) {
public int execInTransaction(Object params) throws BasicException {
if (new PreparedSentence(s
, "UPDATE STOCKCURRENT SET STOCKSECURITY = ?, STOCKMAXIMUM = ? WHERE LOCATION = ? AND PRODUCT = ?"
, new SerializerWriteBasicExt(stockdatas, new int[] {4, 5, 0, 2})).exec(params) == 0) {
return new PreparedSentence(s
, "INSERT INTO STOCKCURRENT(LOCATION, PRODUCT, UNITS, STOCKSECURITY, STOCKMAXIMUM) VALUES (?, ?, 0.0, ?, ?)"
, new SerializerWriteBasicExt(stockdatas, new int[] {0, 2, 4, 5})).exec(params);
} else {
return 1;
}
}
};
}
public final SentenceExec getCatalogCategoryAdd() {
return new StaticSentence(s
, "INSERT INTO PRODUCTS_CAT(PRODUCT, CATORDER) SELECT ID, NULL FROM PRODUCTS WHERE CATEGORY = ?"
, SerializerWriteString.INSTANCE);
}
public final SentenceExec getCatalogCategoryDel() {
return new StaticSentence(s
, "DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ANY (SELECT ID FROM PRODUCTS WHERE CATEGORY = ?)"
, SerializerWriteString.INSTANCE);
}
public final TableDefinition getTableCategories() {
return new TableDefinition(s,
"CATEGORIES"
, new String[] {"ID", "NAME", "PARENTID", "IMAGE"}
, new String[] {"ID", AppLocal.getIntString("Label.Name"), "", AppLocal.getIntString("label.image")}
, new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING, Datas.IMAGE}
, new Formats[] {Formats.STRING, Formats.STRING, Formats.STRING, Formats.NULL}
, new int[] {0}
);
}
public final TableDefinition getTableTaxes() {
return new TableDefinition(s,
"TAXES"
, new String[] {"ID", "NAME", "CATEGORY", "CUSTCATEGORY", "PARENTID", "RATE", "RATECASCADE", "RATEORDER"}
, new String[] {"ID", AppLocal.getIntString("Label.Name"), AppLocal.getIntString("label.taxcategory"), AppLocal.getIntString("label.custtaxcategory"), AppLocal.getIntString("label.taxparent"), AppLocal.getIntString("label.dutyrate"), AppLocal.getIntString("label.cascade"), AppLocal.getIntString("label.order")}
, new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING, Datas.DOUBLE, Datas.BOOLEAN, Datas.INT}
, new Formats[] {Formats.STRING, Formats.STRING, Formats.STRING, Formats.STRING, Formats.STRING, Formats.PERCENT, Formats.BOOLEAN, Formats.INT}
, new int[] {0}
);
}
public final TableDefinition getTableTaxCustCategories() {
return new TableDefinition(s,
"TAXCUSTCATEGORIES"
, new String[] {"ID", "NAME"}
, new String[] {"ID", AppLocal.getIntString("Label.Name")}
, new Datas[] {Datas.STRING, Datas.STRING}
, new Formats[] {Formats.STRING, Formats.STRING}
, new int[] {0}
);
}
public final TableDefinition getTableTaxCategories() {
return new TableDefinition(s,
"TAXCATEGORIES"
, new String[] {"ID", "NAME"}
, new String[] {"ID", AppLocal.getIntString("Label.Name")}
, new Datas[] {Datas.STRING, Datas.STRING}
, new Formats[] {Formats.STRING, Formats.STRING}
, new int[] {0}
);
}
public final TableDefinition getTableLocations() {
return new TableDefinition(s,
"LOCATIONS"
, new String[] {"ID", "NAME", "ADDRESS"}
, new String[] {"ID", AppLocal.getIntString("label.locationname"), AppLocal.getIntString("label.locationaddress")}
, new Datas[] {Datas.STRING, Datas.STRING, Datas.STRING}
, new Formats[] {Formats.STRING, Formats.STRING, Formats.STRING}
, new int[] {0}
);
}
protected static class CustomerExtRead implements SerializerRead {
public Object readValues(DataRead dr) throws BasicException {
CustomerInfoExt c = new CustomerInfoExt(dr.getString(1));
c.setTaxid(dr.getString(2));
c.setSearchkey(dr.getString(3));
c.setName(dr.getString(4));
c.setCard(dr.getString(5));
c.setTaxCustomerID(dr.getString(6));
c.setNotes(dr.getString(7));
c.setMaxdebt(dr.getDouble(8));
c.setVisible(dr.getBoolean(9).booleanValue());
c.setCurdate(dr.getTimestamp(10));
c.setCurdebt(dr.getDouble(11));
c.setFirstname(dr.getString(12));
c.setLastname(dr.getString(13));
c.setEmail(dr.getString(14));
c.setPhone(dr.getString(15));
c.setPhone2(dr.getString(16));
c.setFax(dr.getString(17));
c.setAddress(dr.getString(18));
c.setAddress2(dr.getString(19));
c.setPostal(dr.getString(20));
c.setCity(dr.getString(21));
c.setRegion(dr.getString(22));
c.setCountry(dr.getString(23));
return c;
}
}
}
| true | true | public final void saveTicket(final TicketInfo ticket, final String location) throws BasicException {
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
// Set Receipt Id
if (ticket.getTicketId() == 0) {
switch (ticket.getTicketType()) {
case TicketInfo.RECEIPT_NORMAL:
ticket.setTicketId(getNextTicketIndex().intValue());
break;
case TicketInfo.RECEIPT_REFUND:
ticket.setTicketId(getNextTicketRefundIndex().intValue());
break;
case TicketInfo.RECEIPT_PAYMENT:
ticket.setTicketId(getNextTicketPaymentIndex().intValue());
break;
default:
throw new BasicException();
}
}
// new receipt
new PreparedSentence(s
, "INSERT INTO RECEIPTS (ID, MONEY, DATENEW, ATTRIBUTES) VALUES (?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setString(2, ticket.getActiveCash());
setTimestamp(3, ticket.getDate());
try {
ByteArrayOutputStream o = new ByteArrayOutputStream();
ticket.getProperties().storeToXML(o, AppLocal.APP_NAME, "UTF-8");
setBytes(4, o.toByteArray());
} catch (IOException e) {
setBytes(4, null);
}
}});
// new ticket
new PreparedSentence(s
, "INSERT INTO TICKETS (ID, TICKETTYPE, TICKETID, PERSON, CUSTOMER) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setInt(2, ticket.getTicketType());
setInt(3, ticket.getTicketId());
setString(4, ticket.getUser().getId());
setString(5, ticket.getCustomerId());
}});
SentenceExec ticketlineinsert = new PreparedSentence(s
, "INSERT INTO TICKETLINES (TICKET, LINE, PRODUCT, UNITS, PRICE, TAXID, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?)"
, SerializerWriteBuilder.INSTANCE);
for (TicketLineInfo l : ticket.getLines()) {
ticketlineinsert.exec(l);
if (l.getProductID() != null) {
// update the stock
getStockDiaryInsert().exec(new Object[] {
UUID.randomUUID().toString(),
ticket.getDate(),
l.getMultiply() < 0.0
? MovementReason.IN_REFUND.getKey()
: MovementReason.OUT_SALE.getKey(),
location,
l.getProductID(),
new Double(-l.getMultiply()),
new Double(l.getPrice())
});
}
}
SentenceExec paymentinsert = new PreparedSentence(s
, "INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL, TRANSID, RETURNMSG) VALUES (?, ?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
for (final PaymentInfo p : ticket.getPayments()) {
paymentinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, p.getName());
setDouble(4, p.getTotal());
setString(5, ticket.getTransactionID());
setString(6, ticket.getReturnMessage());
}});
if ("debt".equals(p.getName()) || "debtpaid".equals(p.getName())) {
// udate customer fields...
ticket.getCustomer().updateCurDebt(p.getTotal(), ticket.getDate());
// save customer fields...
getDebtUpdate().exec(new DataParams() { public void writeValues() throws BasicException {
setDouble(1, ticket.getCustomer().getCurdebt());
setTimestamp(2, ticket.getCustomer().getCurdate());
setString(3, ticket.getCustomer().getId());
}});
}
}
SentenceExec taxlinesinsert = new PreparedSentence(s
, "INSERT INTO TAXLINES (ID, RECEIPT, TAXID, BASE, AMOUNT) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
if (ticket.getTaxes() != null) {
for (final TicketTaxInfo tickettax: ticket.getTaxes()) {
taxlinesinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, tickettax.getTaxInfo().getId());
setDouble(4, tickettax.getSubTotal());
setDouble(5, tickettax.getTax());
}});
}
}
return null;
}
};
t.execute();
}
| public final void saveTicket(final TicketInfo ticket, final String location) throws BasicException {
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
// Set Receipt Id
if (ticket.getTicketId() == 0) {
switch (ticket.getTicketType()) {
case TicketInfo.RECEIPT_NORMAL:
ticket.setTicketId(getNextTicketIndex().intValue());
break;
case TicketInfo.RECEIPT_REFUND:
ticket.setTicketId(getNextTicketRefundIndex().intValue());
break;
case TicketInfo.RECEIPT_PAYMENT:
ticket.setTicketId(getNextTicketPaymentIndex().intValue());
break;
default:
throw new BasicException();
}
}
// new receipt
new PreparedSentence(s
, "INSERT INTO RECEIPTS (ID, MONEY, DATENEW, ATTRIBUTES) VALUES (?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setString(2, ticket.getActiveCash());
setTimestamp(3, ticket.getDate());
try {
ByteArrayOutputStream o = new ByteArrayOutputStream();
ticket.getProperties().storeToXML(o, AppLocal.APP_NAME, "UTF-8");
setBytes(4, o.toByteArray());
} catch (IOException e) {
setBytes(4, null);
}
}});
// new ticket
new PreparedSentence(s
, "INSERT INTO TICKETS (ID, TICKETTYPE, TICKETID, PERSON, CUSTOMER) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE
).exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, ticket.getId());
setInt(2, ticket.getTicketType());
setInt(3, ticket.getTicketId());
setString(4, ticket.getUser().getId());
setString(5, ticket.getCustomerId());
}});
SentenceExec ticketlineinsert = new PreparedSentence(s
, "INSERT INTO TICKETLINES (TICKET, LINE, PRODUCT, UNITS, PRICE, TAXID, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?)"
, SerializerWriteBuilder.INSTANCE);
for (TicketLineInfo l : ticket.getLines()) {
ticketlineinsert.exec(l);
if (l.getProductID() != null) {
// update the stock
getStockDiaryInsert().exec(new Object[] {
UUID.randomUUID().toString(),
ticket.getDate(),
l.getMultiply() < 0.0
? MovementReason.IN_REFUND.getKey()
: MovementReason.OUT_SALE.getKey(),
location,
l.getProductID(),
new Double(-l.getMultiply()),
new Double(l.getPrice())
});
}
}
SentenceExec paymentinsert = new PreparedSentence(s
, "INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL, TRANSID, RETURNMSG) VALUES (?, ?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
for (final PaymentInfo p : ticket.getPayments()) {
paymentinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, p.getName());
setDouble(4, p.getTotal());
setString(5, ticket.getTransactionID());
setBytes(6, (byte[]) Formats.BYTEA.parseValue(ticket.getReturnMessage()));
}});
if ("debt".equals(p.getName()) || "debtpaid".equals(p.getName())) {
// udate customer fields...
ticket.getCustomer().updateCurDebt(p.getTotal(), ticket.getDate());
// save customer fields...
getDebtUpdate().exec(new DataParams() { public void writeValues() throws BasicException {
setDouble(1, ticket.getCustomer().getCurdebt());
setTimestamp(2, ticket.getCustomer().getCurdate());
setString(3, ticket.getCustomer().getId());
}});
}
}
SentenceExec taxlinesinsert = new PreparedSentence(s
, "INSERT INTO TAXLINES (ID, RECEIPT, TAXID, BASE, AMOUNT) VALUES (?, ?, ?, ?, ?)"
, SerializerWriteParams.INSTANCE);
if (ticket.getTaxes() != null) {
for (final TicketTaxInfo tickettax: ticket.getTaxes()) {
taxlinesinsert.exec(new DataParams() { public void writeValues() throws BasicException {
setString(1, UUID.randomUUID().toString());
setString(2, ticket.getId());
setString(3, tickettax.getTaxInfo().getId());
setDouble(4, tickettax.getSubTotal());
setDouble(5, tickettax.getTax());
}});
}
}
return null;
}
};
t.execute();
}
|
diff --git a/work-impl/src/main/java/org/cytoscape/work/internal/sync/SyncTunableHandler.java b/work-impl/src/main/java/org/cytoscape/work/internal/sync/SyncTunableHandler.java
index 55ad7fac8..7af577409 100644
--- a/work-impl/src/main/java/org/cytoscape/work/internal/sync/SyncTunableHandler.java
+++ b/work-impl/src/main/java/org/cytoscape/work/internal/sync/SyncTunableHandler.java
@@ -1,34 +1,36 @@
package org.cytoscape.work.internal.sync;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import org.cytoscape.work.AbstractTunableHandler;
import org.cytoscape.work.Tunable;
public class SyncTunableHandler extends AbstractTunableHandler {
private Map<String, Object> valueMap;
public SyncTunableHandler(final Field field, final Object instance, final Tunable tunable) {
super(field, instance, tunable);
}
public SyncTunableHandler(final Method getter, final Method setter, final Object instance, final Tunable tunable) {
super(getter, setter, instance, tunable);
}
@Override
public void handle() {
try {
- setValue(valueMap.get(getName()));
+ if (valueMap.containsKey(getName())) {
+ setValue(valueMap.get(getName()));
+ }
} catch (Exception e) {
throw new RuntimeException("Exception setting tunable value.", e);
}
}
public void setValueMap(final Map<String, Object> valueMap) {
this.valueMap = valueMap;
}
}
| true | true | public void handle() {
try {
setValue(valueMap.get(getName()));
} catch (Exception e) {
throw new RuntimeException("Exception setting tunable value.", e);
}
}
| public void handle() {
try {
if (valueMap.containsKey(getName())) {
setValue(valueMap.get(getName()));
}
} catch (Exception e) {
throw new RuntimeException("Exception setting tunable value.", e);
}
}
|
diff --git a/src/min3d/parser/ParseObjectData.java b/src/min3d/parser/ParseObjectData.java
index fca4915..721354f 100644
--- a/src/min3d/parser/ParseObjectData.java
+++ b/src/min3d/parser/ParseObjectData.java
@@ -1,148 +1,148 @@
package min3d.parser;
import java.util.ArrayList;
import android.util.Log;
import min3d.Min3d;
import min3d.Shared;
import min3d.animation.AnimationObject3d;
import min3d.animation.KeyFrame;
import min3d.core.Object3d;
import min3d.parser.AParser.BitmapAsset;
import min3d.parser.AParser.TextureAtlas;
import min3d.vos.Color4;
import min3d.vos.Face;
import min3d.vos.Number3d;
import min3d.vos.Uv;
public class ParseObjectData {
protected ArrayList<ParseObjectFace> faces;
protected int numFaces = 0;
protected ArrayList<Number3d> vertices;
protected ArrayList<Uv> texCoords;
protected ArrayList<Number3d> normals;
public String name;
public ParseObjectData()
{
this.vertices = new ArrayList<Number3d>();
this.texCoords = new ArrayList<Uv>();
this.normals = new ArrayList<Number3d>();
this.name = "";
faces = new ArrayList<ParseObjectFace>();
}
public ParseObjectData(ArrayList<Number3d> vertices, ArrayList<Uv> texCoords, ArrayList<Number3d> normals)
{
this.vertices = vertices;
this.texCoords = texCoords;
this.normals = normals;
this.name = "";
faces = new ArrayList<ParseObjectFace>();
}
public AnimationObject3d getParsedObject(TextureAtlas textureAtlas, KeyFrame[] frames)
{
AnimationObject3d obj = new AnimationObject3d(numFaces * 3, numFaces, frames.length);
obj.name(name);
obj.setFrames(frames);
parseObject(obj, textureAtlas);
return obj;
}
public Object3d getParsedObject(TextureAtlas textureAtlas) {
Object3d obj = new Object3d(numFaces * 3, numFaces);
obj.name(name);
parseObject(obj, textureAtlas);
return obj;
}
private void parseObject(Object3d obj, TextureAtlas textureAtlas)
{
int numFaces = faces.size();
int faceIndex = 0;
boolean hasBitmaps = textureAtlas.hasBitmaps();
for (int i = 0; i < numFaces; i++) {
ParseObjectFace face = faces.get(i);
BitmapAsset ba = textureAtlas
.getBitmapAssetByName(face.materialKey);
for (int j = 0; j < face.faceLength; j++) {
Number3d newVertex = vertices.get(face.v[j]);
Uv newUv = face.hasuv ? texCoords.get(face.uv[j]).clone()
: new Uv();
Number3d newNormal = face.hasn ? normals.get(face.n[j])
: new Number3d();
Color4 newColor = new Color4(255, 255, 0, 255);
- if(hasBitmaps)
+ if(hasBitmaps && (ba != null))
{
newUv.u = ba.uOffset + newUv.u * ba.uScale;
newUv.v = ba.vOffset + ((newUv.v + 1) * ba.vScale) - 1;
}
obj.vertices().addVertex(newVertex, newUv, newNormal, newColor);
}
if (face.faceLength == 3) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 2));
} else if (face.faceLength == 4) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 3));
obj.faces().add(
new Face(faceIndex + 1, faceIndex + 2, faceIndex + 3));
}
faceIndex += face.faceLength;
}
if (hasBitmaps) {
obj.textures().addById(textureAtlas.getId());
}
cleanup();
}
public void calculateFaceNormal(ParseObjectFace face)
{
Number3d v1 = vertices.get(face.v[0]);
Number3d v2 = vertices.get(face.v[1]);
Number3d v3 = vertices.get(face.v[2]);
Number3d vector1 = Number3d.subtract(v2, v1);
Number3d vector2 = Number3d.subtract(v3, v1);
Number3d normal = new Number3d();
normal.x = (vector1.y * vector2.z) - (vector1.z * vector2.y);
normal.y = -((vector2.z * vector1.x) - (vector2.x * vector1.z));
normal.z = (vector1.x * vector2.y) - (vector1.y * vector2.x);
double normFactor = Math.sqrt((normal.x * normal.x) + (normal.y * normal.y) + (normal.z * normal.z));
normal.x /= normFactor;
normal.y /= normFactor;
normal.z /= normFactor;
normals.add(normal);
int index = normals.size() - 1;
face.n = new int[3];
face.n[0] = index;
face.n[1] = index;
face.n[2] = index;
face.hasn = true;
}
protected void cleanup() {
faces.clear();
}
}
| true | true | private void parseObject(Object3d obj, TextureAtlas textureAtlas)
{
int numFaces = faces.size();
int faceIndex = 0;
boolean hasBitmaps = textureAtlas.hasBitmaps();
for (int i = 0; i < numFaces; i++) {
ParseObjectFace face = faces.get(i);
BitmapAsset ba = textureAtlas
.getBitmapAssetByName(face.materialKey);
for (int j = 0; j < face.faceLength; j++) {
Number3d newVertex = vertices.get(face.v[j]);
Uv newUv = face.hasuv ? texCoords.get(face.uv[j]).clone()
: new Uv();
Number3d newNormal = face.hasn ? normals.get(face.n[j])
: new Number3d();
Color4 newColor = new Color4(255, 255, 0, 255);
if(hasBitmaps)
{
newUv.u = ba.uOffset + newUv.u * ba.uScale;
newUv.v = ba.vOffset + ((newUv.v + 1) * ba.vScale) - 1;
}
obj.vertices().addVertex(newVertex, newUv, newNormal, newColor);
}
if (face.faceLength == 3) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 2));
} else if (face.faceLength == 4) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 3));
obj.faces().add(
new Face(faceIndex + 1, faceIndex + 2, faceIndex + 3));
}
faceIndex += face.faceLength;
}
if (hasBitmaps) {
obj.textures().addById(textureAtlas.getId());
}
cleanup();
}
| private void parseObject(Object3d obj, TextureAtlas textureAtlas)
{
int numFaces = faces.size();
int faceIndex = 0;
boolean hasBitmaps = textureAtlas.hasBitmaps();
for (int i = 0; i < numFaces; i++) {
ParseObjectFace face = faces.get(i);
BitmapAsset ba = textureAtlas
.getBitmapAssetByName(face.materialKey);
for (int j = 0; j < face.faceLength; j++) {
Number3d newVertex = vertices.get(face.v[j]);
Uv newUv = face.hasuv ? texCoords.get(face.uv[j]).clone()
: new Uv();
Number3d newNormal = face.hasn ? normals.get(face.n[j])
: new Number3d();
Color4 newColor = new Color4(255, 255, 0, 255);
if(hasBitmaps && (ba != null))
{
newUv.u = ba.uOffset + newUv.u * ba.uScale;
newUv.v = ba.vOffset + ((newUv.v + 1) * ba.vScale) - 1;
}
obj.vertices().addVertex(newVertex, newUv, newNormal, newColor);
}
if (face.faceLength == 3) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 2));
} else if (face.faceLength == 4) {
obj.faces().add(
new Face(faceIndex, faceIndex + 1, faceIndex + 3));
obj.faces().add(
new Face(faceIndex + 1, faceIndex + 2, faceIndex + 3));
}
faceIndex += face.faceLength;
}
if (hasBitmaps) {
obj.textures().addById(textureAtlas.getId());
}
cleanup();
}
|
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskStudentView.java b/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskStudentView.java
index 7c2f0fc..e1d745f 100644
--- a/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskStudentView.java
+++ b/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskStudentView.java
@@ -1,233 +1,233 @@
/*
* Copyright 2009 - 2011 Sven Strickroth <[email protected]>
*
* This file is part of the SubmissionInterface.
*
* SubmissionInterface is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tuclausthal.submissioninterface.servlets.view;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory;
import de.tuclausthal.submissioninterface.persistence.dao.PointGivenDAOIf;
import de.tuclausthal.submissioninterface.persistence.dao.TestCountDAOIf;
import de.tuclausthal.submissioninterface.persistence.datamodel.PointCategory;
import de.tuclausthal.submissioninterface.persistence.datamodel.PointGiven;
import de.tuclausthal.submissioninterface.persistence.datamodel.Points.PointStatus;
import de.tuclausthal.submissioninterface.persistence.datamodel.Submission;
import de.tuclausthal.submissioninterface.persistence.datamodel.Task;
import de.tuclausthal.submissioninterface.persistence.datamodel.Test;
import de.tuclausthal.submissioninterface.servlets.RequestAdapter;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
import de.tuclausthal.submissioninterface.util.Util;
/**
* View-Servlet for displaying a task in student view
* @author Sven Strickroth
*/
public class ShowTaskStudentView extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Session session = RequestAdapter.getSession(request);
Task task = (Task) request.getAttribute("task");
Submission submission = (Submission) request.getAttribute("submission");
List<String> submittedFiles = (List<String>) request.getAttribute("submittedFiles");
List<String> advisorFiles = (List<String>) request.getAttribute("advisorFiles");
template.printTemplateHeader(task);
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td id=taskdescription>" + Util.makeCleanHTML(task.getDescription()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getStart().toLocaleString()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getDeadline().toLocaleString()));
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
out.println("</tr>");
if (advisorFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Hinterlegte Dateien:</th>");
out.println("<td><ul class=taskfiles>");
for (String file : advisorFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<li><a href=\"" + response.encodeURL("DownloadTaskFile/" + file + "?taskid=" + task.getTaskid()) + "\">Download " + Util.escapeHTML(file) + "</a></li>");
}
out.println("</ul></td>");
out.println("</tr>");
}
out.println("</table>");
if (submission != null) {
out.println("<p><h2>Informationen zu meiner Abgabe:</h2>");
out.println("<table class=border>");
if (submission.getSubmitters().size() > 1) {
out.println("<tr>");
out.println("<th>Bearbeitet von:</th>");
out.println("<td>");
out.println(submission.getSubmitterNames().replaceAll("; ", "<br>"));
out.println("</td>");
out.println("</tr>");
}
if (submission.getLastModified() != null) {
out.println("<tr>");
out.println("<th>Letzte �nderung:</th>");
out.println("<td>");
out.println(Util.escapeHTML(submission.getLastModified().toLocaleString()));
out.println("</td>");
out.println("</tr>");
}
if (submittedFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Besteht aus:</th>");
out.println("<td>");
for (String file : submittedFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<a target=\"_blank\" href=\"" + response.encodeURL("ShowFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">" + Util.escapeHTML(file) + "</a>");
if (task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println(" (<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DeleteFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">l�schen</a>)");
}
out.println("<br>");
}
out.println("</td>");
out.println("</tr>");
}
if (task.getShowPoints().before(Util.correctTimezone(new Date())) && submission.getPoints() != null) {
out.println("<tr>");
out.println("<th>Bewertung:</th>");
out.println("<td>");
if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN.ordinal()) {
if (task.getPointCategories().size() > 0) {
PointGivenDAOIf pointGivenDAO = DAOFactory.PointGivenDAOIf(session);
Iterator<PointGiven> pointsGivenIterator = pointGivenDAO.getPointsGivenOfSubmission(submission).iterator();
PointGiven lastPointGiven = null;
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
}
out.println("<ul>");
for (PointCategory category : task.getPointCategories()) {
int issuedPoints = 0;
while (lastPointGiven != null && category.getPointcatid() > lastPointGiven.getCategory().getPointcatid()) {
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
} else {
lastPointGiven = null;
break;
}
}
if (lastPointGiven != null && category.getPointcatid() == lastPointGiven.getCategory().getPointcatid()) {
issuedPoints = lastPointGiven.getPoints();
} else if (category.isOptional()) {
continue;
}
out.println("<li>" + Util.showPoints(issuedPoints) + "/" + Util.showPoints(category.getPoints()) + " " + Util.escapeHTML(category.getDescription()) + "</li>");
}
out.println("</ul>");
} else {
out.println(Util.showPoints(submission.getPoints().getPointsByStatus()) + " von " + Util.showPoints(task.getMaxPoints()) + " Punkt(e)");
}
} else if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN_FAILED.ordinal()) {
- out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", Abhahme nicht bestanden");
+ out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", Abnahme nicht bestanden");
} else {
out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", nicht abgenommen");
}
out.println("<p>Vergeben von: <a href=\"mailto:" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullEmail()) + "\">" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullName()) + "</a></p>");
out.println("</td>");
out.println("</tr>");
if (submission.getPoints().getPublicComment() != null && !"".equals(submission.getPoints().getPublicComment())) {
out.println("<tr>");
out.println("<th>Kommentar:</th>");
out.println("<td>");
out.println(Util.textToHTML(submission.getPoints().getPublicComment()));
out.println("</td>");
out.println("</tr>");
}
}
out.println("</table>");
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
if (submittedFiles.size() > 0) {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe erweitern</a></div");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
List<Test> tests = DAOFactory.TestDAOIf(session).getStudentTests(task);
TestCountDAOIf testCountDAO = DAOFactory.TestCountDAOIf(session);
if (submittedFiles.size() > 0 && tests.size() > 0 && task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println("<p><h2>M�gliche Tests:</h2>");
out.println("<table class=border>");
for (Test test : tests) {
out.println("<tr>");
out.println("<th>" + Util.escapeHTML(test.getTestTitle()) + "</th>");
out.println("<td>");
out.println(Util.textToHTML(test.getTestDescription()));
out.println("</td>");
out.println("<td>");
if (testCountDAO.canStillRunXTimes(test, submission) > 0) {
out.println("<a href=\"" + response.encodeURL("PerformTest?sid=" + submission.getSubmissionid() + "&testid=" + test.getId()) + "\">Test ausf�hren</a>");
} else {
out.println("Limit erreicht");
}
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
} else {
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
template.printTemplateFooter();
}
}
| true | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Session session = RequestAdapter.getSession(request);
Task task = (Task) request.getAttribute("task");
Submission submission = (Submission) request.getAttribute("submission");
List<String> submittedFiles = (List<String>) request.getAttribute("submittedFiles");
List<String> advisorFiles = (List<String>) request.getAttribute("advisorFiles");
template.printTemplateHeader(task);
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td id=taskdescription>" + Util.makeCleanHTML(task.getDescription()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getStart().toLocaleString()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getDeadline().toLocaleString()));
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
out.println("</tr>");
if (advisorFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Hinterlegte Dateien:</th>");
out.println("<td><ul class=taskfiles>");
for (String file : advisorFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<li><a href=\"" + response.encodeURL("DownloadTaskFile/" + file + "?taskid=" + task.getTaskid()) + "\">Download " + Util.escapeHTML(file) + "</a></li>");
}
out.println("</ul></td>");
out.println("</tr>");
}
out.println("</table>");
if (submission != null) {
out.println("<p><h2>Informationen zu meiner Abgabe:</h2>");
out.println("<table class=border>");
if (submission.getSubmitters().size() > 1) {
out.println("<tr>");
out.println("<th>Bearbeitet von:</th>");
out.println("<td>");
out.println(submission.getSubmitterNames().replaceAll("; ", "<br>"));
out.println("</td>");
out.println("</tr>");
}
if (submission.getLastModified() != null) {
out.println("<tr>");
out.println("<th>Letzte �nderung:</th>");
out.println("<td>");
out.println(Util.escapeHTML(submission.getLastModified().toLocaleString()));
out.println("</td>");
out.println("</tr>");
}
if (submittedFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Besteht aus:</th>");
out.println("<td>");
for (String file : submittedFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<a target=\"_blank\" href=\"" + response.encodeURL("ShowFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">" + Util.escapeHTML(file) + "</a>");
if (task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println(" (<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DeleteFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">l�schen</a>)");
}
out.println("<br>");
}
out.println("</td>");
out.println("</tr>");
}
if (task.getShowPoints().before(Util.correctTimezone(new Date())) && submission.getPoints() != null) {
out.println("<tr>");
out.println("<th>Bewertung:</th>");
out.println("<td>");
if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN.ordinal()) {
if (task.getPointCategories().size() > 0) {
PointGivenDAOIf pointGivenDAO = DAOFactory.PointGivenDAOIf(session);
Iterator<PointGiven> pointsGivenIterator = pointGivenDAO.getPointsGivenOfSubmission(submission).iterator();
PointGiven lastPointGiven = null;
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
}
out.println("<ul>");
for (PointCategory category : task.getPointCategories()) {
int issuedPoints = 0;
while (lastPointGiven != null && category.getPointcatid() > lastPointGiven.getCategory().getPointcatid()) {
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
} else {
lastPointGiven = null;
break;
}
}
if (lastPointGiven != null && category.getPointcatid() == lastPointGiven.getCategory().getPointcatid()) {
issuedPoints = lastPointGiven.getPoints();
} else if (category.isOptional()) {
continue;
}
out.println("<li>" + Util.showPoints(issuedPoints) + "/" + Util.showPoints(category.getPoints()) + " " + Util.escapeHTML(category.getDescription()) + "</li>");
}
out.println("</ul>");
} else {
out.println(Util.showPoints(submission.getPoints().getPointsByStatus()) + " von " + Util.showPoints(task.getMaxPoints()) + " Punkt(e)");
}
} else if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN_FAILED.ordinal()) {
out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", Abhahme nicht bestanden");
} else {
out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", nicht abgenommen");
}
out.println("<p>Vergeben von: <a href=\"mailto:" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullEmail()) + "\">" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullName()) + "</a></p>");
out.println("</td>");
out.println("</tr>");
if (submission.getPoints().getPublicComment() != null && !"".equals(submission.getPoints().getPublicComment())) {
out.println("<tr>");
out.println("<th>Kommentar:</th>");
out.println("<td>");
out.println(Util.textToHTML(submission.getPoints().getPublicComment()));
out.println("</td>");
out.println("</tr>");
}
}
out.println("</table>");
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
if (submittedFiles.size() > 0) {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe erweitern</a></div");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
List<Test> tests = DAOFactory.TestDAOIf(session).getStudentTests(task);
TestCountDAOIf testCountDAO = DAOFactory.TestCountDAOIf(session);
if (submittedFiles.size() > 0 && tests.size() > 0 && task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println("<p><h2>M�gliche Tests:</h2>");
out.println("<table class=border>");
for (Test test : tests) {
out.println("<tr>");
out.println("<th>" + Util.escapeHTML(test.getTestTitle()) + "</th>");
out.println("<td>");
out.println(Util.textToHTML(test.getTestDescription()));
out.println("</td>");
out.println("<td>");
if (testCountDAO.canStillRunXTimes(test, submission) > 0) {
out.println("<a href=\"" + response.encodeURL("PerformTest?sid=" + submission.getSubmissionid() + "&testid=" + test.getId()) + "\">Test ausf�hren</a>");
} else {
out.println("Limit erreicht");
}
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
} else {
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
template.printTemplateFooter();
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Session session = RequestAdapter.getSession(request);
Task task = (Task) request.getAttribute("task");
Submission submission = (Submission) request.getAttribute("submission");
List<String> submittedFiles = (List<String>) request.getAttribute("submittedFiles");
List<String> advisorFiles = (List<String>) request.getAttribute("advisorFiles");
template.printTemplateHeader(task);
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td id=taskdescription>" + Util.makeCleanHTML(task.getDescription()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getStart().toLocaleString()) + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td>" + Util.escapeHTML(task.getDeadline().toLocaleString()));
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
out.println("</tr>");
if (advisorFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Hinterlegte Dateien:</th>");
out.println("<td><ul class=taskfiles>");
for (String file : advisorFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<li><a href=\"" + response.encodeURL("DownloadTaskFile/" + file + "?taskid=" + task.getTaskid()) + "\">Download " + Util.escapeHTML(file) + "</a></li>");
}
out.println("</ul></td>");
out.println("</tr>");
}
out.println("</table>");
if (submission != null) {
out.println("<p><h2>Informationen zu meiner Abgabe:</h2>");
out.println("<table class=border>");
if (submission.getSubmitters().size() > 1) {
out.println("<tr>");
out.println("<th>Bearbeitet von:</th>");
out.println("<td>");
out.println(submission.getSubmitterNames().replaceAll("; ", "<br>"));
out.println("</td>");
out.println("</tr>");
}
if (submission.getLastModified() != null) {
out.println("<tr>");
out.println("<th>Letzte �nderung:</th>");
out.println("<td>");
out.println(Util.escapeHTML(submission.getLastModified().toLocaleString()));
out.println("</td>");
out.println("</tr>");
}
if (submittedFiles.size() > 0) {
out.println("<tr>");
out.println("<th>Besteht aus:</th>");
out.println("<td>");
for (String file : submittedFiles) {
file = file.replace(System.getProperty("file.separator"), "/");
out.println("<a target=\"_blank\" href=\"" + response.encodeURL("ShowFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">" + Util.escapeHTML(file) + "</a>");
if (task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println(" (<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DeleteFile/" + file + "?sid=" + submission.getSubmissionid()) + "\">l�schen</a>)");
}
out.println("<br>");
}
out.println("</td>");
out.println("</tr>");
}
if (task.getShowPoints().before(Util.correctTimezone(new Date())) && submission.getPoints() != null) {
out.println("<tr>");
out.println("<th>Bewertung:</th>");
out.println("<td>");
if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN.ordinal()) {
if (task.getPointCategories().size() > 0) {
PointGivenDAOIf pointGivenDAO = DAOFactory.PointGivenDAOIf(session);
Iterator<PointGiven> pointsGivenIterator = pointGivenDAO.getPointsGivenOfSubmission(submission).iterator();
PointGiven lastPointGiven = null;
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
}
out.println("<ul>");
for (PointCategory category : task.getPointCategories()) {
int issuedPoints = 0;
while (lastPointGiven != null && category.getPointcatid() > lastPointGiven.getCategory().getPointcatid()) {
if (pointsGivenIterator.hasNext()) {
lastPointGiven = pointsGivenIterator.next();
} else {
lastPointGiven = null;
break;
}
}
if (lastPointGiven != null && category.getPointcatid() == lastPointGiven.getCategory().getPointcatid()) {
issuedPoints = lastPointGiven.getPoints();
} else if (category.isOptional()) {
continue;
}
out.println("<li>" + Util.showPoints(issuedPoints) + "/" + Util.showPoints(category.getPoints()) + " " + Util.escapeHTML(category.getDescription()) + "</li>");
}
out.println("</ul>");
} else {
out.println(Util.showPoints(submission.getPoints().getPointsByStatus()) + " von " + Util.showPoints(task.getMaxPoints()) + " Punkt(e)");
}
} else if (submission.getPoints().getPointStatus() == PointStatus.ABGENOMMEN_FAILED.ordinal()) {
out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", Abnahme nicht bestanden");
} else {
out.println("0 von " + Util.showPoints(task.getMaxPoints()) + ", nicht abgenommen");
}
out.println("<p>Vergeben von: <a href=\"mailto:" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullEmail()) + "\">" + Util.escapeHTML(submission.getPoints().getIssuedBy().getUser().getFullName()) + "</a></p>");
out.println("</td>");
out.println("</tr>");
if (submission.getPoints().getPublicComment() != null && !"".equals(submission.getPoints().getPublicComment())) {
out.println("<tr>");
out.println("<th>Kommentar:</th>");
out.println("<td>");
out.println(Util.textToHTML(submission.getPoints().getPublicComment()));
out.println("</td>");
out.println("</tr>");
}
}
out.println("</table>");
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
if (submittedFiles.size() > 0) {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe erweitern</a></div");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
List<Test> tests = DAOFactory.TestDAOIf(session).getStudentTests(task);
TestCountDAOIf testCountDAO = DAOFactory.TestCountDAOIf(session);
if (submittedFiles.size() > 0 && tests.size() > 0 && task.getDeadline().after(Util.correctTimezone(new Date()))) {
out.println("<p><h2>M�gliche Tests:</h2>");
out.println("<table class=border>");
for (Test test : tests) {
out.println("<tr>");
out.println("<th>" + Util.escapeHTML(test.getTestTitle()) + "</th>");
out.println("<td>");
out.println(Util.textToHTML(test.getTestDescription()));
out.println("</td>");
out.println("<td>");
if (testCountDAO.canStillRunXTimes(test, submission) > 0) {
out.println("<a href=\"" + response.encodeURL("PerformTest?sid=" + submission.getSubmissionid() + "&testid=" + test.getId()) + "\">Test ausf�hren</a>");
} else {
out.println("Limit erreicht");
}
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
} else {
out.println("<p>");
if ("-".equals(task.getFilenameRegexp()) && task.isShowTextArea() == false) {
out.println("<div class=mid>Keine Abgabe m�glich.</div>");
} else if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
out.println("<div class=mid>Keine Abgabe mehr m�glich.</div>");
} else {
out.println("<div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Abgabe starten</a></div");
}
}
template.printTemplateFooter();
}
|
diff --git a/Engine/src/main/MainFrame.java b/Engine/src/main/MainFrame.java
index 8f10d01..5e8705e 100644
--- a/Engine/src/main/MainFrame.java
+++ b/Engine/src/main/MainFrame.java
@@ -1,128 +1,128 @@
package main;
import static main.MatrixContainer.*;
import static math.Math.*;
import static org.lwjgl.opengl.GL11.*;
import java.io.*;
import importers.*;
import math.matrices.*;
import openGLCLInterfaces.openGL.shaders.*;
import org.lwjgl.input.*;
import org.lwjgl.opengl.*;
/**
* Main class, where update and draw happens.
*/
public class MainFrame {
private ShaderProgram basicShader;
private Camera camera;
private Model model;
/**
* Method to do initializing stuff.
*/
public void init() {
Mouse.setGrabbed(true);
Keyboard.enableRepeatEvents(false);
initOpenGL();
camera = new Camera(Matrix.vec3(), 180, 0);
try {
model = OBJLoader.loadModelFromOBJ("resources/models/tree.obj");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initializing OpenGL.
*/
private void initOpenGL() {
// set clear color to black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_TEXTURE_2D);
loadShaders();
}
/**
* Loads shaders from files and compiles them.
*/
private void loadShaders() {
basicShader = ShaderProgram.createBasicShader("/shaderFiles/vert.c", "/shaderFiles/frag.c");
}
/**
* Main update logic.
*
* @param delta
* The time passed from last update to this.
*/
public void update(int delta) {
Vector2 mouseMovement = MouseHelper.getMovement();
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
camera.move(-0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
- toRadians(camera.getYRotation() + 90), toRadians(camera.getPitch())));
+ toRadians(camera.getYRotation() + 90), 0));
}
if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
camera.move(0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
- toRadians(camera.getYRotation() + 90), toRadians(camera.getPitch())));
+ toRadians(camera.getYRotation() + 90), 0));
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
camera.setRotation(camera.getYRotation() + 0.1f * mouseMovement.getX(), camera.getPitch()
+ -0.1f * mouseMovement.getY());
if (camera.getPitch() < -90f) {
camera.setRotation(camera.getYRotation(), -90f);
}
if (camera.getPitch() > 90f) {
camera.setRotation(camera.getYRotation(), 90f);
}
if (camera.getYRotation() < -180f) {
camera.setRotation(360f + camera.getYRotation(), camera.getPitch());
}
if (camera.getYRotation() > 180f) {
camera.setRotation(camera.getYRotation() - 360f, camera.getPitch());
}
}
/**
* Draw to the screen
*/
public void draw() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, Display.getWidth(), Display.getHeight());
glDisable(GL_CULL_FACE);
camera.setup();
uploadMatrices();
basicShader.enable();
model.render();
// glBegin(GL_QUADS);
// glVertex3f(-10, -10, 10);
// glVertex3f(-10, 10, 10);
// glVertex3f(10, 10, 10);
// glVertex3f(10, -10, 10);
// glEnd();
basicShader.disable();
}
}
| false | true | public void update(int delta) {
Vector2 mouseMovement = MouseHelper.getMovement();
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
camera.move(-0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation() + 90), toRadians(camera.getPitch())));
}
if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
camera.move(0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation() + 90), toRadians(camera.getPitch())));
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
camera.setRotation(camera.getYRotation() + 0.1f * mouseMovement.getX(), camera.getPitch()
+ -0.1f * mouseMovement.getY());
if (camera.getPitch() < -90f) {
camera.setRotation(camera.getYRotation(), -90f);
}
if (camera.getPitch() > 90f) {
camera.setRotation(camera.getYRotation(), 90f);
}
if (camera.getYRotation() < -180f) {
camera.setRotation(360f + camera.getYRotation(), camera.getPitch());
}
if (camera.getYRotation() > 180f) {
camera.setRotation(camera.getYRotation() - 360f, camera.getPitch());
}
}
| public void update(int delta) {
Vector2 mouseMovement = MouseHelper.getMovement();
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
camera.move(-0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation() + 90), 0));
}
if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
camera.move(0.0001f, delta, camera.getViewVector());
}
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation() + 90), 0));
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
camera.move(-0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
camera.move(0.0001f, delta, Vector3.getDirectionFromRotation(
toRadians(camera.getYRotation()), toRadians(camera.getPitch() + 90)));
}
camera.setRotation(camera.getYRotation() + 0.1f * mouseMovement.getX(), camera.getPitch()
+ -0.1f * mouseMovement.getY());
if (camera.getPitch() < -90f) {
camera.setRotation(camera.getYRotation(), -90f);
}
if (camera.getPitch() > 90f) {
camera.setRotation(camera.getYRotation(), 90f);
}
if (camera.getYRotation() < -180f) {
camera.setRotation(360f + camera.getYRotation(), camera.getPitch());
}
if (camera.getYRotation() > 180f) {
camera.setRotation(camera.getYRotation() - 360f, camera.getPitch());
}
}
|
diff --git a/AssemblyCodeGenerator.java b/AssemblyCodeGenerator.java
index 07bc99c..3692e18 100644
--- a/AssemblyCodeGenerator.java
+++ b/AssemblyCodeGenerator.java
@@ -1,947 +1,952 @@
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class AssemblyCodeGenerator {
private final String COMPILER_IDENT = "WRC 1.0";
private int indent_level = 0;
private Stack<FuncSTO> currentFunc;
private Stack<Integer> stackPointer;
private Stack<StoPair> globalInitStack;
private Stack<String> stackIfLabel;
private Vector<StackRecord> stackValues;
// Error Messages
private static final String ERROR_IO_CLOSE = "Unable to close fileWriter";
private static final String ERROR_IO_CONSTRUCT = "Unable to construct FileWriter for file %s";
private static final String ERROR_IO_WRITE = "Unable to write to fileWriter";
// FileWriter
private FileWriter fileWriter;
// Output file header
private static final String FILE_HEADER =
"/*\n" +
" * Generated %s\n" +
" */\n\n";
private int str_count = 0;
private int float_count = 0;
private int ifLabel_count = 0;
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
public AssemblyCodeGenerator(String fileToWrite) {
try {
fileWriter = new FileWriter(fileToWrite);
// write fileHeader with date/time stamp
writeAssembly(FILE_HEADER, (new Date()).toString());
}
catch (IOException e) {
System.err.printf(ERROR_IO_CONSTRUCT, fileToWrite);
e.printStackTrace();
System.exit(1);
}
currentFunc = new Stack<FuncSTO>();
stackPointer = new Stack<Integer>();
globalInitStack = new Stack<StoPair>();
stackIfLabel = new Stack<String>();
stackValues = new Vector<StackRecord>();
}
//-------------------------------------------------------------------------
// setIndent
//-------------------------------------------------------------------------
public void decreaseIndent(int indent) {
indent_level = indent;
}
//-------------------------------------------------------------------------
// decreaseIndent
//-------------------------------------------------------------------------
public void decreaseIndent() {
if(indent_level > 0)
indent_level--;
}
//-------------------------------------------------------------------------
// increaseIndent
//-------------------------------------------------------------------------
public void increaseIndent() {
indent_level++;
}
//-------------------------------------------------------------------------
// dispose
//-------------------------------------------------------------------------
public void dispose() {
// Close the filewriter
try {
fileWriter.close();
}
catch (IOException e) {
System.err.println(ERROR_IO_CLOSE);
e.printStackTrace();
System.exit(1);
}
}
//-------------------------------------------------------------------------
// writeAssembly
//-------------------------------------------------------------------------
// params = String []
public void writeAssembly(String template, String ... params) {
StringBuilder asStmt = new StringBuilder();
// Indent current line
for (int i=0; i < indent_level; i++) {
asStmt.append(SparcInstr.INDENTOR);
}
asStmt.append(String.format(template, (Object[])params));
try {
fileWriter.write(asStmt.toString());
}
catch (IOException e) {
System.err.println(ERROR_IO_WRITE);
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
// String Utility Functions
//-------------------------------------------------------------------------
public String quoted(String str)
{
return "\"" + str + "\"";
}
public String bracket(String str)
{
return "[" + str + "]";
}
//-------------------------------------------------------------------------
// Other Utility Functions
//-------------------------------------------------------------------------
public String getNextOffset(int size)
{
Integer temp = stackPointer.pop();
temp = temp - size;
stackPointer.push(temp);
currentFunc.peek().addBytes(size);
return stackPointer.peek().toString();
}
public String getOffset()
{
return stackPointer.peek().toString();
}
//-------------------------------------------------------------------------
//
// Code Generation Functions
//
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// WriteComment
//-------------------------------------------------------------------------
public void writeComment(String comment)
{
// ! Comment
writeAssembly(SparcInstr.LINE, SparcInstr.COMMENT + " " + comment);
}
public void writeCommentHeader(String comment)
{
writeAssembly(SparcInstr.BLANK_LINE);
// !----Comment----
writeComment("----" + comment + "----");
}
public void writeStackValues()
{
writeCommentHeader("Stack Records");
writeComment("======================================");
for(StackRecord thisRecord: stackValues) {
writeAssembly(SparcInstr.LINE, SparcInstr.COMMENT + thisRecord.getFunction() + SparcInstr.SEPARATOR
+ thisRecord.getId() + SparcInstr.SEPARATOR + thisRecord.getLocation());
}
}
//-------------------------------------------------------------------------
// DoProgramStart
//-------------------------------------------------------------------------
public void DoProgramStart(String filename)
{
increaseIndent();
writeCommentHeader("Starting Program");
// .file "<filename>"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.FILE_DIR, quoted(filename));
// .ident <COMPILER_IDENT
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.IDENT_DIR, quoted(COMPILER_IDENT));
writeAssembly(SparcInstr.BLANK_LINE);
DoROPrintDefines();
MakeGlobalInitGuard();
stackPointer.push(new Integer(0));
currentFunc.push(new FuncSTO("global", new FuncPtrType(new VoidType(), false)));
}
//-------------------------------------------------------------------------
// DoProgramEnd
//-------------------------------------------------------------------------
public void DoProgramEnd()
{
writeStackValues();
}
//-------------------------------------------------------------------------
// DoROPrintDefines
//-------------------------------------------------------------------------
public void DoROPrintDefines()
{
// !----Default String Formatters----
writeCommentHeader("Default String Formatters");
// .section ".rodata"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.RODATA_SEC);
// _endl: .asciz "\n"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.ENDL, SparcInstr.ASCIZ_DIR, quoted("\\n"));
// _intFmt: .asciz "%d"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.INTFMT, SparcInstr.ASCIZ_DIR, quoted("%d"));
// _boolFmt: .asciz "%s"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.BOOLFMT, SparcInstr.ASCIZ_DIR, quoted("%s"));
// _boolT: .asciz "true"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.BOOLT, SparcInstr.ASCIZ_DIR, quoted("true"));
// _boolF: .asciz "false"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.BOOLF, SparcInstr.ASCIZ_DIR, quoted("false"));
// _strFmt: .asciz "%s"
writeAssembly(SparcInstr.RO_DEFINE, SparcInstr.STRFMT, SparcInstr.ASCIZ_DIR, quoted("%s"));
writeAssembly(SparcInstr.BLANK_LINE);
}
//-------------------------------------------------------------------------
// DoGlobalDecl
//-------------------------------------------------------------------------
public void DoGlobalDecl(STO varSto, STO valueSto)
{
// .global <id>
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.GLOBAL_DIR, varSto.getName());
// .section ".bss"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.BSS_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
decreaseIndent();
// <id>: .skip 4
writeAssembly(SparcInstr.GLOBAL_DEFINE, varSto.getName(), SparcInstr.SKIP_DIR, String.valueOf(4));
increaseIndent();
// Push these for later to initialize when main() starts
if(!valueSto.isNull())
globalInitStack.push(new StoPair(varSto, valueSto));
// set the base and offset to the sto
varSto.store(SparcInstr.REG_GLOBAL0, varSto.getName());
stackValues.addElement(new StackRecord("global", varSto.getName(), varSto.load()));
}
//-------------------------------------------------------------------------
// MakeGlobalInitGuard
//-------------------------------------------------------------------------
public void MakeGlobalInitGuard()
{
// !----Create _init for global init guard----
writeCommentHeader("Create _init for global init guard");
// .section ".bss"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.BSS_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, String.valueOf(4));
// _init: .skip 4
writeAssembly(SparcInstr.GLOBAL_DEFINE, "_init", SparcInstr.SKIP_DIR, String.valueOf(4));
writeAssembly(SparcInstr.BLANK_LINE);
}
//-------------------------------------------------------------------------
// DoGlobalInit
//-------------------------------------------------------------------------
public void DoGlobalInit()
{
// !----Initialize Globals----
writeCommentHeader("Initialize Globals");
// Do Init Guard
writeComment("Check if init is already done");
// set _init, %l0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, "_init", SparcInstr.REG_LOCAL0);
// ld [%l0], %l1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(SparcInstr.REG_LOCAL0), SparcInstr.REG_LOCAL1);
// cmp %l1, %g0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.CMP_OP, SparcInstr.REG_LOCAL1, SparcInstr.REG_GLOBAL0);
// bne _init_done ! Global initialization guard
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.BNE_OP, "_init_done");
// set 1, %l1 ! Branch delay slot
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, String.valueOf(1), SparcInstr.REG_LOCAL1);
writeComment("Set init flag to 1 now that we're about to do the init");
// st %l1, [%l0] ! Mark _init = 1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_LOCAL1, bracket(SparcInstr.REG_LOCAL0));
writeAssembly(SparcInstr.BLANK_LINE);
// Setup Stack iteration
Stack stk = new Stack();
StoPair stopair;
STO varSto;
STO valueSto;
stk.addAll(globalInitStack);
Collections.reverse(stk);
// Loop through all the initialization pairs on the stack
for(Enumeration<StoPair> e = stk.elements(); e.hasMoreElements(); ) {
stopair = e.nextElement();
varSto = stopair.getVarSto();
valueSto = stopair.getValueSto();
if(valueSto.isConst())
DoLiteral((ConstSTO) valueSto);
writeComment("Initializing: " + varSto.getName() + " = " + valueSto.getName());
// ld [<value>], %l1
LoadSto(valueSto, SparcInstr.REG_LOCAL1);
//writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(valueSto.load()), SparcInstr.REG_LOCAL1);
// set x, %l0
//writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(varSto.load()), SparcInstr.REG_LOCAL0);
// add %g0, %l0, %l0
//writeAssembly(SparcInstr.THREE_PARAM, SparcInstr.ADD_OP, SparcInstr.REG_GLOBAL0, SparcInstr.REG_LOCAL0, SparcInstr.REG_LOCAL0);
LoadStoAddr(varSto, SparcInstr.REG_LOCAL0);
// st %l1, [%l0]
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_LOCAL1, bracket(SparcInstr.REG_LOCAL0));
writeAssembly(SparcInstr.BLANK_LINE);
}
// _init_done:
decreaseIndent();
writeAssembly(SparcInstr.LABEL, "_init_done");
writeAssembly(SparcInstr.BLANK_LINE);
increaseIndent();
}
//-------------------------------------------------------------------------
// DoFuncStart
//-------------------------------------------------------------------------
public void DoFuncStart(FuncSTO funcSto)
{
currentFunc.push(funcSto);
stackPointer.push(0);
// !----Function: <funcName>----
writeCommentHeader("Function: " + funcSto.getName());
// .section ".text"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.TEXT_SEC);
// TODO: Is this always 4? Otherwise, calculate the value in general
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, String.valueOf(4));
// .global <funcName>
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.GLOBAL_DIR, funcSto.getName());
writeAssembly(SparcInstr.BLANK_LINE);
// Write the function label
decreaseIndent();
// <funcName>:
writeAssembly(SparcInstr.LABEL, funcSto.getName());
increaseIndent();
// Move the saved offset for this function into %g1 and then execute the save instruction that shifts the stack
// set SAVE.<funcName>, %g1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.SAVE_WORD + "." + funcSto.getName(), SparcInstr.REG_GLOBAL1);
// save %sp, %g1, %sp
writeAssembly(SparcInstr.THREE_PARAM, SparcInstr.SAVE_OP, SparcInstr.REG_STACK, SparcInstr.REG_GLOBAL1, SparcInstr.REG_STACK);
writeAssembly(SparcInstr.BLANK_LINE);
}
//-------------------------------------------------------------------------
// DoFuncFinish
//-------------------------------------------------------------------------
public void DoFuncFinish(FuncSTO funcSto)
{
// Perform return/restore
// TODO: Right now, two sets of ret/restore will be printed if the function did explicit "return"
writeAssembly(SparcInstr.BLANK_LINE);
// ret
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.RET_OP);
// restore
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.RESTORE_OP);
writeAssembly(SparcInstr.BLANK_LINE);
// Write the assembler directive to save the amount of bytes needed for the save operation
decreaseIndent();
// SAVE.<func> = -(92 + BytesOfLocalVarsAndTempStackSpaceNeeded) & -8
writeAssembly(SparcInstr.SAVE_FUNC, funcSto.getName(), String.valueOf(92), String.valueOf(funcSto.getLocalVarBytes()));
increaseIndent();
stackPointer.pop();
currentFunc.pop();
}
//-------------------------------------------------------------------------
// DoReturn
//-------------------------------------------------------------------------
public void DoReturn(FuncSTO funcSto, STO returnSto)
{
// Load the return value into the return register
if(!returnSto.getType().isVoid()) {
if(funcSto.getReturnByRef()) {
// TODO: Set the return value for return by reference
}
else {
// ld [<location>], %i0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(returnSto.load()), SparcInstr.REG_SET_RETURN);
}
}
// Perform return/restore
// ret
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.RET_OP);
// restore
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.RESTORE_OP);
}
//-------------------------------------------------------------------------
// DoCout
//-------------------------------------------------------------------------
public void DoCout(STO sto) {
// !----cout << <sto name>----
writeCommentHeader("cout << " + sto.getName());
if(sto.getType().isInt()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.INTFMT, SparcInstr.REG_ARG0);
// ld [<value>], %o1
LoadSto(sto, SparcInstr.REG_ARG1);
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isBool()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLFMT, SparcInstr.REG_ARG0);
// Set the condition STO into LOCAL0
LoadSto(sto, SparcInstr.REG_LOCAL0);
String ifLabel = ".ifL_" + ifLabel_count;
String elseLabel = ".elseL_" + ifLabel_count;
ifLabel_count++;
// If the condition is true, don't branch and load "true", if false, branch to end of if and load "false"
+ // value == 0
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.CMP_OP, SparcInstr.REG_LOCAL0, SparcInstr.REG_GLOBAL0, "Compare boolean value " + sto.getName() + " to 0");
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BE_OP, ifLabel, "If <cond> is true, don't branch, if false, branch");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// If Code: Load "true" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLT, SparcInstr.REG_ARG1);
// Branch to end of else block
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BA_OP, ifLabel, "Did if code, branch always to bottom of else");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// Print label
+ decreaseIndent();
writeAssembly(SparcInstr.LABEL, ifLabel);
+ increaseIndent();
// Else code: load "false" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLF, SparcInstr.REG_ARG1);
// Else done, print label
+ decreaseIndent();
writeAssembly(SparcInstr.LABEL, elseLabel);
+ increaseIndent();
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isFloat()) {
// ld [sto] %f0
LoadSto(sto, SparcInstr.REG_FLOAT0);
// call printFloat
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTFLOAT);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
// String literal
else if (sto.getType().isString()) {
// .section ".rodata"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.RODATA_SEC);
// str_(str_count): .asciz "string literal"
writeAssembly(SparcInstr.RO_DEFINE, ".str_"+str_count, SparcInstr.ASCIZ_DIR, quoted(sto.getName()));
// .section ".text"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.TEXT_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
// set _strFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set str_(str_count), %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, ".str_"+str_count, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// increment str count
str_count++;
}
// endl
else if (sto.getType().isVoid()) {
// set _strFmt %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set _endl, %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.ENDL, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
}
//-------------------------------------------------------------------------
// DoVarDecl
//-------------------------------------------------------------------------
public void DoVarDecl(STO sto)
{
// TODO: Need to store how many bytes used in function
// Local basic type (int, float, boolean)
String offset = getNextOffset(sto.getType().getSize());
sto.store(SparcInstr.REG_FRAME, offset);
stackValues.addElement(new StackRecord(currentFunc.peek().getName(), sto.getName(), sto.load()));
// Initialize to 0, mostly for testing purposed
writeAssembly(SparcInstr.BLANK_LINE);
writeComment("Declare " + sto.getName());
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.MOV_OP, SparcInstr.REG_GLOBAL0, SparcInstr.REG_LOCAL0);
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_LOCAL0, bracket(sto.load()));
writeAssembly(SparcInstr.BLANK_LINE);
// For float, check DI6 Page on "What about float?"
// Array (TODO: In Phase 2)
// Pointer (TODO: In Phase 3)
}
//-------------------------------------------------------------------------
// DoAssignExpr
//-------------------------------------------------------------------------
public void DoAssignExpr(STO stoVar, STO stoValue)
{
// TODO: My isConst check can go away after we allocate constants onto stack
// If storing a float
/*
// TODO: Float needs to be reconsidered for how you access floats
if(stoDes.getType().isFloat()) {
// Put value-to-assign into %f0
if(stoValue.isConst()) {
// Set the value of constant into %f0
// set <value>, %f0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, stoValue.getValue(), SparcInstr.REG_FLOAT0);
}
else if(stoValue.isVar()) {
// Load value of var into %f0
// ld [<stoValue location>], %f0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(stoValue.load()), SparcInstr.REG_FLOAT0);
}
// If value is not a float, convert it to a float
if(!stoValue.getType().isFloat()) {
// fitos %f0, %f0 ! Convert bit pattern to FP
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.FITOS_OP, SparcInstr.REG_FLOAT0, SparcInstr.REG_FLOAT0);
}
// Store value in %f0 into address of destination sto
// st %f0, [<stoDes location>]
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_FLOAT0, bracket(stoDes.load()));
}
*/
//else {
// Put value-to-assign into %l0
// Load value of var into %l0
// ld [<stoValue location>], %l0
LoadStoAddr(stoVar, SparcInstr.REG_LOCAL0);
StoreSto(stoValue, SparcInstr.REG_LOCAL1, SparcInstr.REG_LOCAL0);
// Store value in %l0 into address of destination sto
// st %l0, [<stoDes location>]
// }
}
//-------------------------------------------------------------------------
// LoadSto
//-------------------------------------------------------------------------
public void LoadSto(STO sto, String reg)
{
writeComment("Load " + sto.getName() + " into " + reg);
// PUT ADDRESS OF STO INTO <reg>
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.SET_OP, sto.getOffset(), reg, "Put the offset/name of " + sto.getName() + " into " + reg);
writeAssembly(SparcInstr.THREE_PARAM_COMM, SparcInstr.ADD_OP, sto.getBase(), reg, reg, "Add offset/name to base reg " + reg);
// LOAD VALUE AT ADDRESS INTO <reg>
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.LOAD_OP, bracket(reg), reg, "Load value of " + sto.getName() + " into " + reg);
}
//-------------------------------------------------------------------------
// LoadStoAddr
//-------------------------------------------------------------------------
public void LoadStoAddr(STO sto, String reg)
{
writeComment("Load address of " + sto.getName() + " into " + reg);
// PUT ADDRESS OF STO INTO <reg>
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.SET_OP, sto.getOffset(), reg, "Put the offset/name of " + sto.getName() + " into " + reg);
writeAssembly(SparcInstr.THREE_PARAM_COMM, SparcInstr.ADD_OP, sto.getBase(), reg, reg, "Add offset/name to base reg " + reg);
}
//-------------------------------------------------------------------------
// StoreSto - Stores a sto's value into destReg
//-------------------------------------------------------------------------
public void StoreSto(STO valueSto, String tmpReg, String destReg)
{
writeComment("Store " + valueSto.getName() + " into " + destReg);
// Load value into tmpReg
LoadSto(valueSto, tmpReg);
// STORE VALUE AT ADDRESS INTO <reg>
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.STORE_OP, tmpReg, bracket(destReg), "Store value of " + valueSto.getName() + " into " + destReg);
}
//-------------------------------------------------------------------------
// StoreValue
//-------------------------------------------------------------------------
public void StoreValue(String valueReg, String destReg)
{
writeComment("Store value in " + valueReg + " into " + destReg);
// STORE VALUE IN valueReg INTO destReg
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.STORE_OP, valueReg, bracket(destReg), "Store value in " + valueReg + " into " + destReg);
}
//-------------------------------------------------------------------------
// StoreValueIntoSto - Stores value in valueReg into destSto
//-------------------------------------------------------------------------
public void StoreValueIntoSto(String valueReg, String tmpReg, STO destSto)
{
writeComment("Store value in " + valueReg + " into sto " + destSto.getName());
// Load sto addr into tmpReg
LoadStoAddr(destSto, tmpReg);
// STORE VALUE IN valueReg INTO destSto (which has addr in tmpReg)
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.STORE_OP, valueReg, bracket(tmpReg), "Store value in " + valueReg + " into sto " + destSto.getName());
}
//-------------------------------------------------------------------------
// DoLiteral
//-------------------------------------------------------------------------
public void DoLiteral(ConstSTO sto)
{
if(currentFunc.peek().getName().equals("global"))
return;
String offset = getNextOffset(sto.getType().getSize());
writeComment("Put literal onto stack");
if(sto.getType().isInt() || sto.getType().isBool()) {
// put the literal in memory
// set <value>, %l0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, String.valueOf(((ConstSTO) sto).getIntValue()), SparcInstr.REG_LOCAL0);
// st %l0, [%fp-offset]
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_LOCAL0, bracket(SparcInstr.REG_FRAME + offset));
}
else if(sto.getType().isFloat()) {
// store literal in rodata section
// .section ".data"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.DATA_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
// float<xxx>: .single 0r5.75
writeAssembly(SparcInstr.RO_DEFINE, ".float_" + String.valueOf(float_count), SparcInstr.SINGLEP, "0r" + (String.valueOf(((ConstSTO) sto).getFloatValue())));
// .section ".text"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.TEXT_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
// set label, %l0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, ".float_" + String.valueOf(float_count), SparcInstr.REG_LOCAL0);
// ld [%l0], %f0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, bracket(SparcInstr.REG_LOCAL0), SparcInstr.REG_FLOAT0);
// st %f0, [%fp-offset]
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.STORE_OP, SparcInstr.REG_FLOAT0, bracket(SparcInstr.REG_FRAME + offset));
float_count++;
}
// store the address on sto
sto.store(SparcInstr.REG_FRAME, offset);
stackValues.addElement(new StackRecord(currentFunc.peek().getName(), sto.getName(), sto.load()));
}
//-------------------------------------------------------------------------
// functionName411
//-------------------------------------------------------------------------
public void functionName413()
{
}
//-------------------------------------------------------------------------
// functionName419
//-------------------------------------------------------------------------
public void functionName421()
{
}
//-------------------------------------------------------------------------
// functionName427
//-------------------------------------------------------------------------
public void functionName429()
{
}
//-------------------------------------------------------------------------
// functionName435
//-------------------------------------------------------------------------
public void functionName437()
{
}
//-------------------------------------------------------------------------
// functionName443
//-------------------------------------------------------------------------
public void functionName445()
{
}
//-------------------------------------------------------------------------
// functionName451
//-------------------------------------------------------------------------
public void functionName453()
{
}
//-------------------------------------------------------------------------
// functionName459
//-------------------------------------------------------------------------
public void functionName461()
{
}
//-------------------------------------------------------------------------
// functionName467
//-------------------------------------------------------------------------
public void functionName469()
{
}
//-------------------------------------------------------------------------
// functionName475
//-------------------------------------------------------------------------
public void functionName477()
{
}
//-------------------------------------------------------------------------
// functionName483
//-------------------------------------------------------------------------
public void functionName485()
{
}
//-------------------------------------------------------------------------
// functionName491
//-------------------------------------------------------------------------
public void functionName493()
{
}
//-------------------------------------------------------------------------
// functionName499
//-------------------------------------------------------------------------
public void functionName501()
{
}
//-------------------------------------------------------------------------
// functionName507
//-------------------------------------------------------------------------
public void functionName509()
{
}
//-------------------------------------------------------------------------
// functionName515
//-------------------------------------------------------------------------
public void functionName517()
{
}
//-------------------------------------------------------------------------
// DoBinaryOp
//-------------------------------------------------------------------------
public void DoBinaryOp(BinaryOp op, STO operand1, STO operand2, STO resultSTO)
{
String operation = "";
if(op.getName().equals("+")){
operation = SparcInstr.ADD_OP;
}
else if(op.getName().equals("-")){
operation = SparcInstr.SUB_OP;
}
else if(op.getName().equals("*")){
operation = SparcInstr.MUL_OP;
}
else if(op.getName().equals("/")){
operation = SparcInstr.DIV_OP;
}
else if(op.getName().equals("%")){
operation = SparcInstr.REM_OP;
}
else if(op.getName().equals("&")){
operation = SparcInstr.AND_OP;
}
else if(op.getName().equals("|")){
operation = SparcInstr.OR_OP;
}
else if(op.getName().equals("^")){
operation = SparcInstr.XOR_OP;
}
LoadSto(operand1, SparcInstr.REG_LOCAL0);
LoadSto(operand2, SparcInstr.REG_LOCAL1);
writeAssembly(SparcInstr.THREE_PARAM_COMM, operation, SparcInstr.REG_LOCAL0, SparcInstr.REG_LOCAL1, SparcInstr.REG_LOCAL0, "Adding Values!");
resultSTO.store(SparcInstr.REG_FRAME, getNextOffset(resultSTO.getType().getSize()));
StoreValueIntoSto(SparcInstr.REG_LOCAL1, SparcInstr.REG_LOCAL0, resultSTO);
}
//-------------------------------------------------------------------------
// DoIf
//-------------------------------------------------------------------------
public void DoIf(ConstSTO condition)
{
// !----if <condition>----
writeComment("if "+condition.getIntValue());
// create if label and increment the count
String ifL = ".ifL_"+ifLabel_count;
ifLabel_count++;
// add the label to the stack
stackIfLabel.add(ifL);
// set condition, %l0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, String.valueOf(condition.getIntValue()), "%l0");
// ld [%l0], %l0
//writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.LOAD_OP, sqBracketed("%l0"), "%l0");
// cmp %l0, %g0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.CMP_OP, "%l0", "%g0");
// be IfL1! Opposite logic
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.BE_OP, ifL);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
increaseIndent();
}
//-------------------------------------------------------------------------
// DoIfCodeBlock
//-------------------------------------------------------------------------
public void DoIfCodeBlock()
{
decreaseIndent();
String label = stackIfLabel.pop();
writeAssembly(SparcInstr.LABEL, label);
}
}
| false | true | public void DoCout(STO sto) {
// !----cout << <sto name>----
writeCommentHeader("cout << " + sto.getName());
if(sto.getType().isInt()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.INTFMT, SparcInstr.REG_ARG0);
// ld [<value>], %o1
LoadSto(sto, SparcInstr.REG_ARG1);
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isBool()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLFMT, SparcInstr.REG_ARG0);
// Set the condition STO into LOCAL0
LoadSto(sto, SparcInstr.REG_LOCAL0);
String ifLabel = ".ifL_" + ifLabel_count;
String elseLabel = ".elseL_" + ifLabel_count;
ifLabel_count++;
// If the condition is true, don't branch and load "true", if false, branch to end of if and load "false"
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.CMP_OP, SparcInstr.REG_LOCAL0, SparcInstr.REG_GLOBAL0, "Compare boolean value " + sto.getName() + " to 0");
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BE_OP, ifLabel, "If <cond> is true, don't branch, if false, branch");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// If Code: Load "true" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLT, SparcInstr.REG_ARG1);
// Branch to end of else block
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BA_OP, ifLabel, "Did if code, branch always to bottom of else");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// Print label
writeAssembly(SparcInstr.LABEL, ifLabel);
// Else code: load "false" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLF, SparcInstr.REG_ARG1);
// Else done, print label
writeAssembly(SparcInstr.LABEL, elseLabel);
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isFloat()) {
// ld [sto] %f0
LoadSto(sto, SparcInstr.REG_FLOAT0);
// call printFloat
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTFLOAT);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
// String literal
else if (sto.getType().isString()) {
// .section ".rodata"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.RODATA_SEC);
// str_(str_count): .asciz "string literal"
writeAssembly(SparcInstr.RO_DEFINE, ".str_"+str_count, SparcInstr.ASCIZ_DIR, quoted(sto.getName()));
// .section ".text"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.TEXT_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
// set _strFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set str_(str_count), %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, ".str_"+str_count, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// increment str count
str_count++;
}
// endl
else if (sto.getType().isVoid()) {
// set _strFmt %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set _endl, %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.ENDL, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
}
| public void DoCout(STO sto) {
// !----cout << <sto name>----
writeCommentHeader("cout << " + sto.getName());
if(sto.getType().isInt()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.INTFMT, SparcInstr.REG_ARG0);
// ld [<value>], %o1
LoadSto(sto, SparcInstr.REG_ARG1);
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isBool()) {
// set _intFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLFMT, SparcInstr.REG_ARG0);
// Set the condition STO into LOCAL0
LoadSto(sto, SparcInstr.REG_LOCAL0);
String ifLabel = ".ifL_" + ifLabel_count;
String elseLabel = ".elseL_" + ifLabel_count;
ifLabel_count++;
// If the condition is true, don't branch and load "true", if false, branch to end of if and load "false"
// value == 0
writeAssembly(SparcInstr.TWO_PARAM_COMM, SparcInstr.CMP_OP, SparcInstr.REG_LOCAL0, SparcInstr.REG_GLOBAL0, "Compare boolean value " + sto.getName() + " to 0");
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BE_OP, ifLabel, "If <cond> is true, don't branch, if false, branch");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// If Code: Load "true" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLT, SparcInstr.REG_ARG1);
// Branch to end of else block
writeAssembly(SparcInstr.ONE_PARAM_COMM, SparcInstr.BA_OP, ifLabel, "Did if code, branch always to bottom of else");
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// Print label
decreaseIndent();
writeAssembly(SparcInstr.LABEL, ifLabel);
increaseIndent();
// Else code: load "false" into %o1 here
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.BOOLF, SparcInstr.REG_ARG1);
// Else done, print label
decreaseIndent();
writeAssembly(SparcInstr.LABEL, elseLabel);
increaseIndent();
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
else if(sto.getType().isFloat()) {
// ld [sto] %f0
LoadSto(sto, SparcInstr.REG_FLOAT0);
// call printFloat
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTFLOAT);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
// String literal
else if (sto.getType().isString()) {
// .section ".rodata"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.RODATA_SEC);
// str_(str_count): .asciz "string literal"
writeAssembly(SparcInstr.RO_DEFINE, ".str_"+str_count, SparcInstr.ASCIZ_DIR, quoted(sto.getName()));
// .section ".text"
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.SECTION_DIR, SparcInstr.TEXT_SEC);
// .align 4
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.ALIGN_DIR, "4");
// set _strFmt, %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set str_(str_count), %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, ".str_"+str_count, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
// increment str count
str_count++;
}
// endl
else if (sto.getType().isVoid()) {
// set _strFmt %o0
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.STRFMT, "%o0");
// set _endl, %o1
writeAssembly(SparcInstr.TWO_PARAM, SparcInstr.SET_OP, SparcInstr.ENDL, "%o1");
// call printf
writeAssembly(SparcInstr.ONE_PARAM, SparcInstr.CALL_OP, SparcInstr.PRINTF);
writeAssembly(SparcInstr.NO_PARAM, SparcInstr.NOP_OP);
}
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/CreateBranchPage.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/CreateBranchPage.java
index a4bbe3db..b5dfa102 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/CreateBranchPage.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/CreateBranchPage.java
@@ -1,273 +1,274 @@
/*******************************************************************************
* Copyright (c) 2010 SAP AG.
* 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:
* Mathias Kinzler (SAP AG) - initial implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.repository;
import java.io.IOException;
import java.util.Map.Entry;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.egit.core.op.CreateLocalBranchOperation;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.ValidationUtils;
import org.eclipse.egit.ui.internal.branch.BranchOperationUI;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* Allows to create a new local branch based on another branch or commit.
* <p>
* If the base is a branch, the source branch can be selected using a drop down.
*/
class CreateBranchPage extends WizardPage {
private final Repository myRepository;
private final IInputValidator myValidator;
private final String myBaseRef;
private final RevCommit myBaseCommit;
private Text nameText;
private Button checkout;
private Combo branchCombo;
/**
* Constructs this page.
* <p>
* If a base branch is provided, the drop down will be selected accordingly
*
* @param repo
* the repository
* @param baseRef
* the branch or tag to base the new branch on, may be null
*/
public CreateBranchPage(Repository repo, Ref baseRef) {
super(CreateBranchPage.class.getName());
this.myRepository = repo;
this.myBaseRef = baseRef.getName();
this.myBaseCommit = null;
this.myValidator = ValidationUtils.getRefNameInputValidator(
myRepository, Constants.R_HEADS, true);
setTitle(UIText.CreateBranchPage_Title);
setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage);
}
/**
* Constructs this page.
* <p>
* If a base branch is provided, the drop down will be selected accordingly
*
* @param repo
* the repository
* @param baseCommit
* the commit to base the new branch on, must not be null
*/
public CreateBranchPage(Repository repo, RevCommit baseCommit) {
super(CreateBranchPage.class.getName());
this.myRepository = repo;
this.myBaseRef = null;
this.myBaseCommit = baseCommit;
this.myValidator = ValidationUtils.getRefNameInputValidator(
myRepository, Constants.R_HEADS, true);
setTitle(UIText.CreateBranchPage_Title);
setMessage(UIText.CreateBranchPage_ChooseNameMessage);
}
public void createControl(Composite parent) {
Composite main = new Composite(parent, SWT.NONE);
main.setLayout(new GridLayout(3, false));
Label sourceLabel = new Label(main, SWT.NONE);
if (this.myBaseCommit != null) {
sourceLabel.setText(UIText.CreateBranchPage_SourceCommitLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceCommitTooltip);
} else {
sourceLabel.setText(UIText.CreateBranchPage_SourceBranchLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceBranchTooltip);
}
this.branchCombo = new Combo(main, SWT.READ_ONLY | SWT.DROP_DOWN);
GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(
this.branchCombo);
if (this.myBaseCommit != null) {
this.branchCombo.add(myBaseCommit.name());
this.branchCombo.setText(myBaseCommit.name());
this.branchCombo.setEnabled(false);
} else {
try {
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_HEADS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_REMOTES).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_TAGS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
} catch (IOException e1) {
// ignore here
}
this.branchCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
// select the current branch in the drop down
if (myBaseRef != null) {
this.branchCombo.setText(myBaseRef);
}
}
Label nameLabel = new Label(main, SWT.NONE);
nameLabel.setText(UIText.CreateBranchPage_BranchNameLabel);
// we visualize the prefix here
Text prefix = new Text(main, SWT.NONE);
prefix.setText(Constants.R_HEADS);
prefix.setEnabled(false);
nameText = new Text(main, SWT.BORDER);
// enable testing with SWTBot
nameText.setData("org.eclipse.swtbot.widget.key", "BranchName"); //$NON-NLS-1$ //$NON-NLS-2$
GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText);
boolean isBare = myRepository.isBare();
checkout = new Button(main, SWT.CHECK);
checkout.setText(UIText.CreateBranchPage_CheckoutButton);
// most of the time, we probably will check this out
// unless we have a bare repository which doesn't allow
// check out at all
checkout.setSelection(!isBare);
checkout.setEnabled(!isBare);
checkout.setVisible(!isBare);
GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(
checkout);
checkout.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
Dialog.applyDialogFont(main);
setControl(main);
nameText.setFocus();
if (myBaseRef != null
&& (myBaseRef.startsWith(Constants.R_REMOTES) || myBaseRef
.startsWith(Constants.R_TAGS))) {
// additional convenience: the last part of the name is suggested
// as name for the local branch
nameText.setText(myBaseRef
.substring(myBaseRef.lastIndexOf('/') + 1));
+ nameText.selectAll();
checkPage();
} else {
// in any case, we will have to enter the name
setPageComplete(false);
}
// add the listener just now to avoid unneeded checkPage()
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
checkPage();
}
});
}
private void checkPage() {
setErrorMessage(null);
try {
if (branchCombo.getText().length() == 0) {
setErrorMessage(UIText.CreateBranchPage_MissingSourceMessage);
return;
}
if (nameText.getText().length() == 0) {
setErrorMessage(UIText.CreateBranchPage_ChooseNameMessage);
return;
}
String message = this.myValidator.isValid(nameText.getText());
if (message != null) {
setErrorMessage(message);
return;
}
} finally {
setPageComplete(getErrorMessage() == null);
}
}
private String getBranchName() {
return nameText.getText();
}
/**
* @param monitor
* @throws CoreException
* @throws IOException
*/
public void createBranch(IProgressMonitor monitor) throws CoreException,
IOException {
monitor.beginTask(UIText.CreateBranchPage_CreatingBranchMessage,
IProgressMonitor.UNKNOWN);
String newRefName = getBranchName();
final CreateLocalBranchOperation cbop;
if (myBaseCommit != null)
cbop = new CreateLocalBranchOperation(myRepository, newRefName,
myBaseCommit);
else
cbop = new CreateLocalBranchOperation(myRepository, newRefName,
myRepository.getRef(this.branchCombo.getText()));
cbop.execute(monitor);
if (checkout.getSelection()) {
if (monitor.isCanceled())
return;
monitor.beginTask(UIText.CreateBranchPage_CheckingOutMessage,
IProgressMonitor.UNKNOWN);
new BranchOperationUI(myRepository, Constants.R_HEADS + newRefName)
.run(monitor);
}
}
}
| true | true | public void createControl(Composite parent) {
Composite main = new Composite(parent, SWT.NONE);
main.setLayout(new GridLayout(3, false));
Label sourceLabel = new Label(main, SWT.NONE);
if (this.myBaseCommit != null) {
sourceLabel.setText(UIText.CreateBranchPage_SourceCommitLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceCommitTooltip);
} else {
sourceLabel.setText(UIText.CreateBranchPage_SourceBranchLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceBranchTooltip);
}
this.branchCombo = new Combo(main, SWT.READ_ONLY | SWT.DROP_DOWN);
GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(
this.branchCombo);
if (this.myBaseCommit != null) {
this.branchCombo.add(myBaseCommit.name());
this.branchCombo.setText(myBaseCommit.name());
this.branchCombo.setEnabled(false);
} else {
try {
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_HEADS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_REMOTES).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_TAGS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
} catch (IOException e1) {
// ignore here
}
this.branchCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
// select the current branch in the drop down
if (myBaseRef != null) {
this.branchCombo.setText(myBaseRef);
}
}
Label nameLabel = new Label(main, SWT.NONE);
nameLabel.setText(UIText.CreateBranchPage_BranchNameLabel);
// we visualize the prefix here
Text prefix = new Text(main, SWT.NONE);
prefix.setText(Constants.R_HEADS);
prefix.setEnabled(false);
nameText = new Text(main, SWT.BORDER);
// enable testing with SWTBot
nameText.setData("org.eclipse.swtbot.widget.key", "BranchName"); //$NON-NLS-1$ //$NON-NLS-2$
GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText);
boolean isBare = myRepository.isBare();
checkout = new Button(main, SWT.CHECK);
checkout.setText(UIText.CreateBranchPage_CheckoutButton);
// most of the time, we probably will check this out
// unless we have a bare repository which doesn't allow
// check out at all
checkout.setSelection(!isBare);
checkout.setEnabled(!isBare);
checkout.setVisible(!isBare);
GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(
checkout);
checkout.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
Dialog.applyDialogFont(main);
setControl(main);
nameText.setFocus();
if (myBaseRef != null
&& (myBaseRef.startsWith(Constants.R_REMOTES) || myBaseRef
.startsWith(Constants.R_TAGS))) {
// additional convenience: the last part of the name is suggested
// as name for the local branch
nameText.setText(myBaseRef
.substring(myBaseRef.lastIndexOf('/') + 1));
checkPage();
} else {
// in any case, we will have to enter the name
setPageComplete(false);
}
// add the listener just now to avoid unneeded checkPage()
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
checkPage();
}
});
}
| public void createControl(Composite parent) {
Composite main = new Composite(parent, SWT.NONE);
main.setLayout(new GridLayout(3, false));
Label sourceLabel = new Label(main, SWT.NONE);
if (this.myBaseCommit != null) {
sourceLabel.setText(UIText.CreateBranchPage_SourceCommitLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceCommitTooltip);
} else {
sourceLabel.setText(UIText.CreateBranchPage_SourceBranchLabel);
sourceLabel
.setToolTipText(UIText.CreateBranchPage_SourceBranchTooltip);
}
this.branchCombo = new Combo(main, SWT.READ_ONLY | SWT.DROP_DOWN);
GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(
this.branchCombo);
if (this.myBaseCommit != null) {
this.branchCombo.add(myBaseCommit.name());
this.branchCombo.setText(myBaseCommit.name());
this.branchCombo.setEnabled(false);
} else {
try {
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_HEADS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_REMOTES).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
for (Entry<String, Ref> ref : myRepository.getRefDatabase()
.getRefs(Constants.R_TAGS).entrySet()) {
if (!ref.getValue().isSymbolic())
this.branchCombo.add(ref.getValue().getName());
}
} catch (IOException e1) {
// ignore here
}
this.branchCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
// select the current branch in the drop down
if (myBaseRef != null) {
this.branchCombo.setText(myBaseRef);
}
}
Label nameLabel = new Label(main, SWT.NONE);
nameLabel.setText(UIText.CreateBranchPage_BranchNameLabel);
// we visualize the prefix here
Text prefix = new Text(main, SWT.NONE);
prefix.setText(Constants.R_HEADS);
prefix.setEnabled(false);
nameText = new Text(main, SWT.BORDER);
// enable testing with SWTBot
nameText.setData("org.eclipse.swtbot.widget.key", "BranchName"); //$NON-NLS-1$ //$NON-NLS-2$
GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText);
boolean isBare = myRepository.isBare();
checkout = new Button(main, SWT.CHECK);
checkout.setText(UIText.CreateBranchPage_CheckoutButton);
// most of the time, we probably will check this out
// unless we have a bare repository which doesn't allow
// check out at all
checkout.setSelection(!isBare);
checkout.setEnabled(!isBare);
checkout.setVisible(!isBare);
GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(
checkout);
checkout.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkPage();
}
});
Dialog.applyDialogFont(main);
setControl(main);
nameText.setFocus();
if (myBaseRef != null
&& (myBaseRef.startsWith(Constants.R_REMOTES) || myBaseRef
.startsWith(Constants.R_TAGS))) {
// additional convenience: the last part of the name is suggested
// as name for the local branch
nameText.setText(myBaseRef
.substring(myBaseRef.lastIndexOf('/') + 1));
nameText.selectAll();
checkPage();
} else {
// in any case, we will have to enter the name
setPageComplete(false);
}
// add the listener just now to avoid unneeded checkPage()
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
checkPage();
}
});
}
|
diff --git a/src/main/java/com/saplo/api/client/HTTPSessionApache.java b/src/main/java/com/saplo/api/client/HTTPSessionApache.java
index 8388399..c47d22a 100644
--- a/src/main/java/com/saplo/api/client/HTTPSessionApache.java
+++ b/src/main/java/com/saplo/api/client/HTTPSessionApache.java
@@ -1,196 +1,196 @@
/**
*
*/
package com.saplo.api.client;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.saplo.api.client.TransportRegistry.SessionFactory;
import com.saplo.api.client.entity.JSONRPCRequestObject;
import com.saplo.api.client.entity.JSONRPCResponseObject;
/**
* @author progre55
*
*/
public class HTTPSessionApache implements Session {
private static Log logger = LogFactory.getLog(HTTPSessionApache.class);
protected URI uri;
protected volatile String params;
// protected int clientsCount;
// protected Stack<DefaultHttpClient> clientPool;
protected HttpHost proxy = new HttpHost("localhost");
protected boolean proxified = false;
public HTTPSessionApache(URI uri, String params, int count) {
this.uri = uri;
this.params = params;
// this.clientsCount = count;
// clientPool = new Stack<DefaultHttpClient>();
// fillPool();
}
public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
- ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes());
+ ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes(Charset.forName("UTF-8")));
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
public void setParams(String params) {
this.params = params;
}
public void setProxy(String address, int port) {
this.proxified = true;
this.proxy = new HttpHost(address, port, "http");
}
// /**
// * Get a client from the pool.
// *
// * @return - HttpClient
// */
// protected synchronized DefaultHttpClient getClient() {
// DefaultHttpClient cl = null;
// try {
// while (clientPool.empty())
// this.wait();
// logger.debug("Remaining clients: " + clientPool.size());
// cl = clientPool.pop();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// return cl;
// }
//
// /**
// * Put the client back into the pool.
// *
// * @param client - the client to return into the pool
// */
// public synchronized void releaseClient(DefaultHttpClient client) {
// clientPool.push(client);
// this.notify();
// }
//
// private void fillPool() {
// for (int i = 0; i < clientsCount; i++) {
// DefaultHttpClient cl = new DefaultHttpClient();
// clientPool.push(cl);
// }
// }
/**
* Close all the clients and clear the pool.
*/
public synchronized void close() {
// for (int i = 0; i < clientsCount; i++) {
// DefaultHttpClient cl = clientPool.pop();
// cl.getConnectionManager().shutdown();
// }
// clientPool.clear();
}
static class SessionFactoryImpl implements SessionFactory {
volatile HashMap<URI, Session> sessionMap = new HashMap<URI, Session>();
public Session newSession(URI uri, String params, int count) {
Session session = sessionMap.get(uri);
if (session == null) {
synchronized (sessionMap) {
session = sessionMap.get(uri);
if(session == null) {
session = new HTTPSessionApache(uri, params, count);
sessionMap.put(uri, session);
}
}
}
return session;
}
}
/**
* Register this transport in 'registry'
*/
public static void register(TransportRegistry registry) {
registry.registerTransport("http", new SessionFactoryImpl());
}
/**
* De-register this transport from the 'registry'
*/
public static void deregister(TransportRegistry registry) {
registry.deregisterTransport("http");
}
}
| true | true | public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes());
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
| public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes(Charset.forName("UTF-8")));
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
|
diff --git a/src/com/jidesoft/swing/SearchableBar.java b/src/com/jidesoft/swing/SearchableBar.java
index e0ca35b8..af569b7f 100644
--- a/src/com/jidesoft/swing/SearchableBar.java
+++ b/src/com/jidesoft/swing/SearchableBar.java
@@ -1,758 +1,760 @@
/*
* @(#)FirefoxSearchBar.java 10/11/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.swing.event.SearchableEvent;
import com.jidesoft.swing.event.SearchableListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
/**
* <code>SearchableBar</code> is a convenient component to enable searching feature for components. As long as the
* component support <code>Searchable</code> feature, it can work with <code>SearchableBar</code>.
* <p/>
* Different from <code>Searchable</code> feature which uses a small popup window to allow user typing in the searching
* text, <code>SearchableBar</code> provides a full-size panel. Although they both pretty provide the same set of
* features, they should be used in different cases to achieve the most desirable result.
* <p/>
* First of all, <code>SearchableBar</code> is a lot bigger than <code>Searchable</code>'s popup and need more space on
* the screen. The component that installs <code>SearchableBar</code> should be large enough. In comparison,
* <code>Searchable</code> can be installed on components of any size as it's a floating popup.
* <p/>
* Secondly, <code>SearchableBar</code> can be set visible all the time or can be set visible by a keystroke and stay
* visible unless user explicitly hides it. If your user is not computer savvy, <code>SearchableBar</code> is more
* appropriate because user can see searching feature very easily. <code>SearchableBar</code> can also be a better
* replacement the traditional "Find" or "Search" dialog because <code>SearchableBar</code> doesn't block user input
* like modal dialog. In comparison, <code>Searchable</code>'s popup is very transient. Mouse clicks outside the popup
* will hide the popup. For computer savvy it is very helpful but it could be hard for non-computer savvy to
* "understand" it. A good example is IntelliJ IDEA heavily uses Searchable popup because the users are all Java
* developers. Firefox, on the other hand, uses SearchableBar because the users are just regular computer users.
* <p/>
* Although appearance wise, these two are very different, they both based on {@link Searchable} interface. So as
* developer, both are almost the same. <code>SearchableBar</code> based on <code>Searchable</code>. So if you have an
* interface of <code>Searchable</code>, all you need is to call
* <code><pre>
* SearchableBar.install(searchable, KeyStroke.getKeyStroke(KeyEvent.VK_F,
* KeyEvent.CTRL_DOWN_MASK),
* new SearchableBar.Installer() {
* public void openSearchBar(SearchableBar searchableBar) {
* // add code to show search bar
* }
* <p/>
* public void closeSearchBar(SearchableBar searchableBar) {
* // add code to close search bar
* }
* });
* </pre></code>
* Or if you want fully control the SearchableBar, you can create one using one of its constructors and add to wherever
* you want.
* <p/>
* There are a few options you can set on <code>SearchableBar</code>. You can set compact or full mode. Compact mode
* will only use icon for buttons v.s. full mode will use both icon and text for buttons. All buttons on the
* <code>SearchableBar</code> can be shown/hidden by using {@link #setVisibleButtons(int)} method. You can also set the
* text field background for mismatch by using {@link #setMismatchForeground(java.awt.Color)}.
* <p/>
*/
public class SearchableBar extends JToolBar implements SearchableProvider {
private Searchable _searchable;
private JLabel _statusLabel;
private JTextField _textField;
protected AbstractButton _closeButton;
protected AbstractButton _findPrevButton;
protected AbstractButton _findNextButton;
protected AbstractButton _highlightsButton;
private AbstractButton _matchCaseCheckBox;
private AbstractButton _repeatCheckBox;
public static final int SHOW_CLOSE = 0x1;
public static final int SHOW_NAVIGATION = 0x2;
public static final int SHOW_HIGHLIGHTS = 0x4;
public static final int SHOW_MATCHCASE = 0x8;
public static final int SHOW_REPEATS = 0x10;
public static final int SHOW_STATUS = 0x20;
public static final int SHOW_ALL = 0xFFFFFFFF;
private int _visibleButtons = SHOW_ALL & ~SHOW_REPEATS; // default is show all but repeats
private boolean _compact;
/**
* Creates a searchable bar.
*
* @param searchable
*/
public SearchableBar(Searchable searchable) {
this(searchable, "", false);
}
/**
* Creates a searchable bar in compact mode or full mode.
*
* @param searchable
*/
public SearchableBar(Searchable searchable, boolean compact) {
this(searchable, "", compact);
}
/**
* Creates a searchable bar with initial searching text and in compact mode or full mode.
*
* @param searchable
*/
public SearchableBar(Searchable searchable, String initialText, boolean compact) {
setFloatable(false);
setRollover(true);
_searchable = searchable;
_searchable.addSearchableListener(new SearchableListener() {
public void searchableEventFired(SearchableEvent e) {
if (e.getID() == SearchableEvent.SEARCHABLE_MODEL_CHANGE) {
highlightAllOrNext();
}
}
});
_searchable.setSearchableProvider(this);
_compact = compact;
initComponents(initialText);
}
private void initComponents(String initialText) {
AbstractAction closeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (getInstaller() != null) {
getInstaller().closeSearchBar(SearchableBar.this);
}
}
};
AbstractAction findNextAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
- int cursor = _searchable.getCursor();
+ int cursor = _searchable.getSelectedIndex();
+ _searchable.setCursor(cursor);
int found = _searchable.findNext(text);
if (found != -1 && _searchable.isRepeats() && found <= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedBottomRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedBottom"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
AbstractAction findPrevAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
- int cursor = _searchable.getCursor();
+ int cursor = _searchable.getSelectedIndex();
+ _searchable.setCursor(cursor);
int found = _searchable.findPrevious(text);
if (found != -1 && _searchable.isRepeats() && found >= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedTopRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedTop"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
_closeButton = createCloseButton(closeAction);
_findNextButton = createFindNextButton(findNextAction);
_findPrevButton = createFindPrevButton(findPrevAction);
_highlightsButton = createHighlightButton();
_matchCaseCheckBox = createMatchCaseButton();
_repeatCheckBox = createRepeatsButton();
_statusLabel = new JLabel();
//setup text field
_textField = createTextField();
_textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_textField.selectAll();
}
});
_textField.setColumns(13);
_textField.getDocument().addDocumentListener(new DocumentListener() {
private Timer timer = new Timer(_searchable.getSearchingDelay(), new ActionListener() {
public void actionPerformed(ActionEvent e) {
highlightAllOrNext();
}
});
public void insertUpdate(DocumentEvent e) {
startTimer();
}
public void removeUpdate(DocumentEvent e) {
startTimer();
}
public void changedUpdate(DocumentEvent e) {
startTimer();
}
void startTimer() {
if (_searchable.getSearchingDelay() > 0) {
if (timer.isRunning()) {
timer.restart();
}
else {
timer.setRepeats(false);
timer.start();
}
}
else {
highlightAllOrNext();
}
}
});
_textField.setText(initialText);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findPrevAction, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
installComponents();
int found = _searchable.findFromCursor(getSearchingText());
if (initialText.length() != 0 && found == -1) {
select(found, initialText, false);
}
}
/**
* Creates the text field where user types the text to be searched.
*
* @return a text field.
*/
protected JTextField createTextField() {
return new JTextField();
}
/**
* Gets the underlying Searchable object.
*
* @return the Searchable object.
*/
public Searchable getSearchable() {
return _searchable;
}
/**
* Creates the close button. Subclass can override it to create your own close button.
*
* @param closeAction
* @return the close button.
*/
protected AbstractButton createCloseButton(AbstractAction closeAction) {
AbstractButton button = new JButton(getImageIcon(SearchableBarIconsFactory.Buttons.CLOSE));
button.addActionListener(closeAction);
button.setRolloverEnabled(true);
button.setBorder(BorderFactory.createEmptyBorder());
button.setOpaque(false);
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.setRolloverIcon(getImageIcon(SearchableBarIconsFactory.Buttons.CLOSE_ROLLOVER));
return button;
}
/**
* Creates the find next button. Subclass can override it to create your own find next button.
*
* @param findNextAction
* @return the find next button.
*/
protected AbstractButton createFindNextButton(AbstractAction findNextAction) {
AbstractButton button = new JButton(_compact ? "" : getResourceString("SearchableBar.findNext"),
getImageIcon(SearchableBarIconsFactory.Buttons.NEXT));
button.setToolTipText(getResourceString("SearchableBar.findNext.tooltip"));
button.setMnemonic(getResourceString("SearchableBar.findNext.mnemonic").charAt(0));
button.setRolloverIcon(getImageIcon(SearchableBarIconsFactory.Buttons.NEXT_ROLLOVER));
button.setDisabledIcon(getImageIcon(SearchableBarIconsFactory.Buttons.NEXT_DISABLED));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.addActionListener(findNextAction);
button.setEnabled(false);
return button;
}
/**
* Creates the find prev button. Subclass can override it to create your own find prev button.
*
* @param findPrevAction
* @return the find prev button.
*/
protected AbstractButton createFindPrevButton(AbstractAction findPrevAction) {
AbstractButton button = new JButton(_compact ? "" : getResourceString("SearchableBar.findPrevious"),
getImageIcon(SearchableBarIconsFactory.Buttons.PREVIOUS));
button.setToolTipText(getResourceString("SearchableBar.findPrevious.tooltip"));
button.setMnemonic(getResourceString("SearchableBar.findPrevious.mnemonic").charAt(0));
button.setRolloverIcon(getImageIcon(SearchableBarIconsFactory.Buttons.PREVIOUS_ROLLOVER));
button.setDisabledIcon(getImageIcon(SearchableBarIconsFactory.Buttons.PREVIOUS_DISABLED));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.addActionListener(findPrevAction);
button.setEnabled(false);
return button;
}
/**
* Creates the highlight button.
*
* @return the highlight button.
*/
protected AbstractButton createHighlightButton() {
AbstractButton button = new JToggleButton(_compact ? "" : getResourceString("SearchableBar.highlights"),
getImageIcon(SearchableBarIconsFactory.Buttons.HIGHLIGHTS));
button.setToolTipText(getResourceString("SearchableBar.highlights.tooltip"));
button.setMnemonic(getResourceString("SearchableBar.highlights.mnemonic").charAt(0));
button.setSelectedIcon(getImageIcon(SearchableBarIconsFactory.Buttons.HIGHLIGHTS_SELECTED));
button.setDisabledIcon(getImageIcon(SearchableBarIconsFactory.Buttons.HIGHLIGHTS_DISABLED));
button.setRolloverIcon(getImageIcon(SearchableBarIconsFactory.Buttons.HIGHLIGHTS_ROLLOVER));
button.setRolloverSelectedIcon(getImageIcon(SearchableBarIconsFactory.Buttons.HIGHLIGHTS_ROLLOVER_SELECTED));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
AbstractAction highlightAllAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
highlightAllOrNext();
}
};
button.addActionListener(highlightAllAction);
button.setEnabled(false);
return button;
}
/**
* Creates the repeat button. By default it will return a JCheckBox. Subclass class can override it to return your
* own button or customize the button created by default as long as it can set underlying Searchable's repeats
* property.
*
* @return the repeat button.
*/
protected AbstractButton createRepeatsButton() {
AbstractButton button = new JCheckBox(getResourceString("SearchableBar.repeats"));
button.setMnemonic(getResourceString("SearchableBar.repeats.mnemonic").charAt(0));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.setSelected(getSearchable().isRepeats());
button.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof AbstractButton) {
getSearchable().setRepeats(((AbstractButton) e.getSource()).isSelected());
}
}
});
return button;
}
/**
* Creates the match case button. By default it will return a JCheckBox. Subclass class can override it to return
* your own button or customize the button created by default as long as it can set underlying Searchable's
* caseSensitive property.
*
* @return the match case button.
*/
protected AbstractButton createMatchCaseButton() {
JCheckBox checkBox = new JCheckBox(getResourceString("SearchableBar.matchCase"));
checkBox.setMnemonic(getResourceString("SearchableBar.matchCase.mnemonic").charAt(0));
checkBox.setRequestFocusEnabled(false);
checkBox.setFocusable(false);
checkBox.setSelected(getSearchable().isCaseSensitive());
checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof AbstractButton) {
getSearchable().setCaseSensitive(((AbstractButton) e.getSource()).isSelected());
highlightAllOrNext();
}
}
});
return checkBox;
}
/**
* Adds the buttons to the SearchableBar. Subclass can override this method to rearrange the layout of those
* buttons.
*/
protected void installComponents() {
setBorder(BorderFactory.createEtchedBorder());
setLayout(new JideBoxLayout(this, JideBoxLayout.X_AXIS));
add(Box.createHorizontalStrut(4), JideBoxLayout.FIX);
if ((_visibleButtons & SHOW_CLOSE) != 0) {
add(_closeButton);
add(Box.createHorizontalStrut(10));
}
// setup the label
JLabel label = new JLabel(getResourceString("SearchableBar.find"));
label.setDisplayedMnemonic(getResourceString("SearchableBar.find.mnemonic").charAt(0));
label.setLabelFor(_textField);
add(label);
add(Box.createHorizontalStrut(2), JideBoxLayout.FIX);
add(JideSwingUtilities.createCenterPanel(_textField), JideBoxLayout.FIX);
add(Box.createHorizontalStrut(2), JideBoxLayout.FIX);
if ((_visibleButtons & SHOW_NAVIGATION) != 0) {
add(_findNextButton);
add(_findPrevButton);
}
if ((_visibleButtons & SHOW_HIGHLIGHTS) != 0) {
add(_highlightsButton);
}
if ((_visibleButtons & SHOW_MATCHCASE) != 0) {
add(_matchCaseCheckBox);
}
if ((_visibleButtons & SHOW_REPEATS) != 0) {
add(_repeatCheckBox);
}
if ((_visibleButtons & SHOW_STATUS) != 0) {
add(Box.createHorizontalStrut(24));
add(_statusLabel, JideBoxLayout.VARY);
}
add(Box.createHorizontalStrut(6), JideBoxLayout.FIX);
}
private void highlightAllOrNext() {
if (_highlightsButton.isSelected()) {
highlighAll();
}
else {
highlightNext();
}
}
private void highlighAll() {
String text = getSearchingText();
if (text == null || text.length() == 0) {
return;
}
boolean old = _searchable.isRepeats();
_searchable.setRepeats(false);
int index = _searchable.findFirst(text);
if (index != -1) {
_searchable.setSelectedIndex(index, false); // clear side effect of ctrl-a will select all items
_searchable.setCursor(index); // as setSelectedIndex is used directly, we have to manually set the cursor value.
_findNextButton.setEnabled(true);
_findPrevButton.setEnabled(true);
_highlightsButton.setEnabled(true);
clearStatus();
}
else {
select(-1, text, false);
_findNextButton.setEnabled(false);
_findPrevButton.setEnabled(false);
_highlightsButton.setEnabled(false);
setStatus(getResourceString("SearchableBar.notFound"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
int firstIndex = -1;
while (index != -1) {
int newIndex = _searchable.findNext(text);
if (index == newIndex) {
index = -1;
}
else {
index = newIndex;
}
if (index != -1) {
if (firstIndex == -1) {
firstIndex = index;
}
select(index, text, true);
}
}
// now select the first one
if (firstIndex != -1) {
select(firstIndex, text, true);
}
_searchable.setRepeats(old);
_searchable.setCursor(0);
}
private void highlightNext() {
String text = getSearchingText();
if (text == null || text.length() == 0) {
_findNextButton.setEnabled(false);
_findPrevButton.setEnabled(false);
_highlightsButton.setEnabled(false);
clearStatus();
return;
}
int found = _searchable.findFromCursor(text);
if (found == -1) {
select(-1, "", false);
_findNextButton.setEnabled(false);
_findPrevButton.setEnabled(false);
_highlightsButton.setEnabled(false);
setStatus(getResourceString("SearchableBar.notFound"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else {
select(found, text, false);
_findNextButton.setEnabled(true);
_findPrevButton.setEnabled(true);
_highlightsButton.setEnabled(true);
clearStatus();
}
}
private void clearStatus() {
_statusLabel.setIcon(null);
_statusLabel.setText("");
_textField.setBackground(UIDefaultsLookup.getColor("TextField.background"));
}
private void setStatus(String message, Icon icon) {
_statusLabel.setIcon(icon);
_statusLabel.setText(message);
}
/**
* Makes the search field having focus.
*/
public void focusSearchField() {
if (_textField != null) {
_textField.requestFocus();
}
}
protected void select(int index, String searchingText, boolean incremental) {
if (index != -1) {
_searchable.setSelectedIndex(index, incremental);
_searchable.setCursor(index);
_textField.setBackground(UIDefaultsLookup.getColor("TextField.background"));
}
else {
_searchable.setSelectedIndex(-1, false);
_textField.setBackground(getMismatchBackground());
}
_searchable.firePropertyChangeEvent(searchingText);
if (index != -1) {
Object element = _searchable.getElementAt(index);
_searchable.fireSearchableEvent(new SearchableEvent(_searchable, SearchableEvent.SEARCHABLE_MATCH, searchingText, element, _searchable.convertElementToString(element)));
}
else {
_searchable.fireSearchableEvent(new SearchableEvent(_searchable, SearchableEvent.SEARCHABLE_NOMATCH, searchingText));
}
}
/**
* Gets the searching text.
*
* @return the searching text.
*/
public String getSearchingText() {
return _textField != null ? _textField.getText() : "";
}
/**
* Sets the searching text.
*
* @param searchingText the new searching text.
*/
public void setSearchingText(String searchingText) {
if (_textField != null) {
_textField.setText(searchingText);
}
}
/**
* Returns false.
*
* @return false.
*/
public boolean isPassive() {
return false;
}
final private static Color DEFAULT_MISMATCH_BACKGROUND = new Color(255, 85, 85);
private Color _mismatchBackground;
/**
* Sets the background for mismatch.
*
* @param mismatchBackground
*/
public void setMismatchForeground(Color mismatchBackground) {
_mismatchBackground = mismatchBackground;
}
/**
* Gets the background color when the searching text doesn't match with any of the elements in the component.
*
* @return the foreground color for mismatch. If you never call {@link #setMismatchForeground(java.awt.Color)}. red
* color will be used.
*/
public Color getMismatchBackground() {
if (_mismatchBackground == null) {
return DEFAULT_MISMATCH_BACKGROUND;
}
else {
return _mismatchBackground;
}
}
private Installer _installer;
/**
* The installer for SearchableBar.
*/
public interface Installer {
/**
* Called to show the SearchableBar so that user can see it.
* <p/>
* For example, if you want to add a SearchableBar to the south of a JTextArea, you should add JTextArea to the
* CENTER of a BorderLayout panel. In this method, you add the SearchableBar to the SOUTH of the same
* BorderLayout panel.
*
* @param searchableBar
*/
public void openSearchBar(SearchableBar searchableBar);
/**
* Called to hide the SearchableBar.
*
* @param searchableBar
*/
public void closeSearchBar(SearchableBar searchableBar);
}
public Installer getInstaller() {
return _installer;
}
/**
* Sets the installer. Installer is responsible for the installation and uninstallation of SearchableBar.
*
* @param installer
*/
public void setInstaller(Installer installer) {
_installer = installer;
}
/**
* Installs a SearchableBar on a component. This is just a convenient method for you, you can install it in your own
* code. See below for the actual code we used in this method.
* <p/>
* <code><pre>
* final SearchableBar searchableBar = new SearchableBar(searchable);
* searchableBar.setInstaller(installer);
* ((JComponent) searchable.getComponent()).registerKeyboardAction(new AbstractAction() {
* public void actionPerformed(ActionEvent e) {
* searchableBar.getInstaller().openSearchBar(searchableBar);
* searchableBar.focusSearchField();
* }
* }, keyStroke, JComponent.WHEN_FOCUSED);
* return searchableBar;
* </pre></code>
*
* @param searchable
* @param keyStroke
* @param installer
* @return the SearchableBar that is created.
*/
public static SearchableBar install(Searchable searchable, KeyStroke keyStroke, Installer installer) {
final SearchableBar searchableBar = new SearchableBar(searchable);
searchableBar.setInstaller(installer);
((JComponent) searchable.getComponent()).registerKeyboardAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
searchableBar.getInstaller().openSearchBar(searchableBar);
searchableBar.focusSearchField();
}
}, keyStroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
return searchableBar;
}
@Override
public void processKeyEvent(KeyEvent e) {
}
public int getVisibleButtons() {
return _visibleButtons;
}
/**
* Sets visible buttons on <code>SearchableBar</code>.
*
* @param visibleButtons bit-wise all of several constants. Valid constants are <ul> <li> {@link #SHOW_CLOSE} - the
* close button <li> {@link #SHOW_NAVIGATION} - the find next and find previous buttons <li>
* {@link #SHOW_HIGHLIGHTS} - highlights all button <li> {@link #SHOW_MATCHCASE} - match case
* button <li> {@link #SHOW_REPEATS} - repeats button <li> {@link #SHOW_STATUS} - status area
* <li> {@link #SHOW_ALL} - all buttons </ul> For example, if you want to show only close and
* highlights all button, call <code>setVisibleButtons(SearchableBar.SHOW_CLOSE |
* SearchableBar.SHOW_HIGHLIGHTS)</code>.
*/
public void setVisibleButtons(int visibleButtons) {
_visibleButtons = visibleButtons;
removeAll();
installComponents();
revalidate();
repaint();
}
/**
* Checks if <code>SearchableBar</code> is in compact mode.
*
* @return true if in compact. Otherwise, false.
*/
public boolean isCompact() {
return _compact;
}
/**
* Sets the <code>SearchableBar</code> to compact or full mode. In compact mode will only use icon for buttons v.s.
* full mode will use both icon and text for buttons.
*
* @param compact
*/
public void setCompact(boolean compact) {
_compact = compact;
_findNextButton.setText(_compact ? "" : getResourceString("SearchableBar.findNext"));
_highlightsButton.setText(_compact ? "" : getResourceString("SearchableBar.highlights"));
_findPrevButton.setText(_compact ? "" : getResourceString("SearchableBar.findPrevious"));
}
/**
* Gets the icons from SearchableBarIconsFactory. Subclass can override this method if they want to provide their
* own icon.
*
* @param name
* @return the icon of the specified name.
*/
protected ImageIcon getImageIcon(String name) {
return SearchableBarIconsFactory.getImageIcon(name);
}
/**
* Gets the localized string from resource bundle. Subclass can override it to provide its own string. Available
* keys are defined in swing.properties that begin with "SearchableBar.".
*
* @param key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(Locale.getDefault()).getString(key);
}
}
| false | true | private void initComponents(String initialText) {
AbstractAction closeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (getInstaller() != null) {
getInstaller().closeSearchBar(SearchableBar.this);
}
}
};
AbstractAction findNextAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
int cursor = _searchable.getCursor();
int found = _searchable.findNext(text);
if (found != -1 && _searchable.isRepeats() && found <= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedBottomRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedBottom"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
AbstractAction findPrevAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
int cursor = _searchable.getCursor();
int found = _searchable.findPrevious(text);
if (found != -1 && _searchable.isRepeats() && found >= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedTopRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedTop"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
_closeButton = createCloseButton(closeAction);
_findNextButton = createFindNextButton(findNextAction);
_findPrevButton = createFindPrevButton(findPrevAction);
_highlightsButton = createHighlightButton();
_matchCaseCheckBox = createMatchCaseButton();
_repeatCheckBox = createRepeatsButton();
_statusLabel = new JLabel();
//setup text field
_textField = createTextField();
_textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_textField.selectAll();
}
});
_textField.setColumns(13);
_textField.getDocument().addDocumentListener(new DocumentListener() {
private Timer timer = new Timer(_searchable.getSearchingDelay(), new ActionListener() {
public void actionPerformed(ActionEvent e) {
highlightAllOrNext();
}
});
public void insertUpdate(DocumentEvent e) {
startTimer();
}
public void removeUpdate(DocumentEvent e) {
startTimer();
}
public void changedUpdate(DocumentEvent e) {
startTimer();
}
void startTimer() {
if (_searchable.getSearchingDelay() > 0) {
if (timer.isRunning()) {
timer.restart();
}
else {
timer.setRepeats(false);
timer.start();
}
}
else {
highlightAllOrNext();
}
}
});
_textField.setText(initialText);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findPrevAction, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
installComponents();
int found = _searchable.findFromCursor(getSearchingText());
if (initialText.length() != 0 && found == -1) {
select(found, initialText, false);
}
}
| private void initComponents(String initialText) {
AbstractAction closeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (getInstaller() != null) {
getInstaller().closeSearchBar(SearchableBar.this);
}
}
};
AbstractAction findNextAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
int cursor = _searchable.getSelectedIndex();
_searchable.setCursor(cursor);
int found = _searchable.findNext(text);
if (found != -1 && _searchable.isRepeats() && found <= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedBottomRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedBottom"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
AbstractAction findPrevAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
_highlightsButton.setSelected(false);
String text = getSearchingText();
int cursor = _searchable.getSelectedIndex();
_searchable.setCursor(cursor);
int found = _searchable.findPrevious(text);
if (found != -1 && _searchable.isRepeats() && found >= cursor) {
select(found, text, false);
setStatus(getResourceString("SearchableBar.reachedTopRepeat"), getImageIcon(SearchableBarIconsFactory.Buttons.REPEAT));
}
else if (!_searchable.isRepeats() && found == -1) {
setStatus(getResourceString("SearchableBar.reachedTop"), getImageIcon(SearchableBarIconsFactory.Buttons.ERROR));
}
else if (found != -1) {
select(found, text, false);
clearStatus();
}
}
};
_closeButton = createCloseButton(closeAction);
_findNextButton = createFindNextButton(findNextAction);
_findPrevButton = createFindPrevButton(findPrevAction);
_highlightsButton = createHighlightButton();
_matchCaseCheckBox = createMatchCaseButton();
_repeatCheckBox = createRepeatsButton();
_statusLabel = new JLabel();
//setup text field
_textField = createTextField();
_textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_textField.selectAll();
}
});
_textField.setColumns(13);
_textField.getDocument().addDocumentListener(new DocumentListener() {
private Timer timer = new Timer(_searchable.getSearchingDelay(), new ActionListener() {
public void actionPerformed(ActionEvent e) {
highlightAllOrNext();
}
});
public void insertUpdate(DocumentEvent e) {
startTimer();
}
public void removeUpdate(DocumentEvent e) {
startTimer();
}
public void changedUpdate(DocumentEvent e) {
startTimer();
}
void startTimer() {
if (_searchable.getSearchingDelay() > 0) {
if (timer.isRunning()) {
timer.restart();
}
else {
timer.setRepeats(false);
timer.start();
}
}
else {
highlightAllOrNext();
}
}
});
_textField.setText(initialText);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findNextAction, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(findPrevAction, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED);
_textField.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
installComponents();
int found = _searchable.findFromCursor(getSearchingText());
if (initialText.length() != 0 && found == -1) {
select(found, initialText, false);
}
}
|
diff --git a/app/models/Photo.java b/app/models/Photo.java
index f6c8838..e8ffcb0 100644
--- a/app/models/Photo.java
+++ b/app/models/Photo.java
@@ -1,93 +1,94 @@
package models;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import javax.persistence.*;
import play.libs.*;
import play.db.jpa.*;
import play.data.validation.*;
import net.coobird.thumbnailator.*;
import net.coobird.thumbnailator.geometry.*;
import net.coobird.thumbnailator.name.*;
@Entity
public class Photo extends Post {
public static final int MAX_PIXEL_SIZE = 1024;
@Required
public Blob image;
@Required
public Blob thumbnail120x120,
thumbnail50x50,
thumbnail30x30;
public Photo(User owner, File image) throws IOException,
FileNotFoundException {
this(owner, image, "");
}
public Photo(User owner, File image, String caption)
throws IOException,
FileNotFoundException {
super(owner, owner, caption);
shrinkImage(image);
this.image = fileToBlob(image);
this.createThumbnails();
}
public void updateImage(File image) throws IOException,
FileNotFoundException {
shrinkImage(image);
this.image = fileToBlob(image);
this.createThumbnails();
}
private void createThumbnails() throws IOException {
this.thumbnail120x120 = this.createThumbnailBlob(120, 120);
this.thumbnail50x50 = this.createThumbnailBlob(50, 50);
this.thumbnail30x30 = this.createThumbnailBlob(30, 30);
}
private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
+ .outputQuality(1.0)
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
/**
* Shrink the image to MAX_PIXEL_SIZE if necessary.
*
* @param image the file to convert.
* @throws IOException
*/
private static void shrinkImage(File image) throws IOException {
BufferedImage bufferedImage = ImageIO.read(image);
if (bufferedImage != null && (bufferedImage.getWidth() > MAX_PIXEL_SIZE ||
bufferedImage.getHeight() > MAX_PIXEL_SIZE)) {
Thumbnailator.createThumbnail(image, image,
MAX_PIXEL_SIZE, MAX_PIXEL_SIZE);
}
}
/**
* Convert a given File to a Photo model.
*
* @param image the file to convert.
* @return the newly created Photo model.
* @throws FileNotFoundException
*/
private static Blob fileToBlob(File image) throws FileNotFoundException {
Blob blob = new Blob();
blob.set(new FileInputStream(image),
MimeTypes.getContentType(image.getName()));
return blob;
}
}
| true | true | private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
| private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
.outputQuality(1.0)
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
|
diff --git a/src/main/java/com/avego/cloudinary/Cloudinary.java b/src/main/java/com/avego/cloudinary/Cloudinary.java
index 8e259ca..a75f76c 100644
--- a/src/main/java/com/avego/cloudinary/Cloudinary.java
+++ b/src/main/java/com/avego/cloudinary/Cloudinary.java
@@ -1,264 +1,264 @@
/*
* Copyright © 2012 Avego Ltd., All Rights Reserved.
* For licensing terms please contact Avego LTD.
* 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.avego.cloudinary;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* Functionality for using the Cloudinary CDN. See: https://cloudinary.com/documentation/upload_images
* @version $Id$
* @author eoghancregan
*/
public class Cloudinary {
private static final Logger LOGGER = Logger.getLogger(Cloudinary.class);
private CloudinaryRepository cloudinaryRepository;
/**
* This creates a Cloudinary
* @param cloudinaryRepository
*/
public Cloudinary(CloudinaryRepository cloudinaryRepository) {
this.cloudinaryRepository = cloudinaryRepository;
}
/**
* Encodes the provided bytes in Base 64, parcels it up in a signed JSON Object and fires it at Cloudinary.
* @param bytes
* @param mimeType
* @return
* @throws CloudinaryException
*/
public String postPhotoToCloudinary(byte[] bytes, String mimeType) throws CloudinaryException {
PostMethod post = new PostMethod(this.cloudinaryRepository.getUploadUrl());
long currentTime = new Date().getTime();
String signature = generateSignature(currentTime, null);
String base64RepresentationOfImage = Base64.encodeBytes(bytes);
StringBuilder payload = buildCreationPayload(base64RepresentationOfImage, currentTime, signature, mimeType);
LOGGER.trace("Sending JSON payload to Cloudinary: " + payload);
String response = postJsonToCloudinary(post, payload);
return extractPublicIdFromJson(response);
}
private String extractPublicIdFromJson(String response) throws CloudinaryException {
String publicId = null;
try {
JSONObject jsonObject = new JSONObject(response);
publicId = (String) jsonObject.get("public_id");
} catch (JSONException e) {
throw new CloudinaryException("Failed to Parse Cloudinary Response as JSON: " + response);
}
return publicId;
}
private String postJsonToCloudinary(PostMethod post, StringBuilder payload) throws CloudinaryException {
HttpClient client = new HttpClient();
StringRequestEntity body;
try {
body = new StringRequestEntity(payload.toString(), "application/json", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CloudinaryException("JSON is not supported by Implementation of String Request Entity.", e);
}
post.setRequestEntity(body);
int status;
try {
status = client.executeMethod(post);
} catch (IOException e) {
throw new CloudinaryException("A HTTP Exception Occurred while attempting to POST JSON to CLoudinary.", e);
}
String response = null;
try {
response = post.getResponseBodyAsString();
} catch (IOException e) {
throw new CloudinaryException("Failed to Retrieve response from POST Method.", e);
}
- if (status != 202) {
+ if (status != 200) {
throw new CloudinaryException("Cloudinary Operation was Unsuccessful. Response was: " + response);
}
LOGGER.info("POST was successfully sent to Cloudinary, response was: " + response);
return response;
}
private StringBuilder buildCreationPayload(String base64RepresentationOfImage, long currentTime, String signature, String mimeType) {
StringBuilder payload = new StringBuilder();
payload.append("{ \"file\":");
payload.append("\"data:" + mimeType + ";base64," + base64RepresentationOfImage + "\"");
payload.append(",\"api_key\":");
payload.append("\"");
payload.append(this.cloudinaryRepository.getApiKey());
payload.append("\"");
payload.append(",\"timestamp\":");
payload.append("\"");
payload.append(Long.toString(currentTime));
payload.append("\"");
payload.append(",\"signature\":");
payload.append("\"");
payload.append(signature);
payload.append("\"");
payload.append("}");
return payload;
}
private StringBuilder buildDeletionPayload(String publicId, long currentTime, String signature) {
StringBuilder payload = new StringBuilder();
payload.append("{ \"public_id\":");
payload.append("\"");
payload.append(publicId);
payload.append("\"");
payload.append(",\"api_key\":");
payload.append("\"");
payload.append(this.cloudinaryRepository.getApiKey());
payload.append("\"");
payload.append(",\"timestamp\":");
payload.append("\"");
payload.append(Long.toString(currentTime));
payload.append("\"");
payload.append(",\"signature\":");
payload.append("\"");
payload.append(signature);
payload.append("\"");
payload.append("}");
return payload;
}
private String generateSignature(long currentTime, String publicId) throws CloudinaryException {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
throw new CloudinaryException("No SHA1 Message Digest Algorithm was available.", e);
}
StringBuilder stringToSign = new StringBuilder();
if (publicId != null) {
stringToSign.append("public_id=");
stringToSign.append(publicId);
stringToSign.append("&");
}
stringToSign.append("timestamp=");
stringToSign.append(Long.toString(currentTime));
stringToSign.append(this.cloudinaryRepository.getSecretkey());
messageDigest.update(stringToSign.toString().getBytes());
String unpaddedSha1Hex = new BigInteger(1, messageDigest.digest()).toString(16);
String sha1Hex = String.format("%40s", unpaddedSha1Hex).replace(' ', '0');
return sha1Hex;
}
/**
* Builds a URL pointing the Image with the provided Public Id, Mime Type and Meta Info.
* @param publicId
* @param mimeType
* @param width
* @param height
* @return
* @throws CloudinaryException
*/
public URI buildCloudinaryPhotoURI(String publicId, String mimeType, int width, int height) throws CloudinaryException {
StringBuilder urlBuilder = new StringBuilder(this.cloudinaryRepository.getDownloadUrl());
applyTransformation(width, height, urlBuilder);
urlBuilder.append("/");
urlBuilder.append(publicId);
if (mimeType == null || mimeType == "image/jpeg") {
urlBuilder.append(".jpg");
}
try {
return new URI(urlBuilder.toString());
} catch (URISyntaxException e) {
throw new CloudinaryException("Failed to Generate valid URI from public id: " + publicId, e);
}
}
private void applyTransformation(int width, int height, StringBuilder urlBuilder) {
if (width > 0 || height > 0) {
urlBuilder.append("/");
if (width > 0) {
urlBuilder.append("w_");
urlBuilder.append(Integer.toString(width));
urlBuilder.append(",");
}
if (height > 0) {
urlBuilder.append("h_");
urlBuilder.append(Integer.toString(height));
urlBuilder.append(",");
}
urlBuilder.append("c_fill");
}
}
/**
* Deletes an Image with the associated Public Id if one exists.
* @param publicId
* @throws CloudinaryException
*/
public void deleteImageFromCloudinary(String publicId) throws CloudinaryException {
PostMethod post = new PostMethod(this.cloudinaryRepository.getDeletionUrl());
long currentTime = new Date().getTime();
String signature = generateSignature(currentTime, publicId);
StringBuilder payload = buildDeletionPayload(publicId, currentTime, signature);
LOGGER.trace("Sending JSON payload to Cloudinary: " + payload);
postJsonToCloudinary(post, payload);
}
}
| true | true | private String postJsonToCloudinary(PostMethod post, StringBuilder payload) throws CloudinaryException {
HttpClient client = new HttpClient();
StringRequestEntity body;
try {
body = new StringRequestEntity(payload.toString(), "application/json", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CloudinaryException("JSON is not supported by Implementation of String Request Entity.", e);
}
post.setRequestEntity(body);
int status;
try {
status = client.executeMethod(post);
} catch (IOException e) {
throw new CloudinaryException("A HTTP Exception Occurred while attempting to POST JSON to CLoudinary.", e);
}
String response = null;
try {
response = post.getResponseBodyAsString();
} catch (IOException e) {
throw new CloudinaryException("Failed to Retrieve response from POST Method.", e);
}
if (status != 202) {
throw new CloudinaryException("Cloudinary Operation was Unsuccessful. Response was: " + response);
}
LOGGER.info("POST was successfully sent to Cloudinary, response was: " + response);
return response;
}
| private String postJsonToCloudinary(PostMethod post, StringBuilder payload) throws CloudinaryException {
HttpClient client = new HttpClient();
StringRequestEntity body;
try {
body = new StringRequestEntity(payload.toString(), "application/json", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CloudinaryException("JSON is not supported by Implementation of String Request Entity.", e);
}
post.setRequestEntity(body);
int status;
try {
status = client.executeMethod(post);
} catch (IOException e) {
throw new CloudinaryException("A HTTP Exception Occurred while attempting to POST JSON to CLoudinary.", e);
}
String response = null;
try {
response = post.getResponseBodyAsString();
} catch (IOException e) {
throw new CloudinaryException("Failed to Retrieve response from POST Method.", e);
}
if (status != 200) {
throw new CloudinaryException("Cloudinary Operation was Unsuccessful. Response was: " + response);
}
LOGGER.info("POST was successfully sent to Cloudinary, response was: " + response);
return response;
}
|
diff --git a/exchange2/src/com/android/exchange/adapter/ProvisionParser.java b/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
index de30111..0825f74 100644
--- a/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
+++ b/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
@@ -1,616 +1,616 @@
/* Copyright (C) 2010 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.exchange.adapter;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import com.android.emailcommon.provider.Policy;
import com.android.exchange.EasSyncService;
import com.android.exchange.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Parse the result of the Provision command
*/
public class ProvisionParser extends Parser {
private final EasSyncService mService;
private Policy mPolicy = null;
private String mSecuritySyncKey = null;
private boolean mRemoteWipe = false;
private boolean mIsSupportable = true;
private boolean smimeRequired = false;
private final Resources mResources;
public ProvisionParser(InputStream in, EasSyncService service) throws IOException {
super(in);
mService = service;
mResources = service.mContext.getResources();
}
public Policy getPolicy() {
return mPolicy;
}
public String getSecuritySyncKey() {
return mSecuritySyncKey;
}
public void setSecuritySyncKey(String securitySyncKey) {
mSecuritySyncKey = securitySyncKey;
}
public boolean getRemoteWipe() {
return mRemoteWipe;
}
public boolean hasSupportablePolicySet() {
return (mPolicy != null) && mIsSupportable;
}
public void clearUnsupportablePolicies() {
mIsSupportable = true;
mPolicy.mProtocolPoliciesUnsupported = null;
}
private void addPolicyString(StringBuilder sb, int res) {
sb.append(mResources.getString(res));
sb.append(Policy.POLICY_STRING_DELIMITER);
}
/**
* Complete setup of a Policy; we normalize it first (removing inconsistencies, etc.) and then
* generate the tokenized "protocol policies enforced" string. Note that unsupported policies
* must have been added prior to calling this method (this is only a possibility with wbxml
* policy documents, as all versions of the OS support the policies in xml documents).
*/
private void setPolicy(Policy policy) {
policy.normalize();
StringBuilder sb = new StringBuilder();
if (policy.mDontAllowAttachments) {
addPolicyString(sb, R.string.policy_dont_allow_attachments);
}
if (policy.mRequireManualSyncWhenRoaming) {
addPolicyString(sb, R.string.policy_require_manual_sync_roaming);
}
policy.mProtocolPoliciesEnforced = sb.toString();
mPolicy = policy;
}
private boolean deviceSupportsEncryption() {
DevicePolicyManager dpm = (DevicePolicyManager)
mService.mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
int status = dpm.getStorageEncryptionStatus();
return status != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
}
private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
- log("Removable: " + volume.getDescription());
+ log("Removable: " + volume.getDescription(mService.mContext));
break; // Break only from the storage volume loop
} else {
- log("Not Removable: " + volume.getDescription());
+ log("Not Removable: " + volume.getDescription(mService.mContext));
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
/**
* Return whether or not either of the application list tags specifies any applications
* @param endTag the tag whose children we're walking through
* @return whether any applications were specified (by name or by hash)
* @throws IOException
*/
private boolean specifiesApplications(int endTag) throws IOException {
boolean specifiesApplications = false;
while (nextTag(endTag) != END) {
switch (tag) {
case Tags.PROVISION_APPLICATION_NAME:
case Tags.PROVISION_HASH:
specifiesApplications = true;
break;
default:
skipTag();
}
}
return specifiesApplications;
}
/*package*/ void parseProvisionDocXml(String doc) throws IOException {
Policy policy = new Policy();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8");
int type = parser.getEventType();
if (type == XmlPullParser.START_DOCUMENT) {
type = parser.next();
if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("wap-provisioningdoc")) {
parseWapProvisioningDoc(parser, policy);
}
}
}
} catch (XmlPullParserException e) {
throw new IOException();
}
setPolicy(policy);
}
/**
* Return true if password is required; otherwise false.
*/
private boolean parseSecurityPolicy(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
boolean passwordRequired = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("parm")) {
String name = parser.getAttributeValue(null, "name");
if (name.equals("4131")) {
String value = parser.getAttributeValue(null, "value");
if (value.equals("1")) {
passwordRequired = false;
}
}
}
}
}
return passwordRequired;
}
private void parseCharacteristic(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
boolean enforceInactivityTimer = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
if (parser.getName().equals("parm")) {
String name = parser.getAttributeValue(null, "name");
String value = parser.getAttributeValue(null, "value");
if (name.equals("AEFrequencyValue")) {
if (enforceInactivityTimer) {
if (value.equals("0")) {
policy.mMaxScreenLockTime = 1;
} else {
policy.mMaxScreenLockTime = 60*Integer.parseInt(value);
}
}
} else if (name.equals("AEFrequencyType")) {
// "0" here means we don't enforce an inactivity timeout
if (value.equals("0")) {
enforceInactivityTimer = false;
}
} else if (name.equals("DeviceWipeThreshold")) {
policy.mPasswordMaxFails = Integer.parseInt(value);
} else if (name.equals("CodewordFrequency")) {
// Ignore; has no meaning for us
} else if (name.equals("MinimumPasswordLength")) {
policy.mPasswordMinLength = Integer.parseInt(value);
} else if (name.equals("PasswordComplexity")) {
if (value.equals("0")) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
} else {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
}
}
}
}
private void parseRegistry(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
parseCharacteristic(parser, policy);
}
}
}
}
private void parseWapProvisioningDoc(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
String atype = parser.getAttributeValue(null, "type");
if (atype.equals("SecurityPolicy")) {
// If a password isn't required, stop here
if (!parseSecurityPolicy(parser, policy)) {
return;
}
} else if (atype.equals("Registry")) {
parseRegistry(parser, policy);
return;
}
}
}
}
}
private void parseProvisionData() throws IOException {
while (nextTag(Tags.PROVISION_DATA) != END) {
if (tag == Tags.PROVISION_EAS_PROVISION_DOC) {
parseProvisionDocWbxml();
} else {
skipTag();
}
}
}
private void parsePolicy() throws IOException {
String policyType = null;
while (nextTag(Tags.PROVISION_POLICY) != END) {
switch (tag) {
case Tags.PROVISION_POLICY_TYPE:
policyType = getValue();
mService.userLog("Policy type: ", policyType);
break;
case Tags.PROVISION_POLICY_KEY:
mSecuritySyncKey = getValue();
break;
case Tags.PROVISION_STATUS:
mService.userLog("Policy status: ", getValue());
break;
case Tags.PROVISION_DATA:
if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) {
// Parse the old style XML document
parseProvisionDocXml(getValue());
} else {
// Parse the newer WBXML data
parseProvisionData();
}
break;
default:
skipTag();
}
}
}
private void parsePolicies() throws IOException {
while (nextTag(Tags.PROVISION_POLICIES) != END) {
if (tag == Tags.PROVISION_POLICY) {
parsePolicy();
} else {
skipTag();
}
}
}
private void parseDeviceInformation() throws IOException {
while (nextTag(Tags.SETTINGS_DEVICE_INFORMATION) != END) {
if (tag == Tags.SETTINGS_STATUS) {
mService.userLog("DeviceInformation status: " + getValue());
} else {
skipTag();
}
}
}
@Override
public boolean parse() throws IOException {
boolean res = false;
if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) {
throw new IOException();
}
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
switch (tag) {
case Tags.PROVISION_STATUS:
int status = getValueInt();
mService.userLog("Provision status: ", status);
res = (status == 1);
break;
case Tags.SETTINGS_DEVICE_INFORMATION:
parseDeviceInformation();
break;
case Tags.PROVISION_POLICIES:
parsePolicies();
break;
case Tags.PROVISION_REMOTE_WIPE:
// Indicate remote wipe command received
mRemoteWipe = true;
break;
default:
skipTag();
}
}
return res;
}
}
| false | true | private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
log("Removable: " + volume.getDescription());
break; // Break only from the storage volume loop
} else {
log("Not Removable: " + volume.getDescription());
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
| private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
log("Removable: " + volume.getDescription(mService.mContext));
break; // Break only from the storage volume loop
} else {
log("Not Removable: " + volume.getDescription(mService.mContext));
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/provider/NavigatorActionProvider.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/provider/NavigatorActionProvider.java
index d11017b71..88ec69f93 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/provider/NavigatorActionProvider.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/provider/NavigatorActionProvider.java
@@ -1,127 +1,128 @@
/*
* Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.developerstudio.eclipse.esb.project.provider;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionConstants;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.part.FileEditorInput;
import org.wso2.developerstudio.eclipse.esb.project.Activator;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
/**
* Custom NavigatorActionProvider for handling editor switching for ESB files
*
*/
public class NavigatorActionProvider extends CommonActionProvider {
private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
private OpenEditorAction openEditorAction;
@Override
public void fillActionBars(IActionBars actionBars) {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
if (selection instanceof TreeSelection) {
TreeSelection treeSelection = (TreeSelection) selection;
Object firstElement = treeSelection.getFirstElement();
if (firstElement instanceof IFile) {
IFile file = (IFile) firstElement;
try {
IContentDescription contentDescription = file.getContentDescription();
if (contentDescription != null) {
IContentType contentType = contentDescription.getContentType();
if (contentType.getId() != null) {
if ("org.wso2.developerstudio.eclipse.esb.contenttype.esbconfxml"
.equals(contentType.getId())) {
openEditorAction.setSelection(file);
actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
openEditorAction);
}
}
}
} catch (CoreException e) {
/* ignore */
}
}
}
}
@Override
public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
openEditorAction = new OpenEditorAction();
}
private static class OpenEditorAction extends Action {
private IFile selection;
@Override
public void run() {
IFile fileTobeOpen = null;
String synFilePath = selection.getFullPath().toOSString();
String diagramFilePath = synFilePath
.replaceFirst("/synapse-config/", "/graphical-synapse-config/")
.replaceFirst("/endpoints/", "/endpoints/endpoint_")
.replaceFirst("/local-entries/", "/local-entries/localentry_")
.replaceFirst("/proxy-services/", "/proxy-services/proxy_")
.replaceFirst("/sequences/", "/sequences/sequence_")
+ .replaceFirst("/tasks/", "/tasks/task_")
.replaceAll(".xml$", ".esb_diagram");
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
try {
if (selection.getWorkspace().getRoot().getFile(new Path(diagramFilePath)).exists()) {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(diagramFilePath));
IDE.openEditor(page, fileTobeOpen);
} else {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(synFilePath));
page.openEditor(new FileEditorInput(fileTobeOpen),
"org.wso2.developerstudio.eclipse.esb.presentation.EsbEditor");
}
} catch (PartInitException e) {
log.error("Can't open " + fileTobeOpen, e);
}
}
public void setSelection(IFile selection) {
this.selection = selection;
}
}
}
| true | true | public void run() {
IFile fileTobeOpen = null;
String synFilePath = selection.getFullPath().toOSString();
String diagramFilePath = synFilePath
.replaceFirst("/synapse-config/", "/graphical-synapse-config/")
.replaceFirst("/endpoints/", "/endpoints/endpoint_")
.replaceFirst("/local-entries/", "/local-entries/localentry_")
.replaceFirst("/proxy-services/", "/proxy-services/proxy_")
.replaceFirst("/sequences/", "/sequences/sequence_")
.replaceAll(".xml$", ".esb_diagram");
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
try {
if (selection.getWorkspace().getRoot().getFile(new Path(diagramFilePath)).exists()) {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(diagramFilePath));
IDE.openEditor(page, fileTobeOpen);
} else {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(synFilePath));
page.openEditor(new FileEditorInput(fileTobeOpen),
"org.wso2.developerstudio.eclipse.esb.presentation.EsbEditor");
}
} catch (PartInitException e) {
log.error("Can't open " + fileTobeOpen, e);
}
}
| public void run() {
IFile fileTobeOpen = null;
String synFilePath = selection.getFullPath().toOSString();
String diagramFilePath = synFilePath
.replaceFirst("/synapse-config/", "/graphical-synapse-config/")
.replaceFirst("/endpoints/", "/endpoints/endpoint_")
.replaceFirst("/local-entries/", "/local-entries/localentry_")
.replaceFirst("/proxy-services/", "/proxy-services/proxy_")
.replaceFirst("/sequences/", "/sequences/sequence_")
.replaceFirst("/tasks/", "/tasks/task_")
.replaceAll(".xml$", ".esb_diagram");
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
try {
if (selection.getWorkspace().getRoot().getFile(new Path(diagramFilePath)).exists()) {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(diagramFilePath));
IDE.openEditor(page, fileTobeOpen);
} else {
fileTobeOpen = selection.getWorkspace().getRoot()
.getFile(new Path(synFilePath));
page.openEditor(new FileEditorInput(fileTobeOpen),
"org.wso2.developerstudio.eclipse.esb.presentation.EsbEditor");
}
} catch (PartInitException e) {
log.error("Can't open " + fileTobeOpen, e);
}
}
|
diff --git a/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java b/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
index af6585d9..407abf2c 100644
--- a/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
+++ b/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
@@ -1,649 +1,654 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.data.osm.visitor;
import static org.openstreetmap.josm.tools.I18n.marktr;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Locale;
import javax.swing.ImageIcon;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.data.osm.RelationMember;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.data.osm.visitor.SimplePaintVisitor;
import org.openstreetmap.josm.gui.mappaint.AreaElemStyle;
import org.openstreetmap.josm.gui.mappaint.ElemStyle;
import org.openstreetmap.josm.gui.mappaint.ElemStyles;
import org.openstreetmap.josm.gui.mappaint.IconElemStyle;
import org.openstreetmap.josm.gui.mappaint.LineElemStyle;
import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
public class MapPaintVisitor extends SimplePaintVisitor {
protected boolean useRealWidth;
protected boolean zoomLevelDisplay;
protected boolean fillAreas;
protected int fillAlpha;
protected Color untaggedColor;
protected Color textColor;
protected boolean currentDashed = false;
protected int currentWidth = 0;
protected Stroke currentStroke = null;
protected Font orderFont;
protected ElemStyles styles;
protected double circum;
protected String regionalNameOrder[];
protected Collection<Way> alreadyDrawnWays = new LinkedList<Way>();
protected Collection<Way> alreadyDrawnAreas = new LinkedList<Way>();
protected boolean isZoomOk(ElemStyle e) {
if (!zoomLevelDisplay) /* show everything if the user wishes so */
return true;
if(e == null) /* the default for things that don't have a rule (show, if scale is smaller than 1500m) */
return (circum < 1500);
// formula to calculate a map scale: natural size / map size = scale
// example: 876000mm (876m as displayed) / 22mm (roughly estimated screen size of legend bar) = 39818
//
// so the exact "correcting value" below depends only on the screen size and resolution
// XXX - do we need a Preference setting for this (if things vary widely)?
return !(circum >= e.maxScale / 22 || circum < e.minScale / 22);
}
/**
* Draw a small rectangle.
* White if selected (as always) or red otherwise.
*
* @param n The node to draw.
*/
public void visit(Node n) {
IconElemStyle nodeStyle = styles.get(n);
if (nodeStyle != null && isZoomOk(nodeStyle))
drawNode(n, nodeStyle.icon, nodeStyle.annotate);
else if (n.selected)
drawNode(n, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
else if (n.tagged)
drawNode(n, nodeColor, taggedNodeSize, taggedNodeRadius, fillUnselectedNode);
else
drawNode(n, nodeColor, unselectedNodeSize, unselectedNodeRadius, fillUnselectedNode);
}
/**
* Draw a line for all segments, according to tags.
* @param w The way to draw.
*/
public void visit(Way w) {
if(w.nodes.size() < 2)
return;
ElemStyle wayStyle = styles.get(w);
if(!isZoomOk(wayStyle))
return;
LineElemStyle l = null;
Color areacolor = untaggedColor;
if(wayStyle!=null)
{
boolean area = false;
if(wayStyle instanceof LineElemStyle)
l = (LineElemStyle)wayStyle;
else if (wayStyle instanceof AreaElemStyle)
{
areacolor = ((AreaElemStyle)wayStyle).color;
l = ((AreaElemStyle)wayStyle).line;
area = true;
}
if (area && fillAreas)
drawWayAsArea(w, areacolor);
}
drawWay(w, l, areacolor);
}
public void drawWay(Way w, LineElemStyle l, Color color) {
// show direction arrows, if draw.segment.relevant_directions_only is not set,
// the way is tagged with a direction key
// (even if the tag is negated as in oneway=false) or the way is selected
boolean showDirection = w.selected || ((!useRealWidth) && (showDirectionArrow
&& (!showRelevantDirectionsOnly || w.hasDirectionKeys)));
int width = defaultSegmentWidth;
int realWidth = 0; //the real width of the element in meters
boolean dashed = false;
if(l != null)
{
color = l.color;
width = l.width;
realWidth = l.realWidth;
dashed = l.dashed;
}
if (realWidth > 0 && useRealWidth && !showDirection)
{
int tmpWidth = (int) (100 / (float) (circum / realWidth));
if (tmpWidth > width) width = tmpWidth;
}
if(w.selected)
color = selectedColor;
Node lastN;
if(l != null && l.overlays != null)
{
for(LineElemStyle s : l.overlays)
{
if(!s.over)
{
lastN = null;
for(Node n : w.nodes)
{
if(lastN != null)
{
drawSeg(lastN, n, s.color != null && !w.selected ? s.color : color,
false, s.getWidth(width), s.dashed);
}
lastN = n;
}
}
}
}
lastN = null;
for(Node n : w.nodes)
{
if(lastN != null)
drawSeg(lastN, n, color, showDirection, width, dashed);
lastN = n;
}
if(l != null && l.overlays != null)
{
for(LineElemStyle s : l.overlays)
{
if(s.over)
{
lastN = null;
for(Node n : w.nodes)
{
if(lastN != null)
{
drawSeg(lastN, n, s.color != null && !w.selected ? s.color : color,
false, s.getWidth(width), s.dashed);
}
lastN = n;
}
}
}
}
if(showOrderNumber)
{
int orderNumber = 0;
lastN = null;
for(Node n : w.nodes)
{
if(lastN != null)
{
orderNumber++;
drawOrderNumber(lastN, n, orderNumber);
}
lastN = n;
}
}
displaySegments();
}
public Collection<Way> joinWays(Collection<Way> join)
{
Collection<Way> res = new LinkedList<Way>();
Object[] joinArray = join.toArray();
int left = join.size();
while(left != 0)
{
Way w = null;
Boolean selected = false;
ArrayList<Node> n = null;
Boolean joined = true;
while(joined && left != 0)
{
joined = false;
for(int i = 0; i < joinArray.length && left != 0; ++i)
{
if(joinArray[i] != null)
{
Way c = (Way)joinArray[i];
if(w == null)
{ w = c; selected = w.selected; joinArray[i] = null; --left; }
else
{
int mode = 0;
int cl = c.nodes.size()-1;
int nl;
if(n == null)
{
nl = w.nodes.size()-1;
if(w.nodes.get(nl) == c.nodes.get(0)) mode = 21;
else if(w.nodes.get(nl) == c.nodes.get(cl)) mode = 22;
else if(w.nodes.get(0) == c.nodes.get(0)) mode = 11;
else if(w.nodes.get(0) == c.nodes.get(cl)) mode = 12;
}
else
{
nl = n.size()-1;
if(n.get(nl) == c.nodes.get(0)) mode = 21;
else if(n.get(0) == c.nodes.get(cl)) mode = 12;
else if(n.get(0) == c.nodes.get(0)) mode = 11;
else if(n.get(nl) == c.nodes.get(cl)) mode = 22;
}
if(mode != 0)
{
joinArray[i] = null;
joined = true;
if(c.selected) selected = true;
--left;
if(n == null) n = new ArrayList(w.nodes);
n.remove((mode == 21 || mode == 22) ? nl : 0);
if(mode == 21)
n.addAll(c.nodes);
else if(mode == 12)
n.addAll(0, c.nodes);
else if(mode == 22)
{
for(Node node : c.nodes)
n.add(nl, node);
}
else /* mode == 11 */
{
for(Node node : c.nodes)
n.add(0, node);
}
}
}
}
} /* for(i = ... */
} /* while(joined) */
if(n != null)
{
w = new Way(w);
w.nodes.clear();
w.nodes.addAll(n);
w.selected = selected;
}
if(!w.isClosed())
{
System.out.println("ERROR: multipolygon way is not closed." + w);
}
res.add(w);
} /* while(left != 0) */
return res;
}
public void visit(Relation r) {
// draw multipolygon relations including their ways
// other relations are not (yet?) drawn.
if (r.incomplete) return;
if(!Main.pref.getBoolean("mappaint.multipolygon",false)) return;
if(!"multipolygon".equals(r.keys.get("type"))) return;
Collection<Way> inner = new LinkedList<Way>();
Collection<Way> outer = new LinkedList<Way>();
Collection<Way> innerclosed = new LinkedList<Way>();
Collection<Way> outerclosed = new LinkedList<Way>();
for (RelationMember m : r.members)
{
if (!m.member.incomplete && !m.member.deleted)
{
if(m.member instanceof Way)
{
Way w = (Way) m.member;
if(w.nodes.size() < 2)
{
System.out.println("ERROR: Way with less than two points " + w);
}
else if("inner".equals(m.role))
inner.add(w);
else if("outer".equals(m.role))
outer.add(w);
else
{
System.out.println("ERROR: No useful role for Way " + w);
if(m.role == null || m.role.length() == 0)
outer.add(w);
}
}
else
{
System.out.println("ERROR: Non-Way in multipolygon " + m.member);
}
}
}
ElemStyle wayStyle = styles.get(r);
/* find one wayStyle, prefer the style from Relation or take the first
one of outer rings */
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
{
for (Way w : outer)
{
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
wayStyle = styles.get(w);
}
}
if(wayStyle != null && wayStyle instanceof AreaElemStyle)
{
Boolean zoomok = isZoomOk(wayStyle);
Collection<Way> join = new LinkedList<Way>();
/* parse all outer rings and join them */
for (Way w : outer)
{
if(w.isClosed()) outerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
outerclosed.add(w);
}
/* parse all inner rings and join them */
join.clear();
for (Way w : inner)
{
if(w.isClosed()) innerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
innerclosed.add(w);
}
/* handle inside out stuff */
if(zoomok) /* draw */
{
for (Way w : outerclosed)
{
Color color = w.selected ? selectedColor
: ((AreaElemStyle)wayStyle).color;
Polygon polygon = new Polygon();
Point pOuter = null;
for (Node n : w.nodes)
{
pOuter = nc.getPoint(n.eastNorth);
polygon.addPoint(pOuter.x,pOuter.y);
}
for (Way wInner : innerclosed)
{
for (Node n : wInner.nodes)
{
Point pInner = nc.getPoint(n.eastNorth);
polygon.addPoint(pInner.x,pInner.y);
}
+ if(!wInner.isClosed())
+ {
+ Point pInner = nc.getPoint(wInner.nodes.get(0).eastNorth);
+ polygon.addPoint(pInner.x,pInner.y);
+ }
polygon.addPoint(pOuter.x,pOuter.y);
}
g.setColor(new Color( color.getRed(), color.getGreen(),
color.getBlue(), fillAlpha));
g.fillPolygon(polygon);
alreadyDrawnAreas.add(w);
}
}
for (Way wInner : inner)
{
ElemStyle innerStyle = styles.get(wInner);
if(innerStyle == null)
{
if(zoomok)
drawWay(wInner, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wInner);
}
else if(wayStyle.equals(innerStyle))
{
System.out.println("WARNING: Inner waystyle equals multipolygon for way " + wInner);
alreadyDrawnAreas.add(wInner);
}
}
for (Way wOuter : outer)
{
ElemStyle outerStyle = styles.get(wOuter);
if(outerStyle == null)
{
if(zoomok)
drawWay(wOuter, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wOuter);
}
else
{
if(!wayStyle.equals(outerStyle))
System.out.println("ERROR: Outer waystyle does not match multipolygon for way " + wOuter);
alreadyDrawnAreas.add(wOuter);
}
}
}
}
protected void drawWayAsArea(Way w, Color color)
{
Polygon polygon = new Polygon();
for (Node n : w.nodes)
{
Point p = nc.getPoint(n.eastNorth);
polygon.addPoint(p.x,p.y);
}
Color mycolor = w.selected ? selectedColor : color;
// set the opacity (alpha) level of the filled polygon
g.setColor(new Color( mycolor.getRed(), mycolor.getGreen(), mycolor.getBlue(), fillAlpha));
g.fillPolygon(polygon);
}
// NEW
protected void drawNode(Node n, ImageIcon icon, boolean annotate) {
Point p = nc.getPoint(n.eastNorth);
if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth()) || (p.y > nc.getHeight())) return;
int w = icon.getIconWidth(), h=icon.getIconHeight();
icon.paintIcon ( Main.map.mapView, g, p.x-w/2, p.y-h/2 );
String name = getNodeName(n);
if (name!=null && annotate)
{
g.setColor(textColor);
Font defaultFont = g.getFont();
g.setFont (orderFont);
g.drawString (name, p.x+w/2+2, p.y+h/2+2);
g.setFont(defaultFont);
}
if (n.selected)
{
g.setColor ( selectedColor );
g.drawRect (p.x-w/2-2,p.y-w/2-2, w+4, h+4);
}
}
protected String getNodeName(Node n) {
String name = null;
if (n.keys != null) {
for (int i = 0; i < regionalNameOrder.length; i++) {
name = n.keys.get(regionalNameOrder[i]);
if (name != null) break;
}
}
return name;
}
private void drawSeg(Node n1, Node n2, Color col, boolean showDirection, int width, boolean dashed) {
if (col != currentColor || width != currentWidth || dashed != currentDashed) {
displaySegments(col, width, dashed);
}
Point p1 = nc.getPoint(n1.eastNorth);
Point p2 = nc.getPoint(n2.eastNorth);
if (!isSegmentVisible(p1, p2)) {
return;
}
currentPath.moveTo(p1.x, p1.y);
currentPath.lineTo(p2.x, p2.y);
if (showDirection) {
double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
currentPath.lineTo((int)(p2.x + 10*Math.cos(t-PHI)), (int)(p2.y + 10*Math.sin(t-PHI)));
currentPath.moveTo((int)(p2.x + 10*Math.cos(t+PHI)), (int)(p2.y + 10*Math.sin(t+PHI)));
currentPath.lineTo(p2.x, p2.y);
}
}
protected void displaySegments() {
displaySegments(null, 0, false);
}
protected void displaySegments(Color newColor, int newWidth, boolean newDash) {
if (currentPath != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(inactive ? inactiveColor : currentColor);
if (currentStroke == null) {
if (currentDashed)
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_BUTT,BasicStroke.JOIN_ROUND,0,new float[] {9},0));
else
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
}
g2d.draw(currentPath);
g2d.setStroke(new BasicStroke(1));
currentPath = new GeneralPath();
currentColor = newColor;
currentWidth = newWidth;
currentDashed = newDash;
currentStroke = null;
}
}
/**
* Draw the node as small rectangle with the given color.
*
* @param n The node to draw.
* @param color The color of the node.
*/
public void drawNode(Node n, Color color, int size, int radius, boolean fill) {
if (isZoomOk(null) && size > 1) {
Point p = nc.getPoint(n.eastNorth);
if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth())
|| (p.y > nc.getHeight()))
return;
g.setColor(color);
if (fill) {
g.fillRect(p.x - radius, p.y - radius, size, size);
g.drawRect(p.x - radius, p.y - radius, size, size);
} else
g.drawRect(p.x - radius, p.y - radius, size, size);
}
}
// NW 111106 Overridden from SimplePaintVisitor in josm-1.4-nw1
// Shows areas before non-areas
public void visitAll(DataSet data, Boolean virtual) {
getSettings(virtual);
untaggedColor = Main.pref.getColor(marktr("untagged"),Color.GRAY);
textColor = Main.pref.getColor (marktr("text"), Color.WHITE);
useRealWidth = Main.pref.getBoolean("mappaint.useRealWidth",false);
zoomLevelDisplay = Main.pref.getBoolean("mappaint.zoomLevelDisplay",false);
fillAreas = Main.pref.getBoolean("mappaint.fillareas", true);
fillAlpha = Math.min(255, Math.max(0, Integer.valueOf(Main.pref.getInteger("mappaint.fillalpha", 50))));
circum = Main.map.mapView.getScale()*100*Main.proj.scaleFactor()*40041455; // circumference of the earth in meter
styles = MapPaintStyles.getStyles();
orderFont = new Font(Main.pref.get("mappaint.font","Helvetica"), Font.PLAIN, Main.pref.getInteger("mappaint.fontsize", 8));
String currentLocale = Locale.getDefault().getLanguage();
regionalNameOrder = Main.pref.get("mappaint.nameOrder", "name:"+currentLocale+";name;int_name").split(";");
if (fillAreas && styles.hasAreas()) {
Collection<Way> noAreaWays = new LinkedList<Way>();
for (final Relation osm : data.relations)
{
if (!osm.deleted && !osm.selected)
{
osm.visit(this);
}
}
for (final Way osm : data.ways)
{
if (!osm.incomplete && !osm.deleted && !alreadyDrawnWays.contains(osm))
{
if(styles.isArea((Way)osm) && !alreadyDrawnAreas.contains(osm))
osm.visit(this);
else
noAreaWays.add((Way)osm);
}
}
// free that stuff
alreadyDrawnWays = null;
alreadyDrawnAreas = null;
fillAreas = false;
for (final OsmPrimitive osm : noAreaWays)
osm.visit(this);
}
else
{
for (final OsmPrimitive osm : data.ways)
if (!osm.incomplete && !osm.deleted)
osm.visit(this);
}
for (final OsmPrimitive osm : data.getSelected())
if (!osm.incomplete && !osm.deleted){
osm.visit(this);
}
displaySegments();
for (final OsmPrimitive osm : data.nodes)
if (!osm.incomplete && !osm.deleted)
osm.visit(this);
if (virtualNodeSize != 0)
{
currentColor = nodeColor;
for (final OsmPrimitive osm : data.ways)
if (!osm.deleted)
visitVirtual((Way)osm);
displaySegments(null);
}
}
/**
* Draw a number of the order of the two consecutive nodes within the
* parents way
*/
protected void drawOrderNumber(Node n1, Node n2, int orderNumber) {
Point p1 = nc.getPoint(n1.eastNorth);
Point p2 = nc.getPoint(n2.eastNorth);
drawOrderNumber(p1, p2, orderNumber);
}
}
| true | true | public void visit(Relation r) {
// draw multipolygon relations including their ways
// other relations are not (yet?) drawn.
if (r.incomplete) return;
if(!Main.pref.getBoolean("mappaint.multipolygon",false)) return;
if(!"multipolygon".equals(r.keys.get("type"))) return;
Collection<Way> inner = new LinkedList<Way>();
Collection<Way> outer = new LinkedList<Way>();
Collection<Way> innerclosed = new LinkedList<Way>();
Collection<Way> outerclosed = new LinkedList<Way>();
for (RelationMember m : r.members)
{
if (!m.member.incomplete && !m.member.deleted)
{
if(m.member instanceof Way)
{
Way w = (Way) m.member;
if(w.nodes.size() < 2)
{
System.out.println("ERROR: Way with less than two points " + w);
}
else if("inner".equals(m.role))
inner.add(w);
else if("outer".equals(m.role))
outer.add(w);
else
{
System.out.println("ERROR: No useful role for Way " + w);
if(m.role == null || m.role.length() == 0)
outer.add(w);
}
}
else
{
System.out.println("ERROR: Non-Way in multipolygon " + m.member);
}
}
}
ElemStyle wayStyle = styles.get(r);
/* find one wayStyle, prefer the style from Relation or take the first
one of outer rings */
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
{
for (Way w : outer)
{
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
wayStyle = styles.get(w);
}
}
if(wayStyle != null && wayStyle instanceof AreaElemStyle)
{
Boolean zoomok = isZoomOk(wayStyle);
Collection<Way> join = new LinkedList<Way>();
/* parse all outer rings and join them */
for (Way w : outer)
{
if(w.isClosed()) outerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
outerclosed.add(w);
}
/* parse all inner rings and join them */
join.clear();
for (Way w : inner)
{
if(w.isClosed()) innerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
innerclosed.add(w);
}
/* handle inside out stuff */
if(zoomok) /* draw */
{
for (Way w : outerclosed)
{
Color color = w.selected ? selectedColor
: ((AreaElemStyle)wayStyle).color;
Polygon polygon = new Polygon();
Point pOuter = null;
for (Node n : w.nodes)
{
pOuter = nc.getPoint(n.eastNorth);
polygon.addPoint(pOuter.x,pOuter.y);
}
for (Way wInner : innerclosed)
{
for (Node n : wInner.nodes)
{
Point pInner = nc.getPoint(n.eastNorth);
polygon.addPoint(pInner.x,pInner.y);
}
polygon.addPoint(pOuter.x,pOuter.y);
}
g.setColor(new Color( color.getRed(), color.getGreen(),
color.getBlue(), fillAlpha));
g.fillPolygon(polygon);
alreadyDrawnAreas.add(w);
}
}
for (Way wInner : inner)
{
ElemStyle innerStyle = styles.get(wInner);
if(innerStyle == null)
{
if(zoomok)
drawWay(wInner, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wInner);
}
else if(wayStyle.equals(innerStyle))
{
System.out.println("WARNING: Inner waystyle equals multipolygon for way " + wInner);
alreadyDrawnAreas.add(wInner);
}
}
for (Way wOuter : outer)
{
ElemStyle outerStyle = styles.get(wOuter);
if(outerStyle == null)
{
if(zoomok)
drawWay(wOuter, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wOuter);
}
else
{
if(!wayStyle.equals(outerStyle))
System.out.println("ERROR: Outer waystyle does not match multipolygon for way " + wOuter);
alreadyDrawnAreas.add(wOuter);
}
}
}
}
| public void visit(Relation r) {
// draw multipolygon relations including their ways
// other relations are not (yet?) drawn.
if (r.incomplete) return;
if(!Main.pref.getBoolean("mappaint.multipolygon",false)) return;
if(!"multipolygon".equals(r.keys.get("type"))) return;
Collection<Way> inner = new LinkedList<Way>();
Collection<Way> outer = new LinkedList<Way>();
Collection<Way> innerclosed = new LinkedList<Way>();
Collection<Way> outerclosed = new LinkedList<Way>();
for (RelationMember m : r.members)
{
if (!m.member.incomplete && !m.member.deleted)
{
if(m.member instanceof Way)
{
Way w = (Way) m.member;
if(w.nodes.size() < 2)
{
System.out.println("ERROR: Way with less than two points " + w);
}
else if("inner".equals(m.role))
inner.add(w);
else if("outer".equals(m.role))
outer.add(w);
else
{
System.out.println("ERROR: No useful role for Way " + w);
if(m.role == null || m.role.length() == 0)
outer.add(w);
}
}
else
{
System.out.println("ERROR: Non-Way in multipolygon " + m.member);
}
}
}
ElemStyle wayStyle = styles.get(r);
/* find one wayStyle, prefer the style from Relation or take the first
one of outer rings */
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
{
for (Way w : outer)
{
if(wayStyle == null || !(wayStyle instanceof AreaElemStyle))
wayStyle = styles.get(w);
}
}
if(wayStyle != null && wayStyle instanceof AreaElemStyle)
{
Boolean zoomok = isZoomOk(wayStyle);
Collection<Way> join = new LinkedList<Way>();
/* parse all outer rings and join them */
for (Way w : outer)
{
if(w.isClosed()) outerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
outerclosed.add(w);
}
/* parse all inner rings and join them */
join.clear();
for (Way w : inner)
{
if(w.isClosed()) innerclosed.add(w);
else join.add(w);
}
if(join.size() != 0)
{
for(Way w : joinWays(join))
innerclosed.add(w);
}
/* handle inside out stuff */
if(zoomok) /* draw */
{
for (Way w : outerclosed)
{
Color color = w.selected ? selectedColor
: ((AreaElemStyle)wayStyle).color;
Polygon polygon = new Polygon();
Point pOuter = null;
for (Node n : w.nodes)
{
pOuter = nc.getPoint(n.eastNorth);
polygon.addPoint(pOuter.x,pOuter.y);
}
for (Way wInner : innerclosed)
{
for (Node n : wInner.nodes)
{
Point pInner = nc.getPoint(n.eastNorth);
polygon.addPoint(pInner.x,pInner.y);
}
if(!wInner.isClosed())
{
Point pInner = nc.getPoint(wInner.nodes.get(0).eastNorth);
polygon.addPoint(pInner.x,pInner.y);
}
polygon.addPoint(pOuter.x,pOuter.y);
}
g.setColor(new Color( color.getRed(), color.getGreen(),
color.getBlue(), fillAlpha));
g.fillPolygon(polygon);
alreadyDrawnAreas.add(w);
}
}
for (Way wInner : inner)
{
ElemStyle innerStyle = styles.get(wInner);
if(innerStyle == null)
{
if(zoomok)
drawWay(wInner, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wInner);
}
else if(wayStyle.equals(innerStyle))
{
System.out.println("WARNING: Inner waystyle equals multipolygon for way " + wInner);
alreadyDrawnAreas.add(wInner);
}
}
for (Way wOuter : outer)
{
ElemStyle outerStyle = styles.get(wOuter);
if(outerStyle == null)
{
if(zoomok)
drawWay(wOuter, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color);
alreadyDrawnWays.add(wOuter);
}
else
{
if(!wayStyle.equals(outerStyle))
System.out.println("ERROR: Outer waystyle does not match multipolygon for way " + wOuter);
alreadyDrawnAreas.add(wOuter);
}
}
}
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DisplaySPPEventsFromDashboardAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DisplaySPPEventsFromDashboardAction.java
index 07570e05b..6b9817b7f 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DisplaySPPEventsFromDashboardAction.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DisplaySPPEventsFromDashboardAction.java
@@ -1,87 +1,88 @@
/**
*
*/
package edu.wustl.catissuecore.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.bizlogic.SPPBizLogic;
import edu.wustl.catissuecore.domain.processingprocedure.SpecimenProcessingProcedure;
import edu.wustl.catissuecore.processor.SPPEventProcessor;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.SecureAction;
/**
* @author suhas_khot
*
*/
public class DisplaySPPEventsFromDashboardAction extends SecureAction
{
/**
* Overrides the execute method of Action class. Initializes the various
* fields in SpecimenEventParameters.jsp Page.
*
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response
* object of HttpServletResponse
* @throws IOException
* I/O exception
* @throws ServletException
* servlet exception
* @return value for ActionForward object
*/
@Override
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
Long sppId = Long.parseLong(request.getParameter("sppId"));
edu.wustl.dao.DAO dao = null;
dao = edu.wustl.catissuecore.util.global.AppUtility.openDAOSession(null);
SpecimenProcessingProcedure processingSPP = (SpecimenProcessingProcedure) dao
.retrieveById(SpecimenProcessingProcedure.class.getName(), sppId);; // TODO - Retrieve SPP object based on
// spp_id from request.
request.setAttribute("selectedAll", request.getParameter("selectedAll"));
request.setAttribute("sppId", sppId);
if (request.getParameter("specimenId") != null)
{
request.setAttribute("specimenId", request.getParameter("specimenId"));
}
else
{
request.setAttribute("scgId", request.getParameter("scgId"));
}
+ request.setAttribute("typeObject", request.getParameter("typeObject"));
request.setAttribute("nameOfSelectedSpp", processingSPP.getName());
request.setAttribute("selectedSppId", processingSPP.getId());
List<Map<String, Object>> sppEventDataCollection = new SPPEventProcessor()
.populateSPPEventsWithDefaultValue(processingSPP.getActionCollection(), true);
request.setAttribute(Constants.SPP_EVENTS, sppEventDataCollection);
request.setAttribute(Constants.DISPLAY_EVENTS_WITH_DEFAULT_VALUES, true);
Map<String, Long> dynamicEventMap = new HashMap<String, Long>();
new SPPBizLogic().getAllSPPEventFormNames(dynamicEventMap);
if (request.getSession().getAttribute("dynamicEventMap") == null)
{
request.getSession().setAttribute("dynamicEventMap", dynamicEventMap);
}
return mapping.findForward("pageOfSppData");
}
}
| true | true | public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
Long sppId = Long.parseLong(request.getParameter("sppId"));
edu.wustl.dao.DAO dao = null;
dao = edu.wustl.catissuecore.util.global.AppUtility.openDAOSession(null);
SpecimenProcessingProcedure processingSPP = (SpecimenProcessingProcedure) dao
.retrieveById(SpecimenProcessingProcedure.class.getName(), sppId);; // TODO - Retrieve SPP object based on
// spp_id from request.
request.setAttribute("selectedAll", request.getParameter("selectedAll"));
request.setAttribute("sppId", sppId);
if (request.getParameter("specimenId") != null)
{
request.setAttribute("specimenId", request.getParameter("specimenId"));
}
else
{
request.setAttribute("scgId", request.getParameter("scgId"));
}
request.setAttribute("nameOfSelectedSpp", processingSPP.getName());
request.setAttribute("selectedSppId", processingSPP.getId());
List<Map<String, Object>> sppEventDataCollection = new SPPEventProcessor()
.populateSPPEventsWithDefaultValue(processingSPP.getActionCollection(), true);
request.setAttribute(Constants.SPP_EVENTS, sppEventDataCollection);
request.setAttribute(Constants.DISPLAY_EVENTS_WITH_DEFAULT_VALUES, true);
Map<String, Long> dynamicEventMap = new HashMap<String, Long>();
new SPPBizLogic().getAllSPPEventFormNames(dynamicEventMap);
if (request.getSession().getAttribute("dynamicEventMap") == null)
{
request.getSession().setAttribute("dynamicEventMap", dynamicEventMap);
}
return mapping.findForward("pageOfSppData");
}
| public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
Long sppId = Long.parseLong(request.getParameter("sppId"));
edu.wustl.dao.DAO dao = null;
dao = edu.wustl.catissuecore.util.global.AppUtility.openDAOSession(null);
SpecimenProcessingProcedure processingSPP = (SpecimenProcessingProcedure) dao
.retrieveById(SpecimenProcessingProcedure.class.getName(), sppId);; // TODO - Retrieve SPP object based on
// spp_id from request.
request.setAttribute("selectedAll", request.getParameter("selectedAll"));
request.setAttribute("sppId", sppId);
if (request.getParameter("specimenId") != null)
{
request.setAttribute("specimenId", request.getParameter("specimenId"));
}
else
{
request.setAttribute("scgId", request.getParameter("scgId"));
}
request.setAttribute("typeObject", request.getParameter("typeObject"));
request.setAttribute("nameOfSelectedSpp", processingSPP.getName());
request.setAttribute("selectedSppId", processingSPP.getId());
List<Map<String, Object>> sppEventDataCollection = new SPPEventProcessor()
.populateSPPEventsWithDefaultValue(processingSPP.getActionCollection(), true);
request.setAttribute(Constants.SPP_EVENTS, sppEventDataCollection);
request.setAttribute(Constants.DISPLAY_EVENTS_WITH_DEFAULT_VALUES, true);
Map<String, Long> dynamicEventMap = new HashMap<String, Long>();
new SPPBizLogic().getAllSPPEventFormNames(dynamicEventMap);
if (request.getSession().getAttribute("dynamicEventMap") == null)
{
request.getSession().setAttribute("dynamicEventMap", dynamicEventMap);
}
return mapping.findForward("pageOfSppData");
}
|
diff --git a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/CreateNewWiki/CreateNewWikiPageObjectStep3.java b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/CreateNewWiki/CreateNewWikiPageObjectStep3.java
index d7bb68a..b3ab0bb 100644
--- a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/CreateNewWiki/CreateNewWikiPageObjectStep3.java
+++ b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/CreateNewWiki/CreateNewWikiPageObjectStep3.java
@@ -1,71 +1,71 @@
package com.wikia.webdriver.PageObjects.PageObject.CreateNewWiki;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.wikia.webdriver.Common.Logging.PageObjectLogging;
import com.wikia.webdriver.PageObjects.PageObject.BasePageObject;
/**
*
* @author Karol
*
*/
public class CreateNewWikiPageObjectStep3 extends BasePageObject{
@FindBy(css="li[data-theme]")
private WebElement themeList;
@FindBy(css="li[id='ThemeWiki'] input[class='next']")
private WebElement submitButton;
public CreateNewWikiPageObjectStep3(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
// TODO Auto-generated constructor stub
}
public void selectTheme(int skinNumber)
{
waitForElementByCss("li[data-theme]");
jQueryClick("li[data-theme]:nth-child("+skinNumber+")");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PageObjectLogging.log("selectTheme", "skin number: " + skinNumber + " selected", true, driver);
}
public NewWikiaHomePage submit(String wikiName)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
int sleep = 0;
- while(js.executeScript("return WikiBuilder.cityId").toString().equals("false")&&sleep<10000)
+ while(js.executeScript("return WikiBuilder.cityId").toString().equals("false")&&sleep<20000)//https://wikia.fogbugz.com/default.asp?51510
{
sleep+=500;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
waitForElementByElement(submitButton);
clickAndWait(submitButton);
PageObjectLogging.log("submit", "Submit button clicked", true, driver);
return new NewWikiaHomePage(driver, wikiName);
}
}
| true | true | public NewWikiaHomePage submit(String wikiName)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
int sleep = 0;
while(js.executeScript("return WikiBuilder.cityId").toString().equals("false")&&sleep<10000)
{
sleep+=500;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
waitForElementByElement(submitButton);
clickAndWait(submitButton);
PageObjectLogging.log("submit", "Submit button clicked", true, driver);
return new NewWikiaHomePage(driver, wikiName);
}
| public NewWikiaHomePage submit(String wikiName)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
int sleep = 0;
while(js.executeScript("return WikiBuilder.cityId").toString().equals("false")&&sleep<20000)//https://wikia.fogbugz.com/default.asp?51510
{
sleep+=500;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
waitForElementByElement(submitButton);
clickAndWait(submitButton);
PageObjectLogging.log("submit", "Submit button clicked", true, driver);
return new NewWikiaHomePage(driver, wikiName);
}
|
diff --git a/src/ussr/samples/atron/simulations/ATRONCarController1.java b/src/ussr/samples/atron/simulations/ATRONCarController1.java
index 529210de..989c7343 100644
--- a/src/ussr/samples/atron/simulations/ATRONCarController1.java
+++ b/src/ussr/samples/atron/simulations/ATRONCarController1.java
@@ -1,75 +1,75 @@
/**
* Unified Simulator for Self-Reconfigurable Robots (USSR)
* (C) University of Southern Denmark 2008
* This software is distributed under the BSD open-source license.
* For licensing see the file LICENCE.txt included in the root of the USSR distribution.
*/
package ussr.samples.atron.simulations;
import java.awt.Color;
import java.util.List;
import com.jme.math.Matrix3f;
import com.jmex.physics.DynamicPhysicsNode;
import ussr.comm.Packet;
import ussr.comm.Receiver;
import ussr.comm.Transmitter;
import ussr.model.Sensor;
import ussr.physics.jme.JMEModuleComponent;
import ussr.samples.GenericSimulation;
import ussr.samples.atron.ATRONController;
/**
* A simple controller for an ATRON car that reports data from the proximity sensors
*
* @author Modular Robots @ MMMI
*
*/
public class ATRONCarController1 extends ATRONController {
/**
* @see ussr.model.ControllerImpl#activate()
*/
public void activate() {
yield();
this.delay(1000); /* rotateContinuous seem to fail sometimes if we do not wait at first */
byte dir = 1;
float lastProx = Float.NEGATIVE_INFINITY; /* for printing out proximity data */
boolean firstTime = true;
while(true) {
// Enable stopping the car interactively:
if(!GenericSimulation.getActuatorsAreActive()) { yield(); firstTime = true; continue; }
// Basic control: first time we enter the loop start rotating and turn the axle
String name = module.getProperty("name");
if(firstTime) {
firstTime = false;
- if(name=="wheel1") rotateContinuous(dir);
- if(name=="wheel2") rotateContinuous(-dir);
- if(name=="wheel3") rotateContinuous(dir);
- if(name=="wheel4") rotateContinuous(-dir);
- if(name=="axleOne5" && firstTime) {
+ if(name.equals("wheel1")) rotateContinuous(dir);
+ if(name.equals("wheel2")) rotateContinuous(-dir);
+ if(name.equals("wheel3")) rotateContinuous(dir);
+ if(name.equals("wheel4")) rotateContinuous(-dir);
+ if(name.equals("axleOne5")) {
this.rotateDegrees(10);
}
}
// Print out proximity information
float max_prox = Float.NEGATIVE_INFINITY;
for(Sensor s: module.getSensors()) {
if(s.getName().startsWith("Proximity")) {
float v = s.readValue();
max_prox = Math.max(max_prox, v);
}
}
if(name.startsWith("wheel")&&Math.abs(lastProx-max_prox)>0.01) {
System.out.println("Proximity "+name+" max = "+max_prox);
lastProx = max_prox;
}
// Always call yield sometimes
yield();
}
}
}
| true | true | public void activate() {
yield();
this.delay(1000); /* rotateContinuous seem to fail sometimes if we do not wait at first */
byte dir = 1;
float lastProx = Float.NEGATIVE_INFINITY; /* for printing out proximity data */
boolean firstTime = true;
while(true) {
// Enable stopping the car interactively:
if(!GenericSimulation.getActuatorsAreActive()) { yield(); firstTime = true; continue; }
// Basic control: first time we enter the loop start rotating and turn the axle
String name = module.getProperty("name");
if(firstTime) {
firstTime = false;
if(name=="wheel1") rotateContinuous(dir);
if(name=="wheel2") rotateContinuous(-dir);
if(name=="wheel3") rotateContinuous(dir);
if(name=="wheel4") rotateContinuous(-dir);
if(name=="axleOne5" && firstTime) {
this.rotateDegrees(10);
}
}
// Print out proximity information
float max_prox = Float.NEGATIVE_INFINITY;
for(Sensor s: module.getSensors()) {
if(s.getName().startsWith("Proximity")) {
float v = s.readValue();
max_prox = Math.max(max_prox, v);
}
}
if(name.startsWith("wheel")&&Math.abs(lastProx-max_prox)>0.01) {
System.out.println("Proximity "+name+" max = "+max_prox);
lastProx = max_prox;
}
// Always call yield sometimes
yield();
}
}
| public void activate() {
yield();
this.delay(1000); /* rotateContinuous seem to fail sometimes if we do not wait at first */
byte dir = 1;
float lastProx = Float.NEGATIVE_INFINITY; /* for printing out proximity data */
boolean firstTime = true;
while(true) {
// Enable stopping the car interactively:
if(!GenericSimulation.getActuatorsAreActive()) { yield(); firstTime = true; continue; }
// Basic control: first time we enter the loop start rotating and turn the axle
String name = module.getProperty("name");
if(firstTime) {
firstTime = false;
if(name.equals("wheel1")) rotateContinuous(dir);
if(name.equals("wheel2")) rotateContinuous(-dir);
if(name.equals("wheel3")) rotateContinuous(dir);
if(name.equals("wheel4")) rotateContinuous(-dir);
if(name.equals("axleOne5")) {
this.rotateDegrees(10);
}
}
// Print out proximity information
float max_prox = Float.NEGATIVE_INFINITY;
for(Sensor s: module.getSensors()) {
if(s.getName().startsWith("Proximity")) {
float v = s.readValue();
max_prox = Math.max(max_prox, v);
}
}
if(name.startsWith("wheel")&&Math.abs(lastProx-max_prox)>0.01) {
System.out.println("Proximity "+name+" max = "+max_prox);
lastProx = max_prox;
}
// Always call yield sometimes
yield();
}
}
|
diff --git a/rest/src/main/java/org/usergrid/rest/applications/users/UserResource.java b/rest/src/main/java/org/usergrid/rest/applications/users/UserResource.java
index ca2d0c57..53c2578d 100644
--- a/rest/src/main/java/org/usergrid/rest/applications/users/UserResource.java
+++ b/rest/src/main/java/org/usergrid/rest/applications/users/UserResource.java
@@ -1,488 +1,488 @@
/*******************************************************************************
* Copyright 2012 Apigee Corporation
*
* 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.usergrid.rest.applications.users;
/*******************************************************************************
* Copyright (c) 2010, 2011 Ed Anuff and Usergrid, all rights reserved.
* http://www.usergrid.com
*
* This file is part of Usergrid Stack.
*
* Usergrid Stack 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.
*
* Usergrid Stack 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 Usergrid Stack. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU AGPL version 3 section 7
*
* Linking Usergrid Stack statically or dynamically with other modules is making
* a combined work based on Usergrid Stack. Thus, the terms and conditions of the
* GNU General Public License cover the whole combination.
*
* In addition, as a special exception, the copyright holders of Usergrid Stack
* give you permission to combine Usergrid Stack with free software programs or
* libraries that are released under the GNU LGPL and with independent modules
* that communicate with Usergrid Stack solely through:
*
* - Classes implementing the org.usergrid.services.Service interface
* - Apache Shiro Realms and Filters
* - Servlet Filters and JAX-RS/Jersey Filters
*
* You may copy and distribute such a system following the terms of the GNU AGPL
* for Usergrid Stack and the licenses of the other code concerned, provided that
******************************************************************************/
import static org.usergrid.security.shiro.utils.SubjectUtils.isApplicationAdmin;
import static org.usergrid.utils.ConversionUtils.string;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.UriInfo;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.usergrid.management.ActivationState;
import org.usergrid.persistence.EntityManager;
import org.usergrid.persistence.Identifier;
import org.usergrid.persistence.entities.User;
import org.usergrid.rest.AbstractContextResource;
import org.usergrid.rest.ApiResponse;
import org.usergrid.rest.applications.ServiceResource;
import org.usergrid.rest.exceptions.RedirectionException;
import org.usergrid.rest.security.annotations.RequireApplicationAccess;
import org.usergrid.security.tokens.exceptions.TokenException;
import com.sun.jersey.api.json.JSONWithPadding;
import com.sun.jersey.api.view.Viewable;
@Component("org.usergrid.rest.applications.users.UserResource")
@Scope("prototype")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource extends ServiceResource {
public static final String USER_EXTENSION_RESOURCE_PREFIX = "org.usergrid.rest.applications.users.extensions.";
private static final Logger logger = LoggerFactory
.getLogger(UserResource.class);
User user;
Identifier userIdentifier;
String errorMsg;
String token;
public UserResource() {
}
public UserResource init(Identifier userIdentifier) throws Exception {
this.userIdentifier = userIdentifier;
return this;
}
@PUT
@Path("password")
public JSONWithPadding setUserPasswordPut(@Context UriInfo ui,
Map<String, Object> json,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("UserResource.setUserPassword");
if (json == null) {
return null;
}
ApiResponse response = new ApiResponse(ui);
response.setAction("set user password");
String oldPassword = string(json.get("oldpassword"));
String newPassword = string(json.get("newpassword"));
if (newPassword == null) {
throw new IllegalArgumentException("newpassword is required");
}
UUID applicationId = getApplicationId();
UUID targetUserId = getUserUuid();
if (targetUserId == null) {
response.setError("User not found");
return new JSONWithPadding(response, callback);
}
if ( isApplicationAdmin()) {
management.setAppUserPassword(applicationId, targetUserId,
newPassword);
}
// we're not an admin user, we can only update the password ourselves
else {
management.setAppUserPassword(getApplicationId(), targetUserId,
oldPassword, newPassword);
}
return new JSONWithPadding(response, callback);
}
@POST
@Path("password")
public JSONWithPadding setUserPasswordPost(@Context UriInfo ui,
Map<String, Object> json,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
return setUserPasswordPut(ui, json, callback);
}
@POST
@Path("deactivate")
public JSONWithPadding deactivate(@Context UriInfo ui,
Map<String, Object> json,
@QueryParam("callback") @DefaultValue("") String callback)
throws Exception {
ApiResponse response = new ApiResponse();
response.setAction("Deactivate user");
User user = management
.deactivateUser(getApplicationId(), getUserUuid());
response.withEntity(user);
return new JSONWithPadding(response, callback);
}
@GET
@Path("sendpin")
public JSONWithPadding sendPin(@Context UriInfo ui,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("UserResource.sendPin");
ApiResponse response = new ApiResponse(ui);
response.setAction("retrieve user pin");
if (getUser() != null) {
management.sendAppUserPin(getApplicationId(), getUserUuid());
} else {
response.setError("User not found");
}
return new JSONWithPadding(response, callback);
}
@POST
@Path("sendpin")
public JSONWithPadding postSendPin(@Context UriInfo ui,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
return sendPin(ui, callback);
}
@GET
@Path("setpin")
@RequireApplicationAccess
public JSONWithPadding setPin(@Context UriInfo ui,
@QueryParam("pin") String pin,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("UserResource.setPin");
ApiResponse response = new ApiResponse(ui);
response.setAction("set user pin");
if (getUser() != null) {
management.setAppUserPin(getApplicationId(), getUserUuid(), pin);
} else {
response.setError("User not found");
}
return new JSONWithPadding(response, callback);
}
@POST
@Path("setpin")
@Consumes("application/x-www-form-urlencoded")
@RequireApplicationAccess
public JSONWithPadding postPin(@Context UriInfo ui,
@FormParam("pin") String pin,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("UserResource.postPin");
ApiResponse response = new ApiResponse(ui);
response.setAction("set user pin");
if (getUser() != null) {
management.setAppUserPin(getApplicationId(), getUserUuid(), pin);
} else {
response.setError("User not found");
}
return new JSONWithPadding(response, callback);
}
@POST
@Path("setpin")
@Consumes(MediaType.APPLICATION_JSON)
@RequireApplicationAccess
public JSONWithPadding jsonPin(@Context UriInfo ui, JsonNode json,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("UserResource.jsonPin");
ApiResponse response = new ApiResponse(ui);
response.setAction("set user pin");
if (getUser() != null) {
String pin = json.path("pin").getTextValue();
management.setAppUserPin(getApplicationId(), getUserUuid(), pin);
} else {
response.setError("User not found");
}
return new JSONWithPadding(response, callback);
}
@GET
@Path("resetpw")
public Viewable showPasswordResetForm(@Context UriInfo ui,
@QueryParam("token") String token) {
logger.info("UserResource.showPasswordResetForm");
this.token = token;
try {
if (management.checkPasswordResetTokenForAppUser(
getApplicationId(), getUserUuid(), token)) {
return handleViewable("resetpw_set_form", this);
} else {
return handleViewable("resetpw_email_form", this);
}
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
@POST
@Path("resetpw")
@Consumes("application/x-www-form-urlencoded")
public Viewable handlePasswordResetForm(@Context UriInfo ui,
@FormParam("token") String token,
@FormParam("password1") String password1,
@FormParam("password2") String password2,
@FormParam("recaptcha_challenge_field") String challenge,
@FormParam("recaptcha_response_field") String uresponse) {
try {
logger.info("UserResource.handlePasswordResetForm");
this.token = token;
if ((password1 != null) || (password2 != null)) {
if (management.checkPasswordResetTokenForAppUser(
getApplicationId(), getUserUuid(), token)) {
if ((password1 != null) && password1.equals(password2)) {
management.setAppUserPassword(getApplicationId(),
getUser().getUuid(), password1);
return handleViewable("resetpw_set_success", this);
} else {
errorMsg = "Passwords didn't match, let's try again...";
return handleViewable("resetpw_set_form", this);
}
} else {
errorMsg = "Something odd happened, let's try again...";
return handleViewable("resetpw_email_form", this);
}
}
if (!useReCaptcha()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
- user);
+ getUser());
return handleViewable("resetpw_email_success", this);
}
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey(properties
.getProperty("usergrid.recaptcha.private"));
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(
httpServletRequest.getRemoteAddr(), challenge, uresponse);
if (reCaptchaResponse.isValid()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
- user);
+ getUser());
return handleViewable("resetpw_email_success", this);
} else {
errorMsg = "Incorrect Captcha";
return handleViewable("resetpw_email_form", this);
}
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
public String getErrorMsg() {
return errorMsg;
}
public String getToken() {
return token;
}
public User getUser() {
if (user == null) {
EntityManager em = getServices().getEntityManager();
try {
user = em.get(em.getUserByIdentifier(userIdentifier),
User.class);
} catch (Exception e) {
logger.error("Unable go get user", e);
}
}
return user;
}
public UUID getUserUuid() {
user = getUser();
if (user == null) {
return null;
}
return user.getUuid();
}
@GET
@Path("activate")
public Viewable activate(@Context UriInfo ui,
@QueryParam("token") String token) {
try {
management.handleActivationTokenForAppUser(getApplicationId(),
getUserUuid(), token);
return handleViewable("activate", this);
} catch (TokenException e) {
return handleViewable("bad_activation_token", this);
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
@GET
@Path("confirm")
public Viewable confirm(@Context UriInfo ui,
@QueryParam("token") String token) {
try {
ActivationState state = management
.handleConfirmationTokenForAppUser(getApplicationId(),
getUserUuid(), token);
if (state == ActivationState.CONFIRMED_AWAITING_ACTIVATION) {
return handleViewable("confirm", this);
}
return handleViewable("activate", this);
} catch (TokenException e) {
return handleViewable("bad_confirmation_token", this);
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
@GET
@Path("reactivate")
public JSONWithPadding reactivate(@Context UriInfo ui,
@QueryParam("callback") @DefaultValue("callback") String callback)
throws Exception {
logger.info("Send activation email for user: " + getUserUuid());
ApiResponse response = new ApiResponse(ui);
management.startAppUserActivationFlow(getApplicationId(), user);
response.setAction("reactivate user");
return new JSONWithPadding(response, callback);
}
@Override
@Path("{itemName}")
public AbstractContextResource addNameParameter(@Context UriInfo ui,
@PathParam("itemName") PathSegment itemName) throws Exception {
// check for user extension
String resourceClass = USER_EXTENSION_RESOURCE_PREFIX
+ StringUtils.capitalize(itemName.getPath()) + "Resource";
AbstractUserExtensionResource extensionResource = null;
try {
@SuppressWarnings("unchecked")
Class<AbstractUserExtensionResource> extensionCls = (Class<AbstractUserExtensionResource>) Class
.forName(resourceClass);
extensionResource = getSubResource(extensionCls);
} catch (Exception e) {
}
if (extensionResource != null) {
return extensionResource;
}
return super.addNameParameter(ui, itemName);
}
}
| false | true | public Viewable handlePasswordResetForm(@Context UriInfo ui,
@FormParam("token") String token,
@FormParam("password1") String password1,
@FormParam("password2") String password2,
@FormParam("recaptcha_challenge_field") String challenge,
@FormParam("recaptcha_response_field") String uresponse) {
try {
logger.info("UserResource.handlePasswordResetForm");
this.token = token;
if ((password1 != null) || (password2 != null)) {
if (management.checkPasswordResetTokenForAppUser(
getApplicationId(), getUserUuid(), token)) {
if ((password1 != null) && password1.equals(password2)) {
management.setAppUserPassword(getApplicationId(),
getUser().getUuid(), password1);
return handleViewable("resetpw_set_success", this);
} else {
errorMsg = "Passwords didn't match, let's try again...";
return handleViewable("resetpw_set_form", this);
}
} else {
errorMsg = "Something odd happened, let's try again...";
return handleViewable("resetpw_email_form", this);
}
}
if (!useReCaptcha()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
user);
return handleViewable("resetpw_email_success", this);
}
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey(properties
.getProperty("usergrid.recaptcha.private"));
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(
httpServletRequest.getRemoteAddr(), challenge, uresponse);
if (reCaptchaResponse.isValid()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
user);
return handleViewable("resetpw_email_success", this);
} else {
errorMsg = "Incorrect Captcha";
return handleViewable("resetpw_email_form", this);
}
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
| public Viewable handlePasswordResetForm(@Context UriInfo ui,
@FormParam("token") String token,
@FormParam("password1") String password1,
@FormParam("password2") String password2,
@FormParam("recaptcha_challenge_field") String challenge,
@FormParam("recaptcha_response_field") String uresponse) {
try {
logger.info("UserResource.handlePasswordResetForm");
this.token = token;
if ((password1 != null) || (password2 != null)) {
if (management.checkPasswordResetTokenForAppUser(
getApplicationId(), getUserUuid(), token)) {
if ((password1 != null) && password1.equals(password2)) {
management.setAppUserPassword(getApplicationId(),
getUser().getUuid(), password1);
return handleViewable("resetpw_set_success", this);
} else {
errorMsg = "Passwords didn't match, let's try again...";
return handleViewable("resetpw_set_form", this);
}
} else {
errorMsg = "Something odd happened, let's try again...";
return handleViewable("resetpw_email_form", this);
}
}
if (!useReCaptcha()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
getUser());
return handleViewable("resetpw_email_success", this);
}
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey(properties
.getProperty("usergrid.recaptcha.private"));
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(
httpServletRequest.getRemoteAddr(), challenge, uresponse);
if (reCaptchaResponse.isValid()) {
management.startAppUserPasswordResetFlow(getApplicationId(),
getUser());
return handleViewable("resetpw_email_success", this);
} else {
errorMsg = "Incorrect Captcha";
return handleViewable("resetpw_email_form", this);
}
} catch (RedirectionException e) {
throw e;
} catch (Exception e) {
return handleViewable("error", e);
}
}
|
diff --git a/src/sbt/eclipse/logic/UnmanagedLibsConfigurer.java b/src/sbt/eclipse/logic/UnmanagedLibsConfigurer.java
index d41eaa6..e4eea13 100644
--- a/src/sbt/eclipse/logic/UnmanagedLibsConfigurer.java
+++ b/src/sbt/eclipse/logic/UnmanagedLibsConfigurer.java
@@ -1,62 +1,62 @@
package sbt.eclipse.logic;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import sbt.eclipse.Constants;
/**
* Adds unmanaged libs to project classpath.
*
* @author Joonas Javanainen
*
*/
public class UnmanagedLibsConfigurer extends AbstractConfigurer {
/**
* @param project
* @throws CoreException
*/
public UnmanagedLibsConfigurer(IProject project) throws CoreException {
super(project);
}
@Override
public void run(IProgressMonitor monitor) throws CoreException {
List<IClasspathEntry> classpaths = new ArrayList<IClasspathEntry>();
- File libFolder = project.getFolder(Constants.DEFAULT_LIB_FOLDER)
- .getFullPath().toFile();
+ File projectRoot = project.getLocation().makeAbsolute().toFile();
+ File libFolder = new File(projectRoot, Constants.DEFAULT_LIB_FOLDER);
if (!libFolder.exists())
return;
List<IPath> wantedLibs = new ArrayList<IPath>();
for (File foundLibFile : libFolder.listFiles()) {
wantedLibs.add(new Path(foundLibFile.getAbsolutePath()));
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
wantedLibs.remove(entry.getPath());
}
classpaths.add(entry);
}
for (IPath libPath : wantedLibs) {
classpaths.add(JavaCore.newLibraryEntry(libPath, null, null));
}
javaProject.setRawClasspath(classpaths
.toArray(Constants.EMPTY_CLASSPATHENTRY_ARRAY), monitor);
}
}
| true | true | public void run(IProgressMonitor monitor) throws CoreException {
List<IClasspathEntry> classpaths = new ArrayList<IClasspathEntry>();
File libFolder = project.getFolder(Constants.DEFAULT_LIB_FOLDER)
.getFullPath().toFile();
if (!libFolder.exists())
return;
List<IPath> wantedLibs = new ArrayList<IPath>();
for (File foundLibFile : libFolder.listFiles()) {
wantedLibs.add(new Path(foundLibFile.getAbsolutePath()));
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
wantedLibs.remove(entry.getPath());
}
classpaths.add(entry);
}
for (IPath libPath : wantedLibs) {
classpaths.add(JavaCore.newLibraryEntry(libPath, null, null));
}
javaProject.setRawClasspath(classpaths
.toArray(Constants.EMPTY_CLASSPATHENTRY_ARRAY), monitor);
}
| public void run(IProgressMonitor monitor) throws CoreException {
List<IClasspathEntry> classpaths = new ArrayList<IClasspathEntry>();
File projectRoot = project.getLocation().makeAbsolute().toFile();
File libFolder = new File(projectRoot, Constants.DEFAULT_LIB_FOLDER);
if (!libFolder.exists())
return;
List<IPath> wantedLibs = new ArrayList<IPath>();
for (File foundLibFile : libFolder.listFiles()) {
wantedLibs.add(new Path(foundLibFile.getAbsolutePath()));
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
wantedLibs.remove(entry.getPath());
}
classpaths.add(entry);
}
for (IPath libPath : wantedLibs) {
classpaths.add(JavaCore.newLibraryEntry(libPath, null, null));
}
javaProject.setRawClasspath(classpaths
.toArray(Constants.EMPTY_CLASSPATHENTRY_ARRAY), monitor);
}
|
diff --git a/src/de/uni_koblenz/jgralab/utilities/tgraphbrowser/TwoDVisualizer.java b/src/de/uni_koblenz/jgralab/utilities/tgraphbrowser/TwoDVisualizer.java
index 23e38b397..1dd26022e 100644
--- a/src/de/uni_koblenz/jgralab/utilities/tgraphbrowser/TwoDVisualizer.java
+++ b/src/de/uni_koblenz/jgralab/utilities/tgraphbrowser/TwoDVisualizer.java
@@ -1,680 +1,683 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2010 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* 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 de.uni_koblenz.jgralab.utilities.tgraphbrowser;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import de.uni_koblenz.jgralab.AttributedElement;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.GraphElement;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueImpl;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueSet;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueSlice;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueType;
import de.uni_koblenz.jgralab.schema.AggregationKind;
import de.uni_koblenz.jgralab.schema.Attribute;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.EdgeClass;
import de.uni_koblenz.jgralab.schema.VertexClass;
import de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot;
import de.uni_koblenz.jgralab.utilities.tgraphbrowser.StateRepository.State;
public class TwoDVisualizer {
public static int SECONDS_TO_WAIT_FOR_DOT = 60;
/**
* Creates the 2D-representation of <code>currentElement</code> and its
* environment, if their type is chosen to be shown. An element belongs to
* the environment if:<br>
* <ul>
* <li><code>currentElement</code> is an instance of Vertex then the element
* has to be in a path<br>
* <code>currentElement</code><->^x where 1<=x<=
* <code>pathLength</code></li>
* <li><code>currentElement</code> is an instance of Edge then the element
* has to be in a path<br>
* y<->^x where 1<=x<= <code>pathLength</code> and y is an
* incident vertex of <code>currentElement</code></li>
* </ul>
*
* @param code
* @param state
* @param sessionId
* @param currentElement
* @param showAttributes
* @param pathLength
*/
public void visualizeElements(StringBuilder code, State state,
Integer sessionId, String workspace, JValue currentElement,
Boolean showAttributes, Integer pathLength,
RequestThread currentThread) {
// set currentVertex or currentEdge to the current element
if (currentElement.isVertex()) {
code.append("current").append("Vertex = \"").append(
currentElement.toVertex().getId()).append("\";\n");
} else if (currentElement.isEdge()) {
code.append("current").append("Edge = \"").append(
currentElement.toEdge().getId()).append("\";\n");
}
// calculate environment
JValueSet elementsToDisplay = new JValueSet();
if (currentElement.isVertex()) {
JValue slice = computeElements(currentElement, pathLength, state
.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else if (currentElement.isEdge()) {
Edge current = currentElement.toEdge();
JValue slice = computeElements(new JValueImpl(current.getAlpha()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
slice = computeElements(new JValueImpl(current.getOmega()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else {
calculateElementsInSet(code, state, elementsToDisplay,
currentElement.toJValueSet());
}
// create temp-folder
File tempFolder = new File(System.getProperty("java.io.tmpdir")
+ File.separator + "tgraphbrowser");
if (!tempFolder.exists()) {
if (!tempFolder.mkdir()) {
TGraphBrowserServer.logger.warning(tempFolder
+ " could not be created.");
}
}
tempFolder.deleteOnExit();
// create .dot-file
String dotFileName = null;
try {
dotFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.dot";
} catch (IOException e1) {
e1.printStackTrace();
}
MyTg2Dot mtd = new MyTg2Dot(elementsToDisplay, dotFileName,
showAttributes, currentElement, state.selectedEdgeClasses,
state.selectedVertexClasses);
mtd.printGraph();
if (mtd.exception != null) {
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(dotFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
// create .svg-file
String svgFileName = null;
try {
svgFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.svg";
} catch (IOException e1) {
e1.printStackTrace();
}
try {
synchronized (StateRepository.dot) {
String execStr = null;
// on windows, we must quote the file names, and on UNIX, we
// must not quote them... And this stupid ProcessBuilder doesn't
// work either...
if (System.getProperty("os.name").startsWith("Windows")) {
execStr = StateRepository.dot + " -Tsvg -o \""
+ svgFileName + "\" \"" + dotFileName + "\"";
} else {
execStr = StateRepository.dot + " -Tsvg -o " + svgFileName
+ " " + dotFileName;
}
ExecutingDot dotThread = new ExecutingDot(execStr,
currentThread);
dotThread.start();
try {
synchronized (currentThread) {
currentThread.wait(SECONDS_TO_WAIT_FOR_DOT * 1000);
}
dotThread.svgCreationProcess.destroy();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (dotThread.exitCode != -1) {
if (dotThread.exitCode != 0) {
if (dotThread.exception != null) {
throw dotThread.exception;
}
}
} else {
// execution of dot is terminated because it took too long
+ code.append("changeView();\n");
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Creation of file ")
- .append(svgFileName)
+ .append(
+ svgFileName.contains("\\") ? svgFileName
+ .replace("\\", "/") : svgFileName)
.append(
" was terminated because it took more than ")
.append(SECONDS_TO_WAIT_FOR_DOT).append(
" seconds.\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
}
} catch (IOException e) {
e.printStackTrace();
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(svgFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
if (!new File(dotFileName).delete()) {
TGraphBrowserServer.logger.warning(dotFileName
+ " could not be deleted");
}
assert svgFileName != null : "svg file name must not be null";
svgFileName = svgFileName.substring(svgFileName
.lastIndexOf(File.separator) + 1);
// svg in HTML-Seite einbinden
code.append("/*@cc_on\n");
code.append("/*@if (@_jscript_version > 5.6)\n");
// code executed in Internet Explorer
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"embed\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.src = \"_").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("@else @*/\n");
// code executed in other browsers
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"object\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.data = \"").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("/*@end\n");
code.append("@*/\n");
code.append("object.onload = function(){\n");
code.append("resize();\n");
code.append("};\n");
}
/**
* Puts all elements of <code>elements</code> into
* <code>elementsToDisplay</code>, if their type is selected to be shown.
*
* @param state
* @param elementsToDisplay
* @param elements
*/
private void calculateElementsInSet(StringBuilder code, State state,
JValueSet elementsToDisplay, JValue elements) {
int totalElements = 0;
int selectedElements = 0;
if (elements.canConvert(JValueType.SLICE)) {
JValueSlice slice = elements.toSlice();
for (JValue v : slice.nodes()) {
totalElements++;
if (v.isVertex()
&& state.selectedVertexClasses.get(v.toVertex()
.getAttributedElementClass())) {
elementsToDisplay.add(v);
selectedElements++;
}
}
for (JValue v : slice.edges()) {
totalElements++;
if (v.isEdge()
&& state.selectedEdgeClasses.get(v.toEdge()
.getAttributedElementClass())) {
elementsToDisplay.add(new JValueImpl(v.toEdge()
.getNormalEdge()));
selectedElements++;
}
}
} else {
for (JValue v : elements.toJValueSet()) {
totalElements++;
if (v.isVertex()
&& state.selectedVertexClasses.get(v.toVertex()
.getAttributedElementClass())) {
elementsToDisplay.add(v);
selectedElements++;
} else if (v.isEdge()
&& state.selectedEdgeClasses.get(v.toEdge()
.getAttributedElementClass())) {
elementsToDisplay.add(new JValueImpl(v.toEdge()
.getNormalEdge()));
selectedElements++;
}
}
}
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("div2D.innerHTML = \"\";\n");
// print number of elements
code
.append(
"document.getElementById(\"h3HowManyElements\").innerHTML = \"")
.append(selectedElements).append(" of ").append(totalElements)
.append(" elements selected.\";\n");
}
/**
* Finds all elements which are on a path of the kind:<br>
* <code>currentElement</code><->^<code>1</code> |<br>
* <code>currentElement</code><->^<code>2</code> |<br>
* ... |<br>
* <code>currentElement</code><->^<code>pathLength</code>
*
* @param currentElement
* @param pathLength
* @param graph
* @return
*/
private JValue computeElements(JValue currentElement, Integer pathLength,
Graph graph) {
HashMap<String, JValue> boundVars = new HashMap<String, JValue>();
boundVars.put("current", currentElement);
StringBuilder query = new StringBuilder("using current: ");
query.append("slice(current,<->^1");
for (int i = 2; i <= pathLength; i++) {
query.append("|<->^" + i);
}
query.append(")");
return StateRepository
.evaluateGReQL(query.toString(), graph, boundVars);
}
/**
* This thread executes dot to create the svg file.
*/
private static final class ExecutingDot extends Thread {
public Process svgCreationProcess;
private final String execStr;
// -1 is the default value to show, that dot is not finished
public int exitCode = -1;
public IOException exception;
private final RequestThread sleepingRequestThread;
public ExecutingDot(String command, RequestThread currentThread) {
execStr = command;
sleepingRequestThread = currentThread;
}
@Override
public void run() {
super.run();
try {
svgCreationProcess = Runtime.getRuntime().exec(execStr);
exitCode = svgCreationProcess.waitFor();
synchronized (sleepingRequestThread) {
if (sleepingRequestThread.getState() == Thread.State.TIMED_WAITING) {
sleepingRequestThread.notify();
}
}
} catch (IOException e) {
exception = e;
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Creates the specific representation for the elements.
*/
private static class MyTg2Dot extends Tg2Dot {
private static final double ranksep = 1.5;
private static final boolean ranksepEqually = false;
private static final double nodesep = 0.25;
private static final String fontname = "Helvetica";
private static final int fontsize = 14;
/**
* The elements to be displayed.
*/
private final JValueSet elements;
/**
* The current Element.
*/
private final GraphElement current;
/**
* If true, the attributes are shown.
*/
private final boolean showAttributes;
/**
* Stores the exception, if one occures.
*/
public Exception exception;
/**
* Number for the unique name of the endnode of the edge, which shows,
* that there are further edges at a node.
*/
private int counter = 0;
private final HashMap<EdgeClass, Boolean> selectedEdgeClasses;
private final HashMap<VertexClass, Boolean> selectedVertexClasses;
/**
* Creates a new MyTg2Dot object. Call printGraph() to create a
* .dot-file.
*
* @param elements
* @param outputFileName
* @param showAttributes
* @param selectedEdgeClasses2
*/
public MyTg2Dot(JValueSet elements, String outputFileName,
Boolean showAttributes, JValue currentElement,
HashMap<EdgeClass, Boolean> selectedEdgeClasses2,
HashMap<VertexClass, Boolean> selectedVertexClasses2) {
selectedEdgeClasses = selectedEdgeClasses2;
selectedVertexClasses = selectedVertexClasses2;
this.elements = elements;
outputName = outputFileName;
this.showAttributes = showAttributes;
setPrintIncidenceNumbers(true);
if (currentElement.isVertex()) {
current = currentElement.toVertex();
} else if (currentElement.isEdge()) {
current = currentElement.toEdge();
} else {
current = null;
}
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.utilities.tg2whatever.Tg2Whatever#printGraph()
*/
@Override
public void printGraph() {
PrintStream out = null;
try {
out = new PrintStream(new BufferedOutputStream(
new FileOutputStream(outputName)));
graphStart(out);
for (JValue v : elements) {
if (v.isVertex()) {
printVertex(out, v.toVertex());
} else if (v.isEdge()) {
printEdge(out, v.toEdge());
}
}
graphEnd(out);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
exception = e;
} finally {
if (out != null) {
out.close();
}
}
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot#graphStart(java.io
* .PrintStream)
*/
@Override
public void graphStart(PrintStream out) {
out.println("digraph \"" + outputName + "\"");
out.println("{");
// Set the ranksep
if (ranksepEqually) {
out.println("ranksep=\"" + ranksep + " equally\";");
} else {
out.println("ranksep=\"" + ranksep + "\";");
}
// Set the nodesep
out.println("nodesep=\"" + nodesep + "\";");
out.println("node [shape=\"record\" " + "style=\"filled\" "
+ "fillcolor=\"white\" " + "fontname=\"" + fontname + "\" "
+ "fontsize=\"" + fontsize + "\" color=\"#999999\"];");
out.println("edge [fontname=\"" + fontname + "\" fontsize=\""
+ fontsize + "\" labelfontname=\"" + fontname
+ "\" labelfontsize=\"" + fontsize + "\" color=\"#999999\""
+ " penwidth=\"3\" arrowsize=\"1.5\" " + "];");
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot#printEdge(java.io.
* PrintStream, de.uni_koblenz.jgralab.Edge)
*/
@Override
protected void printEdge(PrintStream out, Edge e) {
if (!selectedEdgeClasses.get(e.getAttributedElementClass())) {
return;
}
Vertex alpha = e.getAlpha();
Vertex omega = e.getOmega();
// hide deselected vertices
if (!selectedVertexClasses.get(alpha.getAttributedElementClass())
|| !selectedVertexClasses.get(omega
.getAttributedElementClass())) {
return;
}
out.print("v" + alpha.getId() + " -> v" + omega.getId() + " [");
EdgeClass cls = (EdgeClass) e.getAttributedElementClass();
out.print("dir=\"both\" ");
/*
* The first 2 cases handle the case were the
* aggregation/composition diamond is at the opposite side of the
* direction arrow.
*/
if (e.getOmegaSemantics() == AggregationKind.SHARED) {
out.print("arrowtail=\"odiamond\" ");
} else if (e.getOmegaSemantics() == AggregationKind.COMPOSITE) {
out.print("arrowtail=\"diamond\" ");
}
/*
* The next 2 cases handle the case were the aggregation/composition
* diamond is at the same side as the direction arrow. Here, we
* print only the diamond.
*/
else if (e.getAlphaSemantics() == AggregationKind.SHARED) {
out.print("arrowhead=\"odiamondnormal\" ");
out.print("arrowtail=\"none\" ");
} else if (e.getAlphaSemantics() == AggregationKind.COMPOSITE) {
out.print("arrowhead=\"diamondnormal\" ");
out.print("arrowtail=\"none\" ");
}
/*
* Ok, this is the default case with no diamond. So simply
* deactivate one arrow label and keep the implicit normal at the
* other side.
*/
else {
out.print("arrowtail=\"none\" ");
}
out.print(" label=\"e" + e.getId() + ": "
+ cls.getUniqueName().replace('$', '.') + "");
if (showAttributes && cls.getAttributeCount() > 0) {
out.print("\\l");
printAttributes(out, e);
}
out.print("\"");
out.print(" tooltip=\"");
if (!showAttributes) {
printAttributes(out, e);
}
out.print(" \"");
if (isPrintIncidenceNumbers()) {
out
.print(" taillabel=\"" + getIncidenceNumber(e, alpha)
+ "\"");
out
.print(" headlabel=\""
+ getIncidenceNumber(e.getReversedEdge(), omega)
+ "\"");
}
out.print(" href=\"javascript:top.showElement('e" + e.getId()
+ "');\"");
if (e == current) {
out.print(" color=\"red\"");
}
out.println("];");
}
private int getIncidenceNumber(Edge e, Vertex v) {
int num = 1;
for (Edge inc : v.incidences()) {
if (inc == e) {
return num;
}
num++;
}
return -1;
}
private void printAttributes(PrintStream out, AttributedElement elem) {
AttributedElementClass cls = elem.getAttributedElementClass();
StringBuilder value = new StringBuilder();
for (Attribute attr : cls.getAttributeList()) {
String current = attr.getName();
Object attribute = elem.getAttribute(attr.getName());
String attributeString = attribute != null ? attribute
.toString() : "null";
if (attribute instanceof String) {
attributeString = '"' + attributeString + '"';
}
current += " = " + stringQuote(attributeString)
+ (showAttributes ? "\\l" : ";");
if (!showAttributes) {
if (value.length() + current.length() < 400) {
// if the title is too long dot produces nonsense
// and the svg contains forbidden chars
value.append(current);
} else {
value.append(" ...");
break;
}
} else {
value.append(current);
}
}
out.print(value);
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot#printVertex(java.io
* .PrintStream, de.uni_koblenz.jgralab.Vertex)
*/
@Override
protected void printVertex(PrintStream out, Vertex v) {
AttributedElementClass cls = v.getAttributedElementClass();
out.print("v" + v.getId() + " [label=\"{{v" + v.getId() + "|"
+ cls.getUniqueName().replace('$', '.') + "}");
if (showAttributes && cls.getAttributeCount() > 0) {
out.print("|");
printAttributes(out, v);
}
out.print("}\"");
out.print(" href=\"javascript:top.showElement('v" + v.getId()
+ "');\"");
if (v == current) {
out.print(" fillcolor=\"#FFC080\"");
}
out.print(" tooltip=\"");
if (!showAttributes) {
printAttributes(out, v);
}
out.print(" \"");
out.println("];");
// check if this vertex has edges which will not be shown
for (Edge e : v.incidences()) {
if (!elements.contains(new JValueImpl(e.getNormalEdge()))
&& selectedEdgeClasses.get(e.getNormalEdge()
.getAttributedElementClass())) {
// mark this vertex that it has further edges
// print a new node, which is completely white
out.println("nv" + counter
+ " [shape=\"plaintext\" fontcolor=\"white\"]");
// print the little arrow as a new edge
out.println("nv" + counter++ + " -> v" + v.getId()
+ " [style=\"dashed\"]");
break;
}
}
}
}
}
| false | true | public void visualizeElements(StringBuilder code, State state,
Integer sessionId, String workspace, JValue currentElement,
Boolean showAttributes, Integer pathLength,
RequestThread currentThread) {
// set currentVertex or currentEdge to the current element
if (currentElement.isVertex()) {
code.append("current").append("Vertex = \"").append(
currentElement.toVertex().getId()).append("\";\n");
} else if (currentElement.isEdge()) {
code.append("current").append("Edge = \"").append(
currentElement.toEdge().getId()).append("\";\n");
}
// calculate environment
JValueSet elementsToDisplay = new JValueSet();
if (currentElement.isVertex()) {
JValue slice = computeElements(currentElement, pathLength, state
.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else if (currentElement.isEdge()) {
Edge current = currentElement.toEdge();
JValue slice = computeElements(new JValueImpl(current.getAlpha()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
slice = computeElements(new JValueImpl(current.getOmega()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else {
calculateElementsInSet(code, state, elementsToDisplay,
currentElement.toJValueSet());
}
// create temp-folder
File tempFolder = new File(System.getProperty("java.io.tmpdir")
+ File.separator + "tgraphbrowser");
if (!tempFolder.exists()) {
if (!tempFolder.mkdir()) {
TGraphBrowserServer.logger.warning(tempFolder
+ " could not be created.");
}
}
tempFolder.deleteOnExit();
// create .dot-file
String dotFileName = null;
try {
dotFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.dot";
} catch (IOException e1) {
e1.printStackTrace();
}
MyTg2Dot mtd = new MyTg2Dot(elementsToDisplay, dotFileName,
showAttributes, currentElement, state.selectedEdgeClasses,
state.selectedVertexClasses);
mtd.printGraph();
if (mtd.exception != null) {
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(dotFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
// create .svg-file
String svgFileName = null;
try {
svgFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.svg";
} catch (IOException e1) {
e1.printStackTrace();
}
try {
synchronized (StateRepository.dot) {
String execStr = null;
// on windows, we must quote the file names, and on UNIX, we
// must not quote them... And this stupid ProcessBuilder doesn't
// work either...
if (System.getProperty("os.name").startsWith("Windows")) {
execStr = StateRepository.dot + " -Tsvg -o \""
+ svgFileName + "\" \"" + dotFileName + "\"";
} else {
execStr = StateRepository.dot + " -Tsvg -o " + svgFileName
+ " " + dotFileName;
}
ExecutingDot dotThread = new ExecutingDot(execStr,
currentThread);
dotThread.start();
try {
synchronized (currentThread) {
currentThread.wait(SECONDS_TO_WAIT_FOR_DOT * 1000);
}
dotThread.svgCreationProcess.destroy();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (dotThread.exitCode != -1) {
if (dotThread.exitCode != 0) {
if (dotThread.exception != null) {
throw dotThread.exception;
}
}
} else {
// execution of dot is terminated because it took too long
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Creation of file ")
.append(svgFileName)
.append(
" was terminated because it took more than ")
.append(SECONDS_TO_WAIT_FOR_DOT).append(
" seconds.\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
}
} catch (IOException e) {
e.printStackTrace();
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(svgFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
if (!new File(dotFileName).delete()) {
TGraphBrowserServer.logger.warning(dotFileName
+ " could not be deleted");
}
assert svgFileName != null : "svg file name must not be null";
svgFileName = svgFileName.substring(svgFileName
.lastIndexOf(File.separator) + 1);
// svg in HTML-Seite einbinden
code.append("/*@cc_on\n");
code.append("/*@if (@_jscript_version > 5.6)\n");
// code executed in Internet Explorer
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"embed\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.src = \"_").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("@else @*/\n");
// code executed in other browsers
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"object\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.data = \"").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("/*@end\n");
code.append("@*/\n");
code.append("object.onload = function(){\n");
code.append("resize();\n");
code.append("};\n");
}
| public void visualizeElements(StringBuilder code, State state,
Integer sessionId, String workspace, JValue currentElement,
Boolean showAttributes, Integer pathLength,
RequestThread currentThread) {
// set currentVertex or currentEdge to the current element
if (currentElement.isVertex()) {
code.append("current").append("Vertex = \"").append(
currentElement.toVertex().getId()).append("\";\n");
} else if (currentElement.isEdge()) {
code.append("current").append("Edge = \"").append(
currentElement.toEdge().getId()).append("\";\n");
}
// calculate environment
JValueSet elementsToDisplay = new JValueSet();
if (currentElement.isVertex()) {
JValue slice = computeElements(currentElement, pathLength, state
.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else if (currentElement.isEdge()) {
Edge current = currentElement.toEdge();
JValue slice = computeElements(new JValueImpl(current.getAlpha()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
slice = computeElements(new JValueImpl(current.getOmega()),
pathLength, state.getGraph());
calculateElementsInSet(code, state, elementsToDisplay, slice);
} else {
calculateElementsInSet(code, state, elementsToDisplay,
currentElement.toJValueSet());
}
// create temp-folder
File tempFolder = new File(System.getProperty("java.io.tmpdir")
+ File.separator + "tgraphbrowser");
if (!tempFolder.exists()) {
if (!tempFolder.mkdir()) {
TGraphBrowserServer.logger.warning(tempFolder
+ " could not be created.");
}
}
tempFolder.deleteOnExit();
// create .dot-file
String dotFileName = null;
try {
dotFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.dot";
} catch (IOException e1) {
e1.printStackTrace();
}
MyTg2Dot mtd = new MyTg2Dot(elementsToDisplay, dotFileName,
showAttributes, currentElement, state.selectedEdgeClasses,
state.selectedVertexClasses);
mtd.printGraph();
if (mtd.exception != null) {
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(dotFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
// create .svg-file
String svgFileName = null;
try {
svgFileName = tempFolder.getCanonicalPath() + File.separator
+ sessionId + "GraphSnippet.svg";
} catch (IOException e1) {
e1.printStackTrace();
}
try {
synchronized (StateRepository.dot) {
String execStr = null;
// on windows, we must quote the file names, and on UNIX, we
// must not quote them... And this stupid ProcessBuilder doesn't
// work either...
if (System.getProperty("os.name").startsWith("Windows")) {
execStr = StateRepository.dot + " -Tsvg -o \""
+ svgFileName + "\" \"" + dotFileName + "\"";
} else {
execStr = StateRepository.dot + " -Tsvg -o " + svgFileName
+ " " + dotFileName;
}
ExecutingDot dotThread = new ExecutingDot(execStr,
currentThread);
dotThread.start();
try {
synchronized (currentThread) {
currentThread.wait(SECONDS_TO_WAIT_FOR_DOT * 1000);
}
dotThread.svgCreationProcess.destroy();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (dotThread.exitCode != -1) {
if (dotThread.exitCode != 0) {
if (dotThread.exception != null) {
throw dotThread.exception;
}
}
} else {
// execution of dot is terminated because it took too long
code.append("changeView();\n");
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Creation of file ")
.append(
svgFileName.contains("\\") ? svgFileName
.replace("\\", "/") : svgFileName)
.append(
" was terminated because it took more than ")
.append(SECONDS_TO_WAIT_FOR_DOT).append(
" seconds.\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
}
} catch (IOException e) {
e.printStackTrace();
code
.append("document.getElementById('divError').style.display = \"block\";\n");
code
.append(
"document.getElementById('h2ErrorMessage').innerHTML = \"ERROR: ")
.append("Could not create file ").append(svgFileName)
.append("\";\n");
code
.append("document.getElementById('divNonError').style.display = \"none\";\n");
return;
}
if (!new File(dotFileName).delete()) {
TGraphBrowserServer.logger.warning(dotFileName
+ " could not be deleted");
}
assert svgFileName != null : "svg file name must not be null";
svgFileName = svgFileName.substring(svgFileName
.lastIndexOf(File.separator) + 1);
// svg in HTML-Seite einbinden
code.append("/*@cc_on\n");
code.append("/*@if (@_jscript_version > 5.6)\n");
// code executed in Internet Explorer
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"embed\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.src = \"_").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("@else @*/\n");
// code executed in other browsers
code.append("var div2D = document.getElementById(\"div2DGraph\");\n");
code.append("var object = document.createElement(\"object\");\n");
code.append("object.id = \"embed2DGraph\";\n");
code.append("object.data = \"").append(svgFileName).append("\";\n");
code.append("object.type = \"image/svg+xml\";\n");
code.append("div2D.appendChild(object);\n");
code.append("/*@end\n");
code.append("@*/\n");
code.append("object.onload = function(){\n");
code.append("resize();\n");
code.append("};\n");
}
|
diff --git a/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java b/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
index 42fe6e04a..f9bed2535 100644
--- a/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
+++ b/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
@@ -1,242 +1,244 @@
package test.ccn.data.util;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.sql.Timestamp;
import java.util.logging.Level;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.util.Arrays;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import test.ccn.data.content.CCNEncodableCollectionData;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.content.CollectionData;
import com.parc.ccn.data.content.LinkReference;
import com.parc.ccn.data.security.LinkAuthenticator;
import com.parc.ccn.data.security.PublisherID;
import com.parc.ccn.data.security.SignedInfo;
import com.parc.ccn.data.security.PublisherID.PublisherType;
import com.parc.ccn.data.util.NullOutputStream;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.io.CCNVersionedInputStream;
import com.parc.security.crypto.DigestHelper;
/**
* Works. Currently very slow, as it's timing
* out lots of blocks. End of stream markers will help with that, as
* will potentially better binary ccnb decoding.
* @author smetters
*
*/
public class CCNEncodableObjectTest {
static final String baseName = "test";
static final String subName = "smetters";
static final String document1 = "report";
static final String document2 = "key";
static final String document3 = "cv.txt";
static final String prefix = "drawing_";
static ContentName namespace;
static ContentName [] ns = null;
static public byte [] contenthash1 = new byte[32];
static public byte [] contenthash2 = new byte[32];
static public byte [] publisherid1 = new byte[32];
static public byte [] publisherid2 = new byte[32];
static PublisherID pubID1 = null;
static PublisherID pubID2 = null;
static int NUM_LINKS = 100;
static LinkAuthenticator [] las = new LinkAuthenticator[NUM_LINKS];
static LinkReference [] lrs = null;
static CollectionData small1;
static CollectionData small2;
static CollectionData empty;
static CollectionData big;
static CCNLibrary library;
static Level oldLevel;
@AfterClass
public static void tearDownAfterClass() throws Exception {
Library.logger().setLevel(oldLevel);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("Making stuff.");
oldLevel = Library.logger().getLevel();
// Library.logger().setLevel(Level.FINEST);
library = CCNLibrary.open();
namespace = ContentName.fromURI(new String[]{baseName, subName, document1});
ns = new ContentName[NUM_LINKS];
for (int i=0; i < NUM_LINKS; ++i) {
ns[i] = ContentName.fromNative(namespace, prefix+Integer.toString(i));
}
Arrays.fill(publisherid1, (byte)6);
Arrays.fill(publisherid2, (byte)3);
pubID1 = new PublisherID(publisherid1, PublisherType.KEY);
pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY);
las[0] = new LinkAuthenticator(pubID1);
las[1] = null;
las[2] = new LinkAuthenticator(pubID2, null,
SignedInfo.ContentType.LEAF, contenthash1);
las[3] = new LinkAuthenticator(pubID1, new Timestamp(System.currentTimeMillis()),
null, contenthash1);
for (int j=4; j < NUM_LINKS; ++j) {
las[j] = new LinkAuthenticator(pubID2, new Timestamp(System.currentTimeMillis()),null, null);
}
lrs = new LinkReference[NUM_LINKS];
for (int i=0; i < lrs.length; ++i) {
lrs[i] = new LinkReference(ns[i],las[i]);
}
empty = new CollectionData();
small1 = new CollectionData();
small2 = new CollectionData();
for (int i=0; i < 5; ++i) {
small1.add(lrs[i]);
small2.add(lrs[i+5]);
}
big = new CollectionData();
for (int i=0; i < NUM_LINKS; ++i) {
big.add(lrs[i]);
}
}
@Test
public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
- if (!done) // if we have an error, stick around long enough to debug
+ if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
+ System.out.println("Done sleeping, finishing.");
+ }
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
}
| false | true | public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) // if we have an error, stick around long enough to debug
Thread.sleep(100000);
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
| public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
System.out.println("Done sleeping, finishing.");
}
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
|
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java
index 506976835..f81975fc3 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java
@@ -1,128 +1,129 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 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 - Initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.utils;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.*;
/**
* Performs string sharing passes on all string pool participants registered
* with the platform.
*/
public class StringPoolJob extends Job {
private static final long INITIAL_DELAY = 10000;//ten seconds
private static final long RESCHEDULE_DELAY = 300000;//five minutes
private long lastDuration;
/**
* Stores all registered string pool participants, along with the scheduling
* rule required when running it.
*/
private Map participants = Collections.synchronizedMap(new HashMap(10));
public StringPoolJob() {
super(Messages.utils_stringJobName);
setSystem(true);
setPriority(DECORATE);
}
/**
* Adds a string pool participant. The job periodically builds
* a string pool and asks all registered participants to share their strings in
* the pool. Once all participants have added their strings to the pool, the
* pool is discarded to avoid additional memory overhead.
*
* Adding a participant that is equal to a participant already registered will
* replace the scheduling rule associated with the participant, but will otherwise
* be ignored.
*
* @param participant The participant to add
* @param rule The scheduling rule that must be owned at the time the
* participant is called. This allows a participant to protect their data structures
* against access at unsafe times.
*
* @see #removeStringPoolParticipant(IStringPoolParticipant)
* @since 3.1
*/
public void addStringPoolParticipant(IStringPoolParticipant participant, ISchedulingRule rule) {
participants.put(participant, rule);
if (getState() == Job.SLEEPING)
wakeUp(INITIAL_DELAY);
else
schedule(INITIAL_DELAY);
}
/**
* Removes the indicated log listener from the set of registered string
* pool participants. If no such participant is registered, no action is taken.
*
* @param participant the participant to deregister
* @see #addStringPoolParticipant(IStringPoolParticipant, ISchedulingRule)
* @since 3.1
*/
public void removeStringPoolParticipant(IStringPoolParticipant participant) {
participants.remove(participant);
}
/* (non-Javadoc)
* Method declared on Job
*/
protected IStatus run(IProgressMonitor monitor) {
//copy current participants to handle concurrent additions and removals to map
Map.Entry[] entries = (Map.Entry[]) participants.entrySet().toArray(new Map.Entry[0]);
ISchedulingRule[] rules = new ISchedulingRule[entries.length];
IStringPoolParticipant[] toRun = new IStringPoolParticipant[entries.length];
for (int i = 0; i < toRun.length; i++) {
toRun[i] = (IStringPoolParticipant) entries[i].getKey();
rules[i] = (ISchedulingRule) entries[i].getValue();
}
final ISchedulingRule rule = MultiRule.combine(rules);
long start = -1;
int savings = 0;
+ final IJobManager jobManager = Platform.getJobManager();
try {
- Platform.getJobManager().beginRule(rule, monitor);
+ jobManager.beginRule(rule, monitor);
start = System.currentTimeMillis();
savings = shareStrings(toRun, monitor);
} finally {
- Platform.getJobManager().endRule(rule);
+ jobManager.endRule(rule);
}
if (start > 0) {
lastDuration = System.currentTimeMillis() - start;
if (Policy.DEBUG_STRINGS)
Policy.debug("String sharing saved " + savings + " bytes in: " + lastDuration); //$NON-NLS-1$ //$NON-NLS-2$
}
//throttle frequency if it takes too long
long scheduleDelay = Math.max(RESCHEDULE_DELAY, lastDuration*100);
if (Policy.DEBUG_STRINGS)
Policy.debug("Rescheduling string sharing job in: " + scheduleDelay); //$NON-NLS-1$
schedule(scheduleDelay);
return Status.OK_STATUS;
}
private int shareStrings(IStringPoolParticipant[] toRun, IProgressMonitor monitor) {
final StringPool pool = new StringPool();
for (int i = 0; i < toRun.length; i++) {
if (monitor.isCanceled())
break;
final IStringPoolParticipant current = toRun[i];
Platform.run(new ISafeRunnable() {
public void handleException(Throwable exception) {
//exceptions are already logged, so nothing to do
}
public void run() {
current.shareStrings(pool);
}
});
}
return pool.getSavedStringCount();
}
}
| false | true | protected IStatus run(IProgressMonitor monitor) {
//copy current participants to handle concurrent additions and removals to map
Map.Entry[] entries = (Map.Entry[]) participants.entrySet().toArray(new Map.Entry[0]);
ISchedulingRule[] rules = new ISchedulingRule[entries.length];
IStringPoolParticipant[] toRun = new IStringPoolParticipant[entries.length];
for (int i = 0; i < toRun.length; i++) {
toRun[i] = (IStringPoolParticipant) entries[i].getKey();
rules[i] = (ISchedulingRule) entries[i].getValue();
}
final ISchedulingRule rule = MultiRule.combine(rules);
long start = -1;
int savings = 0;
try {
Platform.getJobManager().beginRule(rule, monitor);
start = System.currentTimeMillis();
savings = shareStrings(toRun, monitor);
} finally {
Platform.getJobManager().endRule(rule);
}
if (start > 0) {
lastDuration = System.currentTimeMillis() - start;
if (Policy.DEBUG_STRINGS)
Policy.debug("String sharing saved " + savings + " bytes in: " + lastDuration); //$NON-NLS-1$ //$NON-NLS-2$
}
//throttle frequency if it takes too long
long scheduleDelay = Math.max(RESCHEDULE_DELAY, lastDuration*100);
if (Policy.DEBUG_STRINGS)
Policy.debug("Rescheduling string sharing job in: " + scheduleDelay); //$NON-NLS-1$
schedule(scheduleDelay);
return Status.OK_STATUS;
}
| protected IStatus run(IProgressMonitor monitor) {
//copy current participants to handle concurrent additions and removals to map
Map.Entry[] entries = (Map.Entry[]) participants.entrySet().toArray(new Map.Entry[0]);
ISchedulingRule[] rules = new ISchedulingRule[entries.length];
IStringPoolParticipant[] toRun = new IStringPoolParticipant[entries.length];
for (int i = 0; i < toRun.length; i++) {
toRun[i] = (IStringPoolParticipant) entries[i].getKey();
rules[i] = (ISchedulingRule) entries[i].getValue();
}
final ISchedulingRule rule = MultiRule.combine(rules);
long start = -1;
int savings = 0;
final IJobManager jobManager = Platform.getJobManager();
try {
jobManager.beginRule(rule, monitor);
start = System.currentTimeMillis();
savings = shareStrings(toRun, monitor);
} finally {
jobManager.endRule(rule);
}
if (start > 0) {
lastDuration = System.currentTimeMillis() - start;
if (Policy.DEBUG_STRINGS)
Policy.debug("String sharing saved " + savings + " bytes in: " + lastDuration); //$NON-NLS-1$ //$NON-NLS-2$
}
//throttle frequency if it takes too long
long scheduleDelay = Math.max(RESCHEDULE_DELAY, lastDuration*100);
if (Policy.DEBUG_STRINGS)
Policy.debug("Rescheduling string sharing job in: " + scheduleDelay); //$NON-NLS-1$
schedule(scheduleDelay);
return Status.OK_STATUS;
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java
index 6dcbf91b7..2c2b8f61f 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java
@@ -1,1063 +1,1059 @@
/*******************************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.core;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
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 org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileModificationValidator;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceRuleFactory;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.resources.team.ResourceRuleFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.client.Command;
import org.eclipse.team.internal.ccvs.core.client.Commit;
import org.eclipse.team.internal.ccvs.core.client.Diff;
import org.eclipse.team.internal.ccvs.core.client.Session;
import org.eclipse.team.internal.ccvs.core.client.Command.KSubstOption;
import org.eclipse.team.internal.ccvs.core.client.Command.LocalOption;
import org.eclipse.team.internal.ccvs.core.client.listeners.AdminKSubstListener;
import org.eclipse.team.internal.ccvs.core.client.listeners.DiffListener;
import org.eclipse.team.internal.ccvs.core.client.listeners.EditorsListener;
import org.eclipse.team.internal.ccvs.core.client.listeners.ICommandOutputListener;
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
import org.eclipse.team.internal.ccvs.core.resources.EclipseSynchronizer;
import org.eclipse.team.internal.ccvs.core.syncinfo.FolderSyncInfo;
import org.eclipse.team.internal.ccvs.core.syncinfo.MutableResourceSyncInfo;
import org.eclipse.team.internal.ccvs.core.syncinfo.ResourceSyncInfo;
import org.eclipse.team.internal.ccvs.core.util.Assert;
import org.eclipse.team.internal.ccvs.core.util.MoveDeleteHook;
import org.eclipse.team.internal.ccvs.core.util.ResourceStateChangeListeners;
import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter;
import org.eclipse.team.internal.core.streams.CRLFtoLFInputStream;
import org.eclipse.team.internal.core.streams.LFtoCRLFInputStream;
/**
* This class acts as both the ITeamNature and the ITeamProvider instances
* required by the Team core.
*
* The current stat of this class and it's plugin is EXPERIMENTAL.
* As such, it is subject to change except in it's conformance to the
* TEAM API which it implements.
*
* Questions:
*
* How should a project/reource rename/move effect the provider?
*
* Currently we always update with -P. Is this OK?
* - A way to allow customizable options would be nice
*
* Is the -l option valid for commit and does it work properly for update and commit?
*
* Do we need an IUserInteractionProvider in the CVS core
* - prompt for user info (caching could be separate)
* - get release comments
* - prompt for overwrite of unmanaged files
*
* Need a mechanism for communicating meta-information (provided by Team?)
*
* Should pass null when there are no options for a cvs command
*
* We currently write the files to disk and do a refreshLocal to
* have them appear in Eclipse. This may be changed in the future.
*/
public class CVSTeamProvider extends RepositoryProvider {
private static final ResourceRuleFactory RESOURCE_RULE_FACTORY = new ResourceRuleFactory() {
public ISchedulingRule validateEditRule(IResource[] resources) {
if (resources.length == 0)
return null;
//optimize rule for single file
if (resources.length == 1)
return resources[0].isReadOnly() ? parent(resources[0]) : null;
//need a lock on the parents of all read-only files
HashSet rules = new HashSet();
for (int i = 0; i < resources.length; i++)
if (resources[i].isReadOnly())
rules.add(parent(resources[i]));
if (rules.isEmpty())
return null;
if (rules.size() == 1)
return (ISchedulingRule) rules.iterator().next();
ISchedulingRule[] ruleArray = (ISchedulingRule[]) rules
.toArray(new ISchedulingRule[rules.size()]);
return new MultiRule(ruleArray);
}
};
private static final boolean IS_CRLF_PLATFORM = Arrays.equals(
System.getProperty("line.separator").getBytes(), new byte[] { '\r', '\n' }); //$NON-NLS-1$
public static final IStatus OK = new Status(IStatus.OK, CVSProviderPlugin.ID, 0, Policy.bind("ok"), null); //$NON-NLS-1$
private static final int UNIFIED_FORMAT = 0;
private static final int CONTEXT_FORMAT = 1;
private static final int STANDARD_FORMAT = 2;
private CVSWorkspaceRoot workspaceRoot;
private IProject project;
private static MoveDeleteHook moveDeleteHook= new MoveDeleteHook();
private static IFileModificationValidator fileModificationValidator;
// property used to indicate whether new directories should be discovered for the project
private final static QualifiedName FETCH_ABSENT_DIRECTORIES_PROP_KEY =
new QualifiedName("org.eclipse.team.cvs.core", "fetch_absent_directories"); //$NON-NLS-1$ //$NON-NLS-2$
// property used to indicate whether the project is configured to use Watch/edit
private final static QualifiedName WATCH_EDIT_PROP_KEY =
new QualifiedName("org.eclipse.team.cvs.core", "watch_edit"); //$NON-NLS-1$ //$NON-NLS-2$
/**
* No-arg Constructor for IProjectNature conformance
*/
public CVSTeamProvider() {
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure() {
}
/* (non-Javadoc)
* @see org.eclipse.team.core.RepositoryProvider#deconfigured()
*/
public void deconfigured() {
// when a nature is removed from the project, notify the synchronizer that
// we no longer need the sync info cached. This does not affect the actual CVS
// meta directories on disk, and will remain unless a client calls unmanage().
try {
EclipseSynchronizer.getInstance().deconfigure(getProject(), null);
internalSetWatchEditEnabled(null);
internalSetFetchAbsentDirectories(null);
} catch(CVSException e) {
// Log the exception and let the disconnect continue
CVSProviderPlugin.log(e);
}
ResourceStateChangeListeners.getListener().projectDeconfigured(getProject());
}
/**
* @see IProjectNature#getProject()
*/
public IProject getProject() {
return project;
}
/**
* @see IProjectNature#setProject(IProject)
*/
public void setProject(IProject project) {
this.project = project;
try {
this.workspaceRoot = new CVSWorkspaceRoot(project);
// Ensure that the project has CVS info
if (workspaceRoot.getLocalRoot().getFolderSyncInfo() == null) {
CVSProviderPlugin.log(new CVSException(new CVSStatus(CVSStatus.ERROR, Policy.bind("CVSTeamProvider.noFolderInfo", project.getName())))); //$NON-NLS-1$
}
} catch (CVSException e) {
// Ignore exceptions here. They will be surfaced elsewhere
}
}
/**
* Diff the resources with the repository and write the output to the provided
* PrintStream in a form that is usable as a patch. The patch is rooted at the
* project.
*/
public void diff(IResource resource, LocalOption[] options, PrintStream stream,
IProgressMonitor progress) throws TeamException {
boolean includeNewFiles = false;
boolean doNotRecurse = false;
int format = STANDARD_FORMAT;
// Determine the command root and arguments arguments list
ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource);
ICVSFolder commandRoot;
String[] arguments;
if (cvsResource.isFolder()) {
commandRoot = (ICVSFolder)cvsResource;
arguments = new String[] {Session.CURRENT_LOCAL_FOLDER};
} else {
commandRoot = cvsResource.getParent();
arguments = new String[] {cvsResource.getName()};
}
Session s = new Session(workspaceRoot.getRemoteLocation(), commandRoot);
progress.beginTask(null, 100);
try {
s.open(Policy.subMonitorFor(progress, 20), false /* read-only */);
Command.DIFF.execute(s,
Command.NO_GLOBAL_OPTIONS,
options,
arguments,
new DiffListener(stream),
Policy.subMonitorFor(progress, 80));
} finally {
s.close();
progress.done();
}
// Append our diff output to the server diff output.
// Our diff output includes new files and new files in new directories.
for (int i = 0; i < options.length; i++) {
LocalOption option = options[i];
if (option.equals(Diff.INCLUDE_NEWFILES)) {
includeNewFiles = true;
} else if (option.equals(Diff.DO_NOT_RECURSE)) {
doNotRecurse = true;
} else if (option.equals(Diff.UNIFIED_FORMAT)) {
format = UNIFIED_FORMAT;
} else if (option.equals(Diff.CONTEXT_FORMAT)) {
format = CONTEXT_FORMAT;
}
}
if (includeNewFiles) {
newFileDiff(cvsResource, stream, doNotRecurse, format);
}
}
/**
* This diff adds new files and directories to the stream.
* @param resource
* @param stream
* @param doNotRecurse
* @param format
* @throws CVSException
*/
private void newFileDiff(final ICVSResource resource, final PrintStream stream, final boolean doNotRecurse, final int format) throws CVSException {
final ICVSFolder rootFolder= resource instanceof ICVSFolder ? (ICVSFolder)resource : resource.getParent();
resource.accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
if (!(file.isIgnored() || file.isManaged())) {
addFileToDiff(rootFolder, file, stream, format);
}
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// Even if we are not supposed to recurse we still need to go into
// the root directory.
if (!folder.exists() || folder.isIgnored() || (doNotRecurse && !folder.equals(rootFolder))) {
return;
} else {
folder.acceptChildren(this);
}
}
});
}
private void addFileToDiff(ICVSFolder cmdRoot, ICVSFile file, PrintStream stream, int format) throws CVSException {
String nullFilePrefix = ""; //$NON-NLS-1$
String newFilePrefix = ""; //$NON-NLS-1$
String positionInfo = ""; //$NON-NLS-1$
String linePrefix = ""; //$NON-NLS-1$
String pathString = file.getRelativePath(cmdRoot);
int lines = 0;
BufferedReader fileReader = new BufferedReader(new InputStreamReader(file.getContents()));
try {
while (fileReader.readLine() != null) {
lines++;
}
} catch (IOException e) {
throw CVSException.wrapException(file.getIResource(), Policy.bind("CVSTeamProvider.errorAddingFileToDiff", pathString), e); //$NON-NLS-1$
} finally {
try {
fileReader.close();
} catch (IOException e1) {
//ignore
}
}
// Ignore empty files
if (lines == 0)
return;
switch (format) {
case UNIFIED_FORMAT :
nullFilePrefix = "--- "; //$NON-NLS-1$
newFilePrefix = "+++ "; //$NON-NLS-1$
positionInfo = "@@ -0,0 +1," + lines + " @@" ; //$NON-NLS-1$ //$NON-NLS-2$
linePrefix = "+"; //$NON-NLS-1$
break;
case CONTEXT_FORMAT :
nullFilePrefix = "*** "; //$NON-NLS-1$
newFilePrefix = "--- "; //$NON-NLS-1$
positionInfo = "--- 1," + lines + " ----"; //$NON-NLS-1$ //$NON-NLS-2$
linePrefix = "+ "; //$NON-NLS-1$
break;
default :
positionInfo = "0a1," + lines; //$NON-NLS-1$
linePrefix = "> "; //$NON-NLS-1$
break;
}
fileReader = new BufferedReader(new InputStreamReader(file.getContents()));
try {
stream.println("Index: " + pathString); //$NON-NLS-1$
stream.println("==================================================================="); //$NON-NLS-1$
stream.println("RCS file: " + pathString); //$NON-NLS-1$
stream.println("diff -N " + pathString); //$NON-NLS-1$
if (format != STANDARD_FORMAT) {
stream.println(nullFilePrefix + "/dev/null 1 Jan 1970 00:00:00 -0000"); //$NON-NLS-1$
// Technically this date should be the local file date but nobody really cares.
stream.println(newFilePrefix + pathString + " 1 Jan 1970 00:00:00 -0000"); //$NON-NLS-1$
}
if (format == CONTEXT_FORMAT) {
stream.println("***************"); //$NON-NLS-1$
stream.println("*** 0 ****"); //$NON-NLS-1$
}
stream.println(positionInfo);
for (int i = 0; i < lines; i++) {
stream.print(linePrefix);
stream.println(fileReader.readLine());
}
} catch (IOException e) {
throw CVSException.wrapException(file.getIResource(), Policy.bind("CVSTeamProvider.errorAddingFileToDiff", pathString), e); //$NON-NLS-1$
} finally {
try {
fileReader.close();
} catch (IOException e1) {
}
}
}
/**
* Return the remote location to which the receiver's project is mapped.
*/
public ICVSRepositoryLocation getRemoteLocation() throws CVSException {
try {
return workspaceRoot.getRemoteLocation();
} catch (CVSException e) {
// If we can't get the remote location, we should disconnect since nothing can be done with the provider
try {
RepositoryProvider.unmap(project);
} catch (TeamException ex) {
CVSProviderPlugin.log(ex);
}
// We need to trigger a decorator refresh
throw e;
}
}
/*
* @see ITeamProvider#isDirty(IResource)
*/
public boolean isDirty(IResource resource) {
Assert.isTrue(false);
return false;
}
public CVSWorkspaceRoot getCVSWorkspaceRoot() {
return workspaceRoot;
}
/*
* Generate an exception if the resource is not a child of the project
*/
private void checkIsChild(IResource resource) throws CVSException {
if (!isChildResource(resource))
throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE,
Policy.bind("CVSTeamProvider.invalidResource", //$NON-NLS-1$
new Object[] {resource.getFullPath().toString(), project.getName()}),
null));
}
/*
* Get the arguments to be passed to a commit or update
*/
private String[] getValidArguments(IResource[] resources, LocalOption[] options) throws CVSException {
List arguments = new ArrayList(resources.length);
for (int i=0;i<resources.length;i++) {
checkIsChild(resources[i]);
IPath cvsPath = resources[i].getFullPath().removeFirstSegments(1);
if (cvsPath.segmentCount() == 0) {
arguments.add(Session.CURRENT_LOCAL_FOLDER);
} else {
arguments.add(cvsPath.toString());
}
}
return (String[])arguments.toArray(new String[arguments.size()]);
}
private ICVSResource[] getCVSArguments(IResource[] resources) {
ICVSResource[] cvsResources = new ICVSResource[resources.length];
for (int i = 0; i < cvsResources.length; i++) {
cvsResources[i] = CVSWorkspaceRoot.getCVSResourceFor(resources[i]);
}
return cvsResources;
}
/*
* This method expects to be passed an InfiniteSubProgressMonitor
*/
public void setRemoteRoot(ICVSRepositoryLocation location, IProgressMonitor monitor) throws TeamException {
// Check if there is a differnece between the new and old roots
final String root = location.getLocation();
if (root.equals(workspaceRoot.getRemoteLocation()))
return;
try {
workspaceRoot.getLocalRoot().run(new ICVSRunnable() {
public void run(IProgressMonitor progress) throws CVSException {
try {
// 256 ticks gives us a maximum of 1024 which seems reasonable for folders is a project
progress.beginTask(null, 100);
final IProgressMonitor monitor = Policy.infiniteSubMonitorFor(progress, 100);
monitor.beginTask(Policy.bind("CVSTeamProvider.folderInfo", project.getName()), 256); //$NON-NLS-1$
// Visit all the children folders in order to set the root in the folder sync info
workspaceRoot.getLocalRoot().accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {}
public void visitFolder(ICVSFolder folder) throws CVSException {
monitor.worked(1);
FolderSyncInfo info = folder.getFolderSyncInfo();
if (info != null) {
monitor.subTask(Policy.bind("CVSTeamProvider.updatingFolder", info.getRepository())); //$NON-NLS-1$
folder.setFolderSyncInfo(new FolderSyncInfo(info.getRepository(), root, info.getTag(), info.getIsStatic()));
folder.acceptChildren(this);
}
}
});
} finally {
progress.done();
}
}
}, monitor);
} finally {
monitor.done();
}
}
/*
* Helper to indicate if the resource is a child of the receiver's project
*/
private boolean isChildResource(IResource resource) {
return resource.getProject().getName().equals(project.getName());
}
public void configureProject() throws CoreException {
ResourceStateChangeListeners.getListener().projectConfigured(getProject());
}
/**
* Sets the keyword substitution mode for the specified resources.
* <p>
* Applies the following rules in order:<br>
* <ul>
* <li>If a file is not managed, skips it.</li>
* <li>If a file is not changing modes, skips it.</li>
* <li>If a file is being changed from binary to text, corrects line delimiters
* then commits it, then admins it.</li>
* <li>If a file is added, changes the resource sync information locally.</li>
* <li>Otherwise commits the file (with FORCE to create a new revision), then admins it.</li>
* </ul>
* All files that are admin'd are committed with FORCE to prevent other developers from
* casually trying to commit pending changes to the repository without first checking out
* a new copy. This is not a perfect solution, as they could just as easily do an UPDATE
* and not obtain the new keyword sync info.
* </p>
*
* @param changeSet a map from IFile to KSubstOption
* @param monitor the progress monitor
* @return a status code indicating success or failure of the operation
*
* @throws TeamException
*/
public IStatus setKeywordSubstitution(final Map /* from IFile to KSubstOption */ changeSet,
final String comment,
IProgressMonitor monitor) throws TeamException {
final IStatus[] result = new IStatus[] { ICommandOutputListener.OK };
workspaceRoot.getLocalRoot().run(new ICVSRunnable() {
public void run(final IProgressMonitor monitor) throws CVSException {
final Map /* from KSubstOption to List of String */ filesToAdmin = new HashMap();
- final List /* of ICVSResource */ filesToCommit = new ArrayList();
final Collection /* of ICVSFile */ filesToCommitAsText = new HashSet(); // need fast lookup
final boolean useCRLF = IS_CRLF_PLATFORM && (CVSProviderPlugin.getPlugin().isUsePlatformLineend());
/*** determine the resources to be committed and/or admin'd ***/
for (Iterator it = changeSet.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
IFile file = (IFile) entry.getKey();
KSubstOption toKSubst = (KSubstOption) entry.getValue();
// only set keyword substitution if resource is a managed file
checkIsChild(file);
ICVSFile mFile = CVSWorkspaceRoot.getCVSFileFor(file);
if (! mFile.isManaged()) continue;
// only set keyword substitution if new differs from actual
byte[] syncBytes = mFile.getSyncBytes();
KSubstOption fromKSubst = ResourceSyncInfo.getKeywordMode(syncBytes);
if (toKSubst.equals(fromKSubst)) continue;
// change resource sync info immediately for an outgoing addition
if (ResourceSyncInfo.isAddition(syncBytes)) {
mFile.setSyncBytes(ResourceSyncInfo.setKeywordMode(syncBytes, toKSubst), ICVSFile.UNKNOWN);
continue;
}
// nothing do to for deletions
if (ResourceSyncInfo.isDeletion(syncBytes)) continue;
// file exists remotely so we'll have to commit it
if (fromKSubst.isBinary() && ! toKSubst.isBinary()) {
// converting from binary to text
cleanLineDelimiters(file, useCRLF, new NullProgressMonitor()); // XXX need better progress monitoring
// remember to commit the cleaned resource as text before admin
filesToCommitAsText.add(mFile);
}
- // force a commit to bump the revision number
- makeDirty(file);
- filesToCommit.add(mFile);
// remember to admin the resource
List list = (List) filesToAdmin.get(toKSubst);
if (list == null) {
list = new ArrayList();
filesToAdmin.put(toKSubst, list);
}
list.add(mFile);
}
/*** commit then admin the resources ***/
// compute the total work to be performed
- int totalWork = filesToCommit.size() + 1;
+ int totalWork = filesToCommitAsText.size() + 1;
for (Iterator it = filesToAdmin.values().iterator(); it.hasNext();) {
List list = (List) it.next();
totalWork += list.size();
totalWork += 1; // Add 1 for each connection that needs to be made
}
if (totalWork != 0) {
monitor.beginTask(Policy.bind("CVSTeamProvider.settingKSubst"), totalWork); //$NON-NLS-1$
try {
// commit files that changed from binary to text
// NOTE: The files are committed as text with conversions even if the
// resource sync info still says "binary".
- if (filesToCommit.size() != 0) {
+ if (filesToCommitAsText.size() != 0) {
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
String keywordChangeComment = comment;
if (keywordChangeComment == null || keywordChangeComment.length() == 0)
keywordChangeComment = Policy.bind("CVSTeamProvider.changingKeywordComment"); //$NON-NLS-1$
result[0] = Command.COMMIT.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { Commit.DO_NOT_RECURSE, Commit.FORCE,
Commit.makeArgumentOption(Command.MESSAGE_OPTION, keywordChangeComment) },
- (ICVSResource[]) filesToCommit.toArray(new ICVSResource[filesToCommit.size()]),
+ (ICVSResource[]) filesToCommitAsText.toArray(new ICVSResource[filesToCommitAsText.size()]),
filesToCommitAsText,
null,
- Policy.subMonitorFor(monitor, filesToCommit.size()));
+ Policy.subMonitorFor(monitor, filesToCommitAsText.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
// admin files that changed keyword substitution mode
// NOTE: As confirmation of the completion of a command, the server replies
// with the RCS command output if a change took place. Rather than
// assume that the command succeeded, we listen for these lines
// and update the local ResourceSyncInfo for the particular files that
// were actually changed remotely.
for (Iterator it = filesToAdmin.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
final KSubstOption toKSubst = (KSubstOption) entry.getKey();
final List list = (List) entry.getValue();
// do it
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
result[0] = Command.ADMIN.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { toKSubst },
(ICVSResource[]) list.toArray(new ICVSResource[list.size()]),
new AdminKSubstListener(toKSubst),
Policy.subMonitorFor(monitor, list.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
} finally {
monitor.done();
}
}
}
}, Policy.monitorFor(monitor));
return result[0];
}
/**
* This method translates the contents of a file from binary into text (ASCII).
* Fixes the line delimiters in the local file to reflect the platform's
* native encoding. Performs CR/LF -> LF or LF -> CR/LF conversion
* depending on the platform but does not affect delimiters that are
* already correctly encoded.
*/
public static void cleanLineDelimiters(IFile file, boolean useCRLF, IProgressMonitor progress)
throws CVSException {
try {
// convert delimiters in memory
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = new BufferedInputStream(file.getContents());
try {
// Always convert CR/LF into LFs
is = new CRLFtoLFInputStream(is);
if (useCRLF) {
// For CR/LF platforms, translate LFs to CR/LFs
is = new LFtoCRLFInputStream(is);
}
for (int b; (b = is.read()) != -1;) bos.write(b);
bos.close();
} finally {
is.close();
}
// write file back to disk with corrected delimiters if changes were made
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
file.setContents(bis, false /*force*/, false /*keepHistory*/, progress);
} catch (CoreException e) {
throw CVSException.wrapException(file, Policy.bind("CVSTeamProvider.cleanLineDelimitersException"), e); //$NON-NLS-1$
} catch (IOException e) {
throw CVSException.wrapException(file, Policy.bind("CVSTeamProvider.cleanLineDelimitersException"), e); //$NON-NLS-1$
}
}
/*
* Marks a file as dirty.
*/
private static void makeDirty(IFile file) throws CVSException {
ICVSFile mFile = CVSWorkspaceRoot.getCVSFileFor(file);
ResourceSyncInfo origInfo = mFile.getSyncInfo();
MutableResourceSyncInfo info = origInfo.cloneMutable();
info.setTimeStamp(null);/*set the sync timestamp to null to trigger dirtyness*/
mFile.setSyncInfo(info, ICVSFile.UNKNOWN);
}
/*
* @see RepositoryProvider#getID()
*/
public String getID() {
return CVSProviderPlugin.getTypeId();
}
/*
* @see RepositoryProvider#getMoveDeleteHook()
*/
public IMoveDeleteHook getMoveDeleteHook() {
return moveDeleteHook;
}
/*
* Return the currently registered Move/Delete Hook
*/
public static MoveDeleteHook getRegisteredMoveDeleteHook() {
return moveDeleteHook;
}
/**
* @see org.eclipse.team.core.RepositoryProvider#getFileModificationValidator()
*/
public IFileModificationValidator getFileModificationValidator() {
if (CVSTeamProvider.fileModificationValidator == null) {
CVSTeamProvider.fileModificationValidator = new CVSCoreFileModificationValidator();
}
return CVSTeamProvider.fileModificationValidator;
}
/**
* Checkout (cvs edit) the provided resources so they can be modified locally and committed.
* This will make any read-only resources in the list writable and will notify the server
* that the file is being edited. This notification may be done immediately or at some
* later point depending on whether contact with the server is possble at the time of
* invocation or the value of the notify server parameter.
*
* The recurse parameter is equivalent to the cvs local options -l (<code>true</code>) and
* -R (<code>false</code>). The notifyServer parameter can be used to defer server contact
* until the next command. This may be approrpiate if no shell or progress monitor is available
* to the caller. The notification bit field indicates what temporary watches are to be used while
* the file is being edited. The possible values that can be ORed together are ICVSFile.EDIT,
* ICVSFile.UNEDIT and ICVSFile.COMMIT. There pre-ORed convenience values ICVSFile.NO_NOTIFICATION
* and ICVSFile.NOTIFY_ON_ALL are also available.
*
* @param resources the resources to be edited
* @param recurse indicates whether to recurse (-R) or not (-l)
* @param notifyServer indicates whether to notify the server now, if possible,
* or defer until the next command.
* @param notification the temporary watches.
* @param progress progress monitor to provide progress indication/cancellation or <code>null</code>
* @exception CVSException if this method fails.
* @since 2.1
*
* @see CVSTeamProvider#unedit
*/
public void edit(IResource[] resources, boolean recurse, boolean notifyServer, final int notification, IProgressMonitor progress) throws CVSException {
notifyEditUnedit(resources, recurse, notifyServer, new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
if (file.isReadOnly())
file.edit(notification, Policy.monitorFor(null));
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// nothing needs to be done here as the recurse will handle the traversal
}
}, null /* no scheduling rule */, progress);
}
/**
* Unedit the given resources. Any writtable resources will be reverted to their base contents
* and made read-only and the server will be notified that the file is no longer being edited.
* This notification may be done immediately or at some
* later point depending on whether contact with the server is possble at the time of
* invocation or the value of the notify server parameter.
*
* The recurse parameter is equivalent to the cvs local options -l (<code>true</code>) and
* -R (<code>false</code>). The notifyServer parameter can be used to defer server contact
* until the next command. This may be approrpiate if no shell or progress monitor is available
* to the caller.
*
* @param resources the resources to be unedited
* @param recurse indicates whether to recurse (-R) or not (-l)
* @param notifyServer indicates whether to notify the server now, if possible,
* or defer until the next command.
* @param progress progress monitor to provide progress indication/cancellation or <code>null</code>
* @exception CVSException if this method fails.
* @since 2.1
*
* @see CVSTeamProvider#edit
*/
public void unedit(IResource[] resources, boolean recurse, boolean notifyServer, IProgressMonitor progress) throws CVSException {
notifyEditUnedit(resources, recurse, notifyServer, new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
if (!file.isReadOnly())
file.unedit(Policy.monitorFor(null));
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// nothing needs to be done here as the recurse will handle the traversal
}
}, getProject() /* project scheduling rule */, progress);
}
/*
* This method captures the common behavior between the edit and unedit methods.
*/
private void notifyEditUnedit(final IResource[] resources, final boolean recurse, final boolean notifyServer, final ICVSResourceVisitor editUneditVisitor, ISchedulingRule rule, IProgressMonitor monitor) throws CVSException {
final CVSException[] exception = new CVSException[] { null };
IWorkspaceRunnable workspaceRunnable = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
final ICVSResource[] cvsResources = getCVSArguments(resources);
// mark the files locally as being checked out
try {
for (int i = 0; i < cvsResources.length; i++) {
cvsResources[i].accept(editUneditVisitor, recurse);
}
} catch (CVSException e) {
exception[0] = e;
return;
}
// send the noop command to the server in order to deliver the notifications
if (notifyServer) {
monitor.beginTask(null, 100);
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true);
try {
try {
session.open(Policy.subMonitorFor(monitor, 10), true /* open for modification */);
} catch (CVSException e1) {
// If the connection cannot be opened, just exit normally.
// The notifications will be sent when a connection can be made
return;
}
Command.NOOP.execute(
session,
Command.NO_GLOBAL_OPTIONS,
Command.NO_LOCAL_OPTIONS,
cvsResources,
null,
Policy.subMonitorFor(monitor, 90));
} catch (CVSException e) {
exception[0] = e;
} finally {
session.close();
monitor.done();
}
}
}
};
try {
ResourcesPlugin.getWorkspace().run(workspaceRunnable, rule, 0, Policy.monitorFor(monitor));
} catch (CoreException e) {
if (exception[0] == null) {
throw CVSException.wrapException(e);
} else {
CVSProviderPlugin.log(CVSException.wrapException(e));
}
}
if (exception[0] != null) {
throw exception[0];
}
}
/**
* Gets the etchAbsentDirectories.
* @return Returns a boolean
*/
public boolean getFetchAbsentDirectories() throws CVSException {
try {
String property = getProject().getPersistentProperty(FETCH_ABSENT_DIRECTORIES_PROP_KEY);
if (property == null) return CVSProviderPlugin.getPlugin().getFetchAbsentDirectories();
return Boolean.valueOf(property).booleanValue();
} catch (CoreException e) {
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.errorGettingFetchProperty", project.getName()), e)); //$NON-NLS-1$
}
}
/**
* Sets the fetchAbsentDirectories.
* @param etchAbsentDirectories The etchAbsentDirectories to set
*/
public void setFetchAbsentDirectories(boolean fetchAbsentDirectories) throws CVSException {
internalSetFetchAbsentDirectories(fetchAbsentDirectories ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
}
public void internalSetFetchAbsentDirectories(String fetchAbsentDirectories) throws CVSException {
try {
getProject().setPersistentProperty(FETCH_ABSENT_DIRECTORIES_PROP_KEY, fetchAbsentDirectories);
} catch (CoreException e) {
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.errorSettingFetchProperty", project.getName()), e)); //$NON-NLS-1$
}
}
/**
* @see org.eclipse.team.core.RepositoryProvider#canHandleLinkedResources()
*/
public boolean canHandleLinkedResources() {
return true;
}
/**
* @see org.eclipse.team.core.RepositoryProvider#validateCreateLink(org.eclipse.core.resources.IResource, int, org.eclipse.core.runtime.IPath)
*/
public IStatus validateCreateLink(IResource resource, int updateFlags, IPath location) {
ICVSFolder cvsFolder = CVSWorkspaceRoot.getCVSFolderFor(resource.getParent().getFolder(new Path(resource.getName())));
try {
if (cvsFolder.isCVSFolder()) {
// There is a remote folder that overlaps with the link so disallow
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.overlappingRemoteFolder", resource.getFullPath().toString())); //$NON-NLS-1$
} else {
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(resource.getParent().getFile(new Path(resource.getName())));
if (cvsFile.isManaged()) {
// there is an outgoing file deletion that overlaps the link so disallow
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.overlappingFileDeletion", resource.getFullPath().toString())); //$NON-NLS-1$
}
}
} catch (CVSException e) {
CVSProviderPlugin.log(e);
return e.getStatus();
}
return super.validateCreateLink(resource, updateFlags, location);
}
/**
* Get the editors of the resources by calling the <code>cvs editors</code> command.
*
* @author <a href="mailto:[email protected],[email protected]">Gregor Kohlwes</a>
* @param resources
* @param progress
* @return IEditorsInfo[]
* @throws CVSException
*/
public EditorsInfo[] editors(
IResource[] resources,
IProgressMonitor progress)
throws CVSException {
// Build the local options
LocalOption[] commandOptions = new LocalOption[] {
};
progress.worked(10);
// Build the arguments list
String[] arguments = getValidArguments(resources, commandOptions);
// Build the listener for the command
EditorsListener listener = new EditorsListener();
// Check if canceled
if (progress.isCanceled()) {
return new EditorsInfo[0];
}
// Build the session
Session session =
new Session(
workspaceRoot.getRemoteLocation(),
workspaceRoot.getLocalRoot());
// Check if canceled
if (progress.isCanceled()) {
return new EditorsInfo[0];
}
progress.beginTask(null, 100);
try {
// Opening the session takes 20% of the time
session.open(Policy.subMonitorFor(progress, 20), false /* read-only */);
if (!progress.isCanceled()) {
// Execute the editors command
Command.EDITORS.execute(
session,
Command.NO_GLOBAL_OPTIONS,
commandOptions,
arguments,
listener,
Policy.subMonitorFor(progress, 80));
}
} finally {
session.close();
progress.done();
}
// Return the infos about the editors
return listener.getEditorsInfos();
}
/**
* Return the commit comment template that was provided by the server.
*
* @return String
* @throws CVSException
*/
public String getCommitTemplate() throws CVSException {
ICVSFolder localFolder = getCVSWorkspaceRoot().getLocalRoot();
ICVSFile templateFile = CVSWorkspaceRoot.getCVSFileFor(
SyncFileWriter.getTemplateFile(
(IContainer)localFolder.getIResource()));
if (!templateFile.exists()) return null;
InputStream in = new BufferedInputStream(templateFile.getContents());
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
do {
b = in.read();
if (b != -1)
out.write((byte)b);
} while (b != -1);
out.close();
return new String(out.toString());
} catch (IOException e) {
throw CVSException.wrapException(e);
} finally {
try {
in.close();
} catch (IOException e) {
// Since we already have the contents, just log this exception
CVSProviderPlugin.log(CVSException.wrapException(e));
}
}
}
/**
* Return true if the project is configured to use watch/edit. A project will use
* watch/edit if it was checked out when the global preference to use watch/edit is
* turned on.
* @return boolean
*/
public boolean isWatchEditEnabled() throws CVSException {
IProject project = getProject();
try {
String property = (String)project.getSessionProperty(WATCH_EDIT_PROP_KEY);
if (property == null) {
property = project.getPersistentProperty(WATCH_EDIT_PROP_KEY);
if (property == null) {
// The persistant property for the project was never set (i.e. old project)
// Use the global preference to determine if the project is using watch/edit
return CVSProviderPlugin.getPlugin().isWatchEditEnabled();
} else {
project.setSessionProperty(WATCH_EDIT_PROP_KEY, property);
}
}
return Boolean.valueOf(property).booleanValue();
} catch (CoreException e) {
if (project.isAccessible()) {
// We only care if the project still exists
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.errorGettingWatchEdit", project.getName()), e)); //$NON-NLS-1$
}
}
return false;
}
public void setWatchEditEnabled(boolean enabled) throws CVSException {
internalSetWatchEditEnabled(enabled ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
}
private void internalSetWatchEditEnabled(String enabled) throws CVSException {
try {
IProject project = getProject();
project.setPersistentProperty(WATCH_EDIT_PROP_KEY, enabled);
project.setSessionProperty(WATCH_EDIT_PROP_KEY, enabled);
} catch (CoreException e) {
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSTeamProvider.errorSettingWatchEdit", project.getName()), e)); //$NON-NLS-1$
}
}
/* (non-Javadoc)
* @see org.eclipse.team.core.RepositoryProvider#getRuleFactory()
*/
public IResourceRuleFactory getRuleFactory() {
return RESOURCE_RULE_FACTORY;
}
}
| false | true | public IStatus setKeywordSubstitution(final Map /* from IFile to KSubstOption */ changeSet,
final String comment,
IProgressMonitor monitor) throws TeamException {
final IStatus[] result = new IStatus[] { ICommandOutputListener.OK };
workspaceRoot.getLocalRoot().run(new ICVSRunnable() {
public void run(final IProgressMonitor monitor) throws CVSException {
final Map /* from KSubstOption to List of String */ filesToAdmin = new HashMap();
final List /* of ICVSResource */ filesToCommit = new ArrayList();
final Collection /* of ICVSFile */ filesToCommitAsText = new HashSet(); // need fast lookup
final boolean useCRLF = IS_CRLF_PLATFORM && (CVSProviderPlugin.getPlugin().isUsePlatformLineend());
/*** determine the resources to be committed and/or admin'd ***/
for (Iterator it = changeSet.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
IFile file = (IFile) entry.getKey();
KSubstOption toKSubst = (KSubstOption) entry.getValue();
// only set keyword substitution if resource is a managed file
checkIsChild(file);
ICVSFile mFile = CVSWorkspaceRoot.getCVSFileFor(file);
if (! mFile.isManaged()) continue;
// only set keyword substitution if new differs from actual
byte[] syncBytes = mFile.getSyncBytes();
KSubstOption fromKSubst = ResourceSyncInfo.getKeywordMode(syncBytes);
if (toKSubst.equals(fromKSubst)) continue;
// change resource sync info immediately for an outgoing addition
if (ResourceSyncInfo.isAddition(syncBytes)) {
mFile.setSyncBytes(ResourceSyncInfo.setKeywordMode(syncBytes, toKSubst), ICVSFile.UNKNOWN);
continue;
}
// nothing do to for deletions
if (ResourceSyncInfo.isDeletion(syncBytes)) continue;
// file exists remotely so we'll have to commit it
if (fromKSubst.isBinary() && ! toKSubst.isBinary()) {
// converting from binary to text
cleanLineDelimiters(file, useCRLF, new NullProgressMonitor()); // XXX need better progress monitoring
// remember to commit the cleaned resource as text before admin
filesToCommitAsText.add(mFile);
}
// force a commit to bump the revision number
makeDirty(file);
filesToCommit.add(mFile);
// remember to admin the resource
List list = (List) filesToAdmin.get(toKSubst);
if (list == null) {
list = new ArrayList();
filesToAdmin.put(toKSubst, list);
}
list.add(mFile);
}
/*** commit then admin the resources ***/
// compute the total work to be performed
int totalWork = filesToCommit.size() + 1;
for (Iterator it = filesToAdmin.values().iterator(); it.hasNext();) {
List list = (List) it.next();
totalWork += list.size();
totalWork += 1; // Add 1 for each connection that needs to be made
}
if (totalWork != 0) {
monitor.beginTask(Policy.bind("CVSTeamProvider.settingKSubst"), totalWork); //$NON-NLS-1$
try {
// commit files that changed from binary to text
// NOTE: The files are committed as text with conversions even if the
// resource sync info still says "binary".
if (filesToCommit.size() != 0) {
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
String keywordChangeComment = comment;
if (keywordChangeComment == null || keywordChangeComment.length() == 0)
keywordChangeComment = Policy.bind("CVSTeamProvider.changingKeywordComment"); //$NON-NLS-1$
result[0] = Command.COMMIT.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { Commit.DO_NOT_RECURSE, Commit.FORCE,
Commit.makeArgumentOption(Command.MESSAGE_OPTION, keywordChangeComment) },
(ICVSResource[]) filesToCommit.toArray(new ICVSResource[filesToCommit.size()]),
filesToCommitAsText,
null,
Policy.subMonitorFor(monitor, filesToCommit.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
// admin files that changed keyword substitution mode
// NOTE: As confirmation of the completion of a command, the server replies
// with the RCS command output if a change took place. Rather than
// assume that the command succeeded, we listen for these lines
// and update the local ResourceSyncInfo for the particular files that
// were actually changed remotely.
for (Iterator it = filesToAdmin.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
final KSubstOption toKSubst = (KSubstOption) entry.getKey();
final List list = (List) entry.getValue();
// do it
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
result[0] = Command.ADMIN.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { toKSubst },
(ICVSResource[]) list.toArray(new ICVSResource[list.size()]),
new AdminKSubstListener(toKSubst),
Policy.subMonitorFor(monitor, list.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
} finally {
monitor.done();
}
}
}
}, Policy.monitorFor(monitor));
return result[0];
}
| public IStatus setKeywordSubstitution(final Map /* from IFile to KSubstOption */ changeSet,
final String comment,
IProgressMonitor monitor) throws TeamException {
final IStatus[] result = new IStatus[] { ICommandOutputListener.OK };
workspaceRoot.getLocalRoot().run(new ICVSRunnable() {
public void run(final IProgressMonitor monitor) throws CVSException {
final Map /* from KSubstOption to List of String */ filesToAdmin = new HashMap();
final Collection /* of ICVSFile */ filesToCommitAsText = new HashSet(); // need fast lookup
final boolean useCRLF = IS_CRLF_PLATFORM && (CVSProviderPlugin.getPlugin().isUsePlatformLineend());
/*** determine the resources to be committed and/or admin'd ***/
for (Iterator it = changeSet.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
IFile file = (IFile) entry.getKey();
KSubstOption toKSubst = (KSubstOption) entry.getValue();
// only set keyword substitution if resource is a managed file
checkIsChild(file);
ICVSFile mFile = CVSWorkspaceRoot.getCVSFileFor(file);
if (! mFile.isManaged()) continue;
// only set keyword substitution if new differs from actual
byte[] syncBytes = mFile.getSyncBytes();
KSubstOption fromKSubst = ResourceSyncInfo.getKeywordMode(syncBytes);
if (toKSubst.equals(fromKSubst)) continue;
// change resource sync info immediately for an outgoing addition
if (ResourceSyncInfo.isAddition(syncBytes)) {
mFile.setSyncBytes(ResourceSyncInfo.setKeywordMode(syncBytes, toKSubst), ICVSFile.UNKNOWN);
continue;
}
// nothing do to for deletions
if (ResourceSyncInfo.isDeletion(syncBytes)) continue;
// file exists remotely so we'll have to commit it
if (fromKSubst.isBinary() && ! toKSubst.isBinary()) {
// converting from binary to text
cleanLineDelimiters(file, useCRLF, new NullProgressMonitor()); // XXX need better progress monitoring
// remember to commit the cleaned resource as text before admin
filesToCommitAsText.add(mFile);
}
// remember to admin the resource
List list = (List) filesToAdmin.get(toKSubst);
if (list == null) {
list = new ArrayList();
filesToAdmin.put(toKSubst, list);
}
list.add(mFile);
}
/*** commit then admin the resources ***/
// compute the total work to be performed
int totalWork = filesToCommitAsText.size() + 1;
for (Iterator it = filesToAdmin.values().iterator(); it.hasNext();) {
List list = (List) it.next();
totalWork += list.size();
totalWork += 1; // Add 1 for each connection that needs to be made
}
if (totalWork != 0) {
monitor.beginTask(Policy.bind("CVSTeamProvider.settingKSubst"), totalWork); //$NON-NLS-1$
try {
// commit files that changed from binary to text
// NOTE: The files are committed as text with conversions even if the
// resource sync info still says "binary".
if (filesToCommitAsText.size() != 0) {
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
String keywordChangeComment = comment;
if (keywordChangeComment == null || keywordChangeComment.length() == 0)
keywordChangeComment = Policy.bind("CVSTeamProvider.changingKeywordComment"); //$NON-NLS-1$
result[0] = Command.COMMIT.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { Commit.DO_NOT_RECURSE, Commit.FORCE,
Commit.makeArgumentOption(Command.MESSAGE_OPTION, keywordChangeComment) },
(ICVSResource[]) filesToCommitAsText.toArray(new ICVSResource[filesToCommitAsText.size()]),
filesToCommitAsText,
null,
Policy.subMonitorFor(monitor, filesToCommitAsText.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
// admin files that changed keyword substitution mode
// NOTE: As confirmation of the completion of a command, the server replies
// with the RCS command output if a change took place. Rather than
// assume that the command succeeded, we listen for these lines
// and update the local ResourceSyncInfo for the particular files that
// were actually changed remotely.
for (Iterator it = filesToAdmin.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
final KSubstOption toKSubst = (KSubstOption) entry.getKey();
final List list = (List) entry.getValue();
// do it
Session session = new Session(workspaceRoot.getRemoteLocation(), workspaceRoot.getLocalRoot(), true /* output to console */);
session.open(Policy.subMonitorFor(monitor, 1), true /* open for modification */);
try {
result[0] = Command.ADMIN.execute(
session,
Command.NO_GLOBAL_OPTIONS,
new LocalOption[] { toKSubst },
(ICVSResource[]) list.toArray(new ICVSResource[list.size()]),
new AdminKSubstListener(toKSubst),
Policy.subMonitorFor(monitor, list.size()));
} finally {
session.close();
}
// if errors were encountered, abort
if (! result[0].isOK()) return;
}
} finally {
monitor.done();
}
}
}
}, Policy.monitorFor(monitor));
return result[0];
}
|
diff --git a/scenarioo-api/src/main/java/org/scenarioo/model/docu/entities/Build.java b/scenarioo-api/src/main/java/org/scenarioo/model/docu/entities/Build.java
index fbba7616..d9d0473d 100755
--- a/scenarioo-api/src/main/java/org/scenarioo/model/docu/entities/Build.java
+++ b/scenarioo-api/src/main/java/org/scenarioo/model/docu/entities/Build.java
@@ -1,50 +1,50 @@
/* scenarioo-api
* Copyright (C) 2014, scenarioo.org Development Team
*
* 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.scenarioo.model.docu.entities;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
import org.scenarioo.model.docu.entities.generic.Details;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Build implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String revision;
private Date date;
private String status;
private Details details = new Details();
public Build() {
}
public Build(final String name) {
- this();
+ this.name = name;
}
}
| true | true | public Build(final String name) {
this();
}
| public Build(final String name) {
this.name = name;
}
|
diff --git a/Utility.java b/Utility.java
index 41e3c7c..6b2c21c 100644
--- a/Utility.java
+++ b/Utility.java
@@ -1,124 +1,123 @@
package naybur;
import java.util.ArrayList;
public class Utility
{
/**
* Calculates the squared distance from point a to point b
*
* @param
*/
public static double sqDist(ArrayList<Double> a, ArrayList<Double> b)
{
double dist = 0;
for(int i = 0; i < a.size(); i++)
{
dist += Math.pow(a.get(i) - b.get(i), 2);
}
return dist;
}
/**
* Calculates the squared distance from point a to point b
*
* @param
*/
public static double sqDistArray(double[] a, double[] b)
{
double dist = 0;
for(int i = 0; i < a.length; i++)
{
dist += Math.pow(a[i] - b[i], 2);
}
return dist;
}
/**
* Maps a list of points from one range to another. For example, given a list of points: { {5, 5} {4, 2} {9, 6} } a start_range {0, 10} and end_range {0,1}
* the output would be { {.5,.5} {.4,.2} {.9,.6} }. This function can handle points of any dimensionality.
*
* @param point_list The list of points to be mapped
* @param start_range The range that the points lie within. All coordinates of the point must lie within this range.
* @param end_range The range that the points should be mapped to
* @param dims The dimensionality of the points
*/
public static double[][] map(double[][] point_list, double[] start_range, double[] end_range, int dims)
{
double start_diff = Math.abs(start_range[0] - start_range[1]);
double end_diff = Math.abs(end_range[0] - end_range[1]);
double[][] mapped_list = new double[point_list.length][point_list[0].length];
for(int i = 0; i < point_list.length; i++)
{
for(int j = 0; j < dims; j++)
{
mapped_list[i][j] = ((point_list[i][j] - start_range[0])/start_diff * end_diff) + end_range[0];
}
}
return mapped_list;
}
/**
* Maps a single point from one range to the specified end range.
*
* @param point The point to be mapped
* @param start_range The initial range that the point lies on.
* @param end_range The final range that the point should be mapped to
* @param dims The dimensionality of the point.
*/
public static double[] map(double[] point, double[] start_range, double[] end_range, int dims)
{
double start_diff = Math.abs(start_range[0] - start_range[1]);
double end_diff = Math.abs(end_range[0] - end_range[1]);
double[] mapped_point = new double[point.length];
for(int j = 0; j < dims; j++)
{
mapped_point[j] = ((point[j] - start_range[0])/start_diff * end_diff) + end_range[0];
}
return mapped_point;
}
/**
* Maps a set of 2d points inside a rectangle of any size to the unit square.
*
* @param point_list A set of points to be mapped
* @param range The x and y bounds of the rectangle that contains the points in point_list. For a rectangle with its lower left hand corner at (1,2) and width 7
* and height 10 the range would be { {1,8} {2,12} }. This should always be a 2 x 2 array.
*/
public static double[][] map(double[][] point_list, double range[][])
{
double largest_diff = 0;
int largest_range = 0;
double[][] mapped_list = new double[point_list.length][point_list[0].length];
for(int i = 0; i < range.length; i++)
{
- double diff = Math.abs(start_range[i][0] - start_range[i][1]);
+ double diff = Math.abs(range[i][0] - range[i][1]);
if(diff > largest_diff)
largest_diff = diff;
}
for(int i = 0; i < point_list.length; i++)
{
for(int j = 0; j < 2; j++)
{
- point_list[i][j] = (point_list[i][j] - start_range[j][0])/start_diff;
- mapped_list[i][j] = ((point_list[i][j] - start_range[0])/start_diff * end_diff) + end_range[0];
+ mapped_list[i][j] = ((point_list[i][j] - range[j][0])/largest_diff);
}
}
return mapped_list;
}
}
| false | true | public static double[][] map(double[][] point_list, double range[][])
{
double largest_diff = 0;
int largest_range = 0;
double[][] mapped_list = new double[point_list.length][point_list[0].length];
for(int i = 0; i < range.length; i++)
{
double diff = Math.abs(start_range[i][0] - start_range[i][1]);
if(diff > largest_diff)
largest_diff = diff;
}
for(int i = 0; i < point_list.length; i++)
{
for(int j = 0; j < 2; j++)
{
point_list[i][j] = (point_list[i][j] - start_range[j][0])/start_diff;
mapped_list[i][j] = ((point_list[i][j] - start_range[0])/start_diff * end_diff) + end_range[0];
}
}
return mapped_list;
}
| public static double[][] map(double[][] point_list, double range[][])
{
double largest_diff = 0;
int largest_range = 0;
double[][] mapped_list = new double[point_list.length][point_list[0].length];
for(int i = 0; i < range.length; i++)
{
double diff = Math.abs(range[i][0] - range[i][1]);
if(diff > largest_diff)
largest_diff = diff;
}
for(int i = 0; i < point_list.length; i++)
{
for(int j = 0; j < 2; j++)
{
mapped_list[i][j] = ((point_list[i][j] - range[j][0])/largest_diff);
}
}
return mapped_list;
}
|
diff --git a/org.apache.hdt.ui/src/org/apache/hdt/ui/perspectives/HadoopPerspectiveFactory.java b/org.apache.hdt.ui/src/org/apache/hdt/ui/perspectives/HadoopPerspectiveFactory.java
index 3dada39..880d7cc 100644
--- a/org.apache.hdt.ui/src/org/apache/hdt/ui/perspectives/HadoopPerspectiveFactory.java
+++ b/org.apache.hdt.ui/src/org/apache/hdt/ui/perspectives/HadoopPerspectiveFactory.java
@@ -1,95 +1,95 @@
/**
* 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.hdt.ui.perspectives;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.console.IConsoleConstants;
/**
* Creates links to the new MapReduce-based wizards and views for a MapReduce
* perspective
*
*/
public class HadoopPerspectiveFactory implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
- layout.addNewWizardShortcut("org.apache.hadoop.eclipse.NewDriverWizard");
- layout.addNewWizardShortcut("org.apache.hadoop.eclipse.NewMapperWizard");
+ layout.addNewWizardShortcut("org.apache.hdt.ui.NewDriverWizard");
+ layout.addNewWizardShortcut("org.apache.hdt.ui.NewMapperWizard");
layout
- .addNewWizardShortcut("org.apache.hadoop.eclipse.NewReducerWizard");
+ .addNewWizardShortcut("org.apache.hdt.ui.NewReducerWizard");
IFolderLayout left =
- layout.createFolder("org.apache.hadoop.eclipse.perspective.left",
+ layout.createFolder("org.apache.hdt.ui.HadoopPerspective.left",
IPageLayout.LEFT, 0.2f, layout.getEditorArea());
left.addView("org.eclipse.ui.navigator.ProjectExplorer");
IFolderLayout bottom =
- layout.createFolder("org.apache.hadoop.eclipse.perspective.bottom",
+ layout.createFolder("org.apache.hdt.ui.HadoopPerspective.bottom",
IPageLayout.BOTTOM, 0.7f, layout.getEditorArea());
bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
bottom.addView(IPageLayout.ID_TASK_LIST);
bottom.addView(JavaUI.ID_JAVADOC_VIEW);
- bottom.addView("org.apache.hadoop.eclipse.view.servers");
+ bottom.addView("org.apache.hdt.ui.ClusterView");
bottom.addPlaceholder(JavaUI.ID_SOURCE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_PROGRESS_VIEW);
bottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout right =
- layout.createFolder("org.apache.hadoop.eclipse.perspective.right",
+ layout.createFolder("org.apache.hdt.ui.HadoopPerspective.right",
IPageLayout.RIGHT, 0.8f, layout.getEditorArea());
right.addView(IPageLayout.ID_OUTLINE);
right.addView("org.eclipse.ui.cheatsheets.views.CheatSheetView");
// right.addView(layout.ID); .. cheat sheet here
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_CODING_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
layout.addActionSet(JavaUI.ID_SEARCH_ACTION_SET);
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewEnumCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");
layout
.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");
// CheatSheetViewerFactory.createCheatSheetView().setInput("org.apache.hadoop.eclipse.cheatsheet");
}
}
| false | true | public void createInitialLayout(IPageLayout layout) {
layout.addNewWizardShortcut("org.apache.hadoop.eclipse.NewDriverWizard");
layout.addNewWizardShortcut("org.apache.hadoop.eclipse.NewMapperWizard");
layout
.addNewWizardShortcut("org.apache.hadoop.eclipse.NewReducerWizard");
IFolderLayout left =
layout.createFolder("org.apache.hadoop.eclipse.perspective.left",
IPageLayout.LEFT, 0.2f, layout.getEditorArea());
left.addView("org.eclipse.ui.navigator.ProjectExplorer");
IFolderLayout bottom =
layout.createFolder("org.apache.hadoop.eclipse.perspective.bottom",
IPageLayout.BOTTOM, 0.7f, layout.getEditorArea());
bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
bottom.addView(IPageLayout.ID_TASK_LIST);
bottom.addView(JavaUI.ID_JAVADOC_VIEW);
bottom.addView("org.apache.hadoop.eclipse.view.servers");
bottom.addPlaceholder(JavaUI.ID_SOURCE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_PROGRESS_VIEW);
bottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout right =
layout.createFolder("org.apache.hadoop.eclipse.perspective.right",
IPageLayout.RIGHT, 0.8f, layout.getEditorArea());
right.addView(IPageLayout.ID_OUTLINE);
right.addView("org.eclipse.ui.cheatsheets.views.CheatSheetView");
// right.addView(layout.ID); .. cheat sheet here
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_CODING_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
layout.addActionSet(JavaUI.ID_SEARCH_ACTION_SET);
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewEnumCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");
layout
.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");
// CheatSheetViewerFactory.createCheatSheetView().setInput("org.apache.hadoop.eclipse.cheatsheet");
}
| public void createInitialLayout(IPageLayout layout) {
layout.addNewWizardShortcut("org.apache.hdt.ui.NewDriverWizard");
layout.addNewWizardShortcut("org.apache.hdt.ui.NewMapperWizard");
layout
.addNewWizardShortcut("org.apache.hdt.ui.NewReducerWizard");
IFolderLayout left =
layout.createFolder("org.apache.hdt.ui.HadoopPerspective.left",
IPageLayout.LEFT, 0.2f, layout.getEditorArea());
left.addView("org.eclipse.ui.navigator.ProjectExplorer");
IFolderLayout bottom =
layout.createFolder("org.apache.hdt.ui.HadoopPerspective.bottom",
IPageLayout.BOTTOM, 0.7f, layout.getEditorArea());
bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
bottom.addView(IPageLayout.ID_TASK_LIST);
bottom.addView(JavaUI.ID_JAVADOC_VIEW);
bottom.addView("org.apache.hdt.ui.ClusterView");
bottom.addPlaceholder(JavaUI.ID_SOURCE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_PROGRESS_VIEW);
bottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
bottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout right =
layout.createFolder("org.apache.hdt.ui.HadoopPerspective.right",
IPageLayout.RIGHT, 0.8f, layout.getEditorArea());
right.addView(IPageLayout.ID_OUTLINE);
right.addView("org.eclipse.ui.cheatsheets.views.CheatSheetView");
// right.addView(layout.ID); .. cheat sheet here
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_CODING_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
layout.addActionSet(JavaUI.ID_SEARCH_ACTION_SET);
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewEnumCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard");
layout
.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");
layout
.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");
// CheatSheetViewerFactory.createCheatSheetView().setInput("org.apache.hadoop.eclipse.cheatsheet");
}
|
diff --git a/src/openblocks/OpenBlocks.java b/src/openblocks/OpenBlocks.java
index 2ee7b982..c96fe7a1 100644
--- a/src/openblocks/OpenBlocks.java
+++ b/src/openblocks/OpenBlocks.java
@@ -1,376 +1,376 @@
package openblocks;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.StatBasic;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import openblocks.common.*;
import openblocks.common.block.*;
import openblocks.common.entity.*;
import openblocks.common.item.*;
import openblocks.common.item.ItemImaginationGlasses.ItemCrayonGlasses;
import openblocks.common.tileentity.*;
import openblocks.events.EventTypes;
import openblocks.integration.ModuleComputerCraft;
import openblocks.integration.ModuleOpenPeripheral;
import openblocks.rubbish.BrickManager;
import openmods.Mods;
import openmods.config.RegisterBlock;
import openmods.config.RegisterItem;
import openmods.entity.EntityBlock;
import openmods.item.ItemGeneric;
import openmods.utils.EnchantmentUtils;
import org.apache.commons.lang3.ObjectUtils;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = "OpenBlocks", name = "OpenBlocks", version = "@VERSION@", dependencies = "required-after:OpenMods;after:OpenPeripheral")
@NetworkMod(serverSideRequired = true, clientSideRequired = true)
public class OpenBlocks {
@Instance(value = "OpenBlocks")
public static OpenBlocks instance;
@SidedProxy(clientSide = "openblocks.client.ClientProxy", serverSide = "openblocks.common.ServerProxy")
public static IOpenBlocksProxy proxy;
public static class Blocks {
@RegisterBlock(name = "ladder")
public static BlockLadder ladder;
@RegisterBlock(name = "guide", tileEntity = TileEntityGuide.class)
public static BlockGuide guide;
@RegisterBlock(name = "elevator", tileEntity = TileEntityElevator.class)
public static BlockElevator elevator;
@RegisterBlock(name = "heal", tileEntity = TileEntityHealBlock.class)
public static BlockHeal heal;
@RegisterBlock(name = "target", tileEntity = TileEntityTarget.class)
public static BlockTarget target;
@RegisterBlock(name = "grave", tileEntity = TileEntityGrave.class)
public static BlockGrave grave;
@RegisterBlock(name = "flag", tileEntity = TileEntityFlag.class, itemBlock = ItemFlagBlock.class)
public static BlockFlag flag;
@RegisterBlock(name = "tank", tileEntity = TileEntityTank.class, itemBlock = ItemTankBlock.class)
public static BlockTank tank;
@RegisterBlock(name = "trophy", tileEntity = TileEntityTrophy.class, itemBlock = ItemTrophyBlock.class)
public static BlockTrophy trophy;
@RegisterBlock(name = "beartrap", tileEntity = TileEntityBearTrap.class)
public static BlockBearTrap bearTrap;
@RegisterBlock(name = "sprinkler", tileEntity = TileEntitySprinkler.class)
public static BlockSprinkler sprinkler;
@RegisterBlock(name = "cannon", tileEntity = TileEntityCannon.class)
public static BlockCannon cannon;
@RegisterBlock(name = "vacuumhopper", tileEntity = TileEntityVacuumHopper.class)
public static BlockVacuumHopper vacuumHopper;
@RegisterBlock(name = "sponge", tileEntity = TileEntitySponge.class)
public static BlockSponge sponge;
@RegisterBlock(name = "bigbutton", tileEntity = TileEntityBigButton.class)
public static BlockBigButton bigButton;
@RegisterBlock(name = "imaginary", tileEntity = TileEntityImaginary.class, itemBlock = ItemImaginary.class)
public static BlockImaginary imaginary;
@RegisterBlock(name = "fan", tileEntity = TileEntityFan.class)
public static BlockFan fan;
@RegisterBlock(name = "xpbottler", tileEntity = TileEntityXPBottler.class)
public static BlockXPBottler xpBottler;
@RegisterBlock(name = "village_highlighter", tileEntity = TileEntityVillageHighlighter.class)
public static BlockVillageHighlighter villageHighlighter;
@RegisterBlock(name = "path")
public static BlockPath path;
@RegisterBlock(name = "autoanvil", tileEntity = TileEntityAutoAnvil.class)
public static BlockAutoAnvil autoAnvil;
@RegisterBlock(name = "autoenchantmenttable", tileEntity = TileEntityAutoEnchantmentTable.class)
public static BlockAutoEnchantmentTable autoEnchantmentTable;
@RegisterBlock(name = "xpdrain", tileEntity = TileEntityXPDrain.class)
public static BlockXPDrain xpDrain;
@RegisterBlock(name = "blockbreaker", tileEntity = TileEntityBlockBreaker.class)
public static BlockBlockBreaker blockBreaker;
@RegisterBlock(name = "blockPlacer", tileEntity = TileEntityBlockPlacer.class)
public static BlockBlockPlacer blockPlacer;
@RegisterBlock(name = "itemDropper", tileEntity = TileEntityItemDropper.class)
public static BlockItemDropper itemDropper;
@RegisterBlock(name = "ropeladder", tileEntity = TileEntityRopeLadder.class)
public static BlockRopeLadder ropeLadder;
@RegisterBlock(name = "donationStation", tileEntity = TileEntityDonationStation.class)
public static BlockDonationStation donationStation;
@RegisterBlock(name = "paintmixer", tileEntity = TileEntityPaintMixer.class)
public static BlockPaintMixer paintMixer;
@RegisterBlock(name = "canvas", tileEntity = TileEntityCanvas.class)
public static BlockCanvas canvas;
@RegisterBlock(name = "oreCrusher", tileEntity = TileEntityOreCrusher.class)
public static BlockMachineOreCrusher machineOreCrusher;
@RegisterBlock(name = "paintcan", tileEntity = TileEntityPaintCan.class)
public static BlockPaintCan paintCan;
@RegisterBlock(name = "canvasglass", tileEntity = TileEntityCanvas.class)
public static BlockCanvasGlass canvasGlass;
@RegisterBlock(name = "projector", tileEntity = TileEntityProjector.class)
public static BlockProjector projector;
@RegisterBlock(name = "drawingtable", tileEntity = TileEntityDrawingTable.class)
public static BlockDrawingTable drawingTable;
//@RegisterBlock(name = "goldenegg", tileEntity = TileEntityGoldenEgg.class)
//public static BlockGoldenEgg goldenEgg;
}
public static class Items {
@RegisterItem(name = "hangglider")
public static ItemHangGlider hangGlider;
@RegisterItem(name = "generic")
public static ItemGeneric generic;
@RegisterItem(name = "luggage")
public static ItemLuggage luggage;
@RegisterItem(name = "sonicglasses")
public static ItemSonicGlasses sonicGlasses;
@RegisterItem(name = "pencilGlasses")
public static ItemImaginationGlasses pencilGlasses;
@RegisterItem(name = "crayonGlasses")
public static ItemCrayonGlasses crayonGlasses;
@RegisterItem(name = "technicolorGlasses")
public static ItemImaginationGlasses technicolorGlasses;
@RegisterItem(name = "seriousGlasses")
public static ItemImaginationGlasses seriousGlasses;
@RegisterItem(name = "craneControl")
public static ItemCraneControl craneControl;
@RegisterItem(name = "craneBackpack")
public static ItemCraneBackpack craneBackpack;
@RegisterItem(name = "slimalyzer")
public static ItemSlimalyzer slimalyzer;
@RegisterItem(name = "filledbucket")
public static ItemFilledBucket filledBucket;
@RegisterItem(name = "sleepingBag")
public static ItemSleepingBag sleepingBag;
@RegisterItem(name = "paintBrush")
public static ItemPaintBrush paintBrush;
@RegisterItem(name = "stencil")
public static ItemStencil stencil;
@RegisterItem(name = "squeegee")
public static ItemSqueegee squeegee;
@RegisterItem(name = "heightMap")
public static ItemHeightMap heightMap;
@RegisterItem(name = "emptyMap")
public static ItemEmptyMap emptyMap;
@RegisterItem(name = "cartographer")
public static ItemCartographer cartographer;
@RegisterItem(name = "tastyClay")
public static ItemTastyClay tastyClay;
@RegisterItem(name = "goldenEye")
public static ItemGoldenEye goldenEye;
}
public static class Fluids {
public static Fluid XPJuice;
public static Fluid openBlocksXPJuice;
}
public static FluidStack XP_FLUID = null;
public static enum GuiId {
luggage
}
public static final GuiId[] GUIS = GuiId.values();
public static CreativeTabs tabOpenBlocks = new CreativeTabs("tabOpenBlocks") {
@Override
public ItemStack getIconItemStack() {
return new ItemStack(ObjectUtils.firstNonNull(OpenBlocks.Blocks.flag, Block.sponge), 1, 0);
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
@SideOnly(Side.CLIENT)
public void displayAllReleventItems(List result) {
super.displayAllReleventItems(result);
if (explosiveEnch != null) EnchantmentUtils.addAllBooks(explosiveEnch, result);
}
};
public static int renderId;
public static final Achievement brickAchievement = new Achievement(70997, "openblocks.droppedBrick", 13, 13, Item.brick, null).registerAchievement();
public static final StatBase brickStat = (new StatBasic(70998, "stat.openblocks.bricksDropped")).registerStat();
public static Enchantment explosiveEnch;
@EventHandler
public void preInit(FMLPreInitializationEvent evt) {
EventTypes.registerTypes();
Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
Config.readConfig(configFile);
if (configFile.hasChanged()) configFile.save();
Config.register();
NetworkRegistry.instance().registerGuiHandler(instance, proxy.createGuiHandler());
if (Config.enableGraves) {
MinecraftForge.EVENT_BUS.register(new PlayerDeathHandler());
}
MinecraftForge.EVENT_BUS.register(new TileEntityEventHandler());
if (Config.itemLuggageId > 0) {
EntityRegistry.registerModEntity(EntityLuggage.class, "Luggage", 702, OpenBlocks.instance, 64, 1, true);
}
EntityRegistry.registerModEntity(EntityHangGlider.class, "Hang Glider", 701, OpenBlocks.instance, 64, 1, true);
if (Config.itemCraneId > 0) {
EntityRegistry.registerModEntity(EntityMagnet.class, "Magnet", 703, OpenBlocks.instance, 64, 1, true);
EntityRegistry.registerModEntity(EntityBlock.class, "Block", 704, OpenBlocks.instance, 64, 1, true);
}
if (Config.itemCartographerId > 0) {
EntityRegistry.registerModEntity(EntityCartographer.class, "Cartographer", 705, OpenBlocks.instance, 64, 8, true);
}
/*
EntityRegistry.registerModEntity(EntityMutant.class, "Mutant", 708, OpenBlocks.instance, 64, 8, true);
MutantRegistry.registerMutant(EntityCreeper.class, new DefinitionCreeper());
MutantRegistry.registerMutant(EntityZombie.class, new DefinitionZombie());
MutantRegistry.registerMutant(EntityPig.class, new DefinitionPig());
MutantRegistry.registerMutant(EntityEnderman.class, new DefinitionEnderman());
MutantRegistry.registerMutant(EntitySpider.class, new DefinitionSpider());
MutantRegistry.registerMutant(EntityChicken.class, new DefinitionChicken());
MutantRegistry.registerMutant(EntitySheep.class, new DefinitionSheep());
MutantRegistry.registerMutant(EntityOcelot.class, new DefinitionOcelot());
*/
EntityRegistry.registerModEntity(EntityItemProjectile.class, "EntityItemProjectile", 706, OpenBlocks.instance, 64, 1, true);
if (Config.itemGoldenEyeId > 0) {
EntityRegistry.registerModEntity(EntityGoldenEye.class, "GoldenEye", 707, OpenBlocks.instance, 64, 8, true);
MinecraftForge.EVENT_BUS.register(StructureRegistry.instance);
}
Fluids.openBlocksXPJuice = new Fluid("xpjuice").setLuminosity(10).setDensity(800).setViscosity(1500);
FluidRegistry.registerFluid(Fluids.openBlocksXPJuice);
Fluids.XPJuice = FluidRegistry.getFluid("xpjuice");
XP_FLUID = new FluidStack(OpenBlocks.Fluids.openBlocksXPJuice, 1);
FluidContainerRegistry.registerFluidContainer(Fluids.XPJuice, MetasBucket.xpbucket.newItemStack(), FluidContainerRegistry.EMPTY_BUCKET);
OpenBlocks.Items.generic.initRecipes();
MagnetWhitelists.instance.initTesters();
MinecraftForge.EVENT_BUS.register(MapDataManager.instance);
if (Loader.isModLoaded(Mods.COMPUTERCRAFT)) ModuleComputerCraft.registerAddons();
- if (Loader.isModLoaded(Mods.OPENPERIPHERAL)) ModuleOpenPeripheral.registerAdapters();
+ if (Loader.isModLoaded(Mods.OPENPERIPHERALCORE)) ModuleOpenPeripheral.registerAdapters();
if (!Config.soSerious) {
MinecraftForge.EVENT_BUS.register(new BrickManager());
}
proxy.preInit();
}
/**
* @param evt
*/
@EventHandler
public void init(FMLInitializationEvent evt) {
TickRegistry.registerTickHandler(new ServerTickHandler(), Side.SERVER);
proxy.init();
proxy.registerRenderInformation();
}
/**
* @param evt
*/
@EventHandler
public void postInit(FMLPostInitializationEvent evt) {
proxy.postInit();
}
@Mod.EventHandler
public void processMessage(FMLInterModComms.IMCEvent event) {
for (FMLInterModComms.IMCMessage m : event.getMessages()) {
if (m.isStringMessage() && m.key.equalsIgnoreCase("donateUrl")) {
DonationUrlManager.instance().addUrl(m.getSender(), m.getStringValue());
}
}
}
public static String getModId() {
return OpenBlocks.class.getAnnotation(Mod.class).modid();
}
}
| true | true | public void preInit(FMLPreInitializationEvent evt) {
EventTypes.registerTypes();
Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
Config.readConfig(configFile);
if (configFile.hasChanged()) configFile.save();
Config.register();
NetworkRegistry.instance().registerGuiHandler(instance, proxy.createGuiHandler());
if (Config.enableGraves) {
MinecraftForge.EVENT_BUS.register(new PlayerDeathHandler());
}
MinecraftForge.EVENT_BUS.register(new TileEntityEventHandler());
if (Config.itemLuggageId > 0) {
EntityRegistry.registerModEntity(EntityLuggage.class, "Luggage", 702, OpenBlocks.instance, 64, 1, true);
}
EntityRegistry.registerModEntity(EntityHangGlider.class, "Hang Glider", 701, OpenBlocks.instance, 64, 1, true);
if (Config.itemCraneId > 0) {
EntityRegistry.registerModEntity(EntityMagnet.class, "Magnet", 703, OpenBlocks.instance, 64, 1, true);
EntityRegistry.registerModEntity(EntityBlock.class, "Block", 704, OpenBlocks.instance, 64, 1, true);
}
if (Config.itemCartographerId > 0) {
EntityRegistry.registerModEntity(EntityCartographer.class, "Cartographer", 705, OpenBlocks.instance, 64, 8, true);
}
/*
EntityRegistry.registerModEntity(EntityMutant.class, "Mutant", 708, OpenBlocks.instance, 64, 8, true);
MutantRegistry.registerMutant(EntityCreeper.class, new DefinitionCreeper());
MutantRegistry.registerMutant(EntityZombie.class, new DefinitionZombie());
MutantRegistry.registerMutant(EntityPig.class, new DefinitionPig());
MutantRegistry.registerMutant(EntityEnderman.class, new DefinitionEnderman());
MutantRegistry.registerMutant(EntitySpider.class, new DefinitionSpider());
MutantRegistry.registerMutant(EntityChicken.class, new DefinitionChicken());
MutantRegistry.registerMutant(EntitySheep.class, new DefinitionSheep());
MutantRegistry.registerMutant(EntityOcelot.class, new DefinitionOcelot());
*/
EntityRegistry.registerModEntity(EntityItemProjectile.class, "EntityItemProjectile", 706, OpenBlocks.instance, 64, 1, true);
if (Config.itemGoldenEyeId > 0) {
EntityRegistry.registerModEntity(EntityGoldenEye.class, "GoldenEye", 707, OpenBlocks.instance, 64, 8, true);
MinecraftForge.EVENT_BUS.register(StructureRegistry.instance);
}
Fluids.openBlocksXPJuice = new Fluid("xpjuice").setLuminosity(10).setDensity(800).setViscosity(1500);
FluidRegistry.registerFluid(Fluids.openBlocksXPJuice);
Fluids.XPJuice = FluidRegistry.getFluid("xpjuice");
XP_FLUID = new FluidStack(OpenBlocks.Fluids.openBlocksXPJuice, 1);
FluidContainerRegistry.registerFluidContainer(Fluids.XPJuice, MetasBucket.xpbucket.newItemStack(), FluidContainerRegistry.EMPTY_BUCKET);
OpenBlocks.Items.generic.initRecipes();
MagnetWhitelists.instance.initTesters();
MinecraftForge.EVENT_BUS.register(MapDataManager.instance);
if (Loader.isModLoaded(Mods.COMPUTERCRAFT)) ModuleComputerCraft.registerAddons();
if (Loader.isModLoaded(Mods.OPENPERIPHERAL)) ModuleOpenPeripheral.registerAdapters();
if (!Config.soSerious) {
MinecraftForge.EVENT_BUS.register(new BrickManager());
}
proxy.preInit();
}
| public void preInit(FMLPreInitializationEvent evt) {
EventTypes.registerTypes();
Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
Config.readConfig(configFile);
if (configFile.hasChanged()) configFile.save();
Config.register();
NetworkRegistry.instance().registerGuiHandler(instance, proxy.createGuiHandler());
if (Config.enableGraves) {
MinecraftForge.EVENT_BUS.register(new PlayerDeathHandler());
}
MinecraftForge.EVENT_BUS.register(new TileEntityEventHandler());
if (Config.itemLuggageId > 0) {
EntityRegistry.registerModEntity(EntityLuggage.class, "Luggage", 702, OpenBlocks.instance, 64, 1, true);
}
EntityRegistry.registerModEntity(EntityHangGlider.class, "Hang Glider", 701, OpenBlocks.instance, 64, 1, true);
if (Config.itemCraneId > 0) {
EntityRegistry.registerModEntity(EntityMagnet.class, "Magnet", 703, OpenBlocks.instance, 64, 1, true);
EntityRegistry.registerModEntity(EntityBlock.class, "Block", 704, OpenBlocks.instance, 64, 1, true);
}
if (Config.itemCartographerId > 0) {
EntityRegistry.registerModEntity(EntityCartographer.class, "Cartographer", 705, OpenBlocks.instance, 64, 8, true);
}
/*
EntityRegistry.registerModEntity(EntityMutant.class, "Mutant", 708, OpenBlocks.instance, 64, 8, true);
MutantRegistry.registerMutant(EntityCreeper.class, new DefinitionCreeper());
MutantRegistry.registerMutant(EntityZombie.class, new DefinitionZombie());
MutantRegistry.registerMutant(EntityPig.class, new DefinitionPig());
MutantRegistry.registerMutant(EntityEnderman.class, new DefinitionEnderman());
MutantRegistry.registerMutant(EntitySpider.class, new DefinitionSpider());
MutantRegistry.registerMutant(EntityChicken.class, new DefinitionChicken());
MutantRegistry.registerMutant(EntitySheep.class, new DefinitionSheep());
MutantRegistry.registerMutant(EntityOcelot.class, new DefinitionOcelot());
*/
EntityRegistry.registerModEntity(EntityItemProjectile.class, "EntityItemProjectile", 706, OpenBlocks.instance, 64, 1, true);
if (Config.itemGoldenEyeId > 0) {
EntityRegistry.registerModEntity(EntityGoldenEye.class, "GoldenEye", 707, OpenBlocks.instance, 64, 8, true);
MinecraftForge.EVENT_BUS.register(StructureRegistry.instance);
}
Fluids.openBlocksXPJuice = new Fluid("xpjuice").setLuminosity(10).setDensity(800).setViscosity(1500);
FluidRegistry.registerFluid(Fluids.openBlocksXPJuice);
Fluids.XPJuice = FluidRegistry.getFluid("xpjuice");
XP_FLUID = new FluidStack(OpenBlocks.Fluids.openBlocksXPJuice, 1);
FluidContainerRegistry.registerFluidContainer(Fluids.XPJuice, MetasBucket.xpbucket.newItemStack(), FluidContainerRegistry.EMPTY_BUCKET);
OpenBlocks.Items.generic.initRecipes();
MagnetWhitelists.instance.initTesters();
MinecraftForge.EVENT_BUS.register(MapDataManager.instance);
if (Loader.isModLoaded(Mods.COMPUTERCRAFT)) ModuleComputerCraft.registerAddons();
if (Loader.isModLoaded(Mods.OPENPERIPHERALCORE)) ModuleOpenPeripheral.registerAdapters();
if (!Config.soSerious) {
MinecraftForge.EVENT_BUS.register(new BrickManager());
}
proxy.preInit();
}
|
diff --git a/Zones/src/info/tregmine/listeners/ZoneEntityListener.java b/Zones/src/info/tregmine/listeners/ZoneEntityListener.java
index 5e80385..15d75a1 100644
--- a/Zones/src/info/tregmine/listeners/ZoneEntityListener.java
+++ b/Zones/src/info/tregmine/listeners/ZoneEntityListener.java
@@ -1,98 +1,98 @@
package info.tregmine.listeners;
import java.util.EnumSet;
import java.util.Set;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import info.tregmine.api.Zone;
import info.tregmine.quadtree.Point;
import info.tregmine.zones.ZoneWorld;
import info.tregmine.zones.ZonesPlugin;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
//import org.bukkit.entity.CreatureType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
public class ZoneEntityListener implements Listener
{
private static final Set<EntityType> allowedMobs =
EnumSet.of(EntityType.CHICKEN, EntityType.COW,
EntityType.PIG, EntityType.SHEEP,
EntityType.SQUID, EntityType.WOLF,
EntityType.VILLAGER, EntityType.MUSHROOM_COW);
private final ZonesPlugin plugin;
private final Tregmine tregmine;
public ZoneEntityListener(ZonesPlugin instance)
{
this.plugin = instance;
this.tregmine = instance.tregmine;
}
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event)
{
Entity entity = event.getEntity();
Location location = event.getLocation();
Point pos = new Point(location.getBlockX(), location.getBlockZ());
ZoneWorld world = plugin.getWorld(entity.getWorld());
Zone zone = world.findZone(pos);
if (zone == null || zone.hasHostiles()) {
return;
}
if (!allowedMobs.contains(event.getEntityType())) {
event.setCancelled(true);
}
}
@EventHandler
public void onEntityDamage(EntityDamageEvent event)
{
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
ZoneWorld world = plugin.getWorld(entity.getWorld());
TregminePlayer player = tregmine.getPlayer((Player)event.getEntity());
Location location = player.getLocation();
Point pos = new Point(location.getBlockX(), location.getBlockZ());
Zone currentZone = player.getCurrentZone();
if (currentZone == null || !currentZone.contains(pos)) {
currentZone = world.findZone(pos);
player.setCurrentZone(currentZone);
}
if (currentZone == null || !currentZone.isPvp()) {
- if(event.getCause() == DamageCause.ENTITY_ATTACK) {
+ if(event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE || event.getCause() == DamageCause.MAGIC || event.getCause() == DamageCause.POISON) {
EntityDamageEvent damageEvent = event.getEntity().getLastDamageCause();
EntityDamageByEntityEvent eEvent = (EntityDamageByEntityEvent) damageEvent;
if(eEvent.getDamager() instanceof Player) {
Player offender = (Player) eEvent.getDamager();
offender.sendMessage(ChatColor.YELLOW + "This is a not a pvp zone!");
event.setCancelled(true);
}
}
return;
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event)
{
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
ZoneWorld world = plugin.getWorld(entity.getWorld());
TregminePlayer player = tregmine.getPlayer((Player)event.getEntity());
Location location = player.getLocation();
Point pos = new Point(location.getBlockX(), location.getBlockZ());
Zone currentZone = player.getCurrentZone();
if (currentZone == null || !currentZone.contains(pos)) {
currentZone = world.findZone(pos);
player.setCurrentZone(currentZone);
}
if (currentZone == null || !currentZone.isPvp()) {
if(event.getCause() == DamageCause.ENTITY_ATTACK) {
EntityDamageEvent damageEvent = event.getEntity().getLastDamageCause();
EntityDamageByEntityEvent eEvent = (EntityDamageByEntityEvent) damageEvent;
if(eEvent.getDamager() instanceof Player) {
Player offender = (Player) eEvent.getDamager();
offender.sendMessage(ChatColor.YELLOW + "This is a not a pvp zone!");
event.setCancelled(true);
}
}
return;
}
}
| public void onEntityDamage(EntityDamageEvent event)
{
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
ZoneWorld world = plugin.getWorld(entity.getWorld());
TregminePlayer player = tregmine.getPlayer((Player)event.getEntity());
Location location = player.getLocation();
Point pos = new Point(location.getBlockX(), location.getBlockZ());
Zone currentZone = player.getCurrentZone();
if (currentZone == null || !currentZone.contains(pos)) {
currentZone = world.findZone(pos);
player.setCurrentZone(currentZone);
}
if (currentZone == null || !currentZone.isPvp()) {
if(event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE || event.getCause() == DamageCause.MAGIC || event.getCause() == DamageCause.POISON) {
EntityDamageEvent damageEvent = event.getEntity().getLastDamageCause();
EntityDamageByEntityEvent eEvent = (EntityDamageByEntityEvent) damageEvent;
if(eEvent.getDamager() instanceof Player) {
Player offender = (Player) eEvent.getDamager();
offender.sendMessage(ChatColor.YELLOW + "This is a not a pvp zone!");
event.setCancelled(true);
}
}
return;
}
}
|
diff --git a/src/baseline/filter/BrandnameFilter.java b/src/baseline/filter/BrandnameFilter.java
index f065034..b0349c0 100644
--- a/src/baseline/filter/BrandnameFilter.java
+++ b/src/baseline/filter/BrandnameFilter.java
@@ -1,32 +1,32 @@
package baseline.filter;
import baseline.Dictionary;
public class BrandnameFilter extends MentionFilter{
public BrandnameFilter(Dictionary brandnames) {
super();
this.brandnames = brandnames;
}
Dictionary brandnames;
@Override
public boolean isValidMention(String[] text, int startIndex, int endIndex) {
int noBrands = 0;
for(int i=startIndex; i<=endIndex; i++) {
if(brandnames.contains(text[i]))
noBrands++;
}
//It must not contain two or more different brand names
if(noBrands>1)
return false;
// If 1-token long then it must not be a brand
if(startIndex==endIndex && noBrands==1)
return false;
- return false;
+ return true;
}
}
| true | true | public boolean isValidMention(String[] text, int startIndex, int endIndex) {
int noBrands = 0;
for(int i=startIndex; i<=endIndex; i++) {
if(brandnames.contains(text[i]))
noBrands++;
}
//It must not contain two or more different brand names
if(noBrands>1)
return false;
// If 1-token long then it must not be a brand
if(startIndex==endIndex && noBrands==1)
return false;
return false;
}
| public boolean isValidMention(String[] text, int startIndex, int endIndex) {
int noBrands = 0;
for(int i=startIndex; i<=endIndex; i++) {
if(brandnames.contains(text[i]))
noBrands++;
}
//It must not contain two or more different brand names
if(noBrands>1)
return false;
// If 1-token long then it must not be a brand
if(startIndex==endIndex && noBrands==1)
return false;
return true;
}
|
diff --git a/cruzeira/src/main/java/org/cruzeira/netty/NettyServer.java b/cruzeira/src/main/java/org/cruzeira/netty/NettyServer.java
index d0d09a8..97fbd5e 100644
--- a/cruzeira/src/main/java/org/cruzeira/netty/NettyServer.java
+++ b/cruzeira/src/main/java/org/cruzeira/netty/NettyServer.java
@@ -1,158 +1,158 @@
/*
* This file is part of cruzeira and it's licensed under the project terms.
*/
package org.cruzeira.netty;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.cruzeira.server.OpenWebJar;
import org.cruzeira.server.ServerManager;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NettyServer extends ServletServer {
// private boolean readingChunks;
final Logger logger = LoggerFactory.getLogger(NettyServer.class);
public NettyServer(ServerManager serverManager) {
super(serverManager);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
logger.info("Received");
serverManager.beforeRequest();
HttpRequest request = (HttpRequest) event.getMessage();
if (request.getUri().startsWith("/resources/")) {
return;
}
// is100ContinueExpected(request);
StringBuilder buf = new StringBuilder();
Object[] servlets = doServlet(ctx, event, request, buf);
if (servlets == null) {
} else if (servlets[2] == Boolean.TRUE) {
ctx.sendUpstream(event);
} else if (request.isChunked()) {
// readingChunks = true;
} else {
writeResponse(event, request, buf, servlets[0], servlets[1]);
}
}
public static void main(String[] args) {
Options options = new Options();
options.addOption("p", true, "Http port");
options.addOption("dev", false, "Development mode");
CommandLineParser parser = new BasicParser();
Logger logger = LoggerFactory.getLogger(NettyServer.class);
int port = 8080;
boolean devMode = false;
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("p")) {
try {
port = Integer.valueOf(cmd.getOptionValue("p"));
} catch (Exception e) {
e.printStackTrace();
}
}
devMode = cmd.hasOption("dev");
if (devMode) {
logger.info("Running in development mode");
} else {
logger.info("Running in normal mode");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Error on cli");
}
int cpus = Runtime.getRuntime().availableProcessors();
logger.info("CPUs: {}", cpus);
ChannelFactory factory;
int asyncPool;
if (devMode) {
asyncPool = 1;
- factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
+ factory = new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), 1);
} else {
asyncPool = cpus * 2 * 2;
- factory = new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), 1);
+ factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
}
OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(asyncPool, 0, 0, 30, TimeUnit.SECONDS);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
new OpenWebJar();
bootstrap.setPipelineFactory(new MyPipelineFactory(eventExecutor));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", false);
bootstrap.bind(new InetSocketAddress(port));
logger.info("Running cruzeira {}...", port);
}
static class MyPipelineFactory implements ChannelPipelineFactory {
private ServerManager serverManager;
private Executor pipelineExecutor;
public MyPipelineFactory(Executor executor) {
this.serverManager = new ServerManager();
this.pipelineExecutor = executor;
}
public ChannelPipeline getPipeline() {
// Create a default pipeline implementation.
ChannelPipeline pipeline = Channels.pipeline();
// Uncomment the following line if you want HTTPS
// SSLEngine engine =
// SecureChatSslContextFactory.getServerContext().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(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
// pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("filehandler", new FileServer());
pipeline.addLast("handler", new NettyServer(serverManager));
pipeline.addLast("pipelineExecutor", new ExecutionHandler(pipelineExecutor));
pipeline.addLast("asyncHandler", new AsyncServer(serverManager));
return pipeline;
}
}
}
| false | true | public static void main(String[] args) {
Options options = new Options();
options.addOption("p", true, "Http port");
options.addOption("dev", false, "Development mode");
CommandLineParser parser = new BasicParser();
Logger logger = LoggerFactory.getLogger(NettyServer.class);
int port = 8080;
boolean devMode = false;
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("p")) {
try {
port = Integer.valueOf(cmd.getOptionValue("p"));
} catch (Exception e) {
e.printStackTrace();
}
}
devMode = cmd.hasOption("dev");
if (devMode) {
logger.info("Running in development mode");
} else {
logger.info("Running in normal mode");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Error on cli");
}
int cpus = Runtime.getRuntime().availableProcessors();
logger.info("CPUs: {}", cpus);
ChannelFactory factory;
int asyncPool;
if (devMode) {
asyncPool = 1;
factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
} else {
asyncPool = cpus * 2 * 2;
factory = new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), 1);
}
OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(asyncPool, 0, 0, 30, TimeUnit.SECONDS);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
new OpenWebJar();
bootstrap.setPipelineFactory(new MyPipelineFactory(eventExecutor));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", false);
bootstrap.bind(new InetSocketAddress(port));
logger.info("Running cruzeira {}...", port);
}
| public static void main(String[] args) {
Options options = new Options();
options.addOption("p", true, "Http port");
options.addOption("dev", false, "Development mode");
CommandLineParser parser = new BasicParser();
Logger logger = LoggerFactory.getLogger(NettyServer.class);
int port = 8080;
boolean devMode = false;
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("p")) {
try {
port = Integer.valueOf(cmd.getOptionValue("p"));
} catch (Exception e) {
e.printStackTrace();
}
}
devMode = cmd.hasOption("dev");
if (devMode) {
logger.info("Running in development mode");
} else {
logger.info("Running in normal mode");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Error on cli");
}
int cpus = Runtime.getRuntime().availableProcessors();
logger.info("CPUs: {}", cpus);
ChannelFactory factory;
int asyncPool;
if (devMode) {
asyncPool = 1;
factory = new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), 1);
} else {
asyncPool = cpus * 2 * 2;
factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
}
OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(asyncPool, 0, 0, 30, TimeUnit.SECONDS);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
new OpenWebJar();
bootstrap.setPipelineFactory(new MyPipelineFactory(eventExecutor));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", false);
bootstrap.bind(new InetSocketAddress(port));
logger.info("Running cruzeira {}...", port);
}
|
diff --git a/src/main/java/org/encog/ml/svm/training/SVMSearchTrain.java b/src/main/java/org/encog/ml/svm/training/SVMSearchTrain.java
index 1156a0cc3..4b45a9962 100644
--- a/src/main/java/org/encog/ml/svm/training/SVMSearchTrain.java
+++ b/src/main/java/org/encog/ml/svm/training/SVMSearchTrain.java
@@ -1,391 +1,390 @@
/*
* Encog(tm) Core v3.0 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2011 Heaton Research, Inc.
*
* 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 more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.svm.training;
import org.encog.ml.MLMethod;
import org.encog.ml.TrainingImplementationType;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.svm.KernelType;
import org.encog.ml.svm.SVM;
import org.encog.ml.train.BasicTraining;
import org.encog.neural.networks.training.propagation.TrainingContinuation;
import org.encog.util.Format;
/**
* Provides training for Support Vector Machine networks.
*/
public class SVMSearchTrain extends BasicTraining {
/**
* The default number of folds.
*/
public static final int DEFAULT_FOLDS = 5;
/**
* The default starting number for C.
*/
public static final double DEFAULT_CONST_BEGIN = -5;
/**
* The default ending number for C.
*/
public static final double DEFAULT_CONST_END = 15;
/**
* The default step for C.
*/
public static final double DEFAULT_CONST_STEP = 2;
/**
* The default gamma begin.
*/
public static final double DEFAULT_GAMMA_BEGIN = -10;
/**
* The default gamma end.
*/
public static final double DEFAULT_GAMMA_END = 10;
/**
* The default gamma step.
*/
public static final double DEFAULT_GAMMA_STEP = 1;
/**
* The network that is to be trained.
*/
private final SVM network;
/**
* The number of folds.
*/
private int fold = DEFAULT_FOLDS;
/**
* The beginning value for C.
*/
private double constBegin = SVMSearchTrain.DEFAULT_CONST_BEGIN;
/**
* The step value for C.
*/
private double constStep = SVMSearchTrain.DEFAULT_CONST_END;
/**
* The ending value for C.
*/
private double constEnd = SVMSearchTrain.DEFAULT_CONST_STEP;
/**
* The beginning value for gamma.
*/
private double gammaBegin = SVMSearchTrain.DEFAULT_GAMMA_BEGIN;
/**
* The ending value for gamma.
*/
private double gammaEnd = SVMSearchTrain.DEFAULT_GAMMA_END;
/**
* The step value for gamma.
*/
private double gammaStep = SVMSearchTrain.DEFAULT_GAMMA_STEP;
/**
* The best values found for C.
*/
private double bestConst;
/**
* The best values found for gamma.
*/
private double bestGamma;
/**
* The best error.
*/
private double bestError;
/**
* The current C.
*/
private double currentConst;
/**
* The current gamma.
*/
private double currentGamma;
/**
* Is the network setup.
*/
private boolean isSetup;
/**
* Is the training done.
*/
private boolean trainingDone;
/**
* The internal training object, used for the search.
*/
private final SVMTrain internalTrain;
/**
* Construct a trainer for an SVM network.
*
* @param method
* The method to train.
* @param training
* The training data for this network.
*/
public SVMSearchTrain(final SVM method, final MLDataSet training) {
super(TrainingImplementationType.Iterative);
this.network = method;
setTraining(training);
this.isSetup = false;
this.trainingDone = false;
this.internalTrain = new SVMTrain(network, training);
}
/**
* {@inheritDoc}
*/
@Override
public final boolean canContinue() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public final void finishTraining() {
this.internalTrain.setGamma(this.bestGamma);
this.internalTrain.setC(this.bestConst);
this.internalTrain.iteration();
}
/**
* @return the constBegin
*/
public final double getConstBegin() {
return this.constBegin;
}
/**
* @return the constEnd
*/
public final double getConstEnd() {
return this.constEnd;
}
/**
* @return the constStep
*/
public final double getConstStep() {
return this.constStep;
}
/**
* @return the fold
*/
public final int getFold() {
return this.fold;
}
/**
* @return the gammaBegin
*/
public final double getGammaBegin() {
return this.gammaBegin;
}
/**
* @return the gammaEnd
*/
public final double getGammaEnd() {
return this.gammaEnd;
}
/**
* @return the gammaStep
*/
public final double getGammaStep() {
return this.gammaStep;
}
/**
* {@inheritDoc}
*/
@Override
public final MLMethod getMethod() {
return this.network;
}
/**
* @return True if the training is done.
*/
@Override
public final boolean isTrainingDone() {
return this.trainingDone;
}
/**
* Perform one training iteration.
*/
@Override
public final void iteration() {
if (!this.trainingDone) {
if (!this.isSetup) {
setup();
}
preIteration();
if (this.network.getKernelType()
== KernelType.RadialBasisFunction) {
double totalError = 0;
final double e = this.internalTrain.crossValidate(
- this.currentGamma, this.currentConst)
- / Format.HUNDRED_PERCENT;
+ this.currentGamma, this.currentConst);
System.out.println(this.currentGamma + "," + this.currentConst
+ "," + e);
if (e < this.bestError) {
this.bestConst = this.currentConst;
this.bestGamma = this.currentGamma;
this.bestError = e;
}
this.currentConst += this.constStep;
if (this.currentConst > this.constEnd) {
this.currentConst = this.constBegin;
this.currentGamma += this.gammaStep;
if (this.currentGamma > this.gammaEnd) {
this.trainingDone = true;
}
}
totalError += this.bestError;
setError(totalError / this.network.getOutputCount());
} else {
this.internalTrain.setGamma(this.currentGamma);
this.internalTrain.setC(this.currentConst);
this.internalTrain.iteration();
}
postIteration();
}
}
/**
* {@inheritDoc}
*/
@Override
public final TrainingContinuation pause() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void resume(final TrainingContinuation state) {
}
/**
* @param theConstBegin
* the constBegin to set
*/
public final void setConstBegin(final double theConstBegin) {
this.constBegin = theConstBegin;
}
/**
* @param theConstEnd
* the constEnd to set
*/
public final void setConstEnd(final double theConstEnd) {
this.constEnd = theConstEnd;
}
/**
* @param theConstStep
* the constStep to set
*/
public final void setConstStep(final double theConstStep) {
this.constStep = theConstStep;
}
/**
* @param theFold
* the fold to set
*/
public final void setFold(final int theFold) {
this.fold = theFold;
}
/**
* @param theGammaBegin
* the gammaBegin to set
*/
public final void setGammaBegin(final double theGammaBegin) {
this.gammaBegin = theGammaBegin;
}
/**
* @param theGammaEnd
* the gammaEnd to set.
*/
public final void setGammaEnd(final double theGammaEnd) {
this.gammaEnd = theGammaEnd;
}
/**
* @param theGammaStep
* the gammaStep to set
*/
public final void setGammaStep(final double theGammaStep) {
this.gammaStep = theGammaStep;
}
/**
* Setup to train the SVM.
*/
private void setup() {
this.currentConst = this.constBegin;
this.currentGamma = this.gammaBegin;
this.bestError = Double.POSITIVE_INFINITY;
this.isSetup = true;
}
}
| true | true | public final void iteration() {
if (!this.trainingDone) {
if (!this.isSetup) {
setup();
}
preIteration();
if (this.network.getKernelType()
== KernelType.RadialBasisFunction) {
double totalError = 0;
final double e = this.internalTrain.crossValidate(
this.currentGamma, this.currentConst)
/ Format.HUNDRED_PERCENT;
System.out.println(this.currentGamma + "," + this.currentConst
+ "," + e);
if (e < this.bestError) {
this.bestConst = this.currentConst;
this.bestGamma = this.currentGamma;
this.bestError = e;
}
this.currentConst += this.constStep;
if (this.currentConst > this.constEnd) {
this.currentConst = this.constBegin;
this.currentGamma += this.gammaStep;
if (this.currentGamma > this.gammaEnd) {
this.trainingDone = true;
}
}
totalError += this.bestError;
setError(totalError / this.network.getOutputCount());
} else {
this.internalTrain.setGamma(this.currentGamma);
this.internalTrain.setC(this.currentConst);
this.internalTrain.iteration();
}
postIteration();
}
}
| public final void iteration() {
if (!this.trainingDone) {
if (!this.isSetup) {
setup();
}
preIteration();
if (this.network.getKernelType()
== KernelType.RadialBasisFunction) {
double totalError = 0;
final double e = this.internalTrain.crossValidate(
this.currentGamma, this.currentConst);
System.out.println(this.currentGamma + "," + this.currentConst
+ "," + e);
if (e < this.bestError) {
this.bestConst = this.currentConst;
this.bestGamma = this.currentGamma;
this.bestError = e;
}
this.currentConst += this.constStep;
if (this.currentConst > this.constEnd) {
this.currentConst = this.constBegin;
this.currentGamma += this.gammaStep;
if (this.currentGamma > this.gammaEnd) {
this.trainingDone = true;
}
}
totalError += this.bestError;
setError(totalError / this.network.getOutputCount());
} else {
this.internalTrain.setGamma(this.currentGamma);
this.internalTrain.setC(this.currentConst);
this.internalTrain.iteration();
}
postIteration();
}
}
|
diff --git a/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java b/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
index 1016012b..1f1b36eb 100644
--- a/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
+++ b/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
@@ -1,238 +1,238 @@
/**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* 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 the University of Technology, Sydney 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.
*
* @author Michael Diponio (mdiponio)
* @date 8th April 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.session.impl;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.queuer.QueueInfo;
/**
* Either expires or extends the time of all sessions which are close to
* the session duration duration.
*/
public class SessionExpiryChecker implements Runnable
{
/** Logger. */
private Logger logger;
/** Flag to specify if this is a test run. */
private boolean notTest = true;
public SessionExpiryChecker()
{
this.logger = LoggerActivator.getLogger();
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
org.hibernate.Session db = null;
try
{
db = DataAccessActivator.getNewSession();
boolean kicked = false;
if (db == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = perm.getSessionDuration() + // The allowed session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() == 0)
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time extended.");
ses.setExtensions((short)(ses.getExtensions() - 1));
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout. *
******************************************************************/
else if ((System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
- this.logger.error("Exception rolling back up session expiry transaction (Exception: " +
+ this.logger.error("Exception rolling back session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
}
| true | true | public void run()
{
org.hibernate.Session db = null;
try
{
db = DataAccessActivator.getNewSession();
boolean kicked = false;
if (db == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = perm.getSessionDuration() + // The allowed session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() == 0)
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time extended.");
ses.setExtensions((short)(ses.getExtensions() - 1));
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout. *
******************************************************************/
else if ((System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back up session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
| public void run()
{
org.hibernate.Session db = null;
try
{
db = DataAccessActivator.getNewSession();
boolean kicked = false;
if (db == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = perm.getSessionDuration() + // The allowed session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() == 0)
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time extended.");
ses.setExtensions((short)(ses.getExtensions() - 1));
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout. *
******************************************************************/
else if ((System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
|
diff --git a/src/main/java/org/lds/md/c2/Load.java b/src/main/java/org/lds/md/c2/Load.java
index a05937d..d0e60ed 100644
--- a/src/main/java/org/lds/md/c2/Load.java
+++ b/src/main/java/org/lds/md/c2/Load.java
@@ -1,66 +1,69 @@
package org.lds.md.c2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.commons.httpclient.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
@Component("Load")
public class Load implements BeanRequest, DisposableBean {
private static final Logger log = LoggerFactory.getLogger(Load.class);
KeyValueDatabase database = null;
public void setDatabase(KeyValueDatabase database) {
this.database = database;
}
@Override
public Object get(List<String> parms) {
Helper.fixParms(parms);
if (parms.size() >= 2) {
String table = parms.get(0);
String file = parms.get(1);
if (file.contains("lds")) {
try {
+ log.trace("Getting data from lds.org");
BufferedReader page = KeyValueDatabase.GetLDSPage("nathandegraw", parms.get(2));
+ log.trace("Loading data from lds.org");
KeyValueDatabase.loadMemberData(database, "new_members",
page);
+ log.trace("Finished with data from lds.org");
} catch (HttpException e) {
// TODO Auto-generated catch block
log.error("HttpException", e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
log.error("UnsupportedEncodingException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("IOException", e);
}
} else {
KeyValueDatabase.loadMemberDataFile(database, table, "/var/lib/openshift/513d28c14382ec80940000ac/app-root/data/" +
file);
}
}
return "Data";
}
@Override
public void doWork() {
log.trace("do work");
}
@Override
public void destroy() throws Exception {
database.closeDatabase();
}
}
| false | true | public Object get(List<String> parms) {
Helper.fixParms(parms);
if (parms.size() >= 2) {
String table = parms.get(0);
String file = parms.get(1);
if (file.contains("lds")) {
try {
BufferedReader page = KeyValueDatabase.GetLDSPage("nathandegraw", parms.get(2));
KeyValueDatabase.loadMemberData(database, "new_members",
page);
} catch (HttpException e) {
// TODO Auto-generated catch block
log.error("HttpException", e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
log.error("UnsupportedEncodingException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("IOException", e);
}
} else {
KeyValueDatabase.loadMemberDataFile(database, table, "/var/lib/openshift/513d28c14382ec80940000ac/app-root/data/" +
file);
}
}
return "Data";
}
| public Object get(List<String> parms) {
Helper.fixParms(parms);
if (parms.size() >= 2) {
String table = parms.get(0);
String file = parms.get(1);
if (file.contains("lds")) {
try {
log.trace("Getting data from lds.org");
BufferedReader page = KeyValueDatabase.GetLDSPage("nathandegraw", parms.get(2));
log.trace("Loading data from lds.org");
KeyValueDatabase.loadMemberData(database, "new_members",
page);
log.trace("Finished with data from lds.org");
} catch (HttpException e) {
// TODO Auto-generated catch block
log.error("HttpException", e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
log.error("UnsupportedEncodingException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("IOException", e);
}
} else {
KeyValueDatabase.loadMemberDataFile(database, table, "/var/lib/openshift/513d28c14382ec80940000ac/app-root/data/" +
file);
}
}
return "Data";
}
|
diff --git a/test/src/main/java/org/jvnet/hudson/test/WarExploder.java b/test/src/main/java/org/jvnet/hudson/test/WarExploder.java
index be91c2ed0..e4157b63e 100644
--- a/test/src/main/java/org/jvnet/hudson/test/WarExploder.java
+++ b/test/src/main/java/org/jvnet/hudson/test/WarExploder.java
@@ -1,82 +1,82 @@
package org.jvnet.hudson.test;
import hudson.remoting.Which;
import hudson.FilePath;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
/**
* Ensures that <tt>hudson.war</tt> is exploded.
*
* @author Kohsuke Kawaguchi
*/
final class WarExploder {
public static File getExplodedDir() throws Exception {
// rethrow an exception every time someone tries to do this, so that when explode()
// fails, you can see the cause no matter which test case you look at.
// see http://www.nabble.com/Failing-tests-in-test-harness-module-on-hudson.ramfelt.se-td19258722.html
if(FAILURE !=null) throw new Exception("Failed to initialize exploded war", FAILURE);
return EXPLODE_DIR;
}
private static File EXPLODE_DIR;
private static Exception FAILURE;
static {
try {
EXPLODE_DIR = explode();
} catch (Exception e) {
FAILURE = e;
}
}
/**
* Explodes hudson.war, if necesasry, and returns its root dir.
*/
private static File explode() throws Exception {
// are we in the hudson main workspace? If so, pick up hudson/main/war/resources
// this saves the effort of packaging a war file and makes the debug cycle faster
File d = new File(".").getAbsoluteFile();
for( ; d!=null; d=d.getParentFile()) {
if(!d.getName().equals("main")) continue;
File p = d.getParentFile();
if(p!=null && p.getName().equals("hudson"))
break;
}
if(d!=null) {
File dir = new File(d,"war/target/hudson");
if(dir.exists()) {
System.out.println("Using hudson.war resources from "+dir);
return dir;
}
}
// locate hudson.war
URL winstone = WarExploder.class.getResource("/winstone.jar");
if(winstone==null)
// impossible, since the test harness pulls in hudson.war
throw new AssertionError("hudson.war is not in the classpath.");
File war = Which.jarFile(Class.forName("executable.Executable"));
File explodeDir = new File("./target/hudson-for-test");
File timestamp = new File(explodeDir,".timestamp");
if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) {
System.out.println("Exploding hudson.war at "+war);
new FilePath(explodeDir).deleteRecursive();
new FilePath(war).unzip(new FilePath(explodeDir));
- if(!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605
- throw new IOException("Failed to explode "+war);
+ // Recreating the File Object seems to be necessary to fix HUDSON-2605
+ timestamp = timestamp.getCanonicalFile();
new FileOutputStream(timestamp).close();
timestamp.setLastModified(war.lastModified());
} else {
System.out.println("Picking up existing exploded hudson.war at "+explodeDir.getAbsolutePath());
}
return explodeDir;
}
}
| true | true | private static File explode() throws Exception {
// are we in the hudson main workspace? If so, pick up hudson/main/war/resources
// this saves the effort of packaging a war file and makes the debug cycle faster
File d = new File(".").getAbsoluteFile();
for( ; d!=null; d=d.getParentFile()) {
if(!d.getName().equals("main")) continue;
File p = d.getParentFile();
if(p!=null && p.getName().equals("hudson"))
break;
}
if(d!=null) {
File dir = new File(d,"war/target/hudson");
if(dir.exists()) {
System.out.println("Using hudson.war resources from "+dir);
return dir;
}
}
// locate hudson.war
URL winstone = WarExploder.class.getResource("/winstone.jar");
if(winstone==null)
// impossible, since the test harness pulls in hudson.war
throw new AssertionError("hudson.war is not in the classpath.");
File war = Which.jarFile(Class.forName("executable.Executable"));
File explodeDir = new File("./target/hudson-for-test");
File timestamp = new File(explodeDir,".timestamp");
if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) {
System.out.println("Exploding hudson.war at "+war);
new FilePath(explodeDir).deleteRecursive();
new FilePath(war).unzip(new FilePath(explodeDir));
if(!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605
throw new IOException("Failed to explode "+war);
new FileOutputStream(timestamp).close();
timestamp.setLastModified(war.lastModified());
} else {
System.out.println("Picking up existing exploded hudson.war at "+explodeDir.getAbsolutePath());
}
return explodeDir;
}
| private static File explode() throws Exception {
// are we in the hudson main workspace? If so, pick up hudson/main/war/resources
// this saves the effort of packaging a war file and makes the debug cycle faster
File d = new File(".").getAbsoluteFile();
for( ; d!=null; d=d.getParentFile()) {
if(!d.getName().equals("main")) continue;
File p = d.getParentFile();
if(p!=null && p.getName().equals("hudson"))
break;
}
if(d!=null) {
File dir = new File(d,"war/target/hudson");
if(dir.exists()) {
System.out.println("Using hudson.war resources from "+dir);
return dir;
}
}
// locate hudson.war
URL winstone = WarExploder.class.getResource("/winstone.jar");
if(winstone==null)
// impossible, since the test harness pulls in hudson.war
throw new AssertionError("hudson.war is not in the classpath.");
File war = Which.jarFile(Class.forName("executable.Executable"));
File explodeDir = new File("./target/hudson-for-test");
File timestamp = new File(explodeDir,".timestamp");
if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) {
System.out.println("Exploding hudson.war at "+war);
new FilePath(explodeDir).deleteRecursive();
new FilePath(war).unzip(new FilePath(explodeDir));
// Recreating the File Object seems to be necessary to fix HUDSON-2605
timestamp = timestamp.getCanonicalFile();
new FileOutputStream(timestamp).close();
timestamp.setLastModified(war.lastModified());
} else {
System.out.println("Picking up existing exploded hudson.war at "+explodeDir.getAbsolutePath());
}
return explodeDir;
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
index c5a57ecf0..f6d572cc6 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
@@ -1,295 +1,299 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* 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.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletResponse;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
*
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final String ARGUMENT_TO = "to";
private static final int BUFFER_SIZE = 8192;
public RenderDynamicMethod() {
super(METHOD_PATTERN);
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
- out.flush();
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
+ try {
+ out.flush();
+ } catch (IOException e) {
+ throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
+ }
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
}
| false | true | public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
out.flush();
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
| public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
try {
out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
diff --git a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/GenomeBrowser.java b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/GenomeBrowser.java
index 18acb3ed6..a56300ba4 100644
--- a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/GenomeBrowser.java
+++ b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/GenomeBrowser.java
@@ -1,1132 +1,1132 @@
package fi.csc.microarray.client.visualisation.methods.gbrowser;
import java.awt.CardLayout;
import java.awt.Cursor;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import fi.csc.chipster.tools.gbrowser.SamBamUtils;
import fi.csc.chipster.tools.gbrowser.regions.RegionOperations;
import fi.csc.microarray.client.ClientApplication;
import fi.csc.microarray.client.Session;
import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility;
import fi.csc.microarray.client.dialog.DialogInfo.Severity;
import fi.csc.microarray.client.visualisation.NonScalableChartPanel;
import fi.csc.microarray.client.visualisation.Visualisation;
import fi.csc.microarray.client.visualisation.VisualisationFrame;
import fi.csc.microarray.client.visualisation.methods.gbrowser.GenomePlot.ReadScale;
import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.AreaRequestHandler;
import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.ChunkTreeHandlerThread;
import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.SAMHandlerThread;
import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.TabixHandlerThread;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.BEDParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.CytobandParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ElandParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.GeneParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.HeaderTsvParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.SNPParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.SequenceParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.TranscriptParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.TsvParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AnnotationManager;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.BpCoordRegion;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.Chromosome;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.RegionContent;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AnnotationManager.Genome;
import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AnnotationManager.GenomeAnnotation;
import fi.csc.microarray.client.visualisation.methods.gbrowser.track.SeparatorTrack3D;
import fi.csc.microarray.client.visualisation.methods.gbrowser.track.TrackGroup;
import fi.csc.microarray.constants.VisualConstants;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.exception.MicroarrayException;
import fi.csc.microarray.gbrowser.index.GeneIndexActions;
import fi.csc.microarray.util.IOUtils;
/**
* Chipster style visualisation for genome browser.
*
* @author Petri Klemel�, Aleksi Kallio
*/
public class GenomeBrowser extends Visualisation implements ActionListener,
RegionListener, FocusListener, ComponentListener {
private static final String DEFAULT_ZOOM = "100000";
private static final String DEFAULT_LOCATION = "1000000";
final static String WAITPANEL = "waitpanel";
final static String PLOTPANEL = "plotpanel";
private static class Interpretation {
public TrackType type;
public List<DataBean> summaryDatas = new LinkedList<DataBean>();
public DataBean primaryData;
public DataBean indexData;
public Interpretation(TrackType type, DataBean primaryData) {
this.type = type;
this.primaryData = primaryData;
}
}
private static enum TrackType {
CYTOBANDS(false),
GENES(false),
TRANSCRIPTS(true),
REFERENCE(true),
REGIONS(true),
REGIONS_WITH_HEADER(true),
READS(true),
HIDDEN(false);
private boolean isToggleable;
private TrackType(boolean toggleable) {
this.isToggleable = toggleable;
}
}
private static class Track {
Interpretation interpretation;
JCheckBox checkBox;
String name;
TrackGroup trackGroup = null;
public Track(String name, Interpretation interpretation) {
this.name = name;
this.interpretation = interpretation;
}
public void setTrackGroup(TrackGroup trackGroup) {
this.trackGroup = trackGroup;
}
public TrackGroup getTrackGroup() {
return trackGroup;
}
}
private final ClientApplication application = Session.getSession()
.getApplication();
private List<Interpretation> interpretations;
private List<Track> tracks = new LinkedList<Track>();
private GenomePlot plot;
private JPanel paramPanel;
private JPanel settingsPanel = new JPanel();
private JPanel genomePanel;
private JPanel locationPanel;
private JPanel datasetsPanel;
private JPanel datasetSwitchesPanel;
private JPanel optionsPanel;
private JPanel plotPanel = new JPanel(new CardLayout());
private JButton goButton = new JButton("Go");
private JLabel locationLabel = new JLabel("Location (gene or position)");
private JTextField locationField = new JTextField();
private JLabel zoomLabel = new JLabel("Zoom");
private JTextField zoomField = new JTextField(10);
private JLabel chrLabel = new JLabel("Chromosome");
private JComboBox chrBox = new JComboBox();
private JComboBox genomeBox = new JComboBox();
private Object visibleChromosome;
private AnnotationManager annotationManager;
private JLabel coverageScaleLabel = new JLabel("Coverage scale");
private JComboBox coverageScaleBox = new JComboBox();
private GeneIndexActions gia;
private boolean initialised;
private Map<JCheckBox, String> trackSwitches = new LinkedHashMap<JCheckBox, String>();
private Set<JCheckBox> datasetSwitches = new HashSet<JCheckBox>();
private Long lastLocation;
private Long lastZoom;
public void initialise(VisualisationFrame frame) throws Exception {
super.initialise(frame);
// initialize annotations
this.annotationManager = new AnnotationManager();
this.annotationManager.initialize();
trackSwitches.put(new JCheckBox("Reads", true), "Reads");
trackSwitches.put(new JCheckBox("Highlight SNPs", false), "highlightSNP");
trackSwitches.put(new JCheckBox("Coverage and SNP's", true), "ProfileSNPTrack");
trackSwitches.put(new JCheckBox("Strand-specific coverage", false), "ProfileTrack");
trackSwitches.put(new JCheckBox("Quality coverage", false), "QualityCoverageTrack");
trackSwitches.put(new JCheckBox("Density graph", false), "GelTrack");
// trackSwitches.put(new JCheckBox("Show common SNP's", false), "changeSNP"); // TODO re-enable dbSNP view
}
@Override
public JPanel getParameterPanel() {
if (paramPanel == null) {
paramPanel = new JPanel();
paramPanel.setLayout(new GridBagLayout());
paramPanel.setPreferredSize(Visualisation.PARAMETER_SIZE);
JPanel settings = this.createSettingsPanel();
JTabbedPane tabPane = new JTabbedPane();
tabPane.addTab("Settings", settings);
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.weightx = 1.0;
c.insets.set(5, 0, 0, 0);
paramPanel.add(tabPane, c);
}
return paramPanel;
}
private void createAvailableTracks() {
// for now just always add genes and cytobands
tracks.add(new Track(AnnotationManager.AnnotationType.GENES.getId(), new Interpretation(TrackType.GENES, null)));
tracks.add(new Track(AnnotationManager.AnnotationType.CYTOBANDS.getId(), new Interpretation(TrackType.CYTOBANDS, null)));
for (int i = 0; i < interpretations.size(); i++) {
Interpretation interpretation = interpretations.get(i);
DataBean data = interpretation.primaryData;
tracks.add(new Track(data.getName(), interpretation));
}
// update the dataset switches in the settings panel
updateDatasetSwitches();
}
private JPanel getDatasetsPanel() {
if (this.datasetsPanel == null) {
datasetsPanel = new JPanel(new GridBagLayout());
datasetsPanel.setBorder(VisualConstants.createSettingsPanelSubPanelBorder("Datasets"));
GridBagConstraints dc = new GridBagConstraints();
dc.gridy = 0;
dc.gridx = 0;
dc.anchor = GridBagConstraints.NORTHWEST;
dc.fill = GridBagConstraints.BOTH;
dc.weighty = 1.0;
dc.weightx = 1.0;
datasetSwitchesPanel = new JPanel();
datasetSwitchesPanel.setLayout(new BoxLayout(datasetSwitchesPanel, BoxLayout.Y_AXIS));
JScrollPane scrollPane = new JScrollPane(datasetSwitchesPanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
datasetsPanel.add(scrollPane, dc);
}
return datasetsPanel;
}
private void updateDatasetSwitches() {
datasetSwitches.clear();
datasetSwitchesPanel.removeAll();
for (Track track : tracks) {
JCheckBox box = new JCheckBox(track.name, true);
box.setToolTipText(track.name);
box.setEnabled(false);
track.checkBox = box;
if (track.interpretation.type.isToggleable) {
datasetSwitchesPanel.add(box);
datasetSwitches.add(box);
box.addActionListener(this);
}
}
}
public JPanel getOptionsPanel() {
if (this.optionsPanel == null) {
optionsPanel = new JPanel(new GridBagLayout());
optionsPanel.setBorder(VisualConstants.createSettingsPanelSubPanelBorder("Options"));
GridBagConstraints oc = new GridBagConstraints();
oc.gridy = 0;
oc.gridx = 0;
oc.anchor = GridBagConstraints.PAGE_START;
oc.fill = GridBagConstraints.BOTH;
oc.weighty = 1.0;
oc.weightx = 1.0;
JPanel menu = new JPanel(new GridBagLayout());
menu.setBorder(BorderFactory.createEmptyBorder());
JScrollPane menuScrollPane = new JScrollPane(menu);
menuScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
menuScrollPane.setBorder(BorderFactory.createEmptyBorder());
GridBagConstraints c = new GridBagConstraints();
c.weighty = 0.0;
c.weightx = 1.0;
c.anchor = GridBagConstraints.PAGE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
setTrackSwitchesEnabled(false);
for (JCheckBox trackSwitch : trackSwitches.keySet()) {
trackSwitch.addActionListener(this);
menu.add(trackSwitch, c);
c.gridy++;
}
// coverage scale
coverageScaleLabel.setEnabled(false);
c.insets.set(10,0,0,0);
menu.add(coverageScaleLabel, c);
c.gridy++;
c.insets.set(0,0,0,0);
coverageScaleBox = new JComboBox(GenomePlot.ReadScale.values());
coverageScaleBox.setEnabled(false);
coverageScaleBox.addActionListener(this);
menu.add(coverageScaleBox, c);
optionsPanel.add(menu, oc);
}
return optionsPanel;
}
public JPanel createSettingsPanel() {
settingsPanel.setLayout(new GridBagLayout());
settingsPanel.setPreferredSize(Visualisation.PARAMETER_SIZE);
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.gridx = 0;
c.insets.set(0, 5, 15, 5);
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.weightx = 1.0;
// genome
settingsPanel.add(getGenomePanel(), c);
c.gridy++;
// location
settingsPanel.add(getLocationPanel(), c);
c.gridy++;
c.fill = GridBagConstraints.BOTH;
// options
// c.weighty = 1.0;
settingsPanel.add(getOptionsPanel(), c);
c.gridy++;
// datasets
c.weighty = 0.5;
c.insets.set(0, 5, 5, 5);
settingsPanel.add(getDatasetsPanel(), c);
return settingsPanel;
}
private JPanel getGenomePanel() {
if (this.genomePanel == null) {
this.genomePanel = new JPanel(new GridBagLayout());
genomePanel.setBorder(VisualConstants.createSettingsPanelSubPanelBorder("Genome"));
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.gridx = 0;
c.insets.set(5, 0, 5, 0);
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.weightx = 1.0;
c.gridx = 0;
// genome
Collection<Genome> genomes = annotationManager.getGenomes();
for (Genome genome : genomes) {
genomeBox.addItem(genome);
}
// no selection at startup
genomeBox.setSelectedItem(null);
genomeBox.addActionListener(this);
genomePanel.add(genomeBox, c);
}
return genomePanel;
}
private JPanel getLocationPanel() {
if (this.locationPanel == null) {
locationPanel = new JPanel(new GridBagLayout());
locationPanel.setBorder(VisualConstants.createSettingsPanelSubPanelBorder("Location"));
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.weightx = 1.0;
// chromosome
chrLabel.setEnabled(false);
locationPanel.add(chrLabel, c);
c.gridy++;
chrBox.setEnabled(false);
c.insets.set(0, 0, 10, 0);
locationPanel.add(chrBox, c);
// location
c.gridy++;
c.insets.set(0, 0, 0, 0);
locationLabel.setEnabled(false);
locationPanel.add(locationLabel, c);
locationField.setEnabled(false);
locationField.addActionListener(this);
c.gridy++;
c.insets.set(0, 0, 10, 0);
locationPanel.add(locationField, c);
// zoom
c.gridx = 0;
c.gridwidth = 5;
c.gridy++;
c.insets.set(0, 0, 0, 0);
zoomLabel.setEnabled(false);
locationPanel.add(zoomLabel, c);
c.gridwidth = 4;
c.gridy++;
c.insets.set(0, 0, 10, 0);
zoomField.setEnabled(false);
locationPanel.add(this.zoomField, c);
this.zoomField.addActionListener(this);
// go button
c.gridy++;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
goButton.setEnabled(false);
goButton.addActionListener(this);
locationPanel.add(goButton, c);
}
return locationPanel;
}
private void fillChromosomeBox() throws IOException {
// Gather all chromosome names from all indexed datasets (SAM/BAM)
TreeSet<String> chromosomeNames = new TreeSet<String>();
for (Interpretation interpretation : interpretations) {
if (interpretation.type == TrackType.READS) {
DataBean data = interpretation.primaryData;
InputStream in = null;
try {
in = data.getContentByteStream();
chromosomeNames.addAll(SamBamUtils.readChromosomeNames(in));
} finally {
IOUtils.closeIfPossible(in);
}
}
}
// If we still don't have names, go through non-indexed datasets
if (chromosomeNames.isEmpty()) {
for (Interpretation interpretation : interpretations) {
if (interpretation.type == TrackType.REGIONS) {
DataBean data = interpretation.primaryData;
File file = Session.getSession().getDataManager().getLocalFile(data);
List<RegionContent> rows = new RegionOperations().loadFile(file);
for (RegionContent row : rows) {
chromosomeNames.add(row.region.start.chr.toNormalisedString());
}
}
}
}
// Sort them
LinkedList<Chromosome> chromosomes = new LinkedList<Chromosome>();
for (String chromosomeName : chromosomeNames) {
chromosomes.add(new Chromosome(chromosomeName));
}
Collections.sort(chromosomes);
// Fill in the box
for (Chromosome chromosome : chromosomes) {
chrBox.addItem(chromosome);
}
}
protected JComponent getColorLabel() {
return new JLabel("Color: ");
}
public void updateVisibilityForTracks() {
for (Track track : tracks) {
if (track.trackGroup != null) {
for (JCheckBox trackSwitch : trackSwitches.keySet()) {
track.trackGroup.showOrHide(trackSwitches.get(trackSwitch), trackSwitch.isSelected());
}
}
}
}
/**
* A method defined by the ActionListener interface. Allows this panel to
* listen to actions on its components.
*/
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == goButton || source == locationField || source == zoomField) {
// disable changing of the genome
this.genomeBox.setEnabled(false);
if (!initialised) {
application.runBlockingTask("initialising genome browser", new Runnable() {
@Override
public void run() {
try {
// Preload datas in background thread
initialiseUserDatas();
// Update UI in Event Dispatch Thread
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// Show visualisation
showVisualisation();
// Set track visibility
updateVisibilityForTracks();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
} else {
// Move to correct location
updateLocation();
}
} else if ((datasetSwitches.contains(source) || source == coverageScaleBox) && this.initialised) {
showVisualisation();
updateVisibilityForTracks();
} else if (trackSwitches.keySet().contains(source) && this.initialised) {
updateVisibilityForTracks();
}
// genome selected
else if (source == genomeBox) {
Genome genome = (Genome) genomeBox.getSelectedItem();
// dialog for downloading annotations if not already local
if (!annotationManager.hasLocalAnnotations(genome)) {
annotationManager.openDownloadAnnotationsDialog(genome);
}
// enable other settings
this.goButton.setEnabled(true);
this.chrLabel.setEnabled(true);
this.chrBox.setEnabled(true);
this.locationLabel.setEnabled(true);
this.locationField.setEnabled(true);
this.zoomLabel.setEnabled(true);
this.zoomField.setEnabled(true);
for (Track track : tracks) {
track.checkBox.setEnabled(true);
}
coverageScaleLabel.setEnabled(true);
coverageScaleBox.setEnabled(true);
this.setTrackSwitchesEnabled(true);
}
}
private void setTrackSwitchesEnabled(boolean enabled) {
for (JCheckBox trackSwitch : trackSwitches.keySet()) {
trackSwitch.setEnabled(enabled);
}
}
@Override
public JComponent getVisualisation(DataBean data) throws Exception {
return getVisualisation(Arrays.asList(new DataBean[] { data }));
}
@Override
public JComponent getVisualisation(java.util.List<DataBean> datas) throws Exception {
this.interpretations = interpretUserDatas(datas);
// List available chromosomes from user data files
fillChromosomeBox();
// We can create tracks now that we know the data
this.tracks.clear();
createAvailableTracks();
// Create panel with card layout and put message panel there
JPanel waitPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
waitPanel.add(new JLabel("<html><p style=\"font-size: larger\">Please select genome and click " + goButton.getText() + "</p></html>"), c);
plotPanel.add(waitPanel, WAITPANEL);
return plotPanel;
}
private void showVisualisation() {
// Create tracks only once
initialised = true;
try {
Genome genome = (Genome) genomeBox.getSelectedItem();
// Create gene name index
gia = null;
try {
gia = GeneIndexActions.getInstance(genome, createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.GENES).getUrl(), new GeneParser()));
} catch (Exception e) {
application.reportException(e);
}
// Create the plot
ChartPanel chartPanel = new NonScalableChartPanel();
this.plot = new GenomePlot(chartPanel, true);
// Set scale of profile track containing reads information
this.plot.setReadScale((ReadScale) this.coverageScaleBox.getSelectedItem());
// Add selected annotation tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
switch (track.interpretation.type) {
case CYTOBANDS:
TrackFactory.addCytobandTracks(plot,
createAnnotationDataSource(
annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.CYTOBANDS).getUrl(),
new CytobandParser()));
break;
case GENES:
// Start 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, true));
GenomeAnnotation snpRow = annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.SNP);
TrackGroup geneGroup = TrackFactory.addGeneTracks(plot,
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.GENES).getUrl(),
new GeneParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.TRANSCRIPTS).getUrl(),
new TranscriptParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(),
new SequenceParser()),
snpRow == null ? null :
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.SNP).getUrl(),
new SNPParser())
);
track.setTrackGroup(geneGroup);
break;
case REFERENCE:
// integrated into peaks
break;
case TRANSCRIPTS:
// integrated into genes
break;
}
}
}
// Add selected read tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource treatmentData;
switch (track.interpretation.type) {
case READS:
if (track.interpretation.summaryDatas.size() == 0) {
// No precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroup = TrackFactory.addReadTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName());
track.setTrackGroup(readGroup);
} else {
// Has precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroupWithSummary = TrackFactory.addReadSummaryTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName(), new TabixDataSource(file));
track.setTrackGroup(readGroupWithSummary);
}
break;
}
}
}
// Add selected peak tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource peakData;
switch (track.interpretation.type) {
case REGIONS:
TrackFactory.addThickSeparatorTrack(plot);
- TrackFactory.addTitleTrack(plot, file.getName());
+ TrackFactory.addTitleTrack(plot, track.interpretation.primaryData.getName());
peakData = new ChunkDataSource(file, new BEDParser());
TrackFactory.addPeakTrack(plot, peakData);
break;
case REGIONS_WITH_HEADER:
TrackFactory.addThickSeparatorTrack(plot);
- TrackFactory.addTitleTrack(plot, file.getName());
+ TrackFactory.addTitleTrack(plot, track.interpretation.primaryData.getName());
peakData = new ChunkDataSource(file, new HeaderTsvParser());
TrackFactory.addHeaderPeakTrack(plot, peakData);
break;
}
}
}
// End 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, false));
// Fill in initial positions if not filled in
if (locationField.getText().trim().isEmpty()) {
locationField.setText(DEFAULT_LOCATION);
}
if (zoomField.getText().trim().isEmpty()) {
zoomField.setText(DEFAULT_ZOOM);
}
// Initialise the plot
plot.addDataRegionListener(this);
// Translate gene name in position box, if needed
translateGenename();
// Move to correct location
move();
// Remember chromosome
visibleChromosome = chrBox.getSelectedItem();
// wrap it in a panel
chartPanel.setChart(new JFreeChart(plot));
chartPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
// add mouse listeners
for (View view : plot.getViews()) {
chartPanel.addMouseListener(view);
chartPanel.addMouseMotionListener(view);
chartPanel.addMouseWheelListener(view);
}
// put panel on top of card layout
if (plotPanel.getComponentCount() == 2) {
plotPanel.remove(1);
}
plotPanel.add(chartPanel, PLOTPANEL);
plotPanel.addComponentListener(this);
CardLayout cl = (CardLayout) (plotPanel.getLayout());
cl.show(plotPanel, PLOTPANEL);
} catch (Exception e) {
application.reportException(e);
}
}
private void initialiseUserDatas() throws IOException {
for (Interpretation interpretation : interpretations) {
initialiseUserData(interpretation.primaryData);
initialiseUserData(interpretation.indexData);
for (DataBean summaryData : interpretation.summaryDatas) {
initialiseUserData(summaryData);
}
}
}
private void initialiseUserData(DataBean data) throws IOException {
if (data != null) {
Session.getSession().getDataManager().getLocalFile(data);
}
}
/**
* Create DataSource either for SAM/BAM or ELAND data files.
*
* @param tracks
*
* @param file
* @return
* @throws MicroarrayException
* if index file is not selected properly
* @throws IOException
* if opening data files fails
*/
public DataSource createReadDataSource(DataBean data, DataBean indexData, List<Track> tracks)
throws MicroarrayException, IOException {
DataSource dataSource = null;
// Convert data bean into file
File file = data == null ? null : Session.getSession().getDataManager().getLocalFile(data);
if (file.getName().contains(".bam-summary")) {
dataSource = new TabixDataSource(file);
} else if (file.getName().contains(".bam") || file.getName().contains(".sam")) {
File indexFile = Session.getSession().getDataManager().getLocalFile(indexData);
dataSource = new SAMDataSource(file, indexFile);
} else {
dataSource = new ChunkDataSource(file, new ElandParser());
}
return dataSource;
}
private boolean isIndexData(DataBean bean) {
return bean.getName().endsWith(".bai");
}
/**
* Create AreaRequestHandler either for SAM/BAM or ELAND data files.
*
* @param file
* @return
*/
public Class<?extends AreaRequestHandler> createReadHandler(File file) {
if (file.getName().contains(".bam-summary")) {
return TabixHandlerThread.class;
}
if (file.getName().contains(".bam") || file.getName().contains(".sam")) {
return SAMHandlerThread.class;
}
return ChunkTreeHandlerThread.class;
}
private ChunkDataSource createAnnotationDataSource(URL url,
TsvParser fileParser) throws FileNotFoundException, URISyntaxException {
if ("file".equals(url.getProtocol())) {
return new ChunkDataSource(new File(url.toURI()), fileParser);
} else {
return new ChunkDataSource(url, fileParser);
}
}
@Override
public boolean canVisualise(DataBean data) throws MicroarrayException {
return canVisualise(Arrays.asList(new DataBean[] { data }));
}
@Override
public boolean canVisualise(java.util.List<DataBean> datas) throws MicroarrayException {
return interpretUserDatas(datas) != null;
}
public class ObjVariable extends Variable {
public Object obj;
public ObjVariable(Object obj) {
super(null, null);
this.obj = obj;
}
}
public void regionChanged(BpCoordRegion bpRegion) {
locationField.setText(bpRegion.getMid().toString());
zoomField.setText("" + bpRegion.getLength());
this.lastLocation = bpRegion.getMid();
this.lastZoom = bpRegion.getLength();
}
private List<Interpretation> interpretUserDatas(List<DataBean> datas) {
LinkedList<Interpretation> interpretations = new LinkedList<Interpretation>();
// Find interpretations for all primary data types
for (DataBean data : datas) {
if (data.isContentTypeCompatitible("text/plain")) {
// ELAND result / export
interpretations.add(new Interpretation(TrackType.READS, data));
} else if (data.isContentTypeCompatitible("text/bed")) {
// BED (ChIP-seq peaks)
interpretations.add(new Interpretation(TrackType.REGIONS, data));
} else if (data.isContentTypeCompatitible("text/tab")) {
// peaks (with header in the file)
interpretations.add(new Interpretation(TrackType.REGIONS_WITH_HEADER, data));
} else if ((data.isContentTypeCompatitible("application/octet-stream")) &&
(data.getName().endsWith(".bam"))) {
// BAM file
interpretations.add(new Interpretation(TrackType.READS, data));
}
}
// Find interpretations for all secondary data types
for (DataBean data : datas) {
// Find the interpretation to add this secondary data to
Interpretation primaryInterpretation = null;
for (Interpretation interpretation : interpretations) {
if (data.getName().startsWith(interpretation.primaryData.getName())) {
primaryInterpretation = interpretation;
break;
}
}
if (primaryInterpretation == null) {
return null; // could not bound this secondary data to any primary data
}
if ((data.isContentTypeCompatitible("application/octet-stream")) &&
(data.getName().contains(".bam-summary"))) {
// BAM summary file (from custom preprocessor)
primaryInterpretation.summaryDatas.add(data);
} else if ((data.isContentTypeCompatitible("application/octet-stream")) &&
(isIndexData(data))) {
// BAI file
if (primaryInterpretation.indexData != null) {
return null; // already taken, could not bind this secondary data to any primary data
}
primaryInterpretation.indexData = data;
}
}
// Check that interpretations are now fully initialised
for (Interpretation interpretation : interpretations) {
if (interpretation.primaryData.getName().endsWith(".bam") && interpretation.indexData == null) {
return null; // BAM is missing BAI
}
}
return interpretations;
}
@Override
public boolean isForSingleData() {
return true;
}
@Override
public boolean isForMultipleDatas() {
return true;
}
/**
* Update genome browser to location given in the location panel.
*
* If chromosome changes, reinitialize everything (because some old
* information is left inside the tracks). Otherwise, simply move currently
* viewed bp region.
*
* TODO Instead of showVisualisation, clean track contents. This is nicer
* because we don't have to reinitialize the tracks and track group options
* are saved.
*/
private void updateLocation() {
try {
// If gene name was given, search for it and
// translate it to coordinates.
translateGenename();
// Check how large the update in location was
if (visibleChromosome != null && visibleChromosome != chrBox.getSelectedItem()) {
// Chromosome changed, redraw everything
showVisualisation();
updateVisibilityForTracks();
} else {
// Only bp position within chromosome changed, move there
move();
}
} catch (Exception e) {
application.reportException(e);
}
}
private void translateGenename() throws SQLException {
if (!GeneIndexActions.checkIfNumber(locationField.getText())) {
BpCoordRegion geneLocation = gia.getLocation(locationField.getText().toUpperCase());
if (geneLocation == null) {
// Move to last known location
if (lastLocation != null && lastZoom != null) {
locationField.setText(lastLocation.toString());
zoomField.setText(lastZoom.toString());
} else {
locationField.setText(DEFAULT_LOCATION);
zoomField.setText(DEFAULT_ZOOM);
}
// Tell the user
application.showDialog("Not found",
"Gene was not found", null,
Severity.INFO, true,
DetailsVisibility.DETAILS_ALWAYS_HIDDEN, null);
} else {
// Update coordinate controls with gene's location
chrBox.setSelectedItem(new Chromosome(geneLocation.start.chr));
locationField.setText(Long.toString((geneLocation.end.bp + geneLocation.start.bp) / 2));
zoomField.setText(Long.toString((geneLocation.end.bp - geneLocation.start.bp) * 2));
}
}
}
private void move() {
plot.moveDataBpRegion((Chromosome) chrBox.getSelectedItem(),
Long.parseLong(locationField.getText()), Long
.parseLong(zoomField.getText()));
// Set scale of profile track containing reads information
this.plot.setReadScale((ReadScale) this.coverageScaleBox.getSelectedItem());
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
// skip
}
public void componentHidden(ComponentEvent arg0) {
// skip
}
public void componentMoved(ComponentEvent arg0) {
// skip
}
public void componentResized(ComponentEvent arg0) {
// showVisualisation();
// updateVisibilityForTracks();
this.updateLocation();
plot.redraw();
}
public void componentShown(ComponentEvent arg0) {
// skip
}
public ClientApplication getClientApplication() {
return application;
}
}
| false | true | private void showVisualisation() {
// Create tracks only once
initialised = true;
try {
Genome genome = (Genome) genomeBox.getSelectedItem();
// Create gene name index
gia = null;
try {
gia = GeneIndexActions.getInstance(genome, createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.GENES).getUrl(), new GeneParser()));
} catch (Exception e) {
application.reportException(e);
}
// Create the plot
ChartPanel chartPanel = new NonScalableChartPanel();
this.plot = new GenomePlot(chartPanel, true);
// Set scale of profile track containing reads information
this.plot.setReadScale((ReadScale) this.coverageScaleBox.getSelectedItem());
// Add selected annotation tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
switch (track.interpretation.type) {
case CYTOBANDS:
TrackFactory.addCytobandTracks(plot,
createAnnotationDataSource(
annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.CYTOBANDS).getUrl(),
new CytobandParser()));
break;
case GENES:
// Start 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, true));
GenomeAnnotation snpRow = annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.SNP);
TrackGroup geneGroup = TrackFactory.addGeneTracks(plot,
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.GENES).getUrl(),
new GeneParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.TRANSCRIPTS).getUrl(),
new TranscriptParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(),
new SequenceParser()),
snpRow == null ? null :
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.SNP).getUrl(),
new SNPParser())
);
track.setTrackGroup(geneGroup);
break;
case REFERENCE:
// integrated into peaks
break;
case TRANSCRIPTS:
// integrated into genes
break;
}
}
}
// Add selected read tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource treatmentData;
switch (track.interpretation.type) {
case READS:
if (track.interpretation.summaryDatas.size() == 0) {
// No precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroup = TrackFactory.addReadTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName());
track.setTrackGroup(readGroup);
} else {
// Has precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroupWithSummary = TrackFactory.addReadSummaryTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName(), new TabixDataSource(file));
track.setTrackGroup(readGroupWithSummary);
}
break;
}
}
}
// Add selected peak tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource peakData;
switch (track.interpretation.type) {
case REGIONS:
TrackFactory.addThickSeparatorTrack(plot);
TrackFactory.addTitleTrack(plot, file.getName());
peakData = new ChunkDataSource(file, new BEDParser());
TrackFactory.addPeakTrack(plot, peakData);
break;
case REGIONS_WITH_HEADER:
TrackFactory.addThickSeparatorTrack(plot);
TrackFactory.addTitleTrack(plot, file.getName());
peakData = new ChunkDataSource(file, new HeaderTsvParser());
TrackFactory.addHeaderPeakTrack(plot, peakData);
break;
}
}
}
// End 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, false));
// Fill in initial positions if not filled in
if (locationField.getText().trim().isEmpty()) {
locationField.setText(DEFAULT_LOCATION);
}
if (zoomField.getText().trim().isEmpty()) {
zoomField.setText(DEFAULT_ZOOM);
}
// Initialise the plot
plot.addDataRegionListener(this);
// Translate gene name in position box, if needed
translateGenename();
// Move to correct location
move();
// Remember chromosome
visibleChromosome = chrBox.getSelectedItem();
// wrap it in a panel
chartPanel.setChart(new JFreeChart(plot));
chartPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
// add mouse listeners
for (View view : plot.getViews()) {
chartPanel.addMouseListener(view);
chartPanel.addMouseMotionListener(view);
chartPanel.addMouseWheelListener(view);
}
// put panel on top of card layout
if (plotPanel.getComponentCount() == 2) {
plotPanel.remove(1);
}
plotPanel.add(chartPanel, PLOTPANEL);
plotPanel.addComponentListener(this);
CardLayout cl = (CardLayout) (plotPanel.getLayout());
cl.show(plotPanel, PLOTPANEL);
} catch (Exception e) {
application.reportException(e);
}
}
| private void showVisualisation() {
// Create tracks only once
initialised = true;
try {
Genome genome = (Genome) genomeBox.getSelectedItem();
// Create gene name index
gia = null;
try {
gia = GeneIndexActions.getInstance(genome, createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.GENES).getUrl(), new GeneParser()));
} catch (Exception e) {
application.reportException(e);
}
// Create the plot
ChartPanel chartPanel = new NonScalableChartPanel();
this.plot = new GenomePlot(chartPanel, true);
// Set scale of profile track containing reads information
this.plot.setReadScale((ReadScale) this.coverageScaleBox.getSelectedItem());
// Add selected annotation tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
switch (track.interpretation.type) {
case CYTOBANDS:
TrackFactory.addCytobandTracks(plot,
createAnnotationDataSource(
annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.CYTOBANDS).getUrl(),
new CytobandParser()));
break;
case GENES:
// Start 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, true));
GenomeAnnotation snpRow = annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.SNP);
TrackGroup geneGroup = TrackFactory.addGeneTracks(plot,
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.GENES).getUrl(),
new GeneParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.TRANSCRIPTS).getUrl(),
new TranscriptParser()),
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(),
new SequenceParser()),
snpRow == null ? null :
createAnnotationDataSource(annotationManager.getAnnotation(
genome, AnnotationManager.AnnotationType.SNP).getUrl(),
new SNPParser())
);
track.setTrackGroup(geneGroup);
break;
case REFERENCE:
// integrated into peaks
break;
case TRANSCRIPTS:
// integrated into genes
break;
}
}
}
// Add selected read tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource treatmentData;
switch (track.interpretation.type) {
case READS:
if (track.interpretation.summaryDatas.size() == 0) {
// No precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroup = TrackFactory.addReadTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName());
track.setTrackGroup(readGroup);
} else {
// Has precomputed summary data
TrackFactory.addThickSeparatorTrack(plot);
treatmentData = createReadDataSource(track.interpretation.primaryData, track.interpretation.indexData, tracks);
TrackGroup readGroupWithSummary = TrackFactory.addReadSummaryTracks(plot, treatmentData, createReadHandler(file), createAnnotationDataSource(annotationManager.getAnnotation(genome, AnnotationManager.AnnotationType.REFERENCE).getUrl(), new SequenceParser()), track.interpretation.primaryData.getName(), new TabixDataSource(file));
track.setTrackGroup(readGroupWithSummary);
}
break;
}
}
}
// Add selected peak tracks
for (Track track : tracks) {
if (track.checkBox.isSelected()) {
File file = track.interpretation.primaryData == null ? null : Session
.getSession().getDataManager().getLocalFile(
track.interpretation.primaryData);
DataSource peakData;
switch (track.interpretation.type) {
case REGIONS:
TrackFactory.addThickSeparatorTrack(plot);
TrackFactory.addTitleTrack(plot, track.interpretation.primaryData.getName());
peakData = new ChunkDataSource(file, new BEDParser());
TrackFactory.addPeakTrack(plot, peakData);
break;
case REGIONS_WITH_HEADER:
TrackFactory.addThickSeparatorTrack(plot);
TrackFactory.addTitleTrack(plot, track.interpretation.primaryData.getName());
peakData = new ChunkDataSource(file, new HeaderTsvParser());
TrackFactory.addHeaderPeakTrack(plot, peakData);
break;
}
}
}
// End 3D effect
plot.getDataView().addTrack(new SeparatorTrack3D(plot.getDataView(), 0, Long.MAX_VALUE, false));
// Fill in initial positions if not filled in
if (locationField.getText().trim().isEmpty()) {
locationField.setText(DEFAULT_LOCATION);
}
if (zoomField.getText().trim().isEmpty()) {
zoomField.setText(DEFAULT_ZOOM);
}
// Initialise the plot
plot.addDataRegionListener(this);
// Translate gene name in position box, if needed
translateGenename();
// Move to correct location
move();
// Remember chromosome
visibleChromosome = chrBox.getSelectedItem();
// wrap it in a panel
chartPanel.setChart(new JFreeChart(plot));
chartPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
// add mouse listeners
for (View view : plot.getViews()) {
chartPanel.addMouseListener(view);
chartPanel.addMouseMotionListener(view);
chartPanel.addMouseWheelListener(view);
}
// put panel on top of card layout
if (plotPanel.getComponentCount() == 2) {
plotPanel.remove(1);
}
plotPanel.add(chartPanel, PLOTPANEL);
plotPanel.addComponentListener(this);
CardLayout cl = (CardLayout) (plotPanel.getLayout());
cl.show(plotPanel, PLOTPANEL);
} catch (Exception e) {
application.reportException(e);
}
}
|
diff --git a/src/ui/composites/ColorComposite.java b/src/ui/composites/ColorComposite.java
index 0469c56..191c813 100644
--- a/src/ui/composites/ColorComposite.java
+++ b/src/ui/composites/ColorComposite.java
@@ -1,270 +1,273 @@
package ui.composites;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import shared.Customs;
import shared.Message;
import shared.RoomManager;
import shared.SWTResourceManager;
import ui.room.Room;
import connection.Connection;
import connection.Settings;
public class ColorComposite extends Composite {
public ColorComposite(Composite parent, int style) {
super(parent, style);
setLayout(null);
final Customs customs = new Customs();
List<Combo> messageColorCombos = new ArrayList<Combo>();
Group grpOutputColor = new Group(this, SWT.NONE);
grpOutputColor.setText("Output Colors");
grpOutputColor.setBounds(10, 10, 186, 206);
Label lblConsole = new Label(grpOutputColor, SWT.NONE);
lblConsole.setText("Console");
lblConsole.setBounds(10, 23, 55, 15);
Combo comboConsole = new Combo(grpOutputColor, SWT.READ_ONLY);
comboConsole.setBounds(80, 23, 91, 23);
comboConsole.setData(Message.CONSOLE);
messageColorCombos.add(comboConsole);
Label lblMessage = new Label(grpOutputColor, SWT.NONE);
lblMessage.setText("Message");
lblMessage.setBounds(10, 52, 55, 15);
Combo comboMessage = new Combo(grpOutputColor, SWT.READ_ONLY);
comboMessage.setBounds(80, 52, 91, 23);
comboMessage.setData(Message.MSG);
messageColorCombos.add(comboMessage);
Label lblNotice = new Label(grpOutputColor, SWT.NONE);
lblNotice.setText("Notice");
lblNotice.setBounds(10, 81, 55, 15);
Combo comboNotice = new Combo(grpOutputColor, SWT.READ_ONLY);
comboNotice.setBounds(80, 81, 91, 23);
comboNotice.setData(Message.NOTICE);
messageColorCombos.add(comboNotice);
Label lblAction = new Label(grpOutputColor, SWT.NONE);
lblAction.setText("Action");
lblAction.setBounds(10, 110, 55, 15);
Combo comboAction = new Combo(grpOutputColor, SWT.READ_ONLY);
comboAction.setBounds(80, 110, 91, 23);
comboAction.setData(Message.ACTION);
messageColorCombos.add(comboAction);
Label lblPm = new Label(grpOutputColor, SWT.NONE);
lblPm.setText("PM");
lblPm.setBounds(10, 139, 55, 15);
Combo comboPM = new Combo(grpOutputColor, SWT.READ_ONLY);
comboPM.setBounds(80, 139, 91, 23);
comboPM.setData(Message.PM);
messageColorCombos.add(comboPM);
Label lblBackground = new Label(grpOutputColor, SWT.NONE);
lblBackground.setText("Background");
lblBackground.setBounds(10, 168, 64, 15);
Combo comboBG = new Combo(grpOutputColor, SWT.READ_ONLY);
comboBG.setBounds(80, 168, 91, 23);
comboBG.setData(Settings.BACKGROUND);
messageColorCombos.add(comboBG);
SelectionListener IRCColorListener = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), combo.getText());
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();
//check if all the rooms have to change foreground/background
if(combo.getData().equals(Message.MSG)||combo.getData().equals(Settings.BACKGROUND))
{
for(CTabItem i:RoomManager.getMain().getContainer().getItems())
{
if(i.getControl() instanceof Connection)
{
for(Room r:((Connection)i.getControl()).getRooms())
{
StyledText output = r.getOutput();
StyledText input = r.getInput();
output.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
output.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
input.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
input.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
}
}
}
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
PaintListener pl = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 4;
String colorStr = Settings.getSettings().getOutputColors().get(e.widget.getData());
e.gc.setBackground(customs.colors.get(colorStr));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
for(Combo c:messageColorCombos)
{
c.add("white");
c.add("black");
c.add("dark blue");
c.add("dark green");
c.add("red");
c.add("brown");
c.add("purple");
c.add("olive");
c.add("yellow");
c.add("green");
c.add("teal");
c.add("cyan");
c.add("blue");
c.add("magenta");
c.add("dark gray");
c.add("light gray");
String colorStr = Settings.getSettings().getOutputColors().get((Short)c.getData());
c.setText(colorStr);
c.addSelectionListener(IRCColorListener);
c.addPaintListener(pl);
}
List<Button> statusColorButtons = new ArrayList<Button>();
Group grpRoomStatusColors = new Group(this, SWT.NONE);
grpRoomStatusColors.setText("Room Status Colors");
grpRoomStatusColors.setBounds(218, 10, 202, 177);
Label lblNormal = new Label(grpRoomStatusColors, SWT.NONE);
lblNormal.setText("Normal");
lblNormal.setBounds(10, 23, 85, 15);
Button btnNormal = new Button(grpRoomStatusColors, SWT.NONE);
btnNormal.setBounds(117, 18, 75, 25);
btnNormal.setData(Room.NORMAL);
statusColorButtons.add(btnNormal);
Label lblNewIrcEvent = new Label(grpRoomStatusColors, SWT.NONE);
lblNewIrcEvent.setText("New IRC Event");
lblNewIrcEvent.setBounds(10, 56, 85, 15);
Button btnIRCEvent = new Button(grpRoomStatusColors, SWT.NONE);
btnIRCEvent.setBounds(117, 51, 75, 25);
btnIRCEvent.setData(Room.NEW_IRC_EVENT);
statusColorButtons.add(btnIRCEvent);
Label lblNewMessage = new Label(grpRoomStatusColors, SWT.NONE);
lblNewMessage.setText("New Message");
lblNewMessage.setBounds(10, 87, 85, 15);
Button btnNewMSG = new Button(grpRoomStatusColors, SWT.NONE);
btnNewMSG.setBounds(117, 82, 75, 25);
btnNewMSG.setData(Room.NEW_MESSAGE);
statusColorButtons.add(btnNewMSG);
Label lblNameCalled = new Label(grpRoomStatusColors, SWT.NONE);
lblNameCalled.setText("Name Called");
lblNameCalled.setBounds(10, 118, 85, 15);
Button btnNameCall = new Button(grpRoomStatusColors, SWT.NONE);
btnNameCall.setBounds(117, 113, 75, 25);
btnNameCall.setData(Room.NAME_CALLED);
statusColorButtons.add(btnNameCall);
PaintListener colorPainter = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 6;
RGB rgb = Settings.getSettings().getRoomStatusColors().get(e.widget.getData());
e.gc.setBackground(SWTResourceManager.getColor(rgb));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
SelectionListener sl = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
/*Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), customs.ircColorsStr.get(combo.getText()));
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();*/
ColorDialog cd = new ColorDialog(RoomManager.getMain().getShell());
RGB rgb = cd.open();
+ if(rgb != null)
+ {
Button btn = (Button)e.widget;
HashMap<Integer,RGB> statusColors = Settings.getSettings().getRoomStatusColors();
statusColors.put((Integer)btn.getData(), rgb);
Settings.getSettings().setRoomStatusColors(statusColors);
Settings.writeToFile();
+ }
}
public void widgetDefaultSelected(SelectionEvent e) {
}
};
for(Button btn:statusColorButtons)
{
btn.addPaintListener(colorPainter);
btn.addSelectionListener(sl);
}
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
//Put in a map and a value, and it will return the key if
//map.get(key).equals(value), else it will return null
private Object reverseLookup(Map<?,?> map, Object value)
{
if(!map.containsValue(value))
return null;
for(Object key:map.keySet())
{
if(map.get(key).equals(value))
return key;
}
return null;
}
}
| false | true | public ColorComposite(Composite parent, int style) {
super(parent, style);
setLayout(null);
final Customs customs = new Customs();
List<Combo> messageColorCombos = new ArrayList<Combo>();
Group grpOutputColor = new Group(this, SWT.NONE);
grpOutputColor.setText("Output Colors");
grpOutputColor.setBounds(10, 10, 186, 206);
Label lblConsole = new Label(grpOutputColor, SWT.NONE);
lblConsole.setText("Console");
lblConsole.setBounds(10, 23, 55, 15);
Combo comboConsole = new Combo(grpOutputColor, SWT.READ_ONLY);
comboConsole.setBounds(80, 23, 91, 23);
comboConsole.setData(Message.CONSOLE);
messageColorCombos.add(comboConsole);
Label lblMessage = new Label(grpOutputColor, SWT.NONE);
lblMessage.setText("Message");
lblMessage.setBounds(10, 52, 55, 15);
Combo comboMessage = new Combo(grpOutputColor, SWT.READ_ONLY);
comboMessage.setBounds(80, 52, 91, 23);
comboMessage.setData(Message.MSG);
messageColorCombos.add(comboMessage);
Label lblNotice = new Label(grpOutputColor, SWT.NONE);
lblNotice.setText("Notice");
lblNotice.setBounds(10, 81, 55, 15);
Combo comboNotice = new Combo(grpOutputColor, SWT.READ_ONLY);
comboNotice.setBounds(80, 81, 91, 23);
comboNotice.setData(Message.NOTICE);
messageColorCombos.add(comboNotice);
Label lblAction = new Label(grpOutputColor, SWT.NONE);
lblAction.setText("Action");
lblAction.setBounds(10, 110, 55, 15);
Combo comboAction = new Combo(grpOutputColor, SWT.READ_ONLY);
comboAction.setBounds(80, 110, 91, 23);
comboAction.setData(Message.ACTION);
messageColorCombos.add(comboAction);
Label lblPm = new Label(grpOutputColor, SWT.NONE);
lblPm.setText("PM");
lblPm.setBounds(10, 139, 55, 15);
Combo comboPM = new Combo(grpOutputColor, SWT.READ_ONLY);
comboPM.setBounds(80, 139, 91, 23);
comboPM.setData(Message.PM);
messageColorCombos.add(comboPM);
Label lblBackground = new Label(grpOutputColor, SWT.NONE);
lblBackground.setText("Background");
lblBackground.setBounds(10, 168, 64, 15);
Combo comboBG = new Combo(grpOutputColor, SWT.READ_ONLY);
comboBG.setBounds(80, 168, 91, 23);
comboBG.setData(Settings.BACKGROUND);
messageColorCombos.add(comboBG);
SelectionListener IRCColorListener = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), combo.getText());
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();
//check if all the rooms have to change foreground/background
if(combo.getData().equals(Message.MSG)||combo.getData().equals(Settings.BACKGROUND))
{
for(CTabItem i:RoomManager.getMain().getContainer().getItems())
{
if(i.getControl() instanceof Connection)
{
for(Room r:((Connection)i.getControl()).getRooms())
{
StyledText output = r.getOutput();
StyledText input = r.getInput();
output.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
output.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
input.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
input.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
}
}
}
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
PaintListener pl = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 4;
String colorStr = Settings.getSettings().getOutputColors().get(e.widget.getData());
e.gc.setBackground(customs.colors.get(colorStr));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
for(Combo c:messageColorCombos)
{
c.add("white");
c.add("black");
c.add("dark blue");
c.add("dark green");
c.add("red");
c.add("brown");
c.add("purple");
c.add("olive");
c.add("yellow");
c.add("green");
c.add("teal");
c.add("cyan");
c.add("blue");
c.add("magenta");
c.add("dark gray");
c.add("light gray");
String colorStr = Settings.getSettings().getOutputColors().get((Short)c.getData());
c.setText(colorStr);
c.addSelectionListener(IRCColorListener);
c.addPaintListener(pl);
}
List<Button> statusColorButtons = new ArrayList<Button>();
Group grpRoomStatusColors = new Group(this, SWT.NONE);
grpRoomStatusColors.setText("Room Status Colors");
grpRoomStatusColors.setBounds(218, 10, 202, 177);
Label lblNormal = new Label(grpRoomStatusColors, SWT.NONE);
lblNormal.setText("Normal");
lblNormal.setBounds(10, 23, 85, 15);
Button btnNormal = new Button(grpRoomStatusColors, SWT.NONE);
btnNormal.setBounds(117, 18, 75, 25);
btnNormal.setData(Room.NORMAL);
statusColorButtons.add(btnNormal);
Label lblNewIrcEvent = new Label(grpRoomStatusColors, SWT.NONE);
lblNewIrcEvent.setText("New IRC Event");
lblNewIrcEvent.setBounds(10, 56, 85, 15);
Button btnIRCEvent = new Button(grpRoomStatusColors, SWT.NONE);
btnIRCEvent.setBounds(117, 51, 75, 25);
btnIRCEvent.setData(Room.NEW_IRC_EVENT);
statusColorButtons.add(btnIRCEvent);
Label lblNewMessage = new Label(grpRoomStatusColors, SWT.NONE);
lblNewMessage.setText("New Message");
lblNewMessage.setBounds(10, 87, 85, 15);
Button btnNewMSG = new Button(grpRoomStatusColors, SWT.NONE);
btnNewMSG.setBounds(117, 82, 75, 25);
btnNewMSG.setData(Room.NEW_MESSAGE);
statusColorButtons.add(btnNewMSG);
Label lblNameCalled = new Label(grpRoomStatusColors, SWT.NONE);
lblNameCalled.setText("Name Called");
lblNameCalled.setBounds(10, 118, 85, 15);
Button btnNameCall = new Button(grpRoomStatusColors, SWT.NONE);
btnNameCall.setBounds(117, 113, 75, 25);
btnNameCall.setData(Room.NAME_CALLED);
statusColorButtons.add(btnNameCall);
PaintListener colorPainter = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 6;
RGB rgb = Settings.getSettings().getRoomStatusColors().get(e.widget.getData());
e.gc.setBackground(SWTResourceManager.getColor(rgb));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
SelectionListener sl = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
/*Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), customs.ircColorsStr.get(combo.getText()));
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();*/
ColorDialog cd = new ColorDialog(RoomManager.getMain().getShell());
RGB rgb = cd.open();
Button btn = (Button)e.widget;
HashMap<Integer,RGB> statusColors = Settings.getSettings().getRoomStatusColors();
statusColors.put((Integer)btn.getData(), rgb);
Settings.getSettings().setRoomStatusColors(statusColors);
Settings.writeToFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
};
for(Button btn:statusColorButtons)
{
btn.addPaintListener(colorPainter);
btn.addSelectionListener(sl);
}
}
| public ColorComposite(Composite parent, int style) {
super(parent, style);
setLayout(null);
final Customs customs = new Customs();
List<Combo> messageColorCombos = new ArrayList<Combo>();
Group grpOutputColor = new Group(this, SWT.NONE);
grpOutputColor.setText("Output Colors");
grpOutputColor.setBounds(10, 10, 186, 206);
Label lblConsole = new Label(grpOutputColor, SWT.NONE);
lblConsole.setText("Console");
lblConsole.setBounds(10, 23, 55, 15);
Combo comboConsole = new Combo(grpOutputColor, SWT.READ_ONLY);
comboConsole.setBounds(80, 23, 91, 23);
comboConsole.setData(Message.CONSOLE);
messageColorCombos.add(comboConsole);
Label lblMessage = new Label(grpOutputColor, SWT.NONE);
lblMessage.setText("Message");
lblMessage.setBounds(10, 52, 55, 15);
Combo comboMessage = new Combo(grpOutputColor, SWT.READ_ONLY);
comboMessage.setBounds(80, 52, 91, 23);
comboMessage.setData(Message.MSG);
messageColorCombos.add(comboMessage);
Label lblNotice = new Label(grpOutputColor, SWT.NONE);
lblNotice.setText("Notice");
lblNotice.setBounds(10, 81, 55, 15);
Combo comboNotice = new Combo(grpOutputColor, SWT.READ_ONLY);
comboNotice.setBounds(80, 81, 91, 23);
comboNotice.setData(Message.NOTICE);
messageColorCombos.add(comboNotice);
Label lblAction = new Label(grpOutputColor, SWT.NONE);
lblAction.setText("Action");
lblAction.setBounds(10, 110, 55, 15);
Combo comboAction = new Combo(grpOutputColor, SWT.READ_ONLY);
comboAction.setBounds(80, 110, 91, 23);
comboAction.setData(Message.ACTION);
messageColorCombos.add(comboAction);
Label lblPm = new Label(grpOutputColor, SWT.NONE);
lblPm.setText("PM");
lblPm.setBounds(10, 139, 55, 15);
Combo comboPM = new Combo(grpOutputColor, SWT.READ_ONLY);
comboPM.setBounds(80, 139, 91, 23);
comboPM.setData(Message.PM);
messageColorCombos.add(comboPM);
Label lblBackground = new Label(grpOutputColor, SWT.NONE);
lblBackground.setText("Background");
lblBackground.setBounds(10, 168, 64, 15);
Combo comboBG = new Combo(grpOutputColor, SWT.READ_ONLY);
comboBG.setBounds(80, 168, 91, 23);
comboBG.setData(Settings.BACKGROUND);
messageColorCombos.add(comboBG);
SelectionListener IRCColorListener = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), combo.getText());
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();
//check if all the rooms have to change foreground/background
if(combo.getData().equals(Message.MSG)||combo.getData().equals(Settings.BACKGROUND))
{
for(CTabItem i:RoomManager.getMain().getContainer().getItems())
{
if(i.getControl() instanceof Connection)
{
for(Room r:((Connection)i.getControl()).getRooms())
{
StyledText output = r.getOutput();
StyledText input = r.getInput();
output.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
output.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
input.setForeground(customs.colors.get(Settings.getSettings().getOutputColors().get(Message.MSG)));
input.setBackground(customs.colors.get(Settings.getSettings().getOutputColors().get(Settings.BACKGROUND)));
}
}
}
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
PaintListener pl = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 4;
String colorStr = Settings.getSettings().getOutputColors().get(e.widget.getData());
e.gc.setBackground(customs.colors.get(colorStr));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
for(Combo c:messageColorCombos)
{
c.add("white");
c.add("black");
c.add("dark blue");
c.add("dark green");
c.add("red");
c.add("brown");
c.add("purple");
c.add("olive");
c.add("yellow");
c.add("green");
c.add("teal");
c.add("cyan");
c.add("blue");
c.add("magenta");
c.add("dark gray");
c.add("light gray");
String colorStr = Settings.getSettings().getOutputColors().get((Short)c.getData());
c.setText(colorStr);
c.addSelectionListener(IRCColorListener);
c.addPaintListener(pl);
}
List<Button> statusColorButtons = new ArrayList<Button>();
Group grpRoomStatusColors = new Group(this, SWT.NONE);
grpRoomStatusColors.setText("Room Status Colors");
grpRoomStatusColors.setBounds(218, 10, 202, 177);
Label lblNormal = new Label(grpRoomStatusColors, SWT.NONE);
lblNormal.setText("Normal");
lblNormal.setBounds(10, 23, 85, 15);
Button btnNormal = new Button(grpRoomStatusColors, SWT.NONE);
btnNormal.setBounds(117, 18, 75, 25);
btnNormal.setData(Room.NORMAL);
statusColorButtons.add(btnNormal);
Label lblNewIrcEvent = new Label(grpRoomStatusColors, SWT.NONE);
lblNewIrcEvent.setText("New IRC Event");
lblNewIrcEvent.setBounds(10, 56, 85, 15);
Button btnIRCEvent = new Button(grpRoomStatusColors, SWT.NONE);
btnIRCEvent.setBounds(117, 51, 75, 25);
btnIRCEvent.setData(Room.NEW_IRC_EVENT);
statusColorButtons.add(btnIRCEvent);
Label lblNewMessage = new Label(grpRoomStatusColors, SWT.NONE);
lblNewMessage.setText("New Message");
lblNewMessage.setBounds(10, 87, 85, 15);
Button btnNewMSG = new Button(grpRoomStatusColors, SWT.NONE);
btnNewMSG.setBounds(117, 82, 75, 25);
btnNewMSG.setData(Room.NEW_MESSAGE);
statusColorButtons.add(btnNewMSG);
Label lblNameCalled = new Label(grpRoomStatusColors, SWT.NONE);
lblNameCalled.setText("Name Called");
lblNameCalled.setBounds(10, 118, 85, 15);
Button btnNameCall = new Button(grpRoomStatusColors, SWT.NONE);
btnNameCall.setBounds(117, 113, 75, 25);
btnNameCall.setData(Room.NAME_CALLED);
statusColorButtons.add(btnNameCall);
PaintListener colorPainter = new PaintListener(){
public void paintControl(PaintEvent e) {
int border = 6;
RGB rgb = Settings.getSettings().getRoomStatusColors().get(e.widget.getData());
e.gc.setBackground(SWTResourceManager.getColor(rgb));
e.gc.fillRectangle(border, border, e.width-2*border, e.height-2*border);
}
};
SelectionListener sl = new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
/*Combo combo = (Combo)e.widget;
HashMap<Short,String> outputColors = Settings.getSettings().getOutputColors();
outputColors.put((Short)combo.getData(), customs.ircColorsStr.get(combo.getText()));
Settings.getSettings().setOutputColors(outputColors);
Settings.writeToFile();*/
ColorDialog cd = new ColorDialog(RoomManager.getMain().getShell());
RGB rgb = cd.open();
if(rgb != null)
{
Button btn = (Button)e.widget;
HashMap<Integer,RGB> statusColors = Settings.getSettings().getRoomStatusColors();
statusColors.put((Integer)btn.getData(), rgb);
Settings.getSettings().setRoomStatusColors(statusColors);
Settings.writeToFile();
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
};
for(Button btn:statusColorButtons)
{
btn.addPaintListener(colorPainter);
btn.addSelectionListener(sl);
}
}
|
diff --git a/src/com/gamezgalaxy/GGS/defaults/commands/Load.java b/src/com/gamezgalaxy/GGS/defaults/commands/Load.java
index a369f85..0101559 100644
--- a/src/com/gamezgalaxy/GGS/defaults/commands/Load.java
+++ b/src/com/gamezgalaxy/GGS/defaults/commands/Load.java
@@ -1,48 +1,48 @@
package com.gamezgalaxy.GGS.defaults.commands;
import com.gamezgalaxy.GGS.API.plugin.Command;
import com.gamezgalaxy.GGS.server.Player;
import com.gamezgalaxy.GGS.world.Level;
import com.gamezgalaxy.GGS.world.LevelHandler;
/**
* Created with IntelliJ IDEA.
* User: Oliver Yasuna
* Date: 7/25/12
* Time: 3:27 AM
* To change this template use File | Settings | File Templates.
*/
public class Load extends Command
{
@Override
public String[] getShortcuts()
{
return new String[0];
}
@Override
public String getName()
{
return "load";
}
@Override
public boolean isOpCommand()
{
return true;
}
@Override
public int getDefaultPermissionLevel()
{
return 0;
}
@Override
public void execute(Player player, String[] args)
{
LevelHandler handler = player.getServer().getLevelHandler();
- handler.loadLevel(args[1] + ".ggs");
+ handler.loadLevel("levels/" + args[1] + ".ggs");
}
}
| true | true | public void execute(Player player, String[] args)
{
LevelHandler handler = player.getServer().getLevelHandler();
handler.loadLevel(args[1] + ".ggs");
}
| public void execute(Player player, String[] args)
{
LevelHandler handler = player.getServer().getLevelHandler();
handler.loadLevel("levels/" + args[1] + ".ggs");
}
|
diff --git a/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/TextualInputItemSupport.java b/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/TextualInputItemSupport.java
index faf984b..fdfd25b 100644
--- a/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/TextualInputItemSupport.java
+++ b/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/TextualInputItemSupport.java
@@ -1,44 +1,44 @@
package org.wyona.yanel.impl.jelly;
import org.wyona.yanel.core.api.attributes.creatable.AbstractResourceInputItem;
public abstract class TextualInputItemSupport extends AbstractResourceInputItem {
private String value;
public TextualInputItemSupport(String name) {
super(name);
}
public TextualInputItemSupport(String name, String value) {
super(name);
if(value != null && "".equals(value.trim())){
value = null;
}
this.value = value;
}
public Object getValue() {
return this.value;
}
/**
* Set value
*/
public void doSetValue(Object value) {
if(value == null){
this.value = null;
return;
}
- if (!(value instanceof String)) throw new IllegalArgumentException("Value of input item '" + name + "' is not a string: " + value.toString());
+ if (!(value instanceof String)) throw new IllegalArgumentException("Value of input item '" + getName() + "' is not a string: " + value.toString());
if( "".equals(((String)value).trim())){
value = null;
}
this.value = (String)value;
}
}
| true | true | public void doSetValue(Object value) {
if(value == null){
this.value = null;
return;
}
if (!(value instanceof String)) throw new IllegalArgumentException("Value of input item '" + name + "' is not a string: " + value.toString());
if( "".equals(((String)value).trim())){
value = null;
}
this.value = (String)value;
}
| public void doSetValue(Object value) {
if(value == null){
this.value = null;
return;
}
if (!(value instanceof String)) throw new IllegalArgumentException("Value of input item '" + getName() + "' is not a string: " + value.toString());
if( "".equals(((String)value).trim())){
value = null;
}
this.value = (String)value;
}
|
diff --git a/functional-test/src/main/java/net/dovemq/transport/link/LinkTestMultipleLinksNoSharing.java b/functional-test/src/main/java/net/dovemq/transport/link/LinkTestMultipleLinksNoSharing.java
index d983eb5..e86f31a 100644
--- a/functional-test/src/main/java/net/dovemq/transport/link/LinkTestMultipleLinksNoSharing.java
+++ b/functional-test/src/main/java/net/dovemq/transport/link/LinkTestMultipleLinksNoSharing.java
@@ -1,133 +1,135 @@
package net.dovemq.transport.link;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.management.MalformedObjectNameException;
import net.dovemq.transport.common.CAMQPTestTask;
import net.dovemq.transport.common.JMXProxyWrapper;
import net.dovemq.transport.session.SessionCommand;
public class LinkTestMultipleLinksNoSharing
{
private static final String source = "src";
private static final String target = "target";
private static int NUM_THREADS = 5;
private static class LinkTestMessageSender extends CAMQPTestTask implements Runnable
{
private volatile CAMQPLinkSender linkSender = null;
CAMQPLinkSender getLinkSender()
{
return linkSender;
}
private final int numMessagesToSend;
public LinkTestMessageSender(CountDownLatch startSignal,
CountDownLatch doneSignal, int numMessagesToSend)
{
super(startSignal, doneSignal);
this.numMessagesToSend = numMessagesToSend;
}
@Override
public void run()
{
String linkSource = String.format("%s%d", source, Thread.currentThread().getId());
String linkTarget = String.format("%s%d", target, Thread.currentThread().getId());
CAMQPLinkSender sender = CAMQPLinkFactory.createLinkSender(brokerContainerId, linkSource, linkTarget);
linkSender = sender;
System.out.println("Sender Link created between : " + linkSource + " and: " + linkTarget);
String linkName = linkSender.getLinkName();
mbeanProxy.registerTarget(linkSource, linkTarget);
mbeanProxy.issueLinkCredit(linkName, 10);
LinkTestUtils.sendMessagesOnLink(linkSender, numMessagesToSend);
waitForReady();
linkSender.destroyLink();
done();
}
}
private static String brokerContainerId ;
private static LinkCommandMBean mbeanProxy;
public static void main(String[] args) throws InterruptedException, IOException, MalformedObjectNameException
{
/*
* Read args
*/
String publisherName = args[0];
String brokerIp = args[1];
String jmxPort = args[2];
JMXProxyWrapper jmxWrapper = new JMXProxyWrapper(brokerIp, jmxPort);
NUM_THREADS = Integer.parseInt(args[3]);
int numMessagesToSend = Integer.parseInt(args[4]);
brokerContainerId = String.format("broker@%s", brokerIp);
CAMQPLinkManager.initialize(false, publisherName);
SessionCommand localSessionCommand = new SessionCommand();
localSessionCommand.sessionCreate(brokerContainerId);
mbeanProxy = jmxWrapper.getLinkBean();
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(NUM_THREADS);
LinkTestMessageSender[] senders = new LinkTestMessageSender[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
{
LinkTestMessageSender sender = new LinkTestMessageSender(startSignal, doneSignal, numMessagesToSend);
senders[i] = sender;
executor.submit(sender);
}
Random randomGenerator = new Random();
int iterator = 0;
while (true)
{
int randomInt = randomGenerator.nextInt(50);
long messagesReceived = mbeanProxy.getNumMessagesReceived();
System.out.println("got messages: " + messagesReceived + " issuing link credit: " + randomInt);
if (messagesReceived == numMessagesToSend * NUM_THREADS)
{
break;
}
Thread.sleep(randomGenerator.nextInt(50) + 50);
LinkTestMessageSender sender = senders[iterator % NUM_THREADS];
iterator++;
/*
* Receiver-driven link-credit
*/
- mbeanProxy.issueLinkCredit(sender.getLinkSender().getLinkName(), randomInt);
+ CAMQPLinkSender linksender = sender.getLinkSender();
+ if (linksender != null)
+ mbeanProxy.issueLinkCredit(sender.getLinkSender().getLinkName(), randomInt);
}
startSignal.countDown();
doneSignal.await();
Thread.sleep(2000);
assertTrue(mbeanProxy.getNumMessagesReceived() == numMessagesToSend * NUM_THREADS);
executor.shutdown();
CAMQPLinkManager.shutdown();
mbeanProxy.reset();
jmxWrapper.cleanup();
}
}
| true | true | public static void main(String[] args) throws InterruptedException, IOException, MalformedObjectNameException
{
/*
* Read args
*/
String publisherName = args[0];
String brokerIp = args[1];
String jmxPort = args[2];
JMXProxyWrapper jmxWrapper = new JMXProxyWrapper(brokerIp, jmxPort);
NUM_THREADS = Integer.parseInt(args[3]);
int numMessagesToSend = Integer.parseInt(args[4]);
brokerContainerId = String.format("broker@%s", brokerIp);
CAMQPLinkManager.initialize(false, publisherName);
SessionCommand localSessionCommand = new SessionCommand();
localSessionCommand.sessionCreate(brokerContainerId);
mbeanProxy = jmxWrapper.getLinkBean();
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(NUM_THREADS);
LinkTestMessageSender[] senders = new LinkTestMessageSender[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
{
LinkTestMessageSender sender = new LinkTestMessageSender(startSignal, doneSignal, numMessagesToSend);
senders[i] = sender;
executor.submit(sender);
}
Random randomGenerator = new Random();
int iterator = 0;
while (true)
{
int randomInt = randomGenerator.nextInt(50);
long messagesReceived = mbeanProxy.getNumMessagesReceived();
System.out.println("got messages: " + messagesReceived + " issuing link credit: " + randomInt);
if (messagesReceived == numMessagesToSend * NUM_THREADS)
{
break;
}
Thread.sleep(randomGenerator.nextInt(50) + 50);
LinkTestMessageSender sender = senders[iterator % NUM_THREADS];
iterator++;
/*
* Receiver-driven link-credit
*/
mbeanProxy.issueLinkCredit(sender.getLinkSender().getLinkName(), randomInt);
}
startSignal.countDown();
doneSignal.await();
Thread.sleep(2000);
assertTrue(mbeanProxy.getNumMessagesReceived() == numMessagesToSend * NUM_THREADS);
executor.shutdown();
CAMQPLinkManager.shutdown();
mbeanProxy.reset();
jmxWrapper.cleanup();
}
| public static void main(String[] args) throws InterruptedException, IOException, MalformedObjectNameException
{
/*
* Read args
*/
String publisherName = args[0];
String brokerIp = args[1];
String jmxPort = args[2];
JMXProxyWrapper jmxWrapper = new JMXProxyWrapper(brokerIp, jmxPort);
NUM_THREADS = Integer.parseInt(args[3]);
int numMessagesToSend = Integer.parseInt(args[4]);
brokerContainerId = String.format("broker@%s", brokerIp);
CAMQPLinkManager.initialize(false, publisherName);
SessionCommand localSessionCommand = new SessionCommand();
localSessionCommand.sessionCreate(brokerContainerId);
mbeanProxy = jmxWrapper.getLinkBean();
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(NUM_THREADS);
LinkTestMessageSender[] senders = new LinkTestMessageSender[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
{
LinkTestMessageSender sender = new LinkTestMessageSender(startSignal, doneSignal, numMessagesToSend);
senders[i] = sender;
executor.submit(sender);
}
Random randomGenerator = new Random();
int iterator = 0;
while (true)
{
int randomInt = randomGenerator.nextInt(50);
long messagesReceived = mbeanProxy.getNumMessagesReceived();
System.out.println("got messages: " + messagesReceived + " issuing link credit: " + randomInt);
if (messagesReceived == numMessagesToSend * NUM_THREADS)
{
break;
}
Thread.sleep(randomGenerator.nextInt(50) + 50);
LinkTestMessageSender sender = senders[iterator % NUM_THREADS];
iterator++;
/*
* Receiver-driven link-credit
*/
CAMQPLinkSender linksender = sender.getLinkSender();
if (linksender != null)
mbeanProxy.issueLinkCredit(sender.getLinkSender().getLinkName(), randomInt);
}
startSignal.countDown();
doneSignal.await();
Thread.sleep(2000);
assertTrue(mbeanProxy.getNumMessagesReceived() == numMessagesToSend * NUM_THREADS);
executor.shutdown();
CAMQPLinkManager.shutdown();
mbeanProxy.reset();
jmxWrapper.cleanup();
}
|
diff --git a/src/java/proai/util/MySQLDDLConverter.java b/src/java/proai/util/MySQLDDLConverter.java
index 07640b3..31a17b2 100644
--- a/src/java/proai/util/MySQLDDLConverter.java
+++ b/src/java/proai/util/MySQLDDLConverter.java
@@ -1,120 +1,120 @@
package proai.util;
import java.util.*;
public class MySQLDDLConverter
implements DDLConverter {
public MySQLDDLConverter() {
}
public boolean supportsTableType() {
return true;
}
public String getDropDDL(String command) {
String[] parts = command.split(" ");
String tableName = parts[2];
return "DROP TABLE " + tableName;
}
public List<String> getDDL(TableSpec spec) {
StringBuffer out=new StringBuffer();
StringBuffer end=new StringBuffer();
out.append("CREATE TABLE " + spec.getName() + " (\n");
Iterator<ColumnSpec> csi=spec.columnSpecIterator();
int csNum=0;
while (csi.hasNext()) {
if (csNum>0) {
out.append(",\n");
}
csNum++;
ColumnSpec cs=(ColumnSpec) csi.next();
out.append(" ");
out.append(cs.getName());
out.append(' ');
if (cs.getType().equalsIgnoreCase("text")) {
if (cs.getBinary()) {
out.append("blob");
} else {
out.append(cs.getType());
}
} else {
out.append(cs.getType());
if (cs.getType().toLowerCase().startsWith("varchar")) {
if (cs.getBinary()) {
out.append(" BINARY");
}
}
}
if (cs.isNotNull()) {
out.append(" NOT NULL");
}
if (cs.isAutoIncremented()) {
out.append(" auto_increment");
}
if (cs.getDefaultValue()!=null) {
out.append(" default '");
out.append(cs.getDefaultValue());
out.append("'");
}
if (cs.isUnique()) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" UNIQUE KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getIndexName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" KEY ");
end.append(cs.getIndexName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getForeignTableName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" FOREIGN KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(") REFERENCES ");
end.append(cs.getForeignTableName());
end.append(" (");
end.append(cs.getForeignColumnName());
end.append(")");
if (cs.getOnDeleteAction()!=null) {
end.append(" ON DELETE ");
end.append(cs.getOnDeleteAction());
}
}
}
if (spec.getPrimaryColumnName()!=null) {
out.append(",\n PRIMARY KEY (");
out.append(spec.getPrimaryColumnName());
out.append(")");
}
if (!end.toString().equals("")) {
out.append(",\n");
out.append(end);
}
out.append("\n");
out.append(")");
if (spec.getType()!=null) {
- out.append(" TYPE=" + spec.getType());
+ out.append(" ENGINE=" + spec.getType());
}
ArrayList<String> l=new ArrayList<String>();
l.add(out.toString());
return l;
}
}
| true | true | public List<String> getDDL(TableSpec spec) {
StringBuffer out=new StringBuffer();
StringBuffer end=new StringBuffer();
out.append("CREATE TABLE " + spec.getName() + " (\n");
Iterator<ColumnSpec> csi=spec.columnSpecIterator();
int csNum=0;
while (csi.hasNext()) {
if (csNum>0) {
out.append(",\n");
}
csNum++;
ColumnSpec cs=(ColumnSpec) csi.next();
out.append(" ");
out.append(cs.getName());
out.append(' ');
if (cs.getType().equalsIgnoreCase("text")) {
if (cs.getBinary()) {
out.append("blob");
} else {
out.append(cs.getType());
}
} else {
out.append(cs.getType());
if (cs.getType().toLowerCase().startsWith("varchar")) {
if (cs.getBinary()) {
out.append(" BINARY");
}
}
}
if (cs.isNotNull()) {
out.append(" NOT NULL");
}
if (cs.isAutoIncremented()) {
out.append(" auto_increment");
}
if (cs.getDefaultValue()!=null) {
out.append(" default '");
out.append(cs.getDefaultValue());
out.append("'");
}
if (cs.isUnique()) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" UNIQUE KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getIndexName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" KEY ");
end.append(cs.getIndexName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getForeignTableName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" FOREIGN KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(") REFERENCES ");
end.append(cs.getForeignTableName());
end.append(" (");
end.append(cs.getForeignColumnName());
end.append(")");
if (cs.getOnDeleteAction()!=null) {
end.append(" ON DELETE ");
end.append(cs.getOnDeleteAction());
}
}
}
if (spec.getPrimaryColumnName()!=null) {
out.append(",\n PRIMARY KEY (");
out.append(spec.getPrimaryColumnName());
out.append(")");
}
if (!end.toString().equals("")) {
out.append(",\n");
out.append(end);
}
out.append("\n");
out.append(")");
if (spec.getType()!=null) {
out.append(" TYPE=" + spec.getType());
}
ArrayList<String> l=new ArrayList<String>();
l.add(out.toString());
return l;
}
| public List<String> getDDL(TableSpec spec) {
StringBuffer out=new StringBuffer();
StringBuffer end=new StringBuffer();
out.append("CREATE TABLE " + spec.getName() + " (\n");
Iterator<ColumnSpec> csi=spec.columnSpecIterator();
int csNum=0;
while (csi.hasNext()) {
if (csNum>0) {
out.append(",\n");
}
csNum++;
ColumnSpec cs=(ColumnSpec) csi.next();
out.append(" ");
out.append(cs.getName());
out.append(' ');
if (cs.getType().equalsIgnoreCase("text")) {
if (cs.getBinary()) {
out.append("blob");
} else {
out.append(cs.getType());
}
} else {
out.append(cs.getType());
if (cs.getType().toLowerCase().startsWith("varchar")) {
if (cs.getBinary()) {
out.append(" BINARY");
}
}
}
if (cs.isNotNull()) {
out.append(" NOT NULL");
}
if (cs.isAutoIncremented()) {
out.append(" auto_increment");
}
if (cs.getDefaultValue()!=null) {
out.append(" default '");
out.append(cs.getDefaultValue());
out.append("'");
}
if (cs.isUnique()) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" UNIQUE KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getIndexName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" KEY ");
end.append(cs.getIndexName());
end.append(" (");
end.append(cs.getName());
end.append(")");
}
if (cs.getForeignTableName()!=null) {
if (!end.toString().equals("")) {
end.append(",\n");
}
end.append(" FOREIGN KEY ");
end.append(cs.getName());
end.append(" (");
end.append(cs.getName());
end.append(") REFERENCES ");
end.append(cs.getForeignTableName());
end.append(" (");
end.append(cs.getForeignColumnName());
end.append(")");
if (cs.getOnDeleteAction()!=null) {
end.append(" ON DELETE ");
end.append(cs.getOnDeleteAction());
}
}
}
if (spec.getPrimaryColumnName()!=null) {
out.append(",\n PRIMARY KEY (");
out.append(spec.getPrimaryColumnName());
out.append(")");
}
if (!end.toString().equals("")) {
out.append(",\n");
out.append(end);
}
out.append("\n");
out.append(")");
if (spec.getType()!=null) {
out.append(" ENGINE=" + spec.getType());
}
ArrayList<String> l=new ArrayList<String>();
l.add(out.toString());
return l;
}
|
diff --git a/src/main/java/com/geNAZt/RegionShop/Database/Model/Item.java b/src/main/java/com/geNAZt/RegionShop/Database/Model/Item.java
index 0387438..c959b64 100644
--- a/src/main/java/com/geNAZt/RegionShop/Database/Model/Item.java
+++ b/src/main/java/com/geNAZt/RegionShop/Database/Model/Item.java
@@ -1,117 +1,117 @@
package com.geNAZt.RegionShop.Database.Model;
import com.geNAZt.RegionShop.Database.Database;
import com.geNAZt.RegionShop.Database.ItemStorageHolder;
import com.geNAZt.RegionShop.Database.Table.ItemMeta;
import com.geNAZt.RegionShop.Database.Table.ItemMetaID;
import com.geNAZt.RegionShop.Database.Table.Items;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentWrapper;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Map;
/**
* Created for YEAHWH.AT
* User: geNAZt ([email protected])
* Date: 01.09.13
*/
public class Item {
public static ItemMeta getMeta(ItemStack itemStack) {
return Database.getServer().find(ItemMeta.class).
where().
eq("item_id", itemStack.getTypeId()).
eq("data_value", itemStack.getData().getData()).
findUnique();
}
public static boolean hasMeta(ItemStack itemStack) {
return !(getMeta(itemStack) == null);
}
public static void createMeta(ItemStack itemStack) {
ItemMeta itemMeta = new ItemMeta();
itemMeta.setId(new ItemMetaID(itemStack.getTypeId(), itemStack.getData().getData()));
itemMeta.setMaxStackSize(itemStack.getType().getMaxStackSize());
itemMeta.setMaxDurability(itemStack.getType().getMaxDurability());
Database.getServer().save(itemMeta);
}
public static ItemStack fromDBItem(Items item) {
ItemStack iStack = new ItemStack(Material.getMaterial(item.getMeta().getId().getItemID()), 1);
if(item.getMeta().getId().getDataValue() > 0) {
iStack.getData().setData(item.getMeta().getId().getDataValue());
}
if(item.getDurability() > 0) {
iStack.setDurability(item.getDurability());
} else {
iStack.setDurability((short) item.getMeta().getId().getDataValue());
}
List<com.geNAZt.RegionShop.Database.Table.Enchantment> enchants = Database.getServer().find(com.geNAZt.RegionShop.Database.Table.Enchantment.class).
setUseQueryCache(true).
where().
eq("item", item).
findList();
if(enchants.size() > 0) {
for(com.geNAZt.RegionShop.Database.Table.Enchantment ench : enchants) {
Enchantment enchObj = new EnchantmentWrapper(ench.getEnchId()).getEnchantment();
iStack.addEnchantment(enchObj, ench.getEnchLvl());
}
}
if(item.getCustomName() != null) {
org.bukkit.inventory.meta.ItemMeta iMeta = iStack.getItemMeta();
iMeta.setDisplayName(item.getCustomName());
iStack.setItemMeta(iMeta);
}
return iStack;
}
public static Items toDBItem(ItemStack item, ItemStorageHolder region, String owner, Float buy, Float sell, Integer amount) {
if(!hasMeta(item)) {
createMeta(item);
}
ItemMeta itemMeta = getMeta(item);
Items newItem = new Items();
newItem.setMeta(itemMeta);
newItem.setItemStorage(region.getItemStorage());
newItem.setCurrentAmount(item.getAmount());
newItem.setDurability(item.getDurability());
newItem.setOwner(owner);
- newItem.setCustomName((item.getItemMeta().hasDisplayName()) ? item.getItemMeta().getDisplayName() : null);
+ newItem.setCustomName((item.getItemMeta() != null && item.getItemMeta().hasDisplayName()) ? item.getItemMeta().getDisplayName() : null);
newItem.setBuy(buy);
newItem.setSell(sell);
newItem.setUnitAmount(amount);
Database.getServer().save(newItem);
Map<Enchantment, Integer> itemEnch = item.getEnchantments();
if(itemEnch != null) {
for(Map.Entry<Enchantment, Integer> entry : itemEnch.entrySet()) {
com.geNAZt.RegionShop.Database.Table.Enchantment ench = new com.geNAZt.RegionShop.Database.Table.Enchantment();
ench.setEnchId(entry.getKey().getId());
ench.setEnchLvl(entry.getValue());
ench.setItem(newItem);
Database.getServer().save(ench);
}
}
region.getItemStorage().setItemAmount(region.getItemStorage().getItemAmount() + item.getAmount());
Database.getServer().update(region.getItemStorage());
return newItem;
}
}
| true | true | public static Items toDBItem(ItemStack item, ItemStorageHolder region, String owner, Float buy, Float sell, Integer amount) {
if(!hasMeta(item)) {
createMeta(item);
}
ItemMeta itemMeta = getMeta(item);
Items newItem = new Items();
newItem.setMeta(itemMeta);
newItem.setItemStorage(region.getItemStorage());
newItem.setCurrentAmount(item.getAmount());
newItem.setDurability(item.getDurability());
newItem.setOwner(owner);
newItem.setCustomName((item.getItemMeta().hasDisplayName()) ? item.getItemMeta().getDisplayName() : null);
newItem.setBuy(buy);
newItem.setSell(sell);
newItem.setUnitAmount(amount);
Database.getServer().save(newItem);
Map<Enchantment, Integer> itemEnch = item.getEnchantments();
if(itemEnch != null) {
for(Map.Entry<Enchantment, Integer> entry : itemEnch.entrySet()) {
com.geNAZt.RegionShop.Database.Table.Enchantment ench = new com.geNAZt.RegionShop.Database.Table.Enchantment();
ench.setEnchId(entry.getKey().getId());
ench.setEnchLvl(entry.getValue());
ench.setItem(newItem);
Database.getServer().save(ench);
}
}
region.getItemStorage().setItemAmount(region.getItemStorage().getItemAmount() + item.getAmount());
Database.getServer().update(region.getItemStorage());
return newItem;
}
| public static Items toDBItem(ItemStack item, ItemStorageHolder region, String owner, Float buy, Float sell, Integer amount) {
if(!hasMeta(item)) {
createMeta(item);
}
ItemMeta itemMeta = getMeta(item);
Items newItem = new Items();
newItem.setMeta(itemMeta);
newItem.setItemStorage(region.getItemStorage());
newItem.setCurrentAmount(item.getAmount());
newItem.setDurability(item.getDurability());
newItem.setOwner(owner);
newItem.setCustomName((item.getItemMeta() != null && item.getItemMeta().hasDisplayName()) ? item.getItemMeta().getDisplayName() : null);
newItem.setBuy(buy);
newItem.setSell(sell);
newItem.setUnitAmount(amount);
Database.getServer().save(newItem);
Map<Enchantment, Integer> itemEnch = item.getEnchantments();
if(itemEnch != null) {
for(Map.Entry<Enchantment, Integer> entry : itemEnch.entrySet()) {
com.geNAZt.RegionShop.Database.Table.Enchantment ench = new com.geNAZt.RegionShop.Database.Table.Enchantment();
ench.setEnchId(entry.getKey().getId());
ench.setEnchLvl(entry.getValue());
ench.setItem(newItem);
Database.getServer().save(ench);
}
}
region.getItemStorage().setItemAmount(region.getItemStorage().getItemAmount() + item.getAmount());
Database.getServer().update(region.getItemStorage());
return newItem;
}
|
diff --git a/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/ApplicationLayout.java b/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/ApplicationLayout.java
index 637c237c7..d8796f38a 100644
--- a/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/ApplicationLayout.java
+++ b/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/ApplicationLayout.java
@@ -1,281 +1,282 @@
/*
* Copyright 2008 Niclas Hedhman. All rights Reserved.
* Copyright 2008 Sonny Gill. 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 org.qi4j.library.swing.visualizer;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import prefuse.action.layout.graph.TreeLayout;
import prefuse.render.Renderer;
import prefuse.visual.NodeItem;
import prefuse.data.Node;
public class ApplicationLayout extends TreeLayout
{
public ApplicationLayout( String group )
{
super( group );
}
public void run( double frac )
{
NodeItem root = getLayoutRoot();
Point topLeft = new Point( 50, 50 );
Rectangle size = computeApplicationBounds( root, topLeft );
root.setBounds( topLeft.x, topLeft.y, size.width, size.height );
}
Collection<Collection<NodeItem>> resolveLayerDependencies( Iterator nodes )
{
TreeMap<Integer, Collection<NodeItem>> map = new TreeMap<Integer, Collection<NodeItem>>();
while( nodes.hasNext() )
{
NodeItem layer = (NodeItem) nodes.next();
int level = layer.getInt( GraphConstants.FIELD_LAYER_LEVEL );
Collection<NodeItem> layers = map.get( level );
if( layers == null )
{
layers = new ArrayList<NodeItem>();
map.put( level, layers );
}
layers.add( layer );
}
return map.values();
}
private Rectangle computeApplicationBounds( NodeItem application, Point location )
{
Dimension dimesion = getNodeLabelSize( application );
int x = location.x + GraphConstants.paddingLeft;
int y = location.y + GraphConstants.paddingTop + dimesion.height + GraphConstants.vSpace;
Collection<Collection<NodeItem>> layeredNodeGroups = resolveLayerDependencies( application.children() );
int maxLayerGroupWidth = 0;
for( Collection<NodeItem> nodeGroup : layeredNodeGroups )
{
Point layerGroupLocation = new Point( x, y );
Rectangle bounds = computeLayerGroupBounds( nodeGroup, layerGroupLocation );
y += bounds.height + GraphConstants.vSpace;
if( bounds.width > maxLayerGroupWidth )
{
maxLayerGroupWidth = bounds.width;
}
}
int width = ( x + maxLayerGroupWidth + GraphConstants.paddingRight ) - location.x;
int height = y - location.y;
return new Rectangle( location.x, location.y, width, height );
}
private Map<Node, NodeItem> nodeToVisualNodeItemMap = new HashMap<Node, NodeItem>();
/**
* Tries to suggest a suitable x position and width, if there is only 1 layer in this group.
* The position and width is based on the layers in higher group that use this layer
*/
private Rectangle getSuggestedBounds( Collection<NodeItem> layers, NodeItem layer, int x, int y )
{
nodeToVisualNodeItemMap.put( (Node) layer.getSourceTuple(), layer );
Collection<Node> usedByLayers = (Collection<Node>) layer.get( GraphConstants.FIELD_USED_BY_LAYERS );
if( usedByLayers.isEmpty() )
{
return new Rectangle( x, y, 0, 0 );
}
int left = Integer.MAX_VALUE;
int right = Integer.MIN_VALUE;
int width;
for( Node usedByLayer : usedByLayers )
{
NodeItem item = nodeToVisualNodeItemMap.get( usedByLayer );
Rectangle2D bounds = item.getBounds();
if( bounds.getX() < left )
{
left = (int) bounds.getX();
}
if( ( bounds.getX() + bounds.getWidth() ) > right )
{
right = (int) ( bounds.getX() + bounds.getWidth() );
}
}
width = right - left;
- Rectangle suggestedBounds = new Rectangle( left, y, width, 0 );
+ // Use a height of 1 instead of 0 for correct operation of Rectangle2D.intersects call later
+ Rectangle suggestedBounds = new Rectangle( left, y, width, 1 );
// If there are other layers on this level, and the calculated suggested bounds intersect with
// any layer's bounds, return the default bounds
if( layers.size() > 1 )
{
Set<NodeItem> otherLayers = new HashSet<NodeItem>( layers );
otherLayers.remove( layer );
for( NodeItem otherLayer : otherLayers )
{
if( otherLayer.getBounds().intersects( suggestedBounds ) )
{
return new Rectangle( x, y, 0, 0 );
}
}
}
return suggestedBounds;
}
private Rectangle computeLayerGroupBounds( Collection<NodeItem> layers, Point location )
{
int x = location.x + GraphConstants.paddingLeft;
int y = location.y + GraphConstants.vSpace;
int maxLayerHeight = 0;
for( NodeItem layer : layers )
{
Rectangle suggestedBounds = getSuggestedBounds( layers, layer, x, y );
Point layerLocation = new Point( suggestedBounds.x, y );
Rectangle bounds = computeLayerBounds( layer, layerLocation );
int width = Math.max( bounds.width, suggestedBounds.width );
layer.setBounds( bounds.x, bounds.y, width, bounds.height );
x += width + GraphConstants.hSpace;
if( bounds.height > maxLayerHeight )
{
maxLayerHeight = bounds.height;
}
}
int width = x - location.x;
int height = ( y + maxLayerHeight + GraphConstants.paddingBottom ) - location.y;
return new Rectangle( location.x, location.y, width, height );
}
private Rectangle computeLayerBounds( NodeItem layer, Point location )
{
Dimension dimension = getNodeLabelSize( layer );
int x = location.x + GraphConstants.paddingLeft;
int y = location.y + GraphConstants.paddingTop + dimension.height + GraphConstants.vSpace;
Iterator children = layer.children();
int maxModuleHeight = 0;
while( children.hasNext() )
{
NodeItem module = (NodeItem) children.next();
Point moduleLocation = new Point( x, y );
Rectangle bounds = computeModuleBounds( module, moduleLocation );
module.setBounds( bounds.x, bounds.y, bounds.width, bounds.height );
x += bounds.width + GraphConstants.hSpace;
if( bounds.height > maxModuleHeight )
{
maxModuleHeight = bounds.height;
}
}
if( x < location.x + dimension.width )
{
x = location.x + dimension.width;
}
int width = x - location.x;
int height = ( y + maxModuleHeight + GraphConstants.paddingBottom + GraphConstants.vSpace ) - location.y;
return new Rectangle( location.x, location.y, width, height );
}
private Rectangle computeModuleBounds( NodeItem module, Point location )
{
Dimension dimension = getNodeLabelSize( module );
int x = location.x + GraphConstants.paddingLeft;
int y = location.y + GraphConstants.paddingTop + dimension.height + GraphConstants.vSpace;
Iterator children = module.children();
int maxCompositeWidth = 0;
while( children.hasNext() )
{
NodeItem composite = (NodeItem) children.next();
Point compositeLocation = new Point( x, y );
Rectangle bounds = computeCompositeBounds( composite, compositeLocation );
composite.setBounds( bounds.x, bounds.y, bounds.width, bounds.height );
y += bounds.height + GraphConstants.paddingBottom;
if( bounds.width > maxCompositeWidth )
{
maxCompositeWidth = bounds.width;
}
}
if( maxCompositeWidth < dimension.width )
{
maxCompositeWidth = dimension.width;
}
if( y < location.y + dimension.height )
{
y = location.y + dimension.height;
}
int width = ( x + maxCompositeWidth + GraphConstants.paddingRight ) - location.x;
int height = ( y + GraphConstants.paddingBottom ) - location.y;
return new Rectangle( location.x, location.y, width, height );
}
private Rectangle computeCompositeBounds( NodeItem composite, Point location )
{
Dimension dimension = getNodeLabelSize( composite );
return new Rectangle( location.x, location.y, dimension.width + GraphConstants.paddingLeft,
dimension.height + GraphConstants.paddingTop + GraphConstants.paddingBottom );
}
private String getName( NodeItem node )
{
return (String) node.get( GraphConstants.FIELD_NAME );
}
private Dimension getNodeLabelSize( NodeItem node )
{
Font font = node.getFont();
FontMetrics fm = Renderer.DEFAULT_GRAPHICS.getFontMetrics( font );
// 40 is arbitrarily selected, drawString takes more space than calculated here
// this may be because the Graphics object is different from the one that is used to draw it
int width = fm.stringWidth( getName( node ) ) + 40;
int height = fm.getHeight() + 2;
return new Dimension( width, height );
}
}
| true | true | private Rectangle getSuggestedBounds( Collection<NodeItem> layers, NodeItem layer, int x, int y )
{
nodeToVisualNodeItemMap.put( (Node) layer.getSourceTuple(), layer );
Collection<Node> usedByLayers = (Collection<Node>) layer.get( GraphConstants.FIELD_USED_BY_LAYERS );
if( usedByLayers.isEmpty() )
{
return new Rectangle( x, y, 0, 0 );
}
int left = Integer.MAX_VALUE;
int right = Integer.MIN_VALUE;
int width;
for( Node usedByLayer : usedByLayers )
{
NodeItem item = nodeToVisualNodeItemMap.get( usedByLayer );
Rectangle2D bounds = item.getBounds();
if( bounds.getX() < left )
{
left = (int) bounds.getX();
}
if( ( bounds.getX() + bounds.getWidth() ) > right )
{
right = (int) ( bounds.getX() + bounds.getWidth() );
}
}
width = right - left;
Rectangle suggestedBounds = new Rectangle( left, y, width, 0 );
// If there are other layers on this level, and the calculated suggested bounds intersect with
// any layer's bounds, return the default bounds
if( layers.size() > 1 )
{
Set<NodeItem> otherLayers = new HashSet<NodeItem>( layers );
otherLayers.remove( layer );
for( NodeItem otherLayer : otherLayers )
{
if( otherLayer.getBounds().intersects( suggestedBounds ) )
{
return new Rectangle( x, y, 0, 0 );
}
}
}
return suggestedBounds;
}
| private Rectangle getSuggestedBounds( Collection<NodeItem> layers, NodeItem layer, int x, int y )
{
nodeToVisualNodeItemMap.put( (Node) layer.getSourceTuple(), layer );
Collection<Node> usedByLayers = (Collection<Node>) layer.get( GraphConstants.FIELD_USED_BY_LAYERS );
if( usedByLayers.isEmpty() )
{
return new Rectangle( x, y, 0, 0 );
}
int left = Integer.MAX_VALUE;
int right = Integer.MIN_VALUE;
int width;
for( Node usedByLayer : usedByLayers )
{
NodeItem item = nodeToVisualNodeItemMap.get( usedByLayer );
Rectangle2D bounds = item.getBounds();
if( bounds.getX() < left )
{
left = (int) bounds.getX();
}
if( ( bounds.getX() + bounds.getWidth() ) > right )
{
right = (int) ( bounds.getX() + bounds.getWidth() );
}
}
width = right - left;
// Use a height of 1 instead of 0 for correct operation of Rectangle2D.intersects call later
Rectangle suggestedBounds = new Rectangle( left, y, width, 1 );
// If there are other layers on this level, and the calculated suggested bounds intersect with
// any layer's bounds, return the default bounds
if( layers.size() > 1 )
{
Set<NodeItem> otherLayers = new HashSet<NodeItem>( layers );
otherLayers.remove( layer );
for( NodeItem otherLayer : otherLayers )
{
if( otherLayer.getBounds().intersects( suggestedBounds ) )
{
return new Rectangle( x, y, 0, 0 );
}
}
}
return suggestedBounds;
}
|
diff --git a/src/org/geworkbench/bison/datastructure/biocollections/AdjacencyMatrixDataSet.java b/src/org/geworkbench/bison/datastructure/biocollections/AdjacencyMatrixDataSet.java
index 2f2a5e4e..a688fc5c 100644
--- a/src/org/geworkbench/bison/datastructure/biocollections/AdjacencyMatrixDataSet.java
+++ b/src/org/geworkbench/bison/datastructure/biocollections/AdjacencyMatrixDataSet.java
@@ -1,238 +1,238 @@
package org.geworkbench.bison.datastructure.biocollections;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.AdjacencyMatrix.NodeType;
import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet;
import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker;
import org.geworkbench.bison.datastructure.bioobjects.microarray.DSMicroarray;
import org.geworkbench.bison.util.RandomNumberGenerator;
import org.geworkbench.parsers.InputFileFormatException;
/**
* @author John Watkinson
* @version $Id$
*/
public class AdjacencyMatrixDataSet extends CSAncillaryDataSet<DSMicroarray> {
private static final long serialVersionUID = 2222442531807486171L;
public static final String SIF_FORMART = "sif format";
public static final String ADJ_FORMART = "adj format";
public static final String GENE_NAME = "gene name";
public static final String ENTREZ_ID = "entrez id";
public static final String OTHER = "other";
public static final String PROBESET_ID = "probeset id";
static Log log = LogFactory.getLog(AdjacencyMatrixDataSet.class);
private AdjacencyMatrix matrix;
private final double threshold;
private String networkName;
public AdjacencyMatrixDataSet(final AdjacencyMatrix matrix,
final double threshold, final String name,
final String networkName,
final DSMicroarraySet parent) {
super((DSDataSet<DSMicroarray>) parent, name);
setID(RandomNumberGenerator.getID());
this.matrix = matrix;
this.threshold = threshold;
this.networkName = networkName;
}
public String getExportName(AdjacencyMatrix.Node node) {
if (node.type == NodeType.MARKER) {
return node.marker.getLabel();
} else if (node.type == NodeType.GENE_SYMBOL) {
return node.stringId;
} else if (node.type == NodeType.STRING) {
return node.stringId;
} else {
return "unknown";
}
}
public void writeToFile(String fileName) {
File file = new File(fileName);
try {
file.createNewFile();
if (!file.canWrite()) {
JOptionPane.showMessageDialog(null,
"Cannot write to specified file.");
return;
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
// if entry key is less than 0, for CNKB component, it means the
// gene is in currently selected microarray.
for (AdjacencyMatrix.Node node1 : matrix.getNodes()) {
writer.write(getExportName(node1) + "\t");
for (AdjacencyMatrix.Edge edge : matrix.getEdges(node1)) {
writer.write(getExportName(edge.node2) + "\t"
+ edge.info.value + "\t");
}
writer.write("\n");
}
writer.close();
} catch (IOException e) {
log.error(e);
}
}
/**
* Constructor that takes a filename to create by reading and parsing the
* file.
*
* @param matrix
* @param threshold
* @param name
* @param networkName
* @param parent
* @param fileName
*/
public AdjacencyMatrixDataSet(final double threshold, final String name,
final String networkName,
final DSMicroarraySet parent, String fileName)
throws InputFileFormatException {
super((DSDataSet<DSMicroarray>) parent, name);
setID(RandomNumberGenerator.getID());
this.threshold = threshold;
this.networkName = networkName;
matrix = parseAdjacencyMatrix(fileName, parent, null, ADJ_FORMART,
PROBESET_ID, true);
}
private static AdjacencyMatrix.Node token2node(String token,
final String selectedRepresentedBy, final boolean isRestrict, final DSMicroarraySet maSet) {
DSGeneMarker m = null;
if (selectedRepresentedBy.equals(PROBESET_ID)
|| selectedRepresentedBy.equals(GENE_NAME)
|| selectedRepresentedBy.equals(ENTREZ_ID))
m = maSet.getMarkers().get(token);
AdjacencyMatrix.Node node = null;
if (m == null && isRestrict) {
// we don't have this gene in our MicroarraySet
// we skip it
return null;
} else if (m == null && !isRestrict) {
if (selectedRepresentedBy.equals(GENE_NAME))
node = new AdjacencyMatrix.Node(NodeType.GENE_SYMBOL,
token);
else
node = new AdjacencyMatrix.Node(NodeType.STRING, token);
} else {
if (selectedRepresentedBy.equals(PROBESET_ID))
node = new AdjacencyMatrix.Node(m);
else
node = new AdjacencyMatrix.Node(NodeType.GENE_SYMBOL,
m.getGeneName());
}
return node;
}
public static AdjacencyMatrix parseAdjacencyMatrix(String fileName,
final DSMicroarraySet maSet,
Map<String, String> interactionTypeSifMap, String format,
String selectedRepresentedBy, boolean isRestrict)
throws InputFileFormatException {
AdjacencyMatrix matrix = new AdjacencyMatrix(fileName, maSet,
interactionTypeSifMap);
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
// skip comments
if (line.trim().equals("") || line.startsWith(">")
|| line.startsWith("-"))
continue;
StringTokenizer tr = new StringTokenizer(line, "\t: :");
AdjacencyMatrix.Node node = token2node(tr.nextToken(), selectedRepresentedBy, isRestrict, maSet);
if(node==null) continue; // skip it when we don't have it
String interactionType = null;
if (format.equals(SIF_FORMART) && tr.hasMoreTokens())
interactionType = tr.nextToken().toLowerCase();
while (tr.hasMoreTokens()) {
String strGeneId2 = tr.nextToken();
AdjacencyMatrix.Node node2 = token2node(strGeneId2, selectedRepresentedBy, isRestrict, maSet);
- if(node==null) continue; // skip it when we don't have it
+ if(node2==null) continue; // skip it when we don't have it
float mi = 0.8f;
if (format.equals(ADJ_FORMART)) {
if (!tr.hasMoreTokens())
throw new InputFileFormatException(
"invalid format around " + strGeneId2);
mi = Float.parseFloat(tr.nextToken());
}
matrix.add(node, node2, mi, interactionType);
} // end of the token loop for one line
} // end of reading while loop
} catch (NumberFormatException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (FileNotFoundException ex3) {
throw new InputFileFormatException(ex3.getMessage());
} catch (IOException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (Exception e) {
throw new InputFileFormatException(e.getMessage());
}
return matrix;
}
public AdjacencyMatrix getMatrix() {
return matrix;
}
public double getThreshold() {
return threshold;
}
public File getDataSetFile() {
// no-op
return null;
}
public void setDataSetFile(File file) {
// no-op
}
public String getNetworkName() {
return networkName;
}
public void setNetworkName(String networkName) {
this.networkName = networkName;
}
}
| true | true | public static AdjacencyMatrix parseAdjacencyMatrix(String fileName,
final DSMicroarraySet maSet,
Map<String, String> interactionTypeSifMap, String format,
String selectedRepresentedBy, boolean isRestrict)
throws InputFileFormatException {
AdjacencyMatrix matrix = new AdjacencyMatrix(fileName, maSet,
interactionTypeSifMap);
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
// skip comments
if (line.trim().equals("") || line.startsWith(">")
|| line.startsWith("-"))
continue;
StringTokenizer tr = new StringTokenizer(line, "\t: :");
AdjacencyMatrix.Node node = token2node(tr.nextToken(), selectedRepresentedBy, isRestrict, maSet);
if(node==null) continue; // skip it when we don't have it
String interactionType = null;
if (format.equals(SIF_FORMART) && tr.hasMoreTokens())
interactionType = tr.nextToken().toLowerCase();
while (tr.hasMoreTokens()) {
String strGeneId2 = tr.nextToken();
AdjacencyMatrix.Node node2 = token2node(strGeneId2, selectedRepresentedBy, isRestrict, maSet);
if(node==null) continue; // skip it when we don't have it
float mi = 0.8f;
if (format.equals(ADJ_FORMART)) {
if (!tr.hasMoreTokens())
throw new InputFileFormatException(
"invalid format around " + strGeneId2);
mi = Float.parseFloat(tr.nextToken());
}
matrix.add(node, node2, mi, interactionType);
} // end of the token loop for one line
} // end of reading while loop
} catch (NumberFormatException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (FileNotFoundException ex3) {
throw new InputFileFormatException(ex3.getMessage());
} catch (IOException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (Exception e) {
throw new InputFileFormatException(e.getMessage());
}
return matrix;
}
| public static AdjacencyMatrix parseAdjacencyMatrix(String fileName,
final DSMicroarraySet maSet,
Map<String, String> interactionTypeSifMap, String format,
String selectedRepresentedBy, boolean isRestrict)
throws InputFileFormatException {
AdjacencyMatrix matrix = new AdjacencyMatrix(fileName, maSet,
interactionTypeSifMap);
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
// skip comments
if (line.trim().equals("") || line.startsWith(">")
|| line.startsWith("-"))
continue;
StringTokenizer tr = new StringTokenizer(line, "\t: :");
AdjacencyMatrix.Node node = token2node(tr.nextToken(), selectedRepresentedBy, isRestrict, maSet);
if(node==null) continue; // skip it when we don't have it
String interactionType = null;
if (format.equals(SIF_FORMART) && tr.hasMoreTokens())
interactionType = tr.nextToken().toLowerCase();
while (tr.hasMoreTokens()) {
String strGeneId2 = tr.nextToken();
AdjacencyMatrix.Node node2 = token2node(strGeneId2, selectedRepresentedBy, isRestrict, maSet);
if(node2==null) continue; // skip it when we don't have it
float mi = 0.8f;
if (format.equals(ADJ_FORMART)) {
if (!tr.hasMoreTokens())
throw new InputFileFormatException(
"invalid format around " + strGeneId2);
mi = Float.parseFloat(tr.nextToken());
}
matrix.add(node, node2, mi, interactionType);
} // end of the token loop for one line
} // end of reading while loop
} catch (NumberFormatException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (FileNotFoundException ex3) {
throw new InputFileFormatException(ex3.getMessage());
} catch (IOException ex) {
throw new InputFileFormatException(ex.getMessage());
} catch (Exception e) {
throw new InputFileFormatException(e.getMessage());
}
return matrix;
}
|
diff --git a/backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwGraphics.java b/backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwGraphics.java
index 46683b993..0927c502d 100644
--- a/backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwGraphics.java
+++ b/backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwGraphics.java
@@ -1,304 +1,306 @@
package com.badlogic.gdx.backends.jglfw;
import static com.badlogic.jglfw.Glfw.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.jglfw.gl.GL;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
/** An implementation of the {@link Graphics} interface based on GLFW.
* @author Nathan Sweet */
public class JglfwGraphics implements Graphics {
static int glMajorVersion, glMinorVersion;
JglfwApplicationConfiguration config;
long window;
boolean fullscreen;
int fullscreenMonitorIndex;
final BufferFormat bufferFormat;
volatile boolean isContinuous = true;
float deltaTime;
long frameStart, lastTime;
int frames, fps;
GLCommon gl;
JglfwGL10 gl10;
JglfwGL11 gl11;
JglfwGL20 gl20;
boolean sync;
boolean resize;
volatile boolean requestRendering;
public JglfwGraphics (JglfwApplicationConfiguration config) {
this.config = config;
bufferFormat = new BufferFormat(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.samples, false);
createWindow();
createGL();
}
private void createWindow () {
long fullscreenMonitor = glfwGetPrimaryMonitor();
long[] monitors = glfwGetMonitors();
// Find index of primary monitor.
for (int i = 0, n = monitors.length; i < n; i++) {
if (monitors[i] == fullscreenMonitor) {
fullscreenMonitorIndex = i;
break;
}
}
// Find monitor specified in config.
if (config.fullscreen) {
if (monitors.length > 0) {
if (config.fullscreenMonitorIndex < monitors.length) fullscreenMonitorIndex = config.fullscreenMonitorIndex;
fullscreenMonitor = monitors[fullscreenMonitorIndex];
}
}
// Create window.
if (!setDisplayMode(config.width, config.height, config.fullscreen)) {
throw new GdxRuntimeException("Unable to create window: " + config.width + "x" + config.height + ", fullscreen: "
+ config.fullscreen);
}
setVSync(config.vSync);
if (config.x != -1 && config.y != -1) glfwSetWindowPos(window, config.x, config.y);
}
private void createGL () {
String version = GL.glGetString(GL11.GL_VERSION);
glMajorVersion = Integer.parseInt("" + version.charAt(0));
glMinorVersion = Integer.parseInt("" + version.charAt(2));
if (config.useGL20 && (glMajorVersion >= 2 || version.contains("2.1"))) { // special case for MESA, wtf...
// FIXME - Add check for whether GL 2.0 is actually supported.
gl20 = new JglfwGL20();
gl = gl20;
} else {
gl20 = null;
if (glMajorVersion == 1 && glMinorVersion < 5) {
gl10 = new JglfwGL10();
} else {
gl11 = new JglfwGL11();
gl10 = gl11;
}
gl = gl10;
}
Gdx.gl = gl;
Gdx.gl10 = gl10;
Gdx.gl11 = gl11;
Gdx.gl20 = gl20;
}
public boolean isGL11Available () {
return gl11 != null;
}
public boolean isGL20Available () {
return gl20 != null;
}
public GLCommon getGLCommon () {
return gl;
}
public GL10 getGL10 () {
return gl10;
}
public GL11 getGL11 () {
return gl11;
}
public GL20 getGL20 () {
return gl20;
}
public int getWidth () {
return glfwGetWindowWidth(window);
}
public int getHeight () {
return glfwGetWindowHeight(window);
}
void updateTime () {
long time = System.nanoTime();
deltaTime = (time - lastTime) / 1000000000.0f;
lastTime = time;
if (time - frameStart >= 1000000000) {
fps = frames;
frames = 0;
frameStart = time;
}
frames++;
}
public float getDeltaTime () {
return deltaTime;
}
public float getRawDeltaTime () {
return deltaTime;
}
public int getFramesPerSecond () {
return fps;
}
public GraphicsType getType () {
return GraphicsType.JGLFW;
}
public float getPpiX () {
return Toolkit.getDefaultToolkit().getScreenResolution();
}
public float getPpiY () {
return Toolkit.getDefaultToolkit().getScreenResolution();
}
public float getPpcX () {
return Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f;
}
public float getPpcY () {
return Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f;
}
public float getDensity () {
return Toolkit.getDefaultToolkit().getScreenResolution() / 160f;
}
public boolean supportsDisplayModeChange () {
return true;
}
public DisplayMode[] getDisplayModes () {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
java.awt.DisplayMode desktopMode = device.getDisplayMode();
java.awt.DisplayMode[] displayModes = device.getDisplayModes();
Array<DisplayMode> modes = new Array();
outer:
for (java.awt.DisplayMode mode : displayModes) {
for (DisplayMode other : modes)
if (other.width == mode.getWidth() && other.height == mode.getHeight() && other.bitsPerPixel == mode.getBitDepth())
continue outer; // Duplicate.
if (mode.getBitDepth() != desktopMode.getBitDepth()) continue;
modes.add(new JglfwDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth()));
}
return modes.toArray(DisplayMode.class);
}
public DisplayMode getDesktopDisplayMode () {
java.awt.DisplayMode mode = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();
return new JglfwDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth());
}
public boolean setDisplayMode (DisplayMode displayMode) {
if (displayMode.bitsPerPixel != 0) glfwWindowHint(GLFW_DEPTH_BITS, displayMode.bitsPerPixel);
glfwSetWindowSize(window, displayMode.width, displayMode.height);
return true;
}
public boolean setDisplayMode (int width, int height, boolean fullscreen) {
if (window == 0 || fullscreen != config.fullscreen) {
long fullscreenMonitor = 0;
- long[] monitors = glfwGetMonitors();
- if (monitors.length > 0)
- fullscreenMonitor = fullscreenMonitorIndex < monitors.length ? monitors[fullscreenMonitorIndex] : 0;
+ if (fullscreen) {
+ long[] monitors = glfwGetMonitors();
+ if (monitors.length > 0)
+ fullscreenMonitor = fullscreenMonitorIndex < monitors.length ? monitors[fullscreenMonitorIndex] : 0;
+ }
// need to set the window hints every time we create a window, glfwCreateWindow resets them.
glfwWindowHint(GLFW_RESIZABLE, config.resizable ? 1 : 0);
glfwWindowHint(GLFW_RED_BITS, config.r);
glfwWindowHint(GLFW_GREEN_BITS, config.g);
glfwWindowHint(GLFW_BLUE_BITS, config.b);
glfwWindowHint(GLFW_ALPHA_BITS, config.a);
glfwWindowHint(GLFW_DEPTH_BITS, config.depth);
glfwWindowHint(GLFW_STENCIL_BITS, config.stencil);
glfwWindowHint(GLFW_SAMPLES, config.samples);
glfwWindowHint(GLFW_DEPTH_BITS, config.bitsPerPixel);
// share old window if any, so context service
- long window = glfwCreateWindow(config.width, config.height, config.title, 0, this.window);
+ long window = glfwCreateWindow(config.width, config.height, config.title, fullscreenMonitor, this.window);
if (window == 0) return false;
if (this.window != 0) glfwDestroyWindow(window);
glfwMakeContextCurrent(window);
this.window = window;
return true;
}
glfwSetWindowSize(window, width, height);
return true;
}
public void setTitle (String title) {
glfwSetWindowTitle(window, title);
}
public void setVSync (boolean vsync) {
this.sync = vsync;
glfwSwapInterval(vsync ? 1 : 0);
}
public BufferFormat getBufferFormat () {
return bufferFormat;
}
public boolean supportsExtension (String extension) {
return glfwExtensionSupported(extension);
}
public void setContinuousRendering (boolean isContinuous) {
this.isContinuous = isContinuous;
}
public boolean isContinuousRendering () {
return isContinuous;
}
public void requestRendering () {
synchronized (this) {
requestRendering = true;
}
}
public boolean isFullscreen () {
return config.fullscreen;
}
/** Returns the JGLFW window handle. Note this should not be stored externally as it may change if the window is recreated to
* enter/exit fullscreen. */
public long getWindow () {
return window;
}
boolean shouldRender () {
synchronized (this) {
boolean requestRendering = this.requestRendering;
this.requestRendering = false;
return requestRendering || isContinuous;
}
}
static class JglfwDisplayMode extends DisplayMode {
protected JglfwDisplayMode (int width, int height, int refreshRate, int bitsPerPixel) {
super(width, height, refreshRate, bitsPerPixel);
}
}
}
| false | true | public boolean setDisplayMode (int width, int height, boolean fullscreen) {
if (window == 0 || fullscreen != config.fullscreen) {
long fullscreenMonitor = 0;
long[] monitors = glfwGetMonitors();
if (monitors.length > 0)
fullscreenMonitor = fullscreenMonitorIndex < monitors.length ? monitors[fullscreenMonitorIndex] : 0;
// need to set the window hints every time we create a window, glfwCreateWindow resets them.
glfwWindowHint(GLFW_RESIZABLE, config.resizable ? 1 : 0);
glfwWindowHint(GLFW_RED_BITS, config.r);
glfwWindowHint(GLFW_GREEN_BITS, config.g);
glfwWindowHint(GLFW_BLUE_BITS, config.b);
glfwWindowHint(GLFW_ALPHA_BITS, config.a);
glfwWindowHint(GLFW_DEPTH_BITS, config.depth);
glfwWindowHint(GLFW_STENCIL_BITS, config.stencil);
glfwWindowHint(GLFW_SAMPLES, config.samples);
glfwWindowHint(GLFW_DEPTH_BITS, config.bitsPerPixel);
// share old window if any, so context service
long window = glfwCreateWindow(config.width, config.height, config.title, 0, this.window);
if (window == 0) return false;
if (this.window != 0) glfwDestroyWindow(window);
glfwMakeContextCurrent(window);
this.window = window;
return true;
}
glfwSetWindowSize(window, width, height);
return true;
}
| public boolean setDisplayMode (int width, int height, boolean fullscreen) {
if (window == 0 || fullscreen != config.fullscreen) {
long fullscreenMonitor = 0;
if (fullscreen) {
long[] monitors = glfwGetMonitors();
if (monitors.length > 0)
fullscreenMonitor = fullscreenMonitorIndex < monitors.length ? monitors[fullscreenMonitorIndex] : 0;
}
// need to set the window hints every time we create a window, glfwCreateWindow resets them.
glfwWindowHint(GLFW_RESIZABLE, config.resizable ? 1 : 0);
glfwWindowHint(GLFW_RED_BITS, config.r);
glfwWindowHint(GLFW_GREEN_BITS, config.g);
glfwWindowHint(GLFW_BLUE_BITS, config.b);
glfwWindowHint(GLFW_ALPHA_BITS, config.a);
glfwWindowHint(GLFW_DEPTH_BITS, config.depth);
glfwWindowHint(GLFW_STENCIL_BITS, config.stencil);
glfwWindowHint(GLFW_SAMPLES, config.samples);
glfwWindowHint(GLFW_DEPTH_BITS, config.bitsPerPixel);
// share old window if any, so context service
long window = glfwCreateWindow(config.width, config.height, config.title, fullscreenMonitor, this.window);
if (window == 0) return false;
if (this.window != 0) glfwDestroyWindow(window);
glfwMakeContextCurrent(window);
this.window = window;
return true;
}
glfwSetWindowSize(window, width, height);
return true;
}
|
diff --git a/src/com/ponderingpanda/protobuf/Message.java b/src/com/ponderingpanda/protobuf/Message.java
index a38c782..1b22bea 100644
--- a/src/com/ponderingpanda/protobuf/Message.java
+++ b/src/com/ponderingpanda/protobuf/Message.java
@@ -1,20 +1,20 @@
/*
* Copyright Copyright (c) 2010, Pondering Panda
* All rights reserved.
*
* See COPYING.txt for the complete copyright notice.
*
*/
package com.ponderingpanda.protobuf;
import java.io.IOException;
/**
*
* @author ralf
*/
public interface Message {
- public void serialize(CodedOutputStream out)throws IOException;
+ public void serialize(CodedOutputStream out) throws IOException;
public void deserialize(CodedInputStream in) throws IOException;
}
| true | true | public void serialize(CodedOutputStream out)throws IOException;
| public void serialize(CodedOutputStream out) throws IOException;
|
diff --git a/src/fixengine/messages/fix42/DefaultMessageFactory.java b/src/fixengine/messages/fix42/DefaultMessageFactory.java
index f6dc13a9..ced5f8fc 100644
--- a/src/fixengine/messages/fix42/DefaultMessageFactory.java
+++ b/src/fixengine/messages/fix42/DefaultMessageFactory.java
@@ -1,152 +1,152 @@
/*
* Copyright 2010 the original author or authors.
*
* 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 fixengine.messages.fix42;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang.CharUtils;
import fixengine.messages.Heartbeat;
import fixengine.messages.InvalidMsgTypeException;
import fixengine.messages.Logout;
import fixengine.messages.Message;
import fixengine.messages.MessageFactory;
import fixengine.messages.MessageHeader;
import fixengine.messages.MsgTypeValue;
import fixengine.messages.Reject;
import fixengine.messages.ResendRequest;
import fixengine.messages.SequenceReset;
import fixengine.messages.Tag;
import fixengine.messages.TestRequest;
import fixengine.messages.UnsupportedMsgTypeException;
import fixengine.messages.fix42.BusinessMessageReject;
import java.lang.reflect.Constructor;
public class DefaultMessageFactory implements MessageFactory {
private Map<String, Class<? extends Message>> messageTypes = new HashMap<String, Class<? extends Message>>();
public DefaultMessageFactory() {
message(MsgTypeValue.LOGON, Logon.class);
message(MsgTypeValue.LOGOUT, Logout.class);
message(MsgTypeValue.HEARTBEAT, Heartbeat.class);
message(MsgTypeValue.RESEND_REQUEST, ResendRequest.class);
message(MsgTypeValue.SEQUENCE_RESET, SequenceReset.class);
message(MsgTypeValue.TEST_REQUEST, TestRequest.class);
message(MsgTypeValue.REJECT, Reject.class);
message(MsgTypeValue.BUSINESS_MESSAGE_REJECT, BusinessMessageReject.class);
message(MsgTypeValue.EXECUTION_REPORT, ExecutionReport.class);
message(MsgTypeValue.ORDER_CANCEL_REJECT, OrderCancelReject.class);
message(MsgTypeValue.NEW_ORDER_SINGLE, NewOrderSingle.class);
- message(MsgTypeValue.ORDER_CANCEL_REQUEST, OrderCancelRequestMessage.class);
+ message(MsgTypeValue.ORDER_CANCEL_REQUEST, OrderCancelRequest.class);
message(MsgTypeValue.ORDER_MODIFICATION_REQUEST, OrderModificationRequestMessage.class);
message(MsgTypeValue.ORDER_STATUS_REQUEST, OrderStatusRequest.class);
message(MsgTypeValue.ALLOCATION_INSTRUCTION, Allocation.class);
}
@Override public Message create(String msgType) {
return create(msgType, new MessageHeader(msgType));
}
@Override public Message create(String msgType, MessageHeader header) {
if (!isValid(msgType))
throw new InvalidMsgTypeException("MsgType(35): Invalid message type: " + msgType);
if (!messageTypes.containsKey(msgType))
throw new UnsupportedMsgTypeException("MsgType(35): Unknown message type: " + msgType);
try {
return constructor(msgType).newInstance(header);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override public Tag<?> createTag(String tagName) {
try {
return (Tag<?>) tagClass(tagName).getMethod("Tag").invoke(null);
} catch (Exception e) {
throw new IllegalArgumentException("Tag not found: " + tagName);
}
}
@Override public String getProfile() {
return "default";
}
@SuppressWarnings("unchecked") private Class<Tag<?>> tagClass(String tagName) {
for (String tagsPackage : getTagsPackages()) {
try {
return (Class<Tag<?>>) Class.forName(tagsPackage + "." + tagName);
} catch (ClassNotFoundException e) {
}
}
throw new RuntimeException("Tag not found");
}
protected String getTagsPackage() {
return getClass().getPackage().getName();
}
protected void message(String msgType, Class<? extends Message> clazz) {
messageTypes.put(msgType, clazz);
}
private List<String> getTagsPackages() {
List<String> packages = new ArrayList<String>();
packages.add(getTagsPackage());
packages.add("fixengine.tags.fix42");
packages.add("fixengine.tags.fix43");
packages.add("fixengine.tags.fix44");
packages.add("fixengine.tags");
return packages;
}
private Constructor<? extends Message> constructor(String msgType) throws NoSuchMethodException {
return messageClass(msgType).getDeclaredConstructor(MessageHeader.class);
}
private Class<? extends Message> messageClass(String msgType) {
return messageTypes.get(msgType);
}
protected boolean isValid(String msgType) {
if (msgType.length() == 1) {
return isValidSingle(msgType);
} else if (msgType.length() == 2) {
return isValidWide(msgType);
}
return false;
}
private boolean isValidSingle(String msgType) {
char first = msgType.charAt(0);
return CharUtils.isAsciiAlphanumeric(first);
}
private boolean isValidWide(String msgType) {
char first = msgType.charAt(0);
if (first != 'A')
return false;
char second = msgType.charAt(1);
if (!CharUtils.isAsciiAlphaUpper(second))
return false;
return second >= 'A' && second <= 'I';
}
}
| true | true | public DefaultMessageFactory() {
message(MsgTypeValue.LOGON, Logon.class);
message(MsgTypeValue.LOGOUT, Logout.class);
message(MsgTypeValue.HEARTBEAT, Heartbeat.class);
message(MsgTypeValue.RESEND_REQUEST, ResendRequest.class);
message(MsgTypeValue.SEQUENCE_RESET, SequenceReset.class);
message(MsgTypeValue.TEST_REQUEST, TestRequest.class);
message(MsgTypeValue.REJECT, Reject.class);
message(MsgTypeValue.BUSINESS_MESSAGE_REJECT, BusinessMessageReject.class);
message(MsgTypeValue.EXECUTION_REPORT, ExecutionReport.class);
message(MsgTypeValue.ORDER_CANCEL_REJECT, OrderCancelReject.class);
message(MsgTypeValue.NEW_ORDER_SINGLE, NewOrderSingle.class);
message(MsgTypeValue.ORDER_CANCEL_REQUEST, OrderCancelRequestMessage.class);
message(MsgTypeValue.ORDER_MODIFICATION_REQUEST, OrderModificationRequestMessage.class);
message(MsgTypeValue.ORDER_STATUS_REQUEST, OrderStatusRequest.class);
message(MsgTypeValue.ALLOCATION_INSTRUCTION, Allocation.class);
}
| public DefaultMessageFactory() {
message(MsgTypeValue.LOGON, Logon.class);
message(MsgTypeValue.LOGOUT, Logout.class);
message(MsgTypeValue.HEARTBEAT, Heartbeat.class);
message(MsgTypeValue.RESEND_REQUEST, ResendRequest.class);
message(MsgTypeValue.SEQUENCE_RESET, SequenceReset.class);
message(MsgTypeValue.TEST_REQUEST, TestRequest.class);
message(MsgTypeValue.REJECT, Reject.class);
message(MsgTypeValue.BUSINESS_MESSAGE_REJECT, BusinessMessageReject.class);
message(MsgTypeValue.EXECUTION_REPORT, ExecutionReport.class);
message(MsgTypeValue.ORDER_CANCEL_REJECT, OrderCancelReject.class);
message(MsgTypeValue.NEW_ORDER_SINGLE, NewOrderSingle.class);
message(MsgTypeValue.ORDER_CANCEL_REQUEST, OrderCancelRequest.class);
message(MsgTypeValue.ORDER_MODIFICATION_REQUEST, OrderModificationRequestMessage.class);
message(MsgTypeValue.ORDER_STATUS_REQUEST, OrderStatusRequest.class);
message(MsgTypeValue.ALLOCATION_INSTRUCTION, Allocation.class);
}
|
diff --git a/Model/test/java/fr/cg95/cvq/external/FakeExternalServiceTest.java b/Model/test/java/fr/cg95/cvq/external/FakeExternalServiceTest.java
index d367d1001..b1301b410 100644
--- a/Model/test/java/fr/cg95/cvq/external/FakeExternalServiceTest.java
+++ b/Model/test/java/fr/cg95/cvq/external/FakeExternalServiceTest.java
@@ -1,175 +1,175 @@
package fr.cg95.cvq.external;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.Assert;
import fr.cg95.cvq.business.users.CreationBean;
import fr.cg95.cvq.business.users.HomeFolder;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.payment.ExternalAccountItem;
import fr.cg95.cvq.business.users.payment.ExternalDepositAccountItem;
import fr.cg95.cvq.business.users.payment.ExternalDepositAccountItemDetail;
import fr.cg95.cvq.business.users.payment.ExternalInvoiceItem;
import fr.cg95.cvq.business.users.payment.ExternalInvoiceItemDetail;
import fr.cg95.cvq.business.users.payment.ExternalTicketingContractItem;
import fr.cg95.cvq.business.users.payment.PurchaseItem;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.payment.IPaymentService;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.service.authority.LocalAuthorityConfigurationBean;
import fr.cg95.cvq.service.request.ecitizen.IVoCardRequestService;
import fr.cg95.cvq.testtool.ServiceTestCase;
public class FakeExternalServiceTest extends ServiceTestCase {
private IExternalProviderService fakeExternalService;
public void onSetUp() throws Exception {
super.onSetUp();
fakeExternalService = (IExternalProviderService) getBean("fakeExternalService");
}
public void testContracts() throws CvqException {
// create a vo card request (to create home folder and associates)
// ////////////////////////////////////////////////////////////////
SecurityContext.setCurrentSite(localAuthorityName,
SecurityContext.FRONT_OFFICE_CONTEXT);
// create a vo card request (to create home folder and associates)
CreationBean cb = gimmeAnHomeFolder();
String proposedLogin = cb.getLogin();
SecurityContext.setCurrentEcitizen(proposedLogin);
// get the home folder id
HomeFolder homeFolder = iHomeFolderService.getById(cb.getHomeFolderId());
Long homeFolderId = homeFolder.getId();
// register the mock external provider service with the LACB
ExternalServiceBean esb = new ExternalServiceBean();
List<String> requestTypes = new ArrayList<String>();
requestTypes.add(IVoCardRequestService.VO_CARD_REGISTRATION_REQUEST);
esb.setRequestTypes(requestTypes);
esb.setSupportAccountsByHomeFolder(true);
LocalAuthorityConfigurationBean lacb = SecurityContext.getCurrentConfigurationBean();
lacb.registerExternalService(fakeExternalService, esb);
// retrieve all external accounts directly from fake external service
Map<String, List<ExternalAccountItem>> completeAccount =
fakeExternalService.getAccountsByHomeFolder(homeFolderId, null, null);
if (completeAccount == null) {
logger.debug("testContracts() no contract found for home folder : " + homeFolderId);
return;
}
List<ExternalAccountItem> ticketingAccounts =
completeAccount.get(IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, ticketingAccounts.size());
for (ExternalAccountItem eai : ticketingAccounts) {
ExternalTicketingContractItem etci = (ExternalTicketingContractItem) eai;
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// retrieve external ticketing accounts from home folder service
Set<ExternalAccountItem> externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, externalAccounts.size());
ExternalTicketingContractItem etciToPayOn = null;
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalTicketingContractItem etci =
(ExternalTicketingContractItem) externalAccountItem;
if (etciToPayOn == null)
etciToPayOn = etci;
Assert.assertNotNull(etci.getExternalServiceSpecificDataByKey("child-csn"));
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// make a payment on choosen ticketing contract
Collection<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>();
etciToPayOn.setQuantity(Integer.valueOf(5));
etciToPayOn.setAmount(etciToPayOn.getQuantity() * etciToPayOn.getUnitPrice());
purchaseItems.add(etciToPayOn);
fakeExternalService.creditHomeFolderAccounts(purchaseItems, "cvqReference",
"bankReference", homeFolderId, null, null, new Date());
// retrieve external deposit accounts from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_DEPOSIT_ACCOUNTS);
Assert.assertEquals(2, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalDepositAccountItem edai =
(ExternalDepositAccountItem) externalAccountItem;
logger.debug(edai.getFriendlyLabel());
logger.debug(edai.getInformativeFriendlyLabel());
logger.debug(edai.getExternalItemId());
if (edai.getExternalItemId().equals("95999-3-1910782193")) {
iHomeFolderService.loadExternalDepositAccountDetails(edai);
Assert.assertEquals(2, edai.getAccountDetails().size());
boolean foundCheque = false;
for (ExternalDepositAccountItemDetail edaiDetail : edai.getAccountDetails()) {
Assert.assertEquals("TOULOUSE", edaiDetail.getHolderSurname());
Assert.assertEquals("roger", edaiDetail.getHolderName());
if (edaiDetail.getPaymentType().equals("Chèque")) {
foundCheque = true;
Assert.assertEquals(20345, edaiDetail.getValue().intValue());
Assert.assertEquals("0101566442", edaiDetail.getPaymentId());
}
}
if (!foundCheque)
fail("did not find cheque payment !");
}
}
// retrieve external invoices from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_INVOICES);
Assert.assertEquals(4, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalInvoiceItem eii =
(ExternalInvoiceItem) externalAccountItem;
if (eii.getExternalItemId().equals("95999-3-1910782195")) {
- Assert.assertEquals(Boolean.TRUE, eii.isPaid());
+ Assert.assertEquals(Boolean.FALSE, eii.isPaid());
iHomeFolderService.loadExternalInvoiceDetails(eii);
Assert.assertEquals(2, eii.getInvoiceDetails().size());
boolean foundLolita = false;
for (ExternalInvoiceItemDetail eiiDetail : eii.getInvoiceDetails()) {
Assert.assertEquals("TOULOUSE", eiiDetail.getSubjectSurname());
if (eiiDetail.getSubjectName().equals("Lolita")) {
foundLolita = true;
Assert.assertEquals("Repas restauration scolaire", eiiDetail.getLabel());
Assert.assertEquals(2300, eiiDetail.getUnitPrice().intValue());
Assert.assertEquals(2, eiiDetail.getQuantity().intValue());
Assert.assertEquals(4600, eiiDetail.getValue().intValue());
}
}
if (!foundLolita)
fail("did not find Lolita !");
}
}
// retrieve individuals information on external accounts
Map<Individual, Map<String, String> > individualsInformation =
iHomeFolderService.getIndividualExternalAccountsInformation(homeFolderId);
Assert.assertEquals(individualsInformation.size(), 2);
Map<String, String> individualInformation =
individualsInformation.values().iterator().next();
Assert.assertEquals(individualInformation.size(), 1);
String key = individualInformation.keySet().iterator().next();
Assert.assertEquals(key, "child-csn");
String value = individualInformation.get(key);
Assert.assertNotNull(value);
}
}
| true | true | public void testContracts() throws CvqException {
// create a vo card request (to create home folder and associates)
// ////////////////////////////////////////////////////////////////
SecurityContext.setCurrentSite(localAuthorityName,
SecurityContext.FRONT_OFFICE_CONTEXT);
// create a vo card request (to create home folder and associates)
CreationBean cb = gimmeAnHomeFolder();
String proposedLogin = cb.getLogin();
SecurityContext.setCurrentEcitizen(proposedLogin);
// get the home folder id
HomeFolder homeFolder = iHomeFolderService.getById(cb.getHomeFolderId());
Long homeFolderId = homeFolder.getId();
// register the mock external provider service with the LACB
ExternalServiceBean esb = new ExternalServiceBean();
List<String> requestTypes = new ArrayList<String>();
requestTypes.add(IVoCardRequestService.VO_CARD_REGISTRATION_REQUEST);
esb.setRequestTypes(requestTypes);
esb.setSupportAccountsByHomeFolder(true);
LocalAuthorityConfigurationBean lacb = SecurityContext.getCurrentConfigurationBean();
lacb.registerExternalService(fakeExternalService, esb);
// retrieve all external accounts directly from fake external service
Map<String, List<ExternalAccountItem>> completeAccount =
fakeExternalService.getAccountsByHomeFolder(homeFolderId, null, null);
if (completeAccount == null) {
logger.debug("testContracts() no contract found for home folder : " + homeFolderId);
return;
}
List<ExternalAccountItem> ticketingAccounts =
completeAccount.get(IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, ticketingAccounts.size());
for (ExternalAccountItem eai : ticketingAccounts) {
ExternalTicketingContractItem etci = (ExternalTicketingContractItem) eai;
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// retrieve external ticketing accounts from home folder service
Set<ExternalAccountItem> externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, externalAccounts.size());
ExternalTicketingContractItem etciToPayOn = null;
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalTicketingContractItem etci =
(ExternalTicketingContractItem) externalAccountItem;
if (etciToPayOn == null)
etciToPayOn = etci;
Assert.assertNotNull(etci.getExternalServiceSpecificDataByKey("child-csn"));
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// make a payment on choosen ticketing contract
Collection<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>();
etciToPayOn.setQuantity(Integer.valueOf(5));
etciToPayOn.setAmount(etciToPayOn.getQuantity() * etciToPayOn.getUnitPrice());
purchaseItems.add(etciToPayOn);
fakeExternalService.creditHomeFolderAccounts(purchaseItems, "cvqReference",
"bankReference", homeFolderId, null, null, new Date());
// retrieve external deposit accounts from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_DEPOSIT_ACCOUNTS);
Assert.assertEquals(2, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalDepositAccountItem edai =
(ExternalDepositAccountItem) externalAccountItem;
logger.debug(edai.getFriendlyLabel());
logger.debug(edai.getInformativeFriendlyLabel());
logger.debug(edai.getExternalItemId());
if (edai.getExternalItemId().equals("95999-3-1910782193")) {
iHomeFolderService.loadExternalDepositAccountDetails(edai);
Assert.assertEquals(2, edai.getAccountDetails().size());
boolean foundCheque = false;
for (ExternalDepositAccountItemDetail edaiDetail : edai.getAccountDetails()) {
Assert.assertEquals("TOULOUSE", edaiDetail.getHolderSurname());
Assert.assertEquals("roger", edaiDetail.getHolderName());
if (edaiDetail.getPaymentType().equals("Chèque")) {
foundCheque = true;
Assert.assertEquals(20345, edaiDetail.getValue().intValue());
Assert.assertEquals("0101566442", edaiDetail.getPaymentId());
}
}
if (!foundCheque)
fail("did not find cheque payment !");
}
}
// retrieve external invoices from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_INVOICES);
Assert.assertEquals(4, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalInvoiceItem eii =
(ExternalInvoiceItem) externalAccountItem;
if (eii.getExternalItemId().equals("95999-3-1910782195")) {
Assert.assertEquals(Boolean.TRUE, eii.isPaid());
iHomeFolderService.loadExternalInvoiceDetails(eii);
Assert.assertEquals(2, eii.getInvoiceDetails().size());
boolean foundLolita = false;
for (ExternalInvoiceItemDetail eiiDetail : eii.getInvoiceDetails()) {
Assert.assertEquals("TOULOUSE", eiiDetail.getSubjectSurname());
if (eiiDetail.getSubjectName().equals("Lolita")) {
foundLolita = true;
Assert.assertEquals("Repas restauration scolaire", eiiDetail.getLabel());
Assert.assertEquals(2300, eiiDetail.getUnitPrice().intValue());
Assert.assertEquals(2, eiiDetail.getQuantity().intValue());
Assert.assertEquals(4600, eiiDetail.getValue().intValue());
}
}
if (!foundLolita)
fail("did not find Lolita !");
}
}
// retrieve individuals information on external accounts
Map<Individual, Map<String, String> > individualsInformation =
iHomeFolderService.getIndividualExternalAccountsInformation(homeFolderId);
Assert.assertEquals(individualsInformation.size(), 2);
Map<String, String> individualInformation =
individualsInformation.values().iterator().next();
Assert.assertEquals(individualInformation.size(), 1);
String key = individualInformation.keySet().iterator().next();
Assert.assertEquals(key, "child-csn");
String value = individualInformation.get(key);
Assert.assertNotNull(value);
}
| public void testContracts() throws CvqException {
// create a vo card request (to create home folder and associates)
// ////////////////////////////////////////////////////////////////
SecurityContext.setCurrentSite(localAuthorityName,
SecurityContext.FRONT_OFFICE_CONTEXT);
// create a vo card request (to create home folder and associates)
CreationBean cb = gimmeAnHomeFolder();
String proposedLogin = cb.getLogin();
SecurityContext.setCurrentEcitizen(proposedLogin);
// get the home folder id
HomeFolder homeFolder = iHomeFolderService.getById(cb.getHomeFolderId());
Long homeFolderId = homeFolder.getId();
// register the mock external provider service with the LACB
ExternalServiceBean esb = new ExternalServiceBean();
List<String> requestTypes = new ArrayList<String>();
requestTypes.add(IVoCardRequestService.VO_CARD_REGISTRATION_REQUEST);
esb.setRequestTypes(requestTypes);
esb.setSupportAccountsByHomeFolder(true);
LocalAuthorityConfigurationBean lacb = SecurityContext.getCurrentConfigurationBean();
lacb.registerExternalService(fakeExternalService, esb);
// retrieve all external accounts directly from fake external service
Map<String, List<ExternalAccountItem>> completeAccount =
fakeExternalService.getAccountsByHomeFolder(homeFolderId, null, null);
if (completeAccount == null) {
logger.debug("testContracts() no contract found for home folder : " + homeFolderId);
return;
}
List<ExternalAccountItem> ticketingAccounts =
completeAccount.get(IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, ticketingAccounts.size());
for (ExternalAccountItem eai : ticketingAccounts) {
ExternalTicketingContractItem etci = (ExternalTicketingContractItem) eai;
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// retrieve external ticketing accounts from home folder service
Set<ExternalAccountItem> externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_TICKETING_ACCOUNTS);
Assert.assertEquals(16, externalAccounts.size());
ExternalTicketingContractItem etciToPayOn = null;
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalTicketingContractItem etci =
(ExternalTicketingContractItem) externalAccountItem;
if (etciToPayOn == null)
etciToPayOn = etci;
Assert.assertNotNull(etci.getExternalServiceSpecificDataByKey("child-csn"));
logger.debug(etci.getFriendlyLabel());
logger.debug(etci.getInformativeFriendlyLabel());
}
// make a payment on choosen ticketing contract
Collection<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>();
etciToPayOn.setQuantity(Integer.valueOf(5));
etciToPayOn.setAmount(etciToPayOn.getQuantity() * etciToPayOn.getUnitPrice());
purchaseItems.add(etciToPayOn);
fakeExternalService.creditHomeFolderAccounts(purchaseItems, "cvqReference",
"bankReference", homeFolderId, null, null, new Date());
// retrieve external deposit accounts from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_DEPOSIT_ACCOUNTS);
Assert.assertEquals(2, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalDepositAccountItem edai =
(ExternalDepositAccountItem) externalAccountItem;
logger.debug(edai.getFriendlyLabel());
logger.debug(edai.getInformativeFriendlyLabel());
logger.debug(edai.getExternalItemId());
if (edai.getExternalItemId().equals("95999-3-1910782193")) {
iHomeFolderService.loadExternalDepositAccountDetails(edai);
Assert.assertEquals(2, edai.getAccountDetails().size());
boolean foundCheque = false;
for (ExternalDepositAccountItemDetail edaiDetail : edai.getAccountDetails()) {
Assert.assertEquals("TOULOUSE", edaiDetail.getHolderSurname());
Assert.assertEquals("roger", edaiDetail.getHolderName());
if (edaiDetail.getPaymentType().equals("Chèque")) {
foundCheque = true;
Assert.assertEquals(20345, edaiDetail.getValue().intValue());
Assert.assertEquals("0101566442", edaiDetail.getPaymentId());
}
}
if (!foundCheque)
fail("did not find cheque payment !");
}
}
// retrieve external invoices from home folder service
externalAccounts =
iHomeFolderService.getExternalAccounts(homeFolderId,
IPaymentService.EXTERNAL_INVOICES);
Assert.assertEquals(4, externalAccounts.size());
for (ExternalAccountItem externalAccountItem : externalAccounts) {
ExternalInvoiceItem eii =
(ExternalInvoiceItem) externalAccountItem;
if (eii.getExternalItemId().equals("95999-3-1910782195")) {
Assert.assertEquals(Boolean.FALSE, eii.isPaid());
iHomeFolderService.loadExternalInvoiceDetails(eii);
Assert.assertEquals(2, eii.getInvoiceDetails().size());
boolean foundLolita = false;
for (ExternalInvoiceItemDetail eiiDetail : eii.getInvoiceDetails()) {
Assert.assertEquals("TOULOUSE", eiiDetail.getSubjectSurname());
if (eiiDetail.getSubjectName().equals("Lolita")) {
foundLolita = true;
Assert.assertEquals("Repas restauration scolaire", eiiDetail.getLabel());
Assert.assertEquals(2300, eiiDetail.getUnitPrice().intValue());
Assert.assertEquals(2, eiiDetail.getQuantity().intValue());
Assert.assertEquals(4600, eiiDetail.getValue().intValue());
}
}
if (!foundLolita)
fail("did not find Lolita !");
}
}
// retrieve individuals information on external accounts
Map<Individual, Map<String, String> > individualsInformation =
iHomeFolderService.getIndividualExternalAccountsInformation(homeFolderId);
Assert.assertEquals(individualsInformation.size(), 2);
Map<String, String> individualInformation =
individualsInformation.values().iterator().next();
Assert.assertEquals(individualInformation.size(), 1);
String key = individualInformation.keySet().iterator().next();
Assert.assertEquals(key, "child-csn");
String value = individualInformation.get(key);
Assert.assertNotNull(value);
}
|
diff --git a/src/main/java/org/jenkinsci/plugins/xunit/service/XUnitConversionService.java b/src/main/java/org/jenkinsci/plugins/xunit/service/XUnitConversionService.java
index 199a8b7..6e04b91 100644
--- a/src/main/java/org/jenkinsci/plugins/xunit/service/XUnitConversionService.java
+++ b/src/main/java/org/jenkinsci/plugins/xunit/service/XUnitConversionService.java
@@ -1,125 +1,125 @@
package org.jenkinsci.plugins.xunit.service;
import com.google.inject.Inject;
import com.thalesgroup.dtkit.metrics.model.InputMetric;
import com.thalesgroup.dtkit.metrics.model.InputMetricXSL;
import com.thalesgroup.dtkit.util.converter.ConversionException;
import hudson.FilePath;
import org.jenkinsci.plugins.xunit.exception.XUnitException;
import org.jenkinsci.plugins.xunit.types.CustomInputMetric;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
public class XUnitConversionService extends XUnitService implements Serializable {
private XUnitLog xUnitLog;
@Inject
@SuppressWarnings("unused")
void load(XUnitLog xUnitLog) {
this.xUnitLog = xUnitLog;
}
/**
* Converts the inputFile into a JUnit output file
*
* @param xUnitToolInfo the xUnit info wrapper object
* @param inputFile the input file to be converted
* @param workspace the workspace
* @param junitOutputDirectory the output parent directory that contains the JUnit output file
* @return the converted file
* @throws org.jenkinsci.plugins.xunit.exception.XUnitException
* an XUnitException is thrown if there is a conversion error.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public File convert(XUnitToolInfo xUnitToolInfo, File inputFile, File workspace, File junitOutputDirectory) throws XUnitException {
InputMetric inputMetric = xUnitToolInfo.getInputMetric();
final String JUNIT_FILE_POSTFIX = ".xml";
final String JUNIT_FILE_PREFIX = "TEST-";
File parent = new File(junitOutputDirectory, inputMetric.getToolName());
- if (!parent.mkdirs()) {
+ if (!parent.exists() && !parent.mkdirs()) {
throw new XUnitException("Can't create " + parent);
}
File junitTargetFile = new File(parent, JUNIT_FILE_PREFIX + inputFile.hashCode() + JUNIT_FILE_POSTFIX);
infoSystemLogger("Converting '" + inputFile + "' .");
try {
if (inputMetric instanceof CustomInputMetric) {
return convertCustomInputMetric(xUnitToolInfo, inputFile, workspace, inputMetric, junitTargetFile);
}
if (inputMetric instanceof InputMetricXSL) {
return convertInputMetricXSL(xUnitToolInfo, inputFile, inputMetric, junitTargetFile);
}
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
} catch (ConversionException ce) {
throw new XUnitException("Conversion error " + ce.getMessage(), ce);
} catch (InterruptedException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
} catch (IOException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
}
}
private File convertCustomInputMetric(XUnitToolInfo xUnitToolInfo, File inputFile, File workspace, InputMetric inputMetric, File junitTargetFile) throws IOException, InterruptedException, XUnitException {
CustomInputMetric customInputMetric = (CustomInputMetric) inputMetric;
customInputMetric.setCustomXSLFile(new File(xUnitToolInfo.getCusXSLFile().getRemote()));
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
}
private File convertInputMetricXSL(XUnitToolInfo xUnitToolInfo, File inputFile, InputMetric inputMetric, File junitTargetFile) throws IOException, InterruptedException {
InputMetricXSL inputMetricXSL = (InputMetricXSL) inputMetric;
FilePath userXSLFilePath = xUnitToolInfo.getUserContentRoot().child(inputMetricXSL.getUserContentXSLDirRelativePath());
if (userXSLFilePath.exists()) {
xUnitLog.infoConsoleLogger("Using the native embedded stylesheet in JENKINS_HOME.");
try {
return convertInputMetricXSLWithUserXSL(inputFile, junitTargetFile, inputMetricXSL, userXSLFilePath);
} catch (XUnitException xe) {
xUnitLog.errorConsoleLogger("Error occurs on the use of the user stylesheet: " + xe.getMessage());
xUnitLog.infoConsoleLogger("Trying to use the native embedded stylesheet.");
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
}
}
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
}
private File convertInputMetricXSLWithUserXSL(File inputFile, File junitTargetFile, InputMetricXSL inputMetricXSL, FilePath userXSLFilePath) throws XUnitException {
try {
List<FilePath> filePathList = userXSLFilePath.list();
if (filePathList.isEmpty()) {
throw new XUnitException(String.format("There are no XSLs in '%s'", userXSLFilePath.getRemote()));
}
for (FilePath file : userXSLFilePath.list()) {
if (!file.isDirectory()) {
inputMetricXSL.convert(inputFile, junitTargetFile, file.readToString(), null);
return junitTargetFile;
}
}
throw new XUnitException(String.format("There are no XSLs in '%s'", userXSLFilePath.getRemote()));
} catch (IOException e) {
throw new XUnitException("Error in the use of the user stylesheet", e);
} catch (InterruptedException e) {
throw new XUnitException("Error in the use of the user stylesheet", e);
}
}
}
| true | true | public File convert(XUnitToolInfo xUnitToolInfo, File inputFile, File workspace, File junitOutputDirectory) throws XUnitException {
InputMetric inputMetric = xUnitToolInfo.getInputMetric();
final String JUNIT_FILE_POSTFIX = ".xml";
final String JUNIT_FILE_PREFIX = "TEST-";
File parent = new File(junitOutputDirectory, inputMetric.getToolName());
if (!parent.mkdirs()) {
throw new XUnitException("Can't create " + parent);
}
File junitTargetFile = new File(parent, JUNIT_FILE_PREFIX + inputFile.hashCode() + JUNIT_FILE_POSTFIX);
infoSystemLogger("Converting '" + inputFile + "' .");
try {
if (inputMetric instanceof CustomInputMetric) {
return convertCustomInputMetric(xUnitToolInfo, inputFile, workspace, inputMetric, junitTargetFile);
}
if (inputMetric instanceof InputMetricXSL) {
return convertInputMetricXSL(xUnitToolInfo, inputFile, inputMetric, junitTargetFile);
}
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
} catch (ConversionException ce) {
throw new XUnitException("Conversion error " + ce.getMessage(), ce);
} catch (InterruptedException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
} catch (IOException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
}
}
| public File convert(XUnitToolInfo xUnitToolInfo, File inputFile, File workspace, File junitOutputDirectory) throws XUnitException {
InputMetric inputMetric = xUnitToolInfo.getInputMetric();
final String JUNIT_FILE_POSTFIX = ".xml";
final String JUNIT_FILE_PREFIX = "TEST-";
File parent = new File(junitOutputDirectory, inputMetric.getToolName());
if (!parent.exists() && !parent.mkdirs()) {
throw new XUnitException("Can't create " + parent);
}
File junitTargetFile = new File(parent, JUNIT_FILE_PREFIX + inputFile.hashCode() + JUNIT_FILE_POSTFIX);
infoSystemLogger("Converting '" + inputFile + "' .");
try {
if (inputMetric instanceof CustomInputMetric) {
return convertCustomInputMetric(xUnitToolInfo, inputFile, workspace, inputMetric, junitTargetFile);
}
if (inputMetric instanceof InputMetricXSL) {
return convertInputMetricXSL(xUnitToolInfo, inputFile, inputMetric, junitTargetFile);
}
inputMetric.convert(inputFile, junitTargetFile);
return junitTargetFile;
} catch (ConversionException ce) {
throw new XUnitException("Conversion error " + ce.getMessage(), ce);
} catch (InterruptedException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
} catch (IOException ie) {
throw new XUnitException("Conversion error " + ie.getMessage(), ie);
}
}
|
diff --git a/araqne-log-api/src/main/java/org/araqne/log/api/CsvParser.java b/araqne-log-api/src/main/java/org/araqne/log/api/CsvParser.java
index 3def9dcb..1bcae0e4 100644
--- a/araqne-log-api/src/main/java/org/araqne/log/api/CsvParser.java
+++ b/araqne-log-api/src/main/java/org/araqne/log/api/CsvParser.java
@@ -1,122 +1,124 @@
package org.araqne.log.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CsvParser {
private final char qoute = '"';
private char delimiter;
private char escape;
private ArrayList<String> cachedColumnHeaders = new ArrayList<String>();
public CsvParser(boolean useTab, boolean useDoubleQuote, String[] columnHeaders) {
this.delimiter = ',';
if (useTab)
this.delimiter = '\t';
this.escape = '\\';
if (useDoubleQuote)
this.escape = '"';
if (columnHeaders != null)
for (String header : columnHeaders)
cachedColumnHeaders.add(header);
}
public Map<String, Object> parse(String line) {
boolean containEscape = false;
boolean openQuote = false;
boolean openChar = false;
int startIndex = 0;
int endIndex = 0;
int length = line.length();
List<String> values = new ArrayList<String>();
for (int i = 0; i < length; i++) {
char c = line.charAt(i);
if (c == escape) {
if (!containEscape)
containEscape = true;
if (!openQuote && !openChar) {
openChar = true;
startIndex = i;
}
i++;
if (openChar)
endIndex = i + 1;
} else if (c == qoute) {
if (!openQuote)
startIndex = i + 1;
else
endIndex = i;
openQuote = !openQuote;
} else if (c == delimiter) {
String value = line.substring(startIndex, endIndex);
if (containEscape) {
value = removeEscape(value, escape);
containEscape = false;
}
values.add(value);
+ startIndex = i + 1;
+ endIndex = i + 1;
openChar = false;
} else {
if (!openQuote && !openChar) {
startIndex = i;
openChar = true;
}
if (openChar)
endIndex = i + 1;
}
}
if (endIndex > length)
throw new IllegalArgumentException("invalid csv parse option. delimiter [" + delimiter + "], escape [" + escape
+ "], line [" + line + "]");
String value = line.substring(startIndex, endIndex);
if (containEscape)
value = removeEscape(value, escape);
values.add(value);
return toMap(values);
}
private Map<String, Object> toMap(List<String> values) {
Map<String, Object> m = new HashMap<String, Object>(values.size());
int i = 0;
for (String value : values) {
String header = null;
try {
header = cachedColumnHeaders.get(i);
} catch (IndexOutOfBoundsException e) {
header = "column" + i;
cachedColumnHeaders.add(header);
}
m.put(header, value);
i++;
}
return m;
}
private String removeEscape(String value, char escape) {
StringBuilder sb = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == escape) {
sb.append(value.charAt(++i));
continue;
}
sb.append(c);
}
return sb.toString();
}
}
| true | true | public Map<String, Object> parse(String line) {
boolean containEscape = false;
boolean openQuote = false;
boolean openChar = false;
int startIndex = 0;
int endIndex = 0;
int length = line.length();
List<String> values = new ArrayList<String>();
for (int i = 0; i < length; i++) {
char c = line.charAt(i);
if (c == escape) {
if (!containEscape)
containEscape = true;
if (!openQuote && !openChar) {
openChar = true;
startIndex = i;
}
i++;
if (openChar)
endIndex = i + 1;
} else if (c == qoute) {
if (!openQuote)
startIndex = i + 1;
else
endIndex = i;
openQuote = !openQuote;
} else if (c == delimiter) {
String value = line.substring(startIndex, endIndex);
if (containEscape) {
value = removeEscape(value, escape);
containEscape = false;
}
values.add(value);
openChar = false;
} else {
if (!openQuote && !openChar) {
startIndex = i;
openChar = true;
}
if (openChar)
endIndex = i + 1;
}
}
if (endIndex > length)
throw new IllegalArgumentException("invalid csv parse option. delimiter [" + delimiter + "], escape [" + escape
+ "], line [" + line + "]");
String value = line.substring(startIndex, endIndex);
if (containEscape)
value = removeEscape(value, escape);
values.add(value);
return toMap(values);
}
| public Map<String, Object> parse(String line) {
boolean containEscape = false;
boolean openQuote = false;
boolean openChar = false;
int startIndex = 0;
int endIndex = 0;
int length = line.length();
List<String> values = new ArrayList<String>();
for (int i = 0; i < length; i++) {
char c = line.charAt(i);
if (c == escape) {
if (!containEscape)
containEscape = true;
if (!openQuote && !openChar) {
openChar = true;
startIndex = i;
}
i++;
if (openChar)
endIndex = i + 1;
} else if (c == qoute) {
if (!openQuote)
startIndex = i + 1;
else
endIndex = i;
openQuote = !openQuote;
} else if (c == delimiter) {
String value = line.substring(startIndex, endIndex);
if (containEscape) {
value = removeEscape(value, escape);
containEscape = false;
}
values.add(value);
startIndex = i + 1;
endIndex = i + 1;
openChar = false;
} else {
if (!openQuote && !openChar) {
startIndex = i;
openChar = true;
}
if (openChar)
endIndex = i + 1;
}
}
if (endIndex > length)
throw new IllegalArgumentException("invalid csv parse option. delimiter [" + delimiter + "], escape [" + escape
+ "], line [" + line + "]");
String value = line.substring(startIndex, endIndex);
if (containEscape)
value = removeEscape(value, escape);
values.add(value);
return toMap(values);
}
|
diff --git a/src/integration/java/com/orgsync/api/integration/CheckbooksIntegrationTest.java b/src/integration/java/com/orgsync/api/integration/CheckbooksIntegrationTest.java
index 49ac7ea..360f7be 100644
--- a/src/integration/java/com/orgsync/api/integration/CheckbooksIntegrationTest.java
+++ b/src/integration/java/com/orgsync/api/integration/CheckbooksIntegrationTest.java
@@ -1,137 +1,137 @@
package com.orgsync.api.integration;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Test;
import com.orgsync.api.ApiResponse;
import com.orgsync.api.CheckbooksResource;
import com.orgsync.api.Resources;
import com.orgsync.api.model.Success;
import com.orgsync.api.model.checkbooks.Checkbook;
import com.orgsync.api.model.checkbooks.CheckbookEntry;
import com.typesafe.config.Config;
public class CheckbooksIntegrationTest extends BaseIntegrationTest<CheckbooksResource> {
private static final Config portalConfig = DbTemplate.getList("portals").get(0);
private static final List<? extends Config> checkbooksConfig = portalConfig.getConfigList("checkbooks");
private static final Config checkbookConfig = checkbooksConfig.get(0);
public CheckbooksIntegrationTest() {
super(Resources.CHECKBOOKS);
}
@AfterClass
public static void cleanup() {
BaseIntegrationTest.cleanup(Resources.CHECKBOOKS);
}
@Test
public void testGetCheckbooks() throws Exception {
List<Checkbook> checkbooks = getResult(getResource().getCheckbooks());
testContainsIds(checkbooks, checkbooksConfig);
}
@Test
public void testGetCheckbook() throws Exception {
Checkbook checkbook = getResult(getResource().getCheckbook(checkbookConfig.getInt("id")));
assertEquals(checkbookConfig.getString("name"), checkbook.getName());
}
@Test
public void testCUDCheckbook() throws Exception {
int portalId = portalConfig.getInt("id");
String checkbookName = "test create";
Checkbook result = getResult(getResource().createCheckbook(portalId, checkbookName));
assertEquals(checkbookName, result.getName());
assertEquals(portalId, result.getOrg().getId());
assertEquals("0.0", result.getBalance());
String updatedName = "updated";
Checkbook updated = getResult(getResource().updateCheckbook(result.getId(), updatedName));
assertEquals(updatedName, updated.getName());
Success success = getResult(getResource().deleteCheckbook(result.getId()));
assertTrue(success.isSuccess());
ApiResponse<Checkbook> checkbook = getResource().getCheckbook(result.getId()).get();
assertFalse(checkbook.isSuccess());
}
@Test
public void testGetOrgCheckbooks() throws Exception {
List<Checkbook> checkbooks = getResult(getResource().getOrgCheckbooks(portalConfig.getInt("id")));
Set<Integer> actualIds = new HashSet<Integer>();
for (Checkbook checkbook : checkbooks) {
actualIds.add(checkbook.getId());
}
Set<Integer> expectedIds = new HashSet<Integer>();
for (Config checkbook : checkbooksConfig) {
expectedIds.add(checkbook.getInt("id"));
}
assertThat(actualIds, hasItems(expectedIds.toArray(new Integer[expectedIds.size()])));
}
@Test
public void testGetCheckbookEntries() throws Exception {
List<CheckbookEntry> entries = getResult(getResource().getCheckbookEntries(checkbookConfig.getInt("id")));
testContainsIds(entries, checkbookConfig.getConfigList("entries"));
}
@Test
public void testGetCheckbookEntry() throws Exception {
Config entryConfig = checkbookConfig.getConfigList("entries").get(0);
CheckbookEntry entry = getResult(getResource().getCheckbookEntry(entryConfig.getInt("id")));
assertEquals(entryConfig.getString("description"), entry.getDescription());
}
@Test
public void testCUDCheckbookEntry() throws Exception {
int checkbookId = checkbookConfig.getInt("id");
String amount = "9.99";
String description = "An added checkbook entry";
CheckbookEntry entry = getResult(getResource().createCheckbookEntry(checkbookId, amount, description));
assertEquals(amount, entry.getAmount());
assertEquals(description, entry.getDescription());
- // assertEquals(checkbookId, entry.getCheckbook().getId()); TODO what do we need to do here?
+ assertEquals(checkbookId, entry.getCheckbook().getId());
String updatedAmount = "19.99";
String updatedDescription = "I updated this description";
entry = getResult(getResource().updateCheckbookEntry(entry.getId(), updatedAmount, updatedDescription));
assertEquals(updatedAmount, entry.getAmount());
assertEquals(updatedDescription, entry.getDescription());
Success success = getResult(getResource().deleteCheckbookEntry(entry.getId()));
assertTrue(success.isSuccess());
}
}
| true | true | public void testCUDCheckbookEntry() throws Exception {
int checkbookId = checkbookConfig.getInt("id");
String amount = "9.99";
String description = "An added checkbook entry";
CheckbookEntry entry = getResult(getResource().createCheckbookEntry(checkbookId, amount, description));
assertEquals(amount, entry.getAmount());
assertEquals(description, entry.getDescription());
// assertEquals(checkbookId, entry.getCheckbook().getId()); TODO what do we need to do here?
String updatedAmount = "19.99";
String updatedDescription = "I updated this description";
entry = getResult(getResource().updateCheckbookEntry(entry.getId(), updatedAmount, updatedDescription));
assertEquals(updatedAmount, entry.getAmount());
assertEquals(updatedDescription, entry.getDescription());
Success success = getResult(getResource().deleteCheckbookEntry(entry.getId()));
assertTrue(success.isSuccess());
}
| public void testCUDCheckbookEntry() throws Exception {
int checkbookId = checkbookConfig.getInt("id");
String amount = "9.99";
String description = "An added checkbook entry";
CheckbookEntry entry = getResult(getResource().createCheckbookEntry(checkbookId, amount, description));
assertEquals(amount, entry.getAmount());
assertEquals(description, entry.getDescription());
assertEquals(checkbookId, entry.getCheckbook().getId());
String updatedAmount = "19.99";
String updatedDescription = "I updated this description";
entry = getResult(getResource().updateCheckbookEntry(entry.getId(), updatedAmount, updatedDescription));
assertEquals(updatedAmount, entry.getAmount());
assertEquals(updatedDescription, entry.getDescription());
Success success = getResult(getResource().deleteCheckbookEntry(entry.getId()));
assertTrue(success.isSuccess());
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/common/controller/EntityControllerCollisionHelper.java b/src/main/java/com/bergerkiller/bukkit/common/controller/EntityControllerCollisionHelper.java
index b552f7e..16edb05 100644
--- a/src/main/java/com/bergerkiller/bukkit/common/controller/EntityControllerCollisionHelper.java
+++ b/src/main/java/com/bergerkiller/bukkit/common/controller/EntityControllerCollisionHelper.java
@@ -1,105 +1,106 @@
package com.bergerkiller.bukkit.common.controller;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.block.BlockFace;
import com.bergerkiller.bukkit.common.conversion.Conversion;
import com.bergerkiller.bukkit.common.entity.CommonEntity;
import com.bergerkiller.bukkit.common.internal.CommonNMS;
import com.bergerkiller.bukkit.common.utils.FaceUtil;
import com.bergerkiller.bukkit.common.utils.MathUtil;
import net.minecraft.server.v1_5_R2.AxisAlignedBB;
import net.minecraft.server.v1_5_R2.Block;
import net.minecraft.server.v1_5_R2.Entity;
/**
* Class that deals with AABB-collision resolving for Entity Controllers.
* This method is moved to hide it from the API - results in Class Hierarchy errors otherwise.
*/
class EntityControllerCollisionHelper {
private static final List<AxisAlignedBB> collisionBuffer = new ArrayList<AxisAlignedBB>();
/**
* Obtains all entities/blocks that can be collided with, checking collisions along the way.
* This is similar to NMS.World.getCubes, but with inserted events.
*
* @param bounds
* @return referenced list of collision cubes
*/
public static List<AxisAlignedBB> getCollisions(EntityController<?> controller, AxisAlignedBB bounds) {
final CommonEntity<?> entity = controller.getEntity();
final Entity handle = entity.getHandle(Entity.class);
collisionBuffer.clear();
final int xmin = MathUtil.floor(bounds.a);
final int ymin = MathUtil.floor(bounds.b);
final int zmin = MathUtil.floor(bounds.c);
final int xmax = MathUtil.floor(bounds.d + 1.0);
final int ymax = MathUtil.floor(bounds.e + 1.0);
final int zmax = MathUtil.floor(bounds.f + 1.0);
// Add block collisions
int x, y, z;
for (x = xmin; x < xmax; ++x) {
for (z = zmin; z < zmax; ++z) {
if (handle.world.isLoaded(x, 64, z)) {
for (y = ymin - 1; y < ymax; ++y) {
Block block = Block.byId[handle.world.getTypeId(x, y, z)];
if (block != null) {
block.a(handle.world, x, y, z, bounds, collisionBuffer, handle);
}
}
}
}
}
// Handle block collisions
- double dx, dy, dz;
BlockFace hitFace;
Iterator<AxisAlignedBB> iter = collisionBuffer.iterator();
AxisAlignedBB blockBounds;
+ double dx, dz;
while (iter.hasNext()) {
blockBounds = iter.next();
// Convert to block and block coordinates
org.bukkit.block.Block block = entity.getWorld().getBlockAt(MathUtil.floor(blockBounds.a), MathUtil.floor(blockBounds.b), MathUtil.floor(blockBounds.c));
- dx = entity.loc.getX() - block.getX() - 0.5;
- dy = entity.loc.getY() - block.getY() - 0.5;
- dz = entity.loc.getZ() - block.getZ() - 0.5;
// Find out what direction the block is hit
- if (Math.abs(dx) < 0.1 && Math.abs(dz) < 0.1) {
- hitFace = dy >= 0.0 ? BlockFace.UP : BlockFace.DOWN;
+ if (bounds.e > blockBounds.e) {
+ hitFace = BlockFace.UP;
+ } else if (bounds.b < blockBounds.b) {
+ hitFace = BlockFace.DOWN;
} else {
+ dx = entity.loc.getX() - block.getX() - 0.5;
+ dz = entity.loc.getZ() - block.getZ() - 0.5;
hitFace = FaceUtil.getDirection(dx, dz, false);
}
// Block collision event
if (!controller.onBlockCollision(block, hitFace)) {
iter.remove();
}
}
// Handle and add entities
AxisAlignedBB entityBounds;
for (Entity collider : CommonNMS.getEntitiesIn(handle.world, handle, bounds.grow(0.25, 0.25, 0.25))) {
/*
* This part is completely pointless as E() always returns null May
* this ever change, make sure E() is handled correctly.
*
* entityBounds = entity.E(); if (entityBounds != null &&
* entityBounds.a(bounds)) { collisionBuffer.add(entityBounds); }
*/
entityBounds = collider.boundingBox;
// Entity collision event after the null/inBounds check
if (entityBounds != null && entityBounds.a(bounds) && controller.onEntityCollision(Conversion.toEntity.convert(collider))) {
collisionBuffer.add(entityBounds);
}
}
// Done
return collisionBuffer;
}
}
| false | true | public static List<AxisAlignedBB> getCollisions(EntityController<?> controller, AxisAlignedBB bounds) {
final CommonEntity<?> entity = controller.getEntity();
final Entity handle = entity.getHandle(Entity.class);
collisionBuffer.clear();
final int xmin = MathUtil.floor(bounds.a);
final int ymin = MathUtil.floor(bounds.b);
final int zmin = MathUtil.floor(bounds.c);
final int xmax = MathUtil.floor(bounds.d + 1.0);
final int ymax = MathUtil.floor(bounds.e + 1.0);
final int zmax = MathUtil.floor(bounds.f + 1.0);
// Add block collisions
int x, y, z;
for (x = xmin; x < xmax; ++x) {
for (z = zmin; z < zmax; ++z) {
if (handle.world.isLoaded(x, 64, z)) {
for (y = ymin - 1; y < ymax; ++y) {
Block block = Block.byId[handle.world.getTypeId(x, y, z)];
if (block != null) {
block.a(handle.world, x, y, z, bounds, collisionBuffer, handle);
}
}
}
}
}
// Handle block collisions
double dx, dy, dz;
BlockFace hitFace;
Iterator<AxisAlignedBB> iter = collisionBuffer.iterator();
AxisAlignedBB blockBounds;
while (iter.hasNext()) {
blockBounds = iter.next();
// Convert to block and block coordinates
org.bukkit.block.Block block = entity.getWorld().getBlockAt(MathUtil.floor(blockBounds.a), MathUtil.floor(blockBounds.b), MathUtil.floor(blockBounds.c));
dx = entity.loc.getX() - block.getX() - 0.5;
dy = entity.loc.getY() - block.getY() - 0.5;
dz = entity.loc.getZ() - block.getZ() - 0.5;
// Find out what direction the block is hit
if (Math.abs(dx) < 0.1 && Math.abs(dz) < 0.1) {
hitFace = dy >= 0.0 ? BlockFace.UP : BlockFace.DOWN;
} else {
hitFace = FaceUtil.getDirection(dx, dz, false);
}
// Block collision event
if (!controller.onBlockCollision(block, hitFace)) {
iter.remove();
}
}
// Handle and add entities
AxisAlignedBB entityBounds;
for (Entity collider : CommonNMS.getEntitiesIn(handle.world, handle, bounds.grow(0.25, 0.25, 0.25))) {
/*
* This part is completely pointless as E() always returns null May
* this ever change, make sure E() is handled correctly.
*
* entityBounds = entity.E(); if (entityBounds != null &&
* entityBounds.a(bounds)) { collisionBuffer.add(entityBounds); }
*/
entityBounds = collider.boundingBox;
// Entity collision event after the null/inBounds check
if (entityBounds != null && entityBounds.a(bounds) && controller.onEntityCollision(Conversion.toEntity.convert(collider))) {
collisionBuffer.add(entityBounds);
}
}
// Done
return collisionBuffer;
}
| public static List<AxisAlignedBB> getCollisions(EntityController<?> controller, AxisAlignedBB bounds) {
final CommonEntity<?> entity = controller.getEntity();
final Entity handle = entity.getHandle(Entity.class);
collisionBuffer.clear();
final int xmin = MathUtil.floor(bounds.a);
final int ymin = MathUtil.floor(bounds.b);
final int zmin = MathUtil.floor(bounds.c);
final int xmax = MathUtil.floor(bounds.d + 1.0);
final int ymax = MathUtil.floor(bounds.e + 1.0);
final int zmax = MathUtil.floor(bounds.f + 1.0);
// Add block collisions
int x, y, z;
for (x = xmin; x < xmax; ++x) {
for (z = zmin; z < zmax; ++z) {
if (handle.world.isLoaded(x, 64, z)) {
for (y = ymin - 1; y < ymax; ++y) {
Block block = Block.byId[handle.world.getTypeId(x, y, z)];
if (block != null) {
block.a(handle.world, x, y, z, bounds, collisionBuffer, handle);
}
}
}
}
}
// Handle block collisions
BlockFace hitFace;
Iterator<AxisAlignedBB> iter = collisionBuffer.iterator();
AxisAlignedBB blockBounds;
double dx, dz;
while (iter.hasNext()) {
blockBounds = iter.next();
// Convert to block and block coordinates
org.bukkit.block.Block block = entity.getWorld().getBlockAt(MathUtil.floor(blockBounds.a), MathUtil.floor(blockBounds.b), MathUtil.floor(blockBounds.c));
// Find out what direction the block is hit
if (bounds.e > blockBounds.e) {
hitFace = BlockFace.UP;
} else if (bounds.b < blockBounds.b) {
hitFace = BlockFace.DOWN;
} else {
dx = entity.loc.getX() - block.getX() - 0.5;
dz = entity.loc.getZ() - block.getZ() - 0.5;
hitFace = FaceUtil.getDirection(dx, dz, false);
}
// Block collision event
if (!controller.onBlockCollision(block, hitFace)) {
iter.remove();
}
}
// Handle and add entities
AxisAlignedBB entityBounds;
for (Entity collider : CommonNMS.getEntitiesIn(handle.world, handle, bounds.grow(0.25, 0.25, 0.25))) {
/*
* This part is completely pointless as E() always returns null May
* this ever change, make sure E() is handled correctly.
*
* entityBounds = entity.E(); if (entityBounds != null &&
* entityBounds.a(bounds)) { collisionBuffer.add(entityBounds); }
*/
entityBounds = collider.boundingBox;
// Entity collision event after the null/inBounds check
if (entityBounds != null && entityBounds.a(bounds) && controller.onEntityCollision(Conversion.toEntity.convert(collider))) {
collisionBuffer.add(entityBounds);
}
}
// Done
return collisionBuffer;
}
|
diff --git a/providers/netty/src/main/java/org/asynchttpclient/providers/netty/NettyAsyncHttpProvider.java b/providers/netty/src/main/java/org/asynchttpclient/providers/netty/NettyAsyncHttpProvider.java
index 9730f45cb..4bab73cfd 100644
--- a/providers/netty/src/main/java/org/asynchttpclient/providers/netty/NettyAsyncHttpProvider.java
+++ b/providers/netty/src/main/java/org/asynchttpclient/providers/netty/NettyAsyncHttpProvider.java
@@ -1,2412 +1,2412 @@
/*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.asynchttpclient.providers.netty;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHandler.STATE;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.AsyncHttpProvider;
import org.asynchttpclient.Body;
import org.asynchttpclient.BodyGenerator;
import org.asynchttpclient.ConnectionPoolKeyStrategy;
import org.asynchttpclient.ConnectionsPool;
import org.asynchttpclient.Cookie;
import org.asynchttpclient.FluentCaseInsensitiveStringsMap;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.HttpResponseHeaders;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.MaxRedirectException;
import org.asynchttpclient.ProgressAsyncHandler;
import org.asynchttpclient.ProxyServer;
import org.asynchttpclient.RandomAccessBody;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.asynchttpclient.filter.FilterContext;
import org.asynchttpclient.filter.FilterException;
import org.asynchttpclient.filter.IOExceptionFilter;
import org.asynchttpclient.filter.ResponseFilter;
import org.asynchttpclient.generators.InputStreamBodyGenerator;
import org.asynchttpclient.listener.TransferCompletionHandler;
import org.asynchttpclient.multipart.MultipartBody;
import org.asynchttpclient.multipart.MultipartRequestEntity;
import org.asynchttpclient.ntlm.NTLMEngine;
import org.asynchttpclient.ntlm.NTLMEngineException;
import org.asynchttpclient.org.jboss.netty.handler.codec.http.CookieDecoder;
import org.asynchttpclient.org.jboss.netty.handler.codec.http.CookieEncoder;
import org.asynchttpclient.providers.netty.FeedableBodyGenerator.FeedListener;
import org.asynchttpclient.providers.netty.spnego.SpnegoEngine;
import org.asynchttpclient.providers.netty.util.CleanupChannelGroup;
import org.asynchttpclient.util.AsyncHttpProviderUtils;
import org.asynchttpclient.util.AuthenticatorUtils;
import org.asynchttpclient.util.ProxyUtils;
import org.asynchttpclient.util.SslUtils;
import org.asynchttpclient.util.UTF8UrlEncoder;
import org.asynchttpclient.websocket.WebSocketUpgradeHandler;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.PrematureChannelClosureException;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.asynchttpclient.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.asynchttpclient.util.DateUtil.millisTime;
import static org.asynchttpclient.util.MiscUtil.isNonEmpty;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider {
private final static String HTTP_HANDLER = "httpHandler";
protected final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private static final String WEBSOCKET = "ws";
private static final String WEBSOCKET_SSL = "wss";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final static Charset UTF8 = Charset.forName("UTF-8");
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final ClientBootstrap webSocketBootstrap;
private final ClientBootstrap secureWebSocketBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final boolean allowReleaseSocketChannelFactory;
private final ChannelGroup openChannels = new CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed && trackConnections) {
freeConnections.release();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private Semaphore freeConnections = null;
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = true;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final boolean useRawUrl;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private static SpnegoEngine spnegoEngine = null;
private final Protocol httpProtocol = new HttpProtocol();
private final Protocol webSocketProtocol = new WebSocketProtocol();
private static boolean isNTLM(List<String> auth) {
return isNonEmpty(auth) && auth.get(0).startsWith("NTLM");
}
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() instanceof NettyAsyncHttpProviderConfig) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig.isUseBlockingIO()) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
this.allowReleaseSocketChannelFactory = true;
} else {
// check if external NioClientSocketChannelFactory is defined
NioClientSocketChannelFactory scf = asyncHttpProviderConfig.getSocketChannelFactory();
if (scf != null) {
this.socketChannelFactory = scf;
// cannot allow releasing shared channel factory
this.allowReleaseSocketChannelFactory = false;
} else {
ExecutorService e = asyncHttpProviderConfig.getBossExecutorService();
if (e == null) {
e = Executors.newCachedThreadPool();
}
int numWorkers = config.getIoThreadMultiplier() * Runtime.getRuntime().availableProcessors();
log.debug("Number of application's worker threads is {}", numWorkers);
socketChannelFactory = new NioClientSocketChannelFactory(e, config.executorService(), numWorkers);
this.allowReleaseSocketChannelFactory = true;
}
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
webSocketBootstrap = new ClientBootstrap(socketChannelFactory);
secureWebSocketBootstrap = new ClientBootstrap(socketChannelFactory);
this.config = config;
configureNetty();
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
if (config.getMaxTotalConnections() != -1) {
trackConnections = true;
freeConnections = new Semaphore(config.getMaxTotalConnections());
} else {
trackConnections = false;
}
useRawUrl = config.isUseRawUrl();
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s", config.getMaxTotalConnections() - freeConnections.availablePermits(), openChannels.toString(), connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
String key = entry.getKey();
Object value = entry.getValue();
plainBootstrap.setOption(key, value);
webSocketBootstrap.setOption(key, value);
secureBootstrap.setOption(key, value);
secureWebSocketBootstrap.setOption(key, value);
}
}
plainBootstrap.setPipelineFactory(createPlainPipelineFactory());
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
executeConnectAsync = config.isAsyncConnectMode();
if (!executeConnectAsync) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
webSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("http-decoder", new HttpResponseDecoder());
pipeline.addLast("http-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
protected HttpClientCodec newHttpClientCodec() {
if (asyncHttpProviderConfig != null) {
return new HttpClientCodec(asyncHttpProviderConfig.getMaxInitialLineLength(), asyncHttpProviderConfig.getMaxHeaderSize(), asyncHttpProviderConfig.getMaxChunkSize(), false);
} else {
return new HttpClientCodec();
}
}
protected ChannelPipelineFactory createPlainPipelineFactory() {
return new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
};
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
secureWebSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast("http-decoder", new HttpResponseDecoder());
pipeline.addLast("http-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
private Channel lookupInCache(URI uri, ConnectionPoolKeyStrategy connectionPoolKeyStrategy) {
final Channel channel = connectionsPool.poll(connectionPoolKeyStrategy.getKey(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && isSecure(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel, final AsyncHttpClientConfig config, final NettyResponseFuture<T> future, final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it, we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg != null) {
// Netty issue with chunking.
if (bg instanceof InputStreamBodyGenerator) {
InputStreamBodyGenerator.class.cast(bg).patchNettyChunkingIssue(true);
}
try {
body = bg.createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (future.getAsyncHandler() instanceof TransferCompletionHandler) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
}
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null || future.getRequest().getParts() != null) {
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (future.getRequest().getParts() != null) {
String contentType = future.getNettyRequest().getHeader(HttpHeaders.Names.CONTENT_TYPE);
String length = future.getNettyRequest().getHeader(HttpHeaders.Names.CONTENT_LENGTH);
body = new MultipartBody(future.getRequest().getParts(), contentType, length);
}
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
BodyFileRegion bodyFileRegion = new BodyFileRegion((RandomAccessBody) body);
writeFuture = channel.write(bodyFileRegion);
} else {
BodyChunkedInput bodyChunkedInput = new BodyChunkedInput(body);
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg instanceof FeedableBodyGenerator) {
((FeedableBodyGenerator) bg).setListener(new FeedListener() {
@Override
public void onContentAdded() {
channel.getPipeline().get(ChunkedWriteHandler.class).resumeTransfer();
}
});
}
writeFuture = channel.write(bodyChunkedInput);
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int requestTimeout = AsyncHttpProviderUtils.requestTimeout(config, future.getRequest());
int schedulePeriod = requestTimeout != -1 ? (config.getIdleConnectionTimeoutInMs() != -1 ? Math.min(requestTimeout, config.getIdleConnectionTimeoutInMs()) : requestTimeout) : config.getIdleConnectionTimeoutInMs();
if (schedulePeriod != -1 && !future.isDone() && !future.isCancelled()) {
ReaperFuture reaperFuture = new ReaperFuture(future);
Future<?> scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, 0, schedulePeriod, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri, boolean allowConnect, ChannelBuffer buffer, ProxyServer proxyServer) throws IOException {
String method = request.getMethod();
if (allowConnect && proxyServer != null && isSecure(uri)) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer, proxyServer);
}
private static SpnegoEngine getSpnegoEngine() {
if (spnegoEngine == null)
spnegoEngine = new SpnegoEngine();
return spnegoEngine;
}
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ChannelBuffer buffer, ProxyServer proxyServer) throws IOException {
String host = null;
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
} else {
- AsyncHttpProviderUtils.getHost(uri);
+ host = AsyncHttpProviderUtils.getHost(uri);
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");
}
if (host != null) {
if (request.getVirtualHost() != null || uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (Entry<String, List<String>> header : h) {
String name = header.getKey();
if (!HttpHeaders.Names.HOST.equalsIgnoreCase(name)) {
for (String value : header.getValue()) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNTLM(auth)) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException("Invalid Authentication " + realm);
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!isNTLM(auth)) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue(HttpHeaders.Names.ACCEPT) == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
String userAgentHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.USER_AGENT);
if (userAgentHeader != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, userAgentHeader);
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, config.getUserAgent());
} else {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, CookieEncoder.encodeClientSide(request.getCookies(), config.isRfc6265CookieEncoding()));
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
byte[] bytes = request.getStringData().getBytes(bodyCharset);
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(bytes.length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getHeaders());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for (Channel channel : openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
if (this.allowReleaseSocketChannelFactory) {
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
webSocketBootstrap.releaseExternalResources();
secureWebSocketBootstrap.releaseExternalResources();
}
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status, final HttpResponseHeaders headers, final List<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) {
throw new IOException("WebSocket method must be a GET");
}
ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
boolean useProxy = proxyServer != null;
URI uri;
if (useRawUrl) {
uri = request.getRawURI();
} else {
uri = request.getURI();
}
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
URI connectionKeyUri = useProxy ? proxyServer.getURI() : uri;
channel = lookupInCache(connectionKeyUri, request.getConnectionPoolKeyStrategy());
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null && !f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = isSecure(uri) && !useProxy;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = null;
if (f == null) {
nettyRequest = buildRequest(config, request, uri, false, bufferedBytes, proxyServer);
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this, proxyServer);
} else {
nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes, proxyServer);
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (Exception ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("doConnect.writeRequest()", t);
}
IOException ioe = new IOException(ex.getMessage());
ioe.initCause(ex);
throw ioe;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && !connectionsPool.canCacheConnection()) {
IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections());
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
}
boolean acquiredConnection = false;
if (trackConnections) {
if (!reclaimCache) {
if (!freeConnections.tryAcquire()) {
IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections());
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
} else {
acquiredConnection = true;
}
}
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap);
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
try {
InetSocketAddress remoteAddress;
if (request.getInetAddress() != null) {
remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri));
} else if (proxyServer == null || avoidProxy) {
remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri));
} else {
remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort());
}
if (request.getLocalAddress() != null) {
channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0));
} else {
channelFuture = bootstrap.connect(remoteAddress);
}
} catch (Throwable t) {
if (acquiredConnection) {
freeConnections.release();
}
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
if (acquiredConnection) {
freeConnections.release();
}
channelFuture.cancel();
abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut)));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
if (acquiredConnection) {
freeConnections.release();
}
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
try {
asyncHandler.onThrowable(ioe);
} catch (Throwable t) {
log.warn("c.operationComplete()", t);
}
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
ctx.setAttachment(new DiscardEvent());
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null) {
return;
}
log.debug("Closing Channel {} ", ctx.getChannel());
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
if (ctx.getChannel() != null) {
openChannels.remove(ctx.getChannel());
}
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
} else {
return;
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
ctx.setAttachment(new DiscardEvent());
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.trace("Closing an orphan channel {}", ctx.getChannel());
}
return;
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.handle(ctx, e);
}
private Realm kerberosChallenge(List<String> proxyAuth, Request request, ProxyServer proxyServer, FluentCaseInsensitiveStringsMap headers, Realm realm, NettyResponseFuture<?> future) throws NTLMEngineException {
URI uri = request.getURI();
String host = request.getVirtualHost() == null ? AsyncHttpProviderUtils.getHost(uri) : request.getVirtualHost();
String server = proxyServer == null ? host : proxyServer.getHost();
try {
String challengeHeader = getSpnegoEngine().generateToken(server);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
return realmBuilder.setUri(uri.getRawPath()).setMethodName(request.getMethod()).setScheme(Realm.AuthScheme.KERBEROS).build();
} catch (Throwable throwable) {
if (isNTLM(proxyAuth)) {
return ntlmChallenge(proxyAuth, request, proxyServer, headers, realm, future);
}
abort(future, throwable);
return null;
}
}
private void addType3NTLMAuthorizationHeader(List<String> auth, FluentCaseInsensitiveStringsMap headers, String username, String password, String domain, String workstation)
throws NTLMEngineException {
headers.remove(HttpHeaders.Names.AUTHORIZATION);
if (isNTLM(auth)) {
String serverChallenge = auth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(username, password, domain, workstation, serverChallenge);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
}
}
private Realm ntlmChallenge(List<String> wwwAuth, Request request, ProxyServer proxyServer, FluentCaseInsensitiveStringsMap headers, Realm realm, NettyResponseFuture<?> future) throws NTLMEngineException {
boolean useRealm = (proxyServer == null && realm != null);
String ntlmDomain = useRealm ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = useRealm ? realm.getNtlmHost() : proxyServer.getHost();
String principal = useRealm ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = useRealm ? realm.getPassword() : proxyServer.getPassword();
Realm newRealm;
if (realm != null && !realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);
URI uri = request.getURI();
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme()).setUri(uri.getRawPath()).setMethodName(request.getMethod()).setNtlmMessageType2Received(true).build();
future.getAndSetAuth(false);
} else {
addType3NTLMAuthorizationHeader(wwwAuth, headers, principal, password, ntlmDomain, ntlmHost);
Realm.RealmBuilder realmBuilder;
Realm.AuthScheme authScheme;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
authScheme = realm.getAuthScheme();
} else {
realmBuilder = new Realm.RealmBuilder();
authScheme = Realm.AuthScheme.NTLM;
}
newRealm = realmBuilder.setScheme(authScheme).setUri(request.getURI().getPath()).setMethodName(request.getMethod()).build();
}
return newRealm;
}
private Realm ntlmProxyChallenge(List<String> wwwAuth, Request request, ProxyServer proxyServer, FluentCaseInsensitiveStringsMap headers, Realm realm, NettyResponseFuture<?> future) throws NTLMEngineException {
future.getAndSetAuth(false);
headers.remove(HttpHeaders.Names.PROXY_AUTHORIZATION);
addType3NTLMAuthorizationHeader(wwwAuth, headers, proxyServer.getPrincipal(), proxyServer.getPassword(), proxyServer.getNtlmDomain(), proxyServer.getHost());
Realm newRealm;
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
newRealm = realmBuilder// .setScheme(realm.getAuthScheme())
.setUri(request.getURI().getPath()).setMethodName(request.getMethod()).build();
return newRealm;
}
private String getPoolKey(NettyResponseFuture<?> future) throws MalformedURLException {
URI uri = future.getProxyServer() != null ? future.getProxyServer().getURI() : future.getURI();
return future.getConnectionPoolKeyStrategy().getKey(uri);
}
private void drainChannel(final ChannelHandlerContext ctx, final NettyResponseFuture<?> future) {
ctx.setAttachment(new AsyncCallable(future) {
public Object call() throws Exception {
if (future.isKeepAlive() && ctx.getChannel().isReadable() && connectionsPool.offer(getPoolKey(future), ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
@Override
public String toString() {
return "Draining task for channel " + ctx.getChannel();
}
});
}
private FilterContext handleIoException(FilterContext fc, NettyResponseFuture<?> future) {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
return fc;
}
private void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, HttpResponse response, ChannelHandlerContext ctx) throws IOException {
final Request newRequest = fc.getRequest();
future.setAsyncHandler(fc.getAsyncHandler());
future.setState(NettyResponseFuture.STATE.NEW);
future.touch();
log.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
drainChannel(ctx, future);
nextRequest(newRequest, future);
return;
}
private List<String> getAuthorizationToken(List<Entry<String, String>> list, String headerAuth) {
ArrayList<String> l = new ArrayList<String>();
for (Entry<String, String> e : list) {
if (e.getKey().equalsIgnoreCase(headerAuth)) {
l.add(e.getValue().trim());
}
}
return l;
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future) throws IOException {
nextRequest(request, future, true);
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future, final boolean useCache) throws IOException {
execute(request, future, useCache, true, true);
}
private void abort(NettyResponseFuture<?> future, Throwable t) {
Channel channel = future.channel();
if (channel != null && openChannels.contains(channel)) {
closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
openChannels.remove(channel);
}
if (!future.isCancelled() && !future.isDone()) {
log.debug("Aborting Future {}\n", future);
log.debug(t.getMessage(), t);
}
future.abort(t);
}
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException {
if (p.get(HTTP_HANDLER) != null) {
p.remove(HTTP_HANDLER);
}
if (isSecure(scheme)) {
if (p.get(SSL_HANDLER) == null) {
p.addFirst(HTTP_HANDLER, newHttpClientCodec());
p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
} else {
p.addAfter(SSL_HANDLER, HTTP_HANDLER, newHttpClientCodec());
}
} else {
p.addFirst(HTTP_HANDLER, newHttpClientCodec());
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (isClose.get()) {
return;
}
connectionsPool.removeAll(ctx.getChannel());
try {
super.channelClosed(ctx, e);
} catch (Exception ex) {
log.trace("super.channelClosed", ex);
}
log.debug("Channel Closed: {} with attachment {}", e.getChannel(), ctx.getAttachment());
if (ctx.getAttachment() instanceof AsyncCallable) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ctx.setAttachment(ac.future());
ac.call();
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
if (!config.getIOExceptionFilters().isEmpty()) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler()).request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest() && !future.cannotBeReplay()) {
replayRequest(future, fc, null, ctx);
return;
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onClose(ctx, e);
if (future != null && !future.isDone() && !future.isCancelled()) {
if (!remotelyClosed(ctx.getChannel(), future)) {
abort(future, new IOException("Remotely Closed " + ctx.getChannel()));
}
} else {
closeChannel(ctx);
}
}
}
protected boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) {
if (isClose.get()) {
return false;
}
connectionsPool.removeAll(channel);
if (future == null && channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment() instanceof NettyResponseFuture) {
future = (NettyResponseFuture<?>) channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
}
if (future == null || future.cannotBeReplay()) {
log.debug("Unable to recover future {}\n", future);
return false;
}
future.setState(NettyResponseFuture.STATE.RECONNECTED);
future.getAndSetStatusReceived(false);
log.debug("Trying to recover request {}\n", future.getNettyRequest());
try {
nextRequest(future.getRequest(), future);
return true;
} catch (IOException iox) {
future.setState(NettyResponseFuture.STATE.CLOSED);
future.abort(iox);
log.error("Remotely Closed, unable to recover", iox);
}
return false;
}
private void markAsDone(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx) throws MalformedURLException {
// We need to make sure everything is OK before adding the connection back to the pool.
try {
future.done();
} catch (Throwable t) {
// Never propagate exception once we know we are done.
log.debug(t.getMessage(), t);
}
if (!future.isKeepAlive() || !ctx.getChannel().isReadable()) {
closeChannel(ctx);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean lastValidChunk) throws IOException {
if (lastValidChunk && future.isKeepAlive()) {
drainChannel(ctx, future);
} else {
if (future.isKeepAlive() && ctx.getChannel().isReadable() && connectionsPool.offer(getPoolKey(future), ctx.getChannel())) {
markAsDone(future, ctx);
return;
}
finishChannel(ctx);
}
markAsDone(future, ctx);
}
private final boolean updateStatusAndInterrupt(AsyncHandler<?> handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
private final boolean updateHeadersAndInterrupt(AsyncHandler<?> handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
private final boolean updateBodyAndInterrupt(final NettyResponseFuture<?> future, AsyncHandler<?> handler, HttpResponseBodyPart c) throws Exception {
boolean state = handler.onBodyPartReceived(c) != STATE.CONTINUE;
if (c.closeUnderlyingConnection()) {
future.setKeepAlive(false);
}
return state;
}
// Simple marker for stopping publishing bytes.
final static class DiscardEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
Channel channel = e.getChannel();
Throwable cause = e.getCause();
NettyResponseFuture<?> future = null;
if (e.getCause() instanceof PrematureChannelClosureException) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Unexpected I/O exception on channel {}", channel, cause);
}
try {
if (cause instanceof ClosedChannelException) {
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) ctx.getAttachment();
future.attachChannel(null, false);
future.touch();
if (cause instanceof IOException) {
if (!config.getIOExceptionFilters().isEmpty()) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler()).request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, null, ctx);
return;
}
} else {
// Close the channel so the recovering can occurs.
try {
ctx.getChannel().close();
} catch (Throwable t) {
; // Swallow.
}
return;
}
}
if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
log.debug("Trying to recover from dead Channel: {}", channel);
return;
}
} else if (ctx.getAttachment() instanceof AsyncCallable) {
future = ((AsyncCallable) ctx.getAttachment()).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
log.debug("Was unable to recover Future: {}", future);
abort(future, cause);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onError(ctx, e);
closeChannel(ctx);
ctx.sendUpstream(e);
}
protected static boolean abortOnConnectCloseException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketChannelImpl") && element.getMethodName().equals("checkConnect")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnDisconnectException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("org.jboss.netty.handler.ssl.SslHandler") && element.getMethodName().equals("channelDisconnected")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnReadCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher") && element.getMethodName().equals("read")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
protected static boolean abortOnWriteCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher") && element.getMethodName().equals("write")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int length = (int) request.getContentLength();
if (length == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
length = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (length >= 0) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
}
return length;
}
public static <T> NettyResponseFuture<T> newFuture(URI uri, Request request, AsyncHandler<T> asyncHandler, HttpRequest nettyRequest, AsyncHttpClientConfig config, NettyAsyncHttpProvider provider, ProxyServer proxyServer) {
int requestTimeout = AsyncHttpProviderUtils.requestTimeout(config, request);
NettyResponseFuture<T> f = new NettyResponseFuture<T>(uri,//
request,//
asyncHandler,//
nettyRequest,//
requestTimeout,//
config.getIdleConnectionTimeoutInMs(),//
provider,//
request.getConnectionPoolKeyStrategy(),//
proxyServer);
String expectHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.EXPECT);
if (expectHeader != null && expectHeader.equalsIgnoreCase(HttpHeaders.Values.CONTINUE)) {
f.getAndSetWriteBody(false);
}
return f;
}
private class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler<?> asyncHandler;
private final NettyResponseFuture<?> future;
public ProgressListener(boolean notifyHeaders, AsyncHandler<?> asyncHandler, NettyResponseFuture<?> future) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
this.future = future;
}
public void operationComplete(ChannelFuture cf) {
// The write operation failed. If the channel was cached, it means it got asynchronously closed.
// Let's retry a second time.
Throwable cause = cf.getCause();
if (cause != null && future.getState() != NettyResponseFuture.STATE.NEW) {
if (cause instanceof IllegalStateException) {
log.debug(cause.getMessage(), cause);
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
if (cause instanceof ClosedChannelException || abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
if (log.isDebugEnabled()) {
log.debug(cf.getCause() == null ? "" : cf.getCause().getMessage(), cf.getCause());
}
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
} else {
future.abort(cause);
}
return;
}
future.touch();
/**
* We need to make sure we aren't in the middle of an authorization process before publishing events as we will re-publish again the same event after the authorization, causing unpredictable behavior.
*/
Realm realm = future.getRequest().getRealm() != null ? future.getRequest().getRealm() : NettyAsyncHttpProvider.this.getConfig().getRealm();
boolean startPublishing = future.isInAuth() || realm == null || realm.getUsePreemptiveAuth() == true;
if (startPublishing && asyncHandler instanceof ProgressAsyncHandler) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
future.touch();
if (asyncHandler instanceof ProgressAsyncHandler) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgress(amount, current, total);
}
}
}
/**
* Because some implementation of the ThreadSchedulingService do not clean up cancel task until they try to run them, we wrap the task with the future so the when the NettyResponseFuture cancel the reaper future this wrapper will release the references to the channel and the
* nettyResponseFuture immediately. Otherwise, the memory referenced this way will only be released after the request timeout period which can be arbitrary long.
*/
private final class ReaperFuture implements Future, Runnable {
private Future scheduledFuture;
private NettyResponseFuture<?> nettyResponseFuture;
public ReaperFuture(NettyResponseFuture<?> nettyResponseFuture) {
this.nettyResponseFuture = nettyResponseFuture;
}
public void setScheduledFuture(Future scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
/**
* @Override
*/
public boolean cancel(boolean mayInterruptIfRunning) {
nettyResponseFuture = null;
return scheduledFuture.cancel(mayInterruptIfRunning);
}
/**
* @Override
*/
public Object get() throws InterruptedException, ExecutionException {
return scheduledFuture.get();
}
/**
* @Override
*/
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return scheduledFuture.get(timeout, unit);
}
/**
* @Override
*/
public boolean isCancelled() {
return scheduledFuture.isCancelled();
}
/**
* @Override
*/
public boolean isDone() {
return scheduledFuture.isDone();
}
private void expire(String message) {
log.debug("{} for {}", message, nettyResponseFuture);
abort(nettyResponseFuture, new TimeoutException(message));
nettyResponseFuture = null;
}
/**
* @Override
*/
public synchronized void run() {
if (isClose.get()) {
cancel(true);
return;
}
boolean futureDone = nettyResponseFuture.isDone();
boolean futureCanceled = nettyResponseFuture.isCancelled();
if (nettyResponseFuture != null && !futureDone && !futureCanceled) {
long now = millisTime();
if (nettyResponseFuture.hasRequestTimedOut(now)) {
long age = now - nettyResponseFuture.getStart();
expire("Request reached time out of " + nettyResponseFuture.getRequestTimeoutInMs() + " ms after " + age + " ms");
} else if (nettyResponseFuture.hasConnectionIdleTimedOut(now)) {
long age = now - nettyResponseFuture.getStart();
expire("Request reached idle time out of " + nettyResponseFuture.getIdleConnectionTimeoutInMs() + " ms after " + age + " ms");
}
} else if (nettyResponseFuture == null || futureDone || futureCanceled) {
cancel(true);
}
}
}
private abstract class AsyncCallable implements Callable<Object> {
private final NettyResponseFuture<?> future;
public AsyncCallable(NettyResponseFuture<?> future) {
this.future = future;
}
abstract public Object call() throws Exception;
public NettyResponseFuture<?> future() {
return future;
}
}
public static class ThreadLocalBoolean extends ThreadLocal<Boolean> {
private final boolean defaultValue;
public ThreadLocalBoolean() {
this(false);
}
public ThreadLocalBoolean(boolean defaultValue) {
this.defaultValue = defaultValue;
}
@Override
protected Boolean initialValue() {
return defaultValue ? Boolean.TRUE : Boolean.FALSE;
}
}
public static class OptimizedFileRegion implements FileRegion {
private final FileChannel file;
private final RandomAccessFile raf;
private final long position;
private final long count;
private long byteWritten;
public OptimizedFileRegion(RandomAccessFile raf, long position, long count) {
this.raf = raf;
this.file = raf.getChannel();
this.position = position;
this.count = count;
}
public long getPosition() {
return position;
}
public long getCount() {
return count;
}
public long transferTo(WritableByteChannel target, long position) throws IOException {
long count = this.count - position;
if (count < 0 || position < 0) {
throw new IllegalArgumentException("position out of range: " + position + " (expected: 0 - " + (this.count - 1) + ")");
}
if (count == 0) {
return 0L;
}
long bw = file.transferTo(this.position + position, count, target);
byteWritten += bw;
if (byteWritten == raf.length()) {
releaseExternalResources();
}
return bw;
}
public void releaseExternalResources() {
try {
file.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
}
}
private static class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
private final ChannelBuffer content;
private final FileInputStream file;
private int byteRead = 0;
public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ChannelBuffer content, File file) throws IOException {
super(headers);
this.content = content;
if (file != null) {
this.file = new FileInputStream(file);
} else {
this.file = null;
}
}
@Override
public void getBytes(byte[] bytes) {
if (content.writableBytes() != 0) {
content.getBytes(byteRead, bytes);
byteRead += bytes.length;
} else if (file != null) {
try {
byteRead += file.read(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
protected AsyncHttpClientConfig getConfig() {
return config;
}
private static class NonConnectionsPool implements ConnectionsPool<String, Channel> {
public boolean offer(String uri, Channel connection) {
return false;
}
public Channel poll(String uri) {
return null;
}
public boolean removeAll(Channel connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
}
}
private static final boolean validateWebSocketRequest(Request request, AsyncHandler<?> asyncHandler) {
if (request.getMethod() != "GET" || !(asyncHandler instanceof WebSocketUpgradeHandler)) {
return false;
}
return true;
}
private boolean redirect(Request request, NettyResponseFuture<?> future, HttpResponse response, final ChannelHandlerContext ctx) throws Exception {
int statusCode = response.getStatus().getCode();
boolean redirectEnabled = request.isRedirectOverrideSet() ? request.isRedirectEnabled() : config.isRedirectEnabled();
if (redirectEnabled && (statusCode == 302 || statusCode == 301 || statusCode == 303 || statusCode == 307)) {
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
// We must allow 401 handling again.
future.getAndSetAuth(false);
String location = response.getHeader(HttpHeaders.Names.LOCATION);
URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
boolean stripQueryString = config.isRemoveQueryParamOnRedirect();
if (!uri.toString().equals(future.getURI().toString())) {
final RequestBuilder nBuilder = stripQueryString ? new RequestBuilder(future.getRequest()).setQueryParameters(null) : new RequestBuilder(future.getRequest());
if (!(statusCode < 302 || statusCode > 303) && !(statusCode == 302 && config.isStrict302Handling())) {
nBuilder.setMethod("GET");
}
final boolean initialConnectionKeepAlive = future.isKeepAlive();
final String initialPoolKey = getPoolKey(future);
future.setURI(uri);
String newUrl = uri.toString();
if (request.getUrl().startsWith(WEBSOCKET)) {
newUrl = newUrl.replace(HTTP, WEBSOCKET);
}
log.debug("Redirecting to {}", newUrl);
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE)) {
for (Cookie c : CookieDecoder.decode(cookieStr)) {
nBuilder.addOrReplaceCookie(c);
}
}
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE2)) {
for (Cookie c : CookieDecoder.decode(cookieStr)) {
nBuilder.addOrReplaceCookie(c);
}
}
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
if (initialConnectionKeepAlive && ctx.getChannel().isReadable() && connectionsPool.offer(initialPoolKey, ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
};
if (response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
nextRequest(nBuilder.setUrl(newUrl).build(), future);
return true;
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
return false;
}
private final class HttpProtocol implements Protocol {
// @Override
public void handle(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
// The connect timeout occured.
if (future.isCancelled() || future.isDone()) {
finishChannel(ctx);
return;
}
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler handler = future.getAsyncHandler();
Request request = future.getRequest();
ProxyServer proxyServer = future.getProxyServer();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || !ka.toLowerCase().equals("close"));
List<String> wwwAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.WWW_AUTHENTICATE);
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(handler).request(request).responseStatus(status).responseHeaders(responseHeaders).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
handler = fc.getAsyncHandler();
future.setAsyncHandler(handler);
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
Realm newRealm = null;
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
final RequestBuilder builder = new RequestBuilder(future.getRequest());
// if (realm != null && !future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
// builder.setUrl(future.getURI().toString());
// }
if (statusCode == 401 && realm != null && !wwwAuth.isEmpty() && !future.getAndSetAuth(true)) {
future.setState(NettyResponseFuture.STATE.NEW);
// NTLM
if (!wwwAuth.contains("Kerberos") && (isNTLM(wwwAuth) || (wwwAuth.contains("Negotiate")))) {
newRealm = ntlmChallenge(wwwAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (wwwAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(wwwAuth, request, proxyServer, headers, realm, future);
if (newRealm == null)
return;
} else {
newRealm = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme()).setUri(request.getURI().getPath()).setMethodName(request.getMethod()).setUsePreemptiveAuth(true).parseWWWAuthenticateHeader(wwwAuth.get(0)).build();
}
final Realm nr = new Realm.RealmBuilder().clone(newRealm).setUri(URI.create(request.getUrl()).getPath()).build();
log.debug("Sending authentication to {}", request.getUrl());
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
drainChannel(ctx, future);
nextRequest(builder.setHeaders(headers).setRealm(nr).build(), future);
return null;
}
};
if (future.isKeepAlive() && response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
if (statusCode == 100) {
future.getAndSetWriteHeaders(false);
future.getAndSetWriteBody(true);
writeRequest(ctx.getChannel(), config, future, nettyRequest);
return;
}
List<String> proxyAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.PROXY_AUTHENTICATE);
if (statusCode == 407 && realm != null && !proxyAuth.isEmpty() && !future.getAndSetAuth(true)) {
log.debug("Sending proxy authentication to {}", request.getUrl());
future.setState(NettyResponseFuture.STATE.NEW);
if (!proxyAuth.contains("Kerberos") && (isNTLM(proxyAuth) || (proxyAuth.contains("Negotiate")))) {
newRealm = ntlmProxyChallenge(proxyAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (proxyAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(proxyAuth, request, proxyServer, headers, realm, future);
if (newRealm == null)
return;
} else {
newRealm = future.getRequest().getRealm();
}
Request req = builder.setHeaders(headers).setRealm(newRealm).build();
future.setReuseChannel(true);
future.setConnectAllowed(true);
nextRequest(req, future);
return;
}
if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT) && statusCode == 200) {
log.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());
if (future.isKeepAlive()) {
future.attachChannel(ctx.getChannel(), true);
}
try {
log.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
upgradeProtocol(ctx.getChannel().getPipeline(), request.getURI().getScheme());
} catch (Throwable ex) {
abort(future, ex);
}
Request req = builder.build();
future.setReuseChannel(true);
future.setConnectAllowed(false);
nextRequest(req, future);
return;
}
if (redirect(request, future, response, ctx))
return;
if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, status)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (updateHeadersAndInterrupt(handler, responseHeaders)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
}
finishUpdate(future, ctx, false);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
markAsDone(future, ctx);
drainChannel(ctx, future);
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, chunk, chunk.isLast()))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(), future.getHttpResponse(), NettyAsyncHttpProvider.this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx, !chunk.isLast());
}
}
}
} catch (Exception t) {
if (t instanceof IOException && !config.getIOExceptionFilters().isEmpty()) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler()).request(future.getRequest()).ioException(IOException.class.cast(t)).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
}
try {
abort(future, t);
} finally {
finishUpdate(future, ctx, false);
throw t;
}
}
}
// @Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
}
// @Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
}
}
private final class WebSocketProtocol implements Protocol {
private static final byte OPCODE_CONT = 0x0;
private static final byte OPCODE_TEXT = 0x1;
private static final byte OPCODE_BINARY = 0x2;
private static final byte OPCODE_UNKNOWN = -1;
protected byte pendingOpcode = OPCODE_UNKNOWN;
// We don't need to synchronize as replacing the "ws-decoder" will process using the same thread.
private void invokeOnSucces(ChannelHandlerContext ctx, WebSocketUpgradeHandler h) {
if (!h.touchSuccess()) {
try {
h.onSuccess(new NettyWebSocket(ctx.getChannel()));
} catch (Exception ex) {
NettyAsyncHttpProvider.this.log.warn("onSuccess unexexpected exception", ex);
}
}
}
// @Override
public void handle(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
NettyResponseFuture future = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler());
Request request = future.getRequest();
if (e.getMessage() instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e.getMessage();
HttpResponseStatus s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(h).request(request).responseStatus(s).responseHeaders(responseHeaders).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
future.setAsyncHandler(fc.getAsyncHandler());
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
future.setHttpResponse(response);
if (redirect(request, future, response, ctx))
return;
final org.jboss.netty.handler.codec.http.HttpResponseStatus status = new org.jboss.netty.handler.codec.http.HttpResponseStatus(101, "Web Socket Protocol Handshake");
final boolean validStatus = response.getStatus().equals(status);
final boolean validUpgrade = response.getHeader(HttpHeaders.Names.UPGRADE) != null;
String c = response.getHeader(HttpHeaders.Names.CONNECTION);
if (c == null) {
c = response.getHeader(HttpHeaders.Names.CONNECTION.toLowerCase());
}
final boolean validConnection = c == null ? false : c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE);
s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
final boolean statusReceived = h.onStatusReceived(s) == STATE.UPGRADE;
final boolean headerOK = h.onHeadersReceived(responseHeaders) == STATE.CONTINUE;
if (!headerOK || !validStatus || !validUpgrade || !validConnection || !statusReceived) {
abort(future, new IOException("Invalid handshake response"));
return;
}
String accept = response.getHeader(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT);
String key = WebSocketUtil.getAcceptKey(future.getNettyRequest().getHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY));
if (accept == null || !accept.equals(key)) {
throw new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key));
}
ctx.getPipeline().replace("http-encoder", "ws-encoder", new WebSocket08FrameEncoder(true));
ctx.getPipeline().get(HttpResponseDecoder.class).replace("ws-decoder", new WebSocket08FrameDecoder(false, false));
invokeOnSucces(ctx, h);
future.done();
} else if (e.getMessage() instanceof WebSocketFrame) {
invokeOnSucces(ctx, h);
final WebSocketFrame frame = (WebSocketFrame) e.getMessage();
if (frame instanceof TextWebSocketFrame) {
pendingOpcode = OPCODE_TEXT;
} else if (frame instanceof BinaryWebSocketFrame) {
pendingOpcode = OPCODE_BINARY;
}
HttpChunk webSocketChunk = new HttpChunk() {
private ChannelBuffer content;
// @Override
public boolean isLast() {
return false;
}
// @Override
public ChannelBuffer getContent() {
return content;
}
// @Override
public void setContent(ChannelBuffer content) {
this.content = content;
}
};
if (frame.getBinaryData() != null) {
webSocketChunk.setContent(ChannelBuffers.wrappedBuffer(frame.getBinaryData()));
ResponseBodyPart rp = new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, webSocketChunk, true);
h.onBodyPartReceived(rp);
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
if (webSocket != null) {
if (pendingOpcode == OPCODE_BINARY) {
webSocket.onBinaryFragment(rp.getBodyPartBytes(), frame.isFinalFragment());
} else {
webSocket.onTextFragment(frame.getBinaryData().toString(UTF8), frame.isFinalFragment());
}
if (frame instanceof CloseWebSocketFrame) {
try {
ctx.setAttachment(DiscardEvent.class);
webSocket.onClose(CloseWebSocketFrame.class.cast(frame).getStatusCode(), CloseWebSocketFrame.class.cast(frame).getReasonText());
} catch (Throwable t) {
// Swallow any exception that may comes from a Netty version released before 3.4.0
log.trace("", t);
}
}
} else {
log.debug("UpgradeHandler returned a null NettyWebSocket ");
}
}
} else {
log.error("Invalid attachment {}", ctx.getAttachment());
}
}
// @Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
try {
log.warn("onError {}", e);
if (!(ctx.getAttachment() instanceof NettyResponseFuture)) {
return;
}
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
if (webSocket != null) {
webSocket.onError(e.getCause());
webSocket.close();
}
} catch (Throwable t) {
log.error("onError", t);
}
}
// @Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
log.trace("onClose {}", e);
if (!(ctx.getAttachment() instanceof NettyResponseFuture)) {
return;
}
try {
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
if (!(ctx.getAttachment() instanceof DiscardEvent))
webSocket.close(1006, "Connection was closed abnormally (that is, with no close frame being sent).");
} catch (Throwable t) {
log.error("onError", t);
}
}
}
private static boolean isWebSocket(URI uri) {
return WEBSOCKET.equalsIgnoreCase(uri.getScheme()) || WEBSOCKET_SSL.equalsIgnoreCase(uri.getScheme());
}
private static boolean isSecure(String scheme) {
return HTTPS.equalsIgnoreCase(scheme) || WEBSOCKET_SSL.equalsIgnoreCase(scheme);
}
private static boolean isSecure(URI uri) {
return isSecure(uri.getScheme());
}
}
| true | true | private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ChannelBuffer buffer, ProxyServer proxyServer) throws IOException {
String host = null;
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
} else {
AsyncHttpProviderUtils.getHost(uri);
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");
}
if (host != null) {
if (request.getVirtualHost() != null || uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (Entry<String, List<String>> header : h) {
String name = header.getKey();
if (!HttpHeaders.Names.HOST.equalsIgnoreCase(name)) {
for (String value : header.getValue()) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNTLM(auth)) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException("Invalid Authentication " + realm);
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!isNTLM(auth)) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue(HttpHeaders.Names.ACCEPT) == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
String userAgentHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.USER_AGENT);
if (userAgentHeader != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, userAgentHeader);
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, config.getUserAgent());
} else {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, CookieEncoder.encodeClientSide(request.getCookies(), config.isRfc6265CookieEncoding()));
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
byte[] bytes = request.getStringData().getBytes(bodyCharset);
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(bytes.length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getHeaders());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
| private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ChannelBuffer buffer, ProxyServer proxyServer) throws IOException {
String host = null;
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
} else {
host = AsyncHttpProviderUtils.getHost(uri);
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");
}
if (host != null) {
if (request.getVirtualHost() != null || uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (Entry<String, List<String>> header : h) {
String name = header.getKey();
if (!HttpHeaders.Names.HOST.equalsIgnoreCase(name)) {
for (String value : header.getValue()) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNTLM(auth)) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException("Invalid Authentication " + realm);
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!isNTLM(auth)) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue(HttpHeaders.Names.ACCEPT) == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
String userAgentHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.USER_AGENT);
if (userAgentHeader != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, userAgentHeader);
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, config.getUserAgent());
} else {
nettyRequest.setHeader(HttpHeaders.Names.USER_AGENT, AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, CookieEncoder.encodeClientSide(request.getCookies(), config.isRfc6265CookieEncoding()));
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
byte[] bytes = request.getStringData().getBytes(bodyCharset);
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(bytes.length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getHeaders());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
|
diff --git a/Vision/src/vision/model/Sensor.java b/Vision/src/vision/model/Sensor.java
index 56fb322..20ba930 100644
--- a/Vision/src/vision/model/Sensor.java
+++ b/Vision/src/vision/model/Sensor.java
@@ -1,209 +1,210 @@
package vision.model;
import java.util.ArrayList;
import java.util.List;
/**
* The Sensor class holds all sensor data
*
*/
public class Sensor {
public Sensor() {
this.setMesswert();
- this.setTags();
+ List<String> tags = new ArrayList<String>();
+ this.setTags(tags);
}
public Sensor(String id, int time, List<Sample> samples) {
this.id = id;
samples = new ArrayList<Sample>();
}
/**
* @uml.property name="id"
*/
private String id;
/**
* @uml.property name="tags"
*/
private List<String> tags;
/**
* @uml.property name="Description"
*/
private String description;
/**
* @uml.property name="update"
*/
private long update;
/**
* @uml.property name="registered"
*/
private long registered;
/**
* Getter of the property <tt>id</tt>
*
* @return Returns the id.
* @uml.property name="id"
*/
public String getId() {
return id;
}
/**
* Setter of the property <tt>id</tt>
*
* @param id
* The id to set.
* @uml.property name="id"
*/
public void setId(String id) {
this.id = id;
}
/**
* Getter of the property <tt>tags</tt>
*
* @return Returns the tags.
* @uml.property name="tags"
*/
public List<String> getTags() {
return tags;
}
/**
* Setter of the property <tt>tags</tt>
*
* @param tags
* The tags to set.
* @uml.property name="tags"
*/
public void setTags(List<String> tags) {
this.tags = new ArrayList<String>();
}
/**
* Getter of the property <tt>Description</tt>
*
* @return Returns the description.
* @uml.property name="Description"
*/
public String getDescription() {
return description;
}
/**
* Setter of the property <tt>Description</tt>
*
* @param Description
* The description to set.
* @uml.property name="Description"
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Getter of the property <tt>update</tt>
*
* @return Returns the update.
* @uml.property name="update"
*/
public long getUpdate() {
return update;
}
/**
* Setter of the property <tt>update</tt>
*
* @param update
* The update to set.
* @uml.property name="update"
*/
public void setUpdate(long update) {
this.update = update;
}
/**
* Getter of the property <tt>registered</tt>
*
* @return Returns the registered.
* @uml.property name="registered"
*/
public long registeredTime() {
return registered;
}
/**
* Setter of the property <tt>registered</tt>
*
* @param registered
* The registered to set.
* @uml.property name="registered"
*/
public void setRegistered(long registered) {
this.registered = registered;
}
/**
* Getter of the property <tt>messwerte</tt>
*
* @return Returns the messwerte.
* @uml.property name="messwerte"
*/
public List<Sample> getMesswert() {
return messwert;
}
private List<Sample> messwert;
private void setMesswert() {
this.messwert = new ArrayList<Sample>();
}
public void addToSamples(Sample s) {
this.messwert.add(s);
}
public void addToTags(String s) {
this.tags.add(s);
}
/**
* adds Sample to List of samples
*
* @param sample
*/
/**
* @uml.property name="position"
* @uml.associationEnd inverse="sensor:vision.model.Position"
*/
private Position position;
/**
* Getter of the property <tt>position</tt>
*
* @return Returns the position.
* @uml.property name="position"
*/
public Position getPosition() {
return position;
}
/**
* Setter of the property <tt>position</tt>
*
* @param position
* The position to set.
* @uml.property name="position"
*/
public void setPosition(Position position) {
this.position = position;
}
}
| true | true | public Sensor() {
this.setMesswert();
this.setTags();
}
| public Sensor() {
this.setMesswert();
List<String> tags = new ArrayList<String>();
this.setTags(tags);
}
|
diff --git a/src/com/stu/ihelp/client/PersonalData.java b/src/com/stu/ihelp/client/PersonalData.java
index 50ec40e..db92ba7 100644
--- a/src/com/stu/ihelp/client/PersonalData.java
+++ b/src/com/stu/ihelp/client/PersonalData.java
@@ -1,60 +1,60 @@
package com.stu.ihelp.client;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
public class PersonalData extends Activity {
private EditText et_name, et_contact_phone;
private Button confirm, cancel;
private SharedPreferences spfs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.personal_data);
et_name = (EditText) findViewById(R.id.edit_name);
et_contact_phone = (EditText) findViewById(R.id.edit_contact_phone);
confirm = (Button) findViewById(R.id.btn_submit);
cancel = (Button) findViewById(R.id.btn_cancel);
et_name.setText(Variable.name);
et_contact_phone.setText(Variable.contact_phone);
spfs = getSharedPreferences(Variable.FILENAME, MODE_PRIVATE);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spfs.edit()
- .putString(Variable.name = Variable.NAME,
+ .putString(Variable.NAME,
et_name.getEditableText().toString())
.putString(
- Variable.contact_phone = Variable.CONTACT_PHONE,
+ Variable.CONTACT_PHONE,
et_contact_phone.getEditableText().toString())
.commit();
setResult(RESULT_OK);
PersonalData.this.finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
PersonalData.this.finish();
}
});
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.personal_data);
et_name = (EditText) findViewById(R.id.edit_name);
et_contact_phone = (EditText) findViewById(R.id.edit_contact_phone);
confirm = (Button) findViewById(R.id.btn_submit);
cancel = (Button) findViewById(R.id.btn_cancel);
et_name.setText(Variable.name);
et_contact_phone.setText(Variable.contact_phone);
spfs = getSharedPreferences(Variable.FILENAME, MODE_PRIVATE);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spfs.edit()
.putString(Variable.name = Variable.NAME,
et_name.getEditableText().toString())
.putString(
Variable.contact_phone = Variable.CONTACT_PHONE,
et_contact_phone.getEditableText().toString())
.commit();
setResult(RESULT_OK);
PersonalData.this.finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
PersonalData.this.finish();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.personal_data);
et_name = (EditText) findViewById(R.id.edit_name);
et_contact_phone = (EditText) findViewById(R.id.edit_contact_phone);
confirm = (Button) findViewById(R.id.btn_submit);
cancel = (Button) findViewById(R.id.btn_cancel);
et_name.setText(Variable.name);
et_contact_phone.setText(Variable.contact_phone);
spfs = getSharedPreferences(Variable.FILENAME, MODE_PRIVATE);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spfs.edit()
.putString(Variable.NAME,
et_name.getEditableText().toString())
.putString(
Variable.CONTACT_PHONE,
et_contact_phone.getEditableText().toString())
.commit();
setResult(RESULT_OK);
PersonalData.this.finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
PersonalData.this.finish();
}
});
}
|
diff --git a/src/Word.java b/src/Word.java
index 20b5fef..8ec2e13 100644
--- a/src/Word.java
+++ b/src/Word.java
@@ -1,128 +1,128 @@
import java.util.ArrayList;
import java.util.Collections;
public class Word {
String word;
ArrayList<Link> links = new ArrayList<Link>();
final String eos = "^&eos&^";
public Word(String word) {
this.word = this.trimWord(word);
}
public void addLink(Word otherWord) {
Integer linkPosition = getIndexOfLinkOrNull(otherWord);
if (linkPosition != null) {
this.links.get(linkPosition).plusRate();
} else {
this.links.add(new Link(otherWord));
}
Collections.sort(this.links, new LinksComparator());
}
private String trimWord(String word) {
return word.toLowerCase().replaceFirst("(\\.|!|;|\\-|:|\\?|\\s|,)", "");
}
public ArrayList<Link> getLinks() {
return links;
}
public Word getSingleLink(int index) {
if (links.isEmpty()) {
return null;
} else {
return links.get(index).otherWord;
}
}
public Link getNearestEOSLink() {
if (links.isEmpty()) {
return null;
} else {
for (Link next : links) {
if (next.otherWord.toString().equals(eos)) {
return next;
}
}
}
return null;
}
public Integer getEOSIndexOrNull() {
if (links.isEmpty()) {
return null;
} else {
int count = 0;
for (Link link : links) {
if (link.otherWord.toString().equals(eos)) {
return count;
}
count++;
}
}
return null;
}
public Integer getIndexOfLinkOrNull(Word link) {
int count = 0;
Link otherLink = new Link(link);
for (Link next : links) {
if (next.equals(otherLink)) {
return count;
}
count++;
}
return null;
}
public Word getBestLink() {
Word returnWord;
if (getSingleLink(0) == null) {
return null;
- } else if (getSingleLink(0).toString().equals("^&eos&^") && links.size() > 1) {
+ } else if ((getSingleLink(0).toString().equals("^&eos&^")) && links.size() > 1) {
returnWord = getSingleLink(1);
links.get(1).downRate();
Collections.sort(this.links, new LinksComparator());
} else if (getSingleLink(0).toString().equals("^&eos&^")) {
return null;
} else {
returnWord = getSingleLink(0);
links.get(0).downRate();
Collections.sort(this.links, new LinksComparator());
}
return returnWord;
}
public boolean hasEOSLink() {
for (Link link : links) {
Word x = link.otherWord;
if (x.equals(new Word(eos))) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Word word1 = (Word) o;
return !(word != null ? !word.equals(word1.word) : word1.word != null);
}
@Override
public int hashCode() {
int result = word != null ? word.hashCode() : 0;
result = 31 * result + (links != null ? links.hashCode() : 0);
result = 31 * result + (eos.hashCode());
return result;
}
//override so we can compare vs "eos" via .equals()
@Override
public String toString() {
return this.word;
}
}
| true | true | public Word getBestLink() {
Word returnWord;
if (getSingleLink(0) == null) {
return null;
} else if (getSingleLink(0).toString().equals("^&eos&^") && links.size() > 1) {
returnWord = getSingleLink(1);
links.get(1).downRate();
Collections.sort(this.links, new LinksComparator());
} else if (getSingleLink(0).toString().equals("^&eos&^")) {
return null;
} else {
returnWord = getSingleLink(0);
links.get(0).downRate();
Collections.sort(this.links, new LinksComparator());
}
return returnWord;
}
| public Word getBestLink() {
Word returnWord;
if (getSingleLink(0) == null) {
return null;
} else if ((getSingleLink(0).toString().equals("^&eos&^")) && links.size() > 1) {
returnWord = getSingleLink(1);
links.get(1).downRate();
Collections.sort(this.links, new LinksComparator());
} else if (getSingleLink(0).toString().equals("^&eos&^")) {
return null;
} else {
returnWord = getSingleLink(0);
links.get(0).downRate();
Collections.sort(this.links, new LinksComparator());
}
return returnWord;
}
|
diff --git a/Android-Base-Project/android-base/src/main/java/net/vrallev/android/base/view/ViewHelper.java b/Android-Base-Project/android-base/src/main/java/net/vrallev/android/base/view/ViewHelper.java
index 16a0115..c97b47f 100644
--- a/Android-Base-Project/android-base/src/main/java/net/vrallev/android/base/view/ViewHelper.java
+++ b/Android-Base-Project/android-base/src/main/java/net/vrallev/android/base/view/ViewHelper.java
@@ -1,50 +1,50 @@
package net.vrallev.android.base.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
/**
* @author Ralf Wondratschek
*/
@SuppressWarnings({"ConstantConditions", "UnusedDeclaration"})
public class ViewHelper {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void removeOnGlobalLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
} else {
//noinspection deprecation
view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
}
}
public static void setVisibility(View view, int visibility) {
setVisibility(view, visibility, 300l);
}
public static void setVisibility(final View view, final int visibility, long duration) {
if (view.getVisibility() == visibility) {
return;
}
if (view.getVisibility() != View.VISIBLE && visibility == View.VISIBLE) {
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
- view.animate().alpha(1f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).start();
+ view.animate().alpha(1f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).setListener(null).start();
} else if (view.getVisibility() == View.VISIBLE) {
view.animate().alpha(0f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(visibility);
view.setAlpha(1f);
}
}).start();
}
}
}
| true | true | public static void setVisibility(final View view, final int visibility, long duration) {
if (view.getVisibility() == visibility) {
return;
}
if (view.getVisibility() != View.VISIBLE && visibility == View.VISIBLE) {
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
view.animate().alpha(1f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).start();
} else if (view.getVisibility() == View.VISIBLE) {
view.animate().alpha(0f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(visibility);
view.setAlpha(1f);
}
}).start();
}
}
| public static void setVisibility(final View view, final int visibility, long duration) {
if (view.getVisibility() == visibility) {
return;
}
if (view.getVisibility() != View.VISIBLE && visibility == View.VISIBLE) {
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
view.animate().alpha(1f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).setListener(null).start();
} else if (view.getVisibility() == View.VISIBLE) {
view.animate().alpha(0f).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(duration).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(visibility);
view.setAlpha(1f);
}
}).start();
}
}
|
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/AdvSearchPage.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/AdvSearchPage.java
index 56f67177..0e72e06e 100644
--- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/AdvSearchPage.java
+++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/AdvSearchPage.java
@@ -1,986 +1,987 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* AdvSearchPage.java
*
* Created on September 14, 2006, 11:27 AM
*/
package edu.harvard.iq.dvn.core.web;
import edu.harvard.iq.dvn.core.index.IndexServiceLocal;
import edu.harvard.iq.dvn.core.index.SearchTerm;
import edu.harvard.iq.dvn.core.study.StudyField;
import edu.harvard.iq.dvn.core.study.StudyFieldServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCCollection;
import edu.harvard.iq.dvn.core.vdc.VDCCollectionServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import edu.harvard.iq.dvn.core.web.collection.CollectionModel;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import edu.harvard.iq.dvn.core.web.site.VDCUI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ActionEvent;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlSelectBooleanCheckbox;
import com.icesoft.faces.component.ext.HtmlSelectOneRadio;
import com.icesoft.faces.component.ext.HtmlDataTable;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlPanelGrid;
import edu.harvard.iq.dvn.core.study.VariableServiceLocal;
import javax.faces.component.UIColumn;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.inject.Named;
/**
* <p>Page bean that corresponds to a similarly named JSP page. This
* class contains component definitions (and initialization code) for
* all components that you have defined on this page, as well as
* lifecycle methods and event handlers where you may add behavior
* to respond to incoming events.</p>
*/
@Named("AdvSearchPage")
@ViewScoped
public class AdvSearchPage extends VDCBaseBean implements java.io.Serializable {
@EJB
VDCServiceLocal vdcService;
@EJB
VDCCollectionServiceLocal vdcCollectionService;
@EJB
IndexServiceLocal indexServiceBean;
@EJB
StudyFieldServiceLocal studyFieldService;
@EJB
StudyServiceLocal studyService;
@EJB
VariableServiceLocal varService;
private Locale currentLocale = getExternalContext().getRequestLocale();
private ResourceBundle messages = ResourceBundle.getBundle("Bundle");
private HashMap advSearchFieldMap = new HashMap();
private HashMap operatorMap = new HashMap();
private String[] advancedSearchFields = {"title", "authorName", "globalId", "otherId", "abstractText", "keywordValue", "keywordVocabulary", "topicClassValue", "topicClassVocabulary", "producerName", "distributorName", "fundingAgency", "productionDate", "distributionDate", "dateOfDeposit", "timePeriodCoveredStart", "timePeriodCoveredEnd", "country", "geographicCoverage", "geographicUnit", "universe", "kindOfData"};
private boolean collectionsIncluded;
private boolean variableSearch;
private List <SearchTerm> variableInfoList = new ArrayList();
public boolean isVariableSearch() {
return variableSearch;
}
public void setVariableSearch(boolean variableSearch) {
this.variableSearch = variableSearch;
}
public boolean isCollectionsIncluded() {
return collectionsIncluded;
}
public List getVariableInfoList() {
return variableInfoList;
}
public void setVariableInfoList(List variableInfo) {
this.variableInfoList = variableInfo;
}
// <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
private int __placeholder;
/**
* <p>Automatically managed component initialization. <strong>WARNING:</strong>
* This method is automatically generated, so any user-specified code inserted
* here is subject to being replaced.</p>
*/
public void init() {
super.init();
radioButtonList1DefaultItems = initSelectItemList(new String[]{messages.getString("searchAllCollections"), messages.getString("searchOnlySelectedCollections")});
dropdown3DefaultItems = initSelectItemList(getAdvSearchFieldDefaults());
dropdown4DateItems = initSelectItemList(new String[]{messages.getString("isGreaterThan"), messages.getString("isLessThan")});
dropdown4NotDateItems = initSelectItemList(new String[]{messages.getString("contains"), messages.getString("doesNotContain")});
// Adding 4 rows here and removing user's ability to add/remove in interface.
/* Add these back to xhtml when/if user is given control
<ice:column>
<ice:commandButton image="/resources/images/icon_add.gif" actionListener="#{AdvSearchPage.addRow}"/>
<ice:commandButton rendered="#{AdvSearchPage.dataTableVariableInfo.rowCount gt 1}" image="/resources/images/icon_remove.gif" actionListener="#{AdvSearchPage.removeRow}" />
</ice:column>
*/
initVariableInfoList();
operatorMap.put(messages.getString("contains"), "=");
operatorMap.put(messages.getString("doesNotContain"), "-");
operatorMap.put(messages.getString("isGreaterThan"), ">");
operatorMap.put(messages.getString("isLessThan"), "<");
if (getVDCRequestBean().getCurrentVDC() != null){
long vdcId=getVDCRequestBean().getCurrentVDC().getId().longValue();
dropdown3DefaultItems = initSelectItemList(getSearchScopeList(vdcId));
}
else{
dropdown3DefaultItems = initSelectItemList(getAdvSearchFieldDefaults());
}
collectionModelList = getCollectionsDisplay();
}
private List<SelectItem> initSelectItemList(String[] itemsArray ) {
List<SelectItem> list = new ArrayList();
for (int i = 0; i < itemsArray.length; i++) {
SelectItem selectItem = new SelectItem(itemsArray[i]);
list.add(selectItem);
}
return list;
}
private void initVariableInfoList(){
variableInfoList.add(initVariableSearchTerm());
//We originally added 4 rows but the AND on the search would never return a result.
//left these here as a reminder just in case we re-visit. SEK
//variableInfoList.add(initVariableSearchTerm());
//variableInfoList.add(initVariableSearchTerm());
//variableInfoList.add(initVariableSearchTerm());
}
private SearchTerm initVariableSearchTerm(){
SearchTerm addToList = new SearchTerm();
addToList.setFieldName("variable");
addToList.setOperator("=");
addToList.setValue("");
return addToList;
}
private HtmlSelectOneMenu dropdown1 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown1() {
return dropdown1;
}
/**
* Holds value of property inputVariableInfo.
*/
private HtmlInputText inputVariableInfo;
/**
* Getter for property variableInfo.
* @return Value of property inputVariableInfo.
*/
public HtmlInputText getInputVariableInfo() {
return this.inputVariableInfo;
}
/**
* Setter for property variableInfo.
* @param variableInfo New value of property variableInfo.
*/
public void setInputVariableInfo(HtmlInputText inputVariableInfo) {
this.inputVariableInfo = inputVariableInfo;
}
public void setDropdown1(HtmlSelectOneMenu hsom) {
this.dropdown1 = hsom;
}
private UISelectItems dropdown1SelectItems = new UISelectItems();
public UISelectItems getDropdown1SelectItems() {
return dropdown1SelectItems;
}
public void setDropdown1SelectItems(UISelectItems uisi) {
this.dropdown1SelectItems = uisi;
}
private HtmlCommandButton searchCommand;
private HtmlPanelGrid gridPanel1;
private HtmlInputText textField1 = new HtmlInputText();
public HtmlInputText getTextField1() {
return textField1;
}
public void setTextField1(HtmlInputText hit) {
this.textField1 = hit;
}
private HtmlSelectOneMenu dropdown3 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown3() {
return dropdown3;
}
public void setDropdown3(HtmlSelectOneMenu hsom) {
this.dropdown3 = hsom;
}
private List<SelectItem> dropdown3DefaultItems = new ArrayList();
public List<SelectItem> getDropdown3DefaultItems() {
return dropdown3DefaultItems;
}
public void setDropdown3DefaultItems(List<SelectItem> dropdown3DefaultItems) {
this.dropdown3DefaultItems = dropdown3DefaultItems;
}
private UISelectItems dropdown3SelectItems = new UISelectItems();
public UISelectItems getDropdown3SelectItems() {
return dropdown3SelectItems;
}
public void setDropdown3SelectItems(UISelectItems uisi) {
this.dropdown3SelectItems = uisi;
}
private HtmlSelectOneMenu dropdown4 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown4() {
return dropdown4;
}
public void setDropdown4(HtmlSelectOneMenu hsom) {
this.dropdown4 = hsom;
}
private List<SelectItem> dropdown4DateItems = new ArrayList();
public List<SelectItem> getDropdown4DateItems() {
return dropdown4DateItems;
}
public void setDropdown4DateItems(List<SelectItem> dropdown4DateItems) {
this.dropdown4DateItems = dropdown4DateItems;
}
private List<SelectItem> dropdown4NotDateItems = new ArrayList();
public List<SelectItem> getDropdown4NotDateItems() {
return dropdown4NotDateItems;
}
public void setDropdown4NotDateItems(List<SelectItem> dropdown4NotDateItems) {
this.dropdown4NotDateItems = dropdown4NotDateItems;
}
private UISelectItems dropdown4SelectItems = new UISelectItems();
public UISelectItems getDropdown4SelectItems() {
return dropdown4SelectItems;
}
public void setDropdown4SelectItems(UISelectItems uisi) {
this.dropdown4SelectItems = uisi;
}
private HtmlInputText textField2 = new HtmlInputText();
public HtmlInputText getTextField2() {
return textField2;
}
public void setTextField2(HtmlInputText hit) {
this.textField2 = hit;
}
private HtmlSelectOneMenu dropdown5 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown5() {
return dropdown5;
}
public void setDropdown5(HtmlSelectOneMenu hsom) {
this.dropdown5 = hsom;
}
private UISelectItems dropdown3SelectItems1 = new UISelectItems();
public UISelectItems getDropdown3SelectItems1() {
return dropdown3SelectItems1;
}
public void setDropdown3SelectItems1(UISelectItems uisi) {
this.dropdown3SelectItems1 = uisi;
}
private HtmlSelectOneMenu dropdown6 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown6() {
return dropdown6;
}
public void setDropdown6(HtmlSelectOneMenu hsom) {
this.dropdown6 = hsom;
}
private UISelectItems dropdown4SelectItems1 = new UISelectItems();
public UISelectItems getDropdown4SelectItems1() {
return dropdown4SelectItems1;
}
public void setDropdown4SelectItems1(UISelectItems uisi) {
this.dropdown4SelectItems1 = uisi;
}
private HtmlInputText textField3 = new HtmlInputText();
public HtmlInputText getTextField3() {
return textField3;
}
public void setTextField3(HtmlInputText hit) {
this.textField3 = hit;
}
private HtmlSelectOneMenu dropdown7 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown7() {
return dropdown7;
}
public void setDropdown7(HtmlSelectOneMenu hsom) {
this.dropdown7 = hsom;
}
private UISelectItems dropdown3SelectItems2 = new UISelectItems();
public UISelectItems getDropdown3SelectItems2() {
return dropdown3SelectItems2;
}
public void setDropdown3SelectItems2(UISelectItems uisi) {
this.dropdown3SelectItems2 = uisi;
}
private HtmlSelectOneMenu dropdown8 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown8() {
return dropdown8;
}
public void setDropdown8(HtmlSelectOneMenu hsom) {
this.dropdown8 = hsom;
}
private UISelectItems dropdown4SelectItems2 = new UISelectItems();
public UISelectItems getDropdown4SelectItems2() {
return dropdown4SelectItems2;
}
public void setDropdown4SelectItems2(UISelectItems uisi) {
this.dropdown4SelectItems2 = uisi;
}
private HtmlInputText textField4 = new HtmlInputText();
public HtmlInputText getTextField4() {
return textField4;
}
public void setTextField4(HtmlInputText hit) {
this.textField4 = hit;
}
private HtmlSelectOneRadio radioButtonList1 = new HtmlSelectOneRadio();
public HtmlSelectOneRadio getRadioButtonList1() {
return radioButtonList1;
}
public void setRadioButtonList1(HtmlSelectOneRadio hsor) {
this.radioButtonList1 = hsor;
}
private List<SelectItem> radioButtonList1DefaultItems = new ArrayList();
public List<SelectItem> getRadioButtonList1DefaultItems() {
return radioButtonList1DefaultItems;
}
public void setRadioButtonList1DefaultItems(List<SelectItem> radioButtonList1DefaultItems) {
this.radioButtonList1DefaultItems = radioButtonList1DefaultItems;
}
private UISelectItems radioButtonList1SelectItems = new UISelectItems();
public UISelectItems getRadioButtonList1SelectItems() {
return radioButtonList1SelectItems;
}
public void setRadioButtonList1SelectItems(UISelectItems uisi) {
this.radioButtonList1SelectItems = uisi;
}
private HtmlSelectOneMenu dropdown9 = new HtmlSelectOneMenu();
public HtmlSelectOneMenu getDropdown9() {
return dropdown9;
}
public void setDropdown9(HtmlSelectOneMenu hsom) {
this.dropdown9 = hsom;
}
private UISelectItems dropdown4SelectItems3 = new UISelectItems();
public UISelectItems getDropdown4SelectItems3() {
return dropdown4SelectItems3;
}
public void setDropdown4SelectItems3(UISelectItems uisi) {
this.dropdown4SelectItems3 = uisi;
}
private HtmlDataTable dataTable1 = new HtmlDataTable();
public HtmlDataTable getDataTable1() {
return dataTable1;
}
public void setDataTable1(HtmlDataTable hdt) {
this.dataTable1 = hdt;
}
private List<CollectionModel> collectionModelList = new ArrayList();
public List<CollectionModel> getCollectionModelList() {
return collectionModelList;
}
public void setCollectionModelList(List<CollectionModel> collectionModelList) {
this.collectionModelList = collectionModelList;
}
private UIColumn column1 = new UIColumn();
public UIColumn getColumn1() {
return column1;
}
public void setColumn1(UIColumn uic) {
this.column1 = uic;
}
private HtmlSelectBooleanCheckbox checkbox1 = new HtmlSelectBooleanCheckbox();
public HtmlSelectBooleanCheckbox getCheckbox1() {
return checkbox1;
}
public void setCheckbox1(HtmlSelectBooleanCheckbox hsbc) {
this.checkbox1 = hsbc;
}
// </editor-fold>
/**
* Holds value of property dataVariableInfo.
*/
private HtmlDataTable dataTableVariableInfo;
/**
* Getter for property dataVariableInfo.
* @return Value of property dataVariableInfo.
*/
public HtmlDataTable getDataTableVariableInfo() {
return this.dataTableVariableInfo;
}
public void setDataTableVariableInfo(HtmlDataTable hdt) {
this.dataTableVariableInfo = hdt;
}
private HtmlInputText input_VariableInfo;
/**
* <p>Construct a new Page bean instance.</p>
*/
public AdvSearchPage() {
}
/**
* <p>Callback method that is called after the component tree has been
* restored, but before any event processing takes place. This method
* will <strong>only</strong> be called on a postback request that
* is processing a form submit. Customize this method to allocate
* resources that will be required in your event handlers.</p>
*/
public void preprocess() {
}
/**
* <p>Callback method that is called just before rendering takes place.
* This method will <strong>only</strong> be called for the page that
* will actually be rendered (and not, for example, on a page that
* handled a postback and then navigated to a different page). Customize
* this method to allocate resources that will be required for rendering
* this page.</p>
*/
public void prerender() {
}
/**
* <p>Callback method that is called after rendering is completed for
* this request, if <code>init()</code> was called (regardless of whether
* or not this was the page that was actually rendered). Customize this
* method to release resources acquired in the <code>init()</code>,
* <code>preprocess()</code>, or <code>prerender()</code> methods (or
* acquired during execution of an event handler).</p>
*/
public void destroy() {
}
public void checkboxList1_processValueChange(ValueChangeEvent vce) {
// TODO: Replace with your code
}
public String[] getAdvSearchFieldDefaults() {
// List advSearchFieldDefault = studyFieldService.findAdvSearchDefault();
String[] advS = getFieldList(advancedSearchFields);
// String [] advS = getFieldList(advancedSearchFields);
return advS;
}
public String[] getSearchScopeList(long vdcId) {
// ArrayList displayNames = new ArrayList();
VDC vdc = vdcService.find(new Long(vdcId));
Collection advSearchFields = vdc.getAdvSearchFields();
String[] advS = getFieldList(advSearchFields);
return advS;
}
private String[] getFieldList(final Collection advSearchFields) {
String[] advS = new String[advSearchFields.size()];
// DefaultSelectItemsArray dsia = new DefaultSelectItemsArray();
int i = 0;
for (Iterator it = advSearchFields.iterator(); it.hasNext();) {
StudyField elem = (StudyField) it.next();
elem.getId();
advS[i++] = getUserFriendlySearchField(elem.getName());
advSearchFieldMap.put(getUserFriendlySearchField(elem.getName()), elem.getName());
}
return advS;
}
private String[] getFieldList(String[] advSearchFields) {
String[] advS = new String[advSearchFields.length];
for (int i = 0; i < advS.length; i++) {
advS[i] = getUserFriendlySearchField(advSearchFields[i]);
advSearchFieldMap.put(getUserFriendlySearchField(advSearchFields[i]), advSearchFields[i]);
}
// DefaultSelectItemsArray dsia = new DefaultSelectItemsArray();
/*
int i=0;
for (Iterator it = advSearchFields.iterator(); it.hasNext();) {
String name = (String) it.next();
advS[i++]=messages.getString(name);
advSearchFieldMap.put(messages.getString(name),name);
}
*/
return advS;
}
private String getUserFriendlySearchField(String searchField) {
try {
return ResourceBundle.getBundle("SearchFieldBundle").getString(searchField);
} catch (MissingResourceException e) {
return searchField;
}
}
public List getCollectionsDisplay() {
ArrayList collections = new ArrayList();
VDC vdc = getVDCRequestBean().getCurrentVDC();
if (vdc != null) {
getVDCCollections(vdc, collections);
} else {
collectionsIncluded = false;
}
return collections;
}
private void getVDCCollections(final VDC vdc, final ArrayList collections) {
int treeLevel = 1;
if ( !new VDCUI(vdc).containsOnlyLinkedCollections() ) {
VDCCollection vdcRootCollection = vdc.getRootCollection();
CollectionModel row = getRow(vdcRootCollection, treeLevel);
collections.add(row);
List<VDCCollection> subcollections = vdcCollectionService.findSubCollections(vdcRootCollection.getId(), false);
if (!subcollections.isEmpty()) {
collectionsIncluded = true;
}
buildDisplayModel(collections, subcollections, treeLevel);
}
// linked collections
List<VDCCollection> linkedCollections = new VDCUI(vdc).getLinkedCollections(false);
for (Iterator it = linkedCollections.iterator(); it.hasNext();) {
VDCCollection link = (VDCCollection) it.next();
CollectionModel linkedRow = getRow(link, treeLevel);
collections.add(linkedRow);
// linked collection subcollections
buildDisplayModel(collections, vdcCollectionService.findSubCollections(link.getId(), false), treeLevel);
}
if (!linkedCollections.isEmpty()) {
collectionsIncluded = true;
}
}
private int buildDisplayModel(ArrayList collections, List<VDCCollection> vdcCollections, int level) {
level++;
for (Iterator it = vdcCollections.iterator(); it.hasNext();) {
VDCCollection elem = (VDCCollection) it.next();
// collection.setLevel(level);
CollectionModel row = getRow(elem, level);
// collections.add(collection);
collections.add(row);
List<VDCCollection> subcollections = vdcCollectionService.findSubCollections(elem.getId(), false);
// Collection <VDCCollection> subcollections = elem.getSubCollections();
if (!subcollections.isEmpty()) {
buildDisplayModel(collections, subcollections, level);
}
}
level--;
return level;
}
private CollectionModel getRow(final VDCCollection collection, final int level) {
CollectionModel row = new CollectionModel();
row.setLevel(level);
row.setId(collection.getId());
row.setName(collection.getName());
row.setSelected(false);
return row;
}
public String search() {
// String query = buildQuery();
List searchCollections = null;
boolean searchOnlySelectedCollections = false;
if (validateAllSearchCriteria()){
if (radioButtonList1.getValue() != null) {
String radioButtonStr = (String) radioButtonList1.getValue();
if (radioButtonStr.indexOf("Only") > 1) {
searchOnlySelectedCollections = true;
searchCollections = new ArrayList();
for (Iterator it = collectionModelList.iterator(); it.hasNext();) {
CollectionModel elem = (CollectionModel) it.next();
if (elem.isSelected()) {
VDCCollection selectedCollection = vdcCollectionService.find(elem.getId());
searchCollections.add(selectedCollection);
}
}
if (searchCollections.isEmpty()) {
searchOnlySelectedCollections = false;
}
}
}
List<SearchTerm> searchTerms = buildSearchTermList();
VDC thisVDC = getVDCRequestBean().getCurrentVDC();
List<Long> viewableIds = null;
if (searchOnlySelectedCollections) {
viewableIds = indexServiceBean.search(thisVDC, searchCollections, searchTerms);
} else {
viewableIds = indexServiceBean.search(thisVDC, searchTerms);
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
+ sl.setVdcId(getVDCRequestBean().getCurrentVDCId());
sl.setSearchTerms(searchTerms);
if (isVariableSearch()) {
Map variableMap = new HashMap();
List studies = new ArrayList();
varService.determineStudiesFromVariables(viewableIds, studies, variableMap);
sl.setStudyIds(studies);
sl.setVariableMap(variableMap);
} else {
sl.setStudyIds(viewableIds);
}
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
else{
return "";
}
}
public boolean isDateItem(String s) {
// there is an issue with the date items, so for the time being, we are treating all fields as non date
//boolean retVal = s != null && (s.equalsIgnoreCase("Production Date") || s.equalsIgnoreCase("Distribution Date") || s.equalsIgnoreCase("Date of Deposit") || s.startsWith("Time Period Covered"));
//return retVal;
return false;
}
public boolean isDateItem1() {
return isDateItem(dropdown1.getValue().toString());
}
public boolean isDateItem2() {
return isDateItem(dropdown3.getValue().toString());
}
public boolean isDateItem3() {
return isDateItem(dropdown5.getValue().toString());
}
public boolean isDateItem4() {
return isDateItem(dropdown7.getValue().toString());
}
public void searchFieldListener(ValueChangeEvent vce) {
FacesContext.getCurrentInstance().renderResponse();
}
public String indexAll() {
indexServiceBean.indexAll();
return "success";
}
protected String buildQuery() {
StringBuffer query = new StringBuffer();
if (((String) textField1.getValue()).length() > 0) {
query.append(advSearchFieldIndexName((String) dropdown1.getValue()) + " " + operatorToken((String) dropdown9.getValue()) + " " + (String) textField1.getValue());
}
if (((String) textField2.getValue()).length() > 0) {
query.append(" AND " + advSearchFieldIndexName((String) dropdown3.getValue()) + " " + operatorToken((String) dropdown4.getValue()) + " " + (String) textField2.getValue());
}
if (((String) textField3.getValue()).length() > 0) {
query.append(" AND " + advSearchFieldIndexName((String) dropdown5.getValue()) + " " + operatorToken((String) dropdown6.getValue()) + " " + (String) textField3.getValue());
}
if (((String) textField4.getValue()).length() > 0) {
query.append(" AND " + advSearchFieldIndexName((String) dropdown7.getValue()) + " " + operatorToken((String) dropdown8.getValue()) + " " + (String) textField4.getValue());
}
return query.toString();
}
protected List<SearchTerm> buildSearchTermList() {
List<SearchTerm> searchTerms = new ArrayList();
if (((String) textField1.getValue()).length() > 0) {
SearchTerm searchTerm1 = new SearchTerm();
searchTerm1.setFieldName(advSearchFieldIndexName((String) dropdown1.getValue()));
searchTerm1.setOperator(operatorToken((String) dropdown9.getValue()));
searchTerm1.setValue((String) textField1.getValue());
searchTerms.add(searchTerm1);
}
if (((String) textField2.getValue()).length() > 0) {
SearchTerm searchTerm2 = new SearchTerm();
searchTerm2.setFieldName(advSearchFieldIndexName((String) dropdown3.getValue()));
searchTerm2.setOperator(operatorToken((String) dropdown4.getValue()));
searchTerm2.setValue((String) textField2.getValue());
searchTerms.add(searchTerm2);
}
if (((String) textField3.getValue()).length() > 0) {
SearchTerm searchTerm3 = new SearchTerm();
searchTerm3.setFieldName(advSearchFieldIndexName((String) dropdown5.getValue()));
searchTerm3.setOperator(operatorToken((String) dropdown6.getValue()));
searchTerm3.setValue((String) textField3.getValue());
searchTerms.add(searchTerm3);
}
if (((String) textField4.getValue()).length() > 0) {
SearchTerm searchTerm4 = new SearchTerm();
searchTerm4.setFieldName(advSearchFieldIndexName((String) dropdown7.getValue()));
searchTerm4.setOperator(operatorToken((String) dropdown8.getValue()));
searchTerm4.setValue((String) textField4.getValue());
searchTerms.add(searchTerm4);
}
if (variableInfoList.size() > 0){
for (SearchTerm searchTerm : variableInfoList) {
if ( searchTerm.getValue().length() > 0 ){
searchTerms.add(searchTerm);
setVariableSearch(true);
}
}
}
return searchTerms;
}
protected String operatorToken(String operator) {
return (String) operatorMap.get(operator);
}
protected String advSearchFieldIndexName(String displayName) {
return (String) advSearchFieldMap.get(displayName);
}
private boolean isValid(String dateString, String pattern) {
boolean valid;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false);
try {
sdf.parse(dateString);
valid = true;
} catch (ParseException e) {
valid = false;
}
return valid;
}
public boolean validateAllSearchCriteria() {
if (hasCatalogSearchCriteria() && !hasCatalogSearchCriteriaWithContains()) {
FacesMessage message = new FacesMessage("Must enter at least one 'Contains' for Cataloging Information Search.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(textField1.getClientId(fc), message);
return false;
}
if (!hasVariableSearchCriteria() && !hasCatalogSearchCriteria() ) {
//((UIInput)gridPanel1).setValid(false);
FacesMessage message = new FacesMessage("Must enter some Search Criteria.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(textField1.getClientId(fc), message);
return false;
}
return true;
}
private boolean hasCatalogSearchCriteria(){
if (((String) textField1.getValue()).length() > 0) {
return true;
}
if (((String) textField2.getValue()).length() > 0 ) {
return true;
}
if (((String) textField3.getValue()).length() > 0) {
return true;
}
if (((String) textField4.getValue()).length() > 0) {
return true;
}
return false;
}
private boolean hasCatalogSearchCriteriaWithContains(){
if (((String) textField1.getValue()).length() > 0) {
if (operatorToken((String) dropdown9.getValue()).equalsIgnoreCase("=")){
return true;
}
}
if (((String) textField2.getValue()).length() > 0 ) {
if (operatorToken((String) dropdown4.getValue()).equalsIgnoreCase("=")){
return true;
}
}
if (((String) textField3.getValue()).length() > 0) {
if (operatorToken((String) dropdown6.getValue()).equalsIgnoreCase("=")){
return true;
}
}
if (((String) textField4.getValue()).length() > 0) {
if (operatorToken((String) dropdown8.getValue()).equalsIgnoreCase("=")){
return true;
}
}
return false;
}
protected boolean hasVariableSearchCriteria(){
if (variableInfoList.size() > 0){
for (SearchTerm searchTerm : variableInfoList) {
if ( searchTerm.getValue().length() > 0 ){
setVariableSearch(true);
return true;
}
}
}
return false;
}
public void validateDate(FacesContext context,
UIComponent toValidate,
Object value) {
String dateString = (String) value;
boolean valid = false;
String monthDayYear = "yyyy-MM-dd";
String monthYear = "yyyy-MM";
String year = "yyyy";
if (dateString.length() == 4) {
valid = isValid(dateString, year);
} else if (dateString.length() > 4 && dateString.length() <= 7) {
valid = isValid(dateString, monthYear);
} else if (dateString.length() > 7) {
valid = isValid(dateString, monthDayYear);
}
if (!valid) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Invalid Date Format. Valid formats are YYYY-MM-DD, YYYY-MM, or YYYY.");
context.addMessage(toValidate.getClientId(context), message);
}
}
public void addRow(ActionEvent ae) {
HtmlDataTable dataTable = (HtmlDataTable)ae.getComponent().getParent().getParent();
if (dataTable.equals(dataTableVariableInfo)) {
this.variableInfoList.add(dataTable.getRowIndex()+1, initVariableSearchTerm());
}
}
public void removeRow(ActionEvent ae) {
HtmlDataTable dataTable = (HtmlDataTable)ae.getComponent().getParent().getParent();
if (dataTable.getRowCount()>1) {
List data = (List)dataTable.getValue();
int i = dataTable.getRowIndex();
data.remove(i);
}
}
}
| true | true | public String search() {
// String query = buildQuery();
List searchCollections = null;
boolean searchOnlySelectedCollections = false;
if (validateAllSearchCriteria()){
if (radioButtonList1.getValue() != null) {
String radioButtonStr = (String) radioButtonList1.getValue();
if (radioButtonStr.indexOf("Only") > 1) {
searchOnlySelectedCollections = true;
searchCollections = new ArrayList();
for (Iterator it = collectionModelList.iterator(); it.hasNext();) {
CollectionModel elem = (CollectionModel) it.next();
if (elem.isSelected()) {
VDCCollection selectedCollection = vdcCollectionService.find(elem.getId());
searchCollections.add(selectedCollection);
}
}
if (searchCollections.isEmpty()) {
searchOnlySelectedCollections = false;
}
}
}
List<SearchTerm> searchTerms = buildSearchTermList();
VDC thisVDC = getVDCRequestBean().getCurrentVDC();
List<Long> viewableIds = null;
if (searchOnlySelectedCollections) {
viewableIds = indexServiceBean.search(thisVDC, searchCollections, searchTerms);
} else {
viewableIds = indexServiceBean.search(thisVDC, searchTerms);
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
sl.setSearchTerms(searchTerms);
if (isVariableSearch()) {
Map variableMap = new HashMap();
List studies = new ArrayList();
varService.determineStudiesFromVariables(viewableIds, studies, variableMap);
sl.setStudyIds(studies);
sl.setVariableMap(variableMap);
} else {
sl.setStudyIds(viewableIds);
}
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
else{
return "";
}
}
| public String search() {
// String query = buildQuery();
List searchCollections = null;
boolean searchOnlySelectedCollections = false;
if (validateAllSearchCriteria()){
if (radioButtonList1.getValue() != null) {
String radioButtonStr = (String) radioButtonList1.getValue();
if (radioButtonStr.indexOf("Only") > 1) {
searchOnlySelectedCollections = true;
searchCollections = new ArrayList();
for (Iterator it = collectionModelList.iterator(); it.hasNext();) {
CollectionModel elem = (CollectionModel) it.next();
if (elem.isSelected()) {
VDCCollection selectedCollection = vdcCollectionService.find(elem.getId());
searchCollections.add(selectedCollection);
}
}
if (searchCollections.isEmpty()) {
searchOnlySelectedCollections = false;
}
}
}
List<SearchTerm> searchTerms = buildSearchTermList();
VDC thisVDC = getVDCRequestBean().getCurrentVDC();
List<Long> viewableIds = null;
if (searchOnlySelectedCollections) {
viewableIds = indexServiceBean.search(thisVDC, searchCollections, searchTerms);
} else {
viewableIds = indexServiceBean.search(thisVDC, searchTerms);
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
sl.setVdcId(getVDCRequestBean().getCurrentVDCId());
sl.setSearchTerms(searchTerms);
if (isVariableSearch()) {
Map variableMap = new HashMap();
List studies = new ArrayList();
varService.determineStudiesFromVariables(viewableIds, studies, variableMap);
sl.setStudyIds(studies);
sl.setVariableMap(variableMap);
} else {
sl.setStudyIds(viewableIds);
}
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
else{
return "";
}
}
|
diff --git a/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java b/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
index dcf41a157..d01ec18b6 100644
--- a/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
+++ b/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
@@ -1,315 +1,315 @@
/* -*- compile-command: "cd ../../../../../; ant install"; -*- */
/*
* Copyright 2009-2010 by Eric House ([email protected]). All
* rights reserved.
*
* 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.
*/
package org.eehouse.android.xw4;
import android.app.ListActivity;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Button;
import android.view.MenuInflater;
import java.io.File;
import android.preference.PreferenceManager;
import junit.framework.Assert;
import org.eehouse.android.xw4.jni.*;
public class GamesList extends ListActivity {
private static final int WARN_NODICT = Utils.DIALOG_LAST + 1;
private static final int CONFIRM_DELETE_ALL = Utils.DIALOG_LAST + 2;
private GameListAdapter m_adapter;
private String m_invalPath = null;
private String m_missingDict;
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
switch( id ) {
case WARN_NODICT:
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.no_dict_title )
.setMessage( "" ) // required to get to change it later
.setPositiveButton( R.string.button_ok, null )
.setNegativeButton( R.string.button_download,
new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
Intent intent =
Utils.mkDownloadActivity(GamesList.this);
startActivity( intent );
}
})
.create();
break;
case CONFIRM_DELETE_ALL:
DialogInterface.OnClickListener lstnr =
new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
for( String game:GameUtils.gamesList(GamesList.this)) {
GameUtils.deleteGame( GamesList.this, game );
}
m_adapter = new GameListAdapter( GamesList.this );
setListAdapter( m_adapter );
}
};
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.query_title )
.setMessage( R.string.confirm_delete_all )
.setPositiveButton( R.string.button_ok, lstnr )
.setNegativeButton( R.string.button_cancel, null )
.create();
break;
default:
dialog = Utils.onCreateDialog( this, id );
}
return dialog;
}
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
if ( WARN_NODICT == id ) {
String format = getString( R.string.no_dictf );
String msg = String.format( format, m_missingDict );
((AlertDialog)dialog).setMessage( msg );
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues( this, R.xml.xwprefs, false );
setContentView(R.layout.game_list);
// setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
registerForContextMenu( getListView() );
Button newGameB = (Button)findViewById(R.id.new_game);
newGameB.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
saveNew( new CurGameInfo( GamesList.this ) );
onContentChanged();
}
} );
m_adapter = new GameListAdapter( this );
setListAdapter( m_adapter );
}
@Override
public void onWindowFocusChanged( boolean hasFocus )
{
super.onWindowFocusChanged( hasFocus );
if ( hasFocus && null != m_invalPath ) {
m_adapter.inval( m_invalPath );
m_invalPath = null;
onContentChanged();
}
}
@Override
public void onCreateContextMenu( ContextMenu menu, View view,
ContextMenuInfo menuInfo )
{
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.games_list_item_menu, menu );
}
@Override
public boolean onContextItemSelected( MenuItem item )
{
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Utils.logf( "bad menuInfo:" + e.toString() );
return false;
}
return handleMenuItem( item.getItemId(), info.position );
} // onContextItemSelected
public boolean onCreateOptionsMenu( Menu menu )
{
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.games_list_menu, menu );
return true;
}
public boolean onOptionsItemSelected( MenuItem item )
{
boolean handled = true;
Intent intent;
switch (item.getItemId()) {
case R.id.gamel_menu_delete_all:
if ( GameUtils.gamesList( this ).length > 0 ) {
showDialog( CONFIRM_DELETE_ALL );
}
handled = true;
break;
case R.id.gamel_menu_dicts:
intent = new Intent( this, DictsActivity.class );
startActivity( intent );
break;
case R.id.gamel_menu_prefs:
intent = new Intent( this, PrefsActivity.class );
startActivity( intent );
break;
case R.id.gamel_menu_about:
showDialog( Utils.DIALOG_ABOUT );
break;
// case R.id.gamel_menu_view_hidden:
// Utils.notImpl( this );
// break;
default:
handled = false;
}
return handled;
}
@Override
protected void onListItemClick( ListView l, View v, int position, long id )
{
super.onListItemClick( l, v, position, id );
if ( CommonPrefs.getClickLaunches( this ) ) {
handleMenuItem( R.id.list_item_play, position );
} else {
v.showContextMenu();
}
}
private boolean handleMenuItem( int menuID, int position )
{
boolean handled = true;
byte[] stream;
String invalPath = null;
String path = GameUtils.gamesList( this )[position];
if ( R.id.list_item_delete == menuID ) {
GameUtils.deleteGame( this, path );
invalPath = path;
} else {
String[] missingName = new String[1];
boolean hasDict = GameUtils.gameDictHere( this, path, missingName );
if ( !hasDict ) {
m_missingDict = missingName[0];
showDialog( WARN_NODICT );
} else {
switch ( menuID ) {
case R.id.list_item_play:
File file = new File( path );
Uri uri = Uri.fromFile( file );
Intent intent = new Intent( Intent.ACTION_EDIT, uri,
this, BoardActivity.class );
startActivity( intent );
m_invalPath = path;
break;
case R.id.list_item_config:
doConfig( path );
- invalPath = path;
+ m_invalPath = path;
break;
case R.id.list_item_reset:
GameUtils.resetGame( this, path, path );
invalPath = path;
break;
case R.id.list_item_new_from:
String newName = GameUtils.resetGame( this, path );
invalPath = newName;
break;
case R.id.list_item_copy:
stream = GameUtils.savedGame( this, path );
newName = GameUtils.saveGame( this, stream );
DBUtils.saveSummary( newName,
DBUtils.getSummary( this, path ) );
break;
// These require some notion of predictable sort order.
// Maybe put off until I'm using a db?
// case R.id.list_item_hide:
// case R.id.list_item_move_up:
// case R.id.list_item_move_down:
// case R.id.list_item_move_to_top:
// case R.id.list_item_move_to_bottom:
// Utils.notImpl( this );
// break;
default:
handled = false;
break;
}
}
}
if ( null != invalPath ) {
m_adapter.inval( invalPath );
}
if ( handled ) {
onContentChanged();
}
return handled;
} // handleMenuItem
private void doConfig( String path )
{
Uri uri = Uri.fromFile( new File(path) );
Intent intent = new Intent( Intent.ACTION_EDIT, uri,
this, GameConfig.class );
startActivity( intent );
}
private void saveNew( CurGameInfo gi )
{
byte[] bytes = XwJNI.gi_to_stream( gi );
if ( null != bytes ) {
GameUtils.saveGame( this, bytes );
} else {
Utils.logf( "gi_to_stream=>null" );
}
}
}
| true | true | private boolean handleMenuItem( int menuID, int position )
{
boolean handled = true;
byte[] stream;
String invalPath = null;
String path = GameUtils.gamesList( this )[position];
if ( R.id.list_item_delete == menuID ) {
GameUtils.deleteGame( this, path );
invalPath = path;
} else {
String[] missingName = new String[1];
boolean hasDict = GameUtils.gameDictHere( this, path, missingName );
if ( !hasDict ) {
m_missingDict = missingName[0];
showDialog( WARN_NODICT );
} else {
switch ( menuID ) {
case R.id.list_item_play:
File file = new File( path );
Uri uri = Uri.fromFile( file );
Intent intent = new Intent( Intent.ACTION_EDIT, uri,
this, BoardActivity.class );
startActivity( intent );
m_invalPath = path;
break;
case R.id.list_item_config:
doConfig( path );
invalPath = path;
break;
case R.id.list_item_reset:
GameUtils.resetGame( this, path, path );
invalPath = path;
break;
case R.id.list_item_new_from:
String newName = GameUtils.resetGame( this, path );
invalPath = newName;
break;
case R.id.list_item_copy:
stream = GameUtils.savedGame( this, path );
newName = GameUtils.saveGame( this, stream );
DBUtils.saveSummary( newName,
DBUtils.getSummary( this, path ) );
break;
// These require some notion of predictable sort order.
// Maybe put off until I'm using a db?
// case R.id.list_item_hide:
// case R.id.list_item_move_up:
// case R.id.list_item_move_down:
// case R.id.list_item_move_to_top:
// case R.id.list_item_move_to_bottom:
// Utils.notImpl( this );
// break;
default:
handled = false;
break;
}
}
}
if ( null != invalPath ) {
m_adapter.inval( invalPath );
}
if ( handled ) {
onContentChanged();
}
return handled;
} // handleMenuItem
| private boolean handleMenuItem( int menuID, int position )
{
boolean handled = true;
byte[] stream;
String invalPath = null;
String path = GameUtils.gamesList( this )[position];
if ( R.id.list_item_delete == menuID ) {
GameUtils.deleteGame( this, path );
invalPath = path;
} else {
String[] missingName = new String[1];
boolean hasDict = GameUtils.gameDictHere( this, path, missingName );
if ( !hasDict ) {
m_missingDict = missingName[0];
showDialog( WARN_NODICT );
} else {
switch ( menuID ) {
case R.id.list_item_play:
File file = new File( path );
Uri uri = Uri.fromFile( file );
Intent intent = new Intent( Intent.ACTION_EDIT, uri,
this, BoardActivity.class );
startActivity( intent );
m_invalPath = path;
break;
case R.id.list_item_config:
doConfig( path );
m_invalPath = path;
break;
case R.id.list_item_reset:
GameUtils.resetGame( this, path, path );
invalPath = path;
break;
case R.id.list_item_new_from:
String newName = GameUtils.resetGame( this, path );
invalPath = newName;
break;
case R.id.list_item_copy:
stream = GameUtils.savedGame( this, path );
newName = GameUtils.saveGame( this, stream );
DBUtils.saveSummary( newName,
DBUtils.getSummary( this, path ) );
break;
// These require some notion of predictable sort order.
// Maybe put off until I'm using a db?
// case R.id.list_item_hide:
// case R.id.list_item_move_up:
// case R.id.list_item_move_down:
// case R.id.list_item_move_to_top:
// case R.id.list_item_move_to_bottom:
// Utils.notImpl( this );
// break;
default:
handled = false;
break;
}
}
}
if ( null != invalPath ) {
m_adapter.inval( invalPath );
}
if ( handled ) {
onContentChanged();
}
return handled;
} // handleMenuItem
|
diff --git a/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/mow/core/api/wiki/AttachmentImpl.java b/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/mow/core/api/wiki/AttachmentImpl.java
index 1c34c00ae..7cc4dad30 100644
--- a/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/mow/core/api/wiki/AttachmentImpl.java
+++ b/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/mow/core/api/wiki/AttachmentImpl.java
@@ -1,156 +1,155 @@
/*
* Copyright (C) 2003-2010 eXo Platform SAS.
*
* This program 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.
*
* 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.exoplatform.wiki.mow.core.api.wiki;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.chromattic.api.annotations.Destroy;
import org.chromattic.api.annotations.ManyToOne;
import org.chromattic.api.annotations.Name;
import org.chromattic.api.annotations.Path;
import org.chromattic.api.annotations.PrimaryType;
import org.chromattic.api.annotations.Property;
import org.chromattic.api.annotations.WorkspaceName;
import org.chromattic.ext.ntdef.NTFile;
import org.chromattic.ext.ntdef.Resource;
import org.exoplatform.wiki.mow.api.Attachment;
import org.exoplatform.wiki.mow.api.Wiki;
import org.exoplatform.wiki.mow.api.WikiNodeType;
import org.exoplatform.wiki.utils.Utils;
/**
* Created by The eXo Platform SAS
* May, 2010
*/
@PrimaryType(name = WikiNodeType.WIKI_ATTACHMENT)
public abstract class AttachmentImpl extends NTFile implements Attachment {
@Name
public abstract String getName();
public abstract void setName(String name);
@Path
public abstract String getPath();
public String getJCRContentPath() {
return getPath() + "/jcr:content";
}
@WorkspaceName
public abstract String getWorkspace();
@Property(name = WikiNodeType.Definition.TITLE)
public abstract String getTitle();
public abstract void setTitle(String title);
@Property(name = WikiNodeType.Definition.FILE_TYPE)
public abstract String getFileType();
public abstract void setFileType(String fileType);
@Property(name = WikiNodeType.Definition.CREATOR)
public abstract String getCreator();
public abstract void setCreator(String creator);
public Calendar getCreatedDate(){
try {
Calendar calendar = GregorianCalendar.getInstance() ;
calendar.setTime(getCreated()) ;
return calendar ;
}catch(Exception e) {
}
return null ;
}
public long getWeightInBytes(){
try {
return getContentResource().getData().length ;
}catch(Exception e) {
}
return 0 ;
}
public Calendar getUpdatedDate(){
try {
Calendar calendar = GregorianCalendar.getInstance() ;
calendar.setTime(getLastModified()) ;
return calendar ;
}catch(Exception e) {
}
return null ;
}
public String getDownloadURL() {
StringBuilder sb = new StringBuilder();
String mimeType = getContentResource().getMimeType();
- if (mimeType != null && mimeType.startsWith("image/")) {
- PageImpl page = this.getParentPage();
- Wiki wiki = page.getWiki();
- String wikiType = wiki.getType();
+ PageImpl page = this.getParentPage();
+ Wiki wiki = page.getWiki();
+ if (mimeType != null && mimeType.startsWith("image/") && wiki != null) {
// Build REST url to view image
sb.append(Utils.getDefaultRestBaseURI())
.append("/wiki/images/")
- .append(wikiType)
+ .append(wiki.getType())
.append("/")
- .append(Utils.validateWikiOwner(wikiType, wiki.getOwner()))
+ .append(Utils.validateWikiOwner(wiki.getType(), wiki.getOwner()))
.append("/")
.append(page.getName())
.append("/")
.append(this.getName());
} else {
sb.append(Utils.getDefaultRepositoryWebDavUri());
sb.append(getWorkspace());
String path = getPath();
try {
String parentPath = path.substring(0, path.lastIndexOf("/"));
sb.append(parentPath + "/" + URLEncoder.encode(getName(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
sb.append(path);
}
}
return sb.toString();
}
public String getFullTitle() {
String fullTitle = (getFileType() == null) ? getTitle() : getTitle().concat(getFileType());
return (fullTitle != null) ? fullTitle : getName();
}
@ManyToOne
public abstract PageImpl getParentPage();
@Destroy
public abstract void remove();
public String getText() throws Exception {
Resource textContent = getContentResource();
if (textContent == null) {
setText("");
textContent = getContentResource();
}
return new String(textContent.getData(), "UTF-8");
}
public void setText(String text) {
text = text != null ? text : "";
Resource textContent = Resource.createPlainText(text);
setContentResource(textContent);
}
}
| false | true | public String getDownloadURL() {
StringBuilder sb = new StringBuilder();
String mimeType = getContentResource().getMimeType();
if (mimeType != null && mimeType.startsWith("image/")) {
PageImpl page = this.getParentPage();
Wiki wiki = page.getWiki();
String wikiType = wiki.getType();
// Build REST url to view image
sb.append(Utils.getDefaultRestBaseURI())
.append("/wiki/images/")
.append(wikiType)
.append("/")
.append(Utils.validateWikiOwner(wikiType, wiki.getOwner()))
.append("/")
.append(page.getName())
.append("/")
.append(this.getName());
} else {
sb.append(Utils.getDefaultRepositoryWebDavUri());
sb.append(getWorkspace());
String path = getPath();
try {
String parentPath = path.substring(0, path.lastIndexOf("/"));
sb.append(parentPath + "/" + URLEncoder.encode(getName(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
sb.append(path);
}
}
return sb.toString();
}
| public String getDownloadURL() {
StringBuilder sb = new StringBuilder();
String mimeType = getContentResource().getMimeType();
PageImpl page = this.getParentPage();
Wiki wiki = page.getWiki();
if (mimeType != null && mimeType.startsWith("image/") && wiki != null) {
// Build REST url to view image
sb.append(Utils.getDefaultRestBaseURI())
.append("/wiki/images/")
.append(wiki.getType())
.append("/")
.append(Utils.validateWikiOwner(wiki.getType(), wiki.getOwner()))
.append("/")
.append(page.getName())
.append("/")
.append(this.getName());
} else {
sb.append(Utils.getDefaultRepositoryWebDavUri());
sb.append(getWorkspace());
String path = getPath();
try {
String parentPath = path.substring(0, path.lastIndexOf("/"));
sb.append(parentPath + "/" + URLEncoder.encode(getName(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
sb.append(path);
}
}
return sb.toString();
}
|
diff --git a/src/com/github/andlyticsproject/CommentsListAdapter.java b/src/com/github/andlyticsproject/CommentsListAdapter.java
index 12bbb3c..b1910da 100644
--- a/src/com/github/andlyticsproject/CommentsListAdapter.java
+++ b/src/com/github/andlyticsproject/CommentsListAdapter.java
@@ -1,340 +1,344 @@
package com.github.andlyticsproject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.model.CommentGroup;
import com.github.andlyticsproject.util.Utils;
public class CommentsListAdapter extends BaseExpandableListAdapter {
private static final int TYPE_COMMENT = 0;
private static final int TYPE_REPLY = 1;
private LayoutInflater layoutInflater;
private ArrayList<CommentGroup> commentGroups;
private CommentsActivity context;
private DateFormat commentDateFormat = DateFormat
.getDateInstance(DateFormat.FULL);
public CommentsListAdapter(CommentsActivity activity) {
this.setCommentGroups(new ArrayList<CommentGroup>());
this.layoutInflater = activity.getLayoutInflater();
this.context = activity;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
- String getOriginalText[] = comment.getOriginalText().split("\\t");
- if (getOriginalText != null && getOriginalText.length > 1) {
- holder.title.setText(getOriginalText[0]);
- holder.text.setText(commentText);
+ String originalText[] = comment.getOriginalText().split("\\t");
+ if (originalText != null && originalText.length > 1) {
+ holder.title.setText(originalText[0]);
+ if (Preferences.isShowCommentAutoTranslations(context)) {
+ holder.text.setText(commentText);
+ } else {
+ holder.text.setText(originalText[1]);
+ }
holder.text.setVisibility(View.VISIBLE);
- } else if (getOriginalText != null && getOriginalText.length == 1) {
+ } else if (originalText != null && originalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
private boolean isGoogleTranslateInstalled() {
return Utils.isPackageInstalled(context,
"com.google.android.apps.translate");
}
private String formatLanguageString(String language) {
if (language != null && language.indexOf("_") > 0) {
String[] parts = language.split("_");
if (parts.length > 1
&& parts[0].toUpperCase(Locale.ENGLISH).equals(
parts[1].toUpperCase(Locale.ENGLISH))) {
return parts[1].toUpperCase(Locale.ENGLISH);
} else {
return language.replaceAll("_", "/");
}
} else {
return language;
}
}
private void sendToGoogleTranslate(String text, String displayLanguage) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.putExtra("key_text_input", text);
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "auto");
i.putExtra("key_language_to", displayLanguage);
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
context.startActivity(i);
}
@Override
public int getChildType(int groupPosition, int childPosition) {
return getChild(groupPosition, childPosition).isReply() ? TYPE_REPLY
: TYPE_COMMENT;
}
@Override
public int getChildTypeCount() {
return 2;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewHolderGroup holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.comments_list_item_group_header, null);
holder = new ViewHolderGroup();
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
convertView.setTag(holder);
} else {
holder = (ViewHolderGroup) convertView.getTag();
}
CommentGroup commentGroup = getGroup(groupPosition);
holder.date.setText(formatCommentDate(commentGroup.getDate()));
return convertView;
}
private boolean isNotEmptyOrNull(String str) {
return str != null && str.length() > 0;
}
static class ViewHolderGroup {
TextView date;
}
static class ViewHolderChild {
RatingBar rating;
TextView text;
TextView title;
TextView user;
TextView date;
LinearLayout deviceVersionContainer;
ImageView deviceIcon;
ImageView versionIcon;
TextView device;
TextView version;
TextView language;
ImageView languageIcon;
}
@Override
public int getGroupCount() {
return getCommentGroups().size();
}
@Override
public int getChildrenCount(int groupPosition) {
return getCommentGroups().get(groupPosition).getComments().size();
}
@Override
public CommentGroup getGroup(int groupPosition) {
return getCommentGroups().get(groupPosition);
}
@Override
public Comment getChild(int groupPosition, int childPosition) {
return getCommentGroups().get(groupPosition).getComments()
.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
public void setCommentGroups(ArrayList<CommentGroup> commentGroups) {
this.commentGroups = commentGroups;
}
public ArrayList<CommentGroup> getCommentGroups() {
return commentGroups;
}
private String formatCommentDate(Date date) {
return commentDateFormat.format(date);
}
}
| false | true | public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
String getOriginalText[] = comment.getOriginalText().split("\\t");
if (getOriginalText != null && getOriginalText.length > 1) {
holder.title.setText(getOriginalText[0]);
holder.text.setText(commentText);
holder.text.setVisibility(View.VISIBLE);
} else if (getOriginalText != null && getOriginalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
| public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
String originalText[] = comment.getOriginalText().split("\\t");
if (originalText != null && originalText.length > 1) {
holder.title.setText(originalText[0]);
if (Preferences.isShowCommentAutoTranslations(context)) {
holder.text.setText(commentText);
} else {
holder.text.setText(originalText[1]);
}
holder.text.setVisibility(View.VISIBLE);
} else if (originalText != null && originalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/events/RepositoryEventProxyModeChangedInspector.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/events/RepositoryEventProxyModeChangedInspector.java
index 5dbff216c..0dbf4c232 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/events/RepositoryEventProxyModeChangedInspector.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/events/RepositoryEventProxyModeChangedInspector.java
@@ -1,95 +1,95 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License 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 General Public License Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.nexus.events;
import org.codehaus.plexus.component.annotations.Component;
import org.sonatype.nexus.feeds.FeedRecorder;
import org.sonatype.nexus.proxy.events.AbstractFeedRecorderEventInspector;
import org.sonatype.nexus.proxy.events.EventInspector;
import org.sonatype.nexus.proxy.events.RepositoryEventProxyModeChanged;
import org.sonatype.nexus.proxy.repository.ProxyMode;
import org.sonatype.plexus.appevents.Event;
/**
* @author Juven Xu
*/
@Component( role = EventInspector.class, hint = "RepositoryEventProxyModeChanged" )
public class RepositoryEventProxyModeChangedInspector
extends AbstractFeedRecorderEventInspector
{
public boolean accepts( Event<?> evt )
{
if ( evt instanceof RepositoryEventProxyModeChanged )
{
return true;
}
return false;
}
public void inspect( Event<?> evt )
{
RepositoryEventProxyModeChanged revt = (RepositoryEventProxyModeChanged) evt;
StringBuffer sb = new StringBuffer( "The proxy mode of repository '" );
sb.append( revt.getRepository().getName() );
sb.append( "' (ID='" ).append( revt.getRepository().getId() ).append( "') was set to " );
- if ( ProxyMode.ALLOW.equals( revt.getRepository().getProxyMode() ) )
+ if ( ProxyMode.ALLOW.equals( revt.getNewProxyMode() ) )
{
sb.append( "Allow." );
}
- else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getRepository().getProxyMode() ) )
+ else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getNewProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
- else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getRepository().getProxyMode() ) )
+ else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getNewProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getRepository().getProxyMode().toString() ).append( "." );
}
sb.append( " The previous state was " );
if ( ProxyMode.ALLOW.equals( revt.getOldProxyMode() ) )
{
sb.append( "Allow." );
}
else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getOldProxyMode().toString() ).append( "." );
}
if ( revt.getCause() != null )
{
sb.append( " Last detected transport error: " ).append( revt.getCause().getMessage() );
}
getFeedRecorder().addSystemEvent( FeedRecorder.SYSTEM_REPO_PSTATUS_CHANGES_ACTION, sb.toString() );
}
}
| false | true | public void inspect( Event<?> evt )
{
RepositoryEventProxyModeChanged revt = (RepositoryEventProxyModeChanged) evt;
StringBuffer sb = new StringBuffer( "The proxy mode of repository '" );
sb.append( revt.getRepository().getName() );
sb.append( "' (ID='" ).append( revt.getRepository().getId() ).append( "') was set to " );
if ( ProxyMode.ALLOW.equals( revt.getRepository().getProxyMode() ) )
{
sb.append( "Allow." );
}
else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getRepository().getProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getRepository().getProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getRepository().getProxyMode().toString() ).append( "." );
}
sb.append( " The previous state was " );
if ( ProxyMode.ALLOW.equals( revt.getOldProxyMode() ) )
{
sb.append( "Allow." );
}
else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getOldProxyMode().toString() ).append( "." );
}
if ( revt.getCause() != null )
{
sb.append( " Last detected transport error: " ).append( revt.getCause().getMessage() );
}
getFeedRecorder().addSystemEvent( FeedRecorder.SYSTEM_REPO_PSTATUS_CHANGES_ACTION, sb.toString() );
}
| public void inspect( Event<?> evt )
{
RepositoryEventProxyModeChanged revt = (RepositoryEventProxyModeChanged) evt;
StringBuffer sb = new StringBuffer( "The proxy mode of repository '" );
sb.append( revt.getRepository().getName() );
sb.append( "' (ID='" ).append( revt.getRepository().getId() ).append( "') was set to " );
if ( ProxyMode.ALLOW.equals( revt.getNewProxyMode() ) )
{
sb.append( "Allow." );
}
else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getNewProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getNewProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getRepository().getProxyMode().toString() ).append( "." );
}
sb.append( " The previous state was " );
if ( ProxyMode.ALLOW.equals( revt.getOldProxyMode() ) )
{
sb.append( "Allow." );
}
else if ( ProxyMode.BLOCKED_AUTO.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (auto)." );
}
else if ( ProxyMode.BLOCKED_MANUAL.equals( revt.getOldProxyMode() ) )
{
sb.append( "Blocked (by user)." );
}
else
{
sb.append( revt.getOldProxyMode().toString() ).append( "." );
}
if ( revt.getCause() != null )
{
sb.append( " Last detected transport error: " ).append( revt.getCause().getMessage() );
}
getFeedRecorder().addSystemEvent( FeedRecorder.SYSTEM_REPO_PSTATUS_CHANGES_ACTION, sb.toString() );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.