lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 9ebab73c67dd3c74fe11ceda87c5caa826b17ccd | 0 | colczr/sakai,introp-software/sakai,hackbuteer59/sakai,kingmook/sakai,puramshetty/sakai,surya-janani/sakai,clhedrick/sakai,puramshetty/sakai,bkirschn/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,hackbuteer59/sakai,pushyamig/sakai,conder/sakai,Fudan-University/sakai,ktakacs/sakai,udayg/sakai,hackbuteer59/sakai,frasese/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,liubo404/sakai,kwedoff1/sakai,conder/sakai,udayg/sakai,buckett/sakai-gitflow,clhedrick/sakai,pushyamig/sakai,ouit0408/sakai,clhedrick/sakai,kingmook/sakai,OpenCollabZA/sakai,noondaysun/sakai,pushyamig/sakai,frasese/sakai,whumph/sakai,bzhouduke123/sakai,hackbuteer59/sakai,noondaysun/sakai,kingmook/sakai,lorenamgUMU/sakai,conder/sakai,OpenCollabZA/sakai,willkara/sakai,ktakacs/sakai,whumph/sakai,surya-janani/sakai,bkirschn/sakai,surya-janani/sakai,colczr/sakai,ktakacs/sakai,rodriguezdevera/sakai,bkirschn/sakai,joserabal/sakai,willkara/sakai,bkirschn/sakai,willkara/sakai,frasese/sakai,colczr/sakai,joserabal/sakai,kwedoff1/sakai,frasese/sakai,puramshetty/sakai,colczr/sakai,liubo404/sakai,bzhouduke123/sakai,introp-software/sakai,whumph/sakai,buckett/sakai-gitflow,joserabal/sakai,rodriguezdevera/sakai,zqian/sakai,frasese/sakai,joserabal/sakai,clhedrick/sakai,kingmook/sakai,zqian/sakai,willkara/sakai,Fudan-University/sakai,bzhouduke123/sakai,whumph/sakai,rodriguezdevera/sakai,ouit0408/sakai,liubo404/sakai,Fudan-University/sakai,joserabal/sakai,lorenamgUMU/sakai,liubo404/sakai,conder/sakai,rodriguezdevera/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,udayg/sakai,kingmook/sakai,willkara/sakai,buckett/sakai-gitflow,kingmook/sakai,Fudan-University/sakai,ktakacs/sakai,frasese/sakai,noondaysun/sakai,noondaysun/sakai,buckett/sakai-gitflow,surya-janani/sakai,rodriguezdevera/sakai,zqian/sakai,lorenamgUMU/sakai,surya-janani/sakai,noondaysun/sakai,ouit0408/sakai,rodriguezdevera/sakai,kwedoff1/sakai,surya-janani/sakai,Fudan-University/sakai,OpenCollabZA/sakai,wfuedu/sakai,bzhouduke123/sakai,wfuedu/sakai,introp-software/sakai,pushyamig/sakai,kwedoff1/sakai,introp-software/sakai,surya-janani/sakai,puramshetty/sakai,frasese/sakai,hackbuteer59/sakai,kwedoff1/sakai,joserabal/sakai,udayg/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,bzhouduke123/sakai,ouit0408/sakai,ktakacs/sakai,zqian/sakai,introp-software/sakai,buckett/sakai-gitflow,kwedoff1/sakai,lorenamgUMU/sakai,wfuedu/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,whumph/sakai,udayg/sakai,introp-software/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,bkirschn/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,zqian/sakai,liubo404/sakai,noondaysun/sakai,pushyamig/sakai,conder/sakai,pushyamig/sakai,Fudan-University/sakai,colczr/sakai,zqian/sakai,liubo404/sakai,joserabal/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,colczr/sakai,kingmook/sakai,zqian/sakai,buckett/sakai-gitflow,frasese/sakai,udayg/sakai,ouit0408/sakai,OpenCollabZA/sakai,conder/sakai,introp-software/sakai,joserabal/sakai,clhedrick/sakai,whumph/sakai,conder/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,noondaysun/sakai,colczr/sakai,OpenCollabZA/sakai,wfuedu/sakai,ouit0408/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,tl-its-umich-edu/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,kingmook/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,whumph/sakai,wfuedu/sakai,hackbuteer59/sakai,lorenamgUMU/sakai,udayg/sakai,bzhouduke123/sakai,ktakacs/sakai,zqian/sakai,bzhouduke123/sakai,bkirschn/sakai,ouit0408/sakai,puramshetty/sakai,whumph/sakai,ktakacs/sakai,kwedoff1/sakai,wfuedu/sakai,clhedrick/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,ktakacs/sakai,kwedoff1/sakai,noondaysun/sakai,pushyamig/sakai,OpenCollabZA/sakai,bkirschn/sakai,liubo404/sakai,OpenCollabZA/sakai,puramshetty/sakai,buckett/sakai-gitflow,conder/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,udayg/sakai | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java $
* $Id: DiscussionForumTool.java 9227 2006-05-15 15:02:42Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.tool.messageforums;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIData;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.Area;
import org.sakaiproject.api.app.messageforums.AreaManager;
import org.sakaiproject.api.app.messageforums.Attachment;
import org.sakaiproject.api.app.messageforums.DBMembershipItem;
import org.sakaiproject.api.app.messageforums.DiscussionForum;
import org.sakaiproject.api.app.messageforums.DiscussionTopic;
import org.sakaiproject.api.app.messageforums.MembershipManager;
import org.sakaiproject.api.app.messageforums.Message;
import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager;
import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager;
import org.sakaiproject.api.app.messageforums.OpenForum;
import org.sakaiproject.api.app.messageforums.PermissionLevel;
import org.sakaiproject.api.app.messageforums.PermissionLevelManager;
import org.sakaiproject.api.app.messageforums.PermissionsMask;
import org.sakaiproject.api.app.messageforums.PrivateMessage;
import org.sakaiproject.api.app.messageforums.Topic;
import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager;
import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager;
import org.sakaiproject.api.app.messageforums.ui.UIPermissionsManager;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.component.app.messageforums.MembershipItem;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.CommentDefinition;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.messageforums.ui.DecoratedAttachment;
import org.sakaiproject.tool.messageforums.ui.DiscussionAreaBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionForumBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionMessageBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionTopicBean;
import org.sakaiproject.tool.messageforums.ui.PermissionBean;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
/**
* @author <a href="mailto:[email protected]">Rashmi Shastri</a>
* @author Chen wen
*/
public class DiscussionForumTool
{
private static final Log LOG = LogFactory.getLog(DiscussionForumTool.class);
/**
* List individual forum details
*/
private static final String MAIN = "main";
private static final String FORUMS_MAIN = "forumsMain";
private static final String TEMPLATE_SETTING = "dfTemplateSettings";
private static final String TEMPLATE_ORGANIZE = "dfTemplateOrganize";
private static final String FORUM_DETAILS = "dfForumDetail";
private static final String FORUM_SETTING = "dfForumSettings";
private static final String FORUM_SETTING_REVISE = "dfReviseForumSettings";
private static final String TOPIC_SETTING = "dfTopicSettings";
private static final String TOPIC_SETTING_REVISE = "dfReviseTopicSettings";
private static final String MESSAGE_COMPOSE = "dfCompose";
private static final String MESSAGE_VIEW = "dfViewMessage";
private static final String THREAD_VIEW = "dfViewThread";
private static final String ALL_MESSAGES = "dfAllMessages";
private static final String SUBJECT_ONLY = "dfSubjectOnly";
private static final String ENTIRE_MSG = "dfEntireMsg";
private static final String EXPANDED_VIEW = "dfExpandAllView";
private static final String THREADED_VIEW = "dfThreadedView";
private static final String FLAT_VIEW = "dfFlatView";
private static final String UNREAD_VIEW = "dfUnreadView";
private static final String GRADE_MESSAGE = "dfMsgGrade";
private static final String FORUM_STATISTICS = "dfStatisticsList";
private static final String FORUM_STATISTICS_USER = "dfStatisticsUser";
private static final String ADD_COMMENT = "dfMsgAddComment";
private static final String PENDING_MSG_QUEUE = "dfPendingMessages";
private static final String PERMISSION_MODE_TEMPLATE = "template";
private static final String PERMISSION_MODE_FORUM = "forum";
private static final String PERMISSION_MODE_TOPIC = "topic";
private DiscussionForumBean selectedForum;
private DiscussionTopicBean selectedTopic;
private DiscussionTopicBean searchResults;
private DiscussionMessageBean selectedMessage;
private DiscussionAreaBean template;
private DiscussionMessageBean selectedThreadHead;
private List selectedThread = new ArrayList();
private UIData forumTable;
private List groupsUsersList;
private List totalGroupsUsersList;
private List selectedGroupsUsersList;
private Map courseMemberMap;
private List permissions;
private List levels;
private AreaManager areaManager;
private int numPendingMessages = 0;
private boolean refreshPendingMsgs = true;
private static final String TOPIC_ID = "topicId";
private static final String FORUM_ID = "forumId";
private static final String MESSAGE_ID = "messageId";
private static final String REDIRECT_PROCESS_ACTION = "redirectToProcessAction";
private static final String MESSAGECENTER_TOOL_ID = "sakai.messagecenter";
private static final String FORUMS_TOOL_ID = "sakai.forums";
private static final String MESSAGECENTER_BUNDLE = "org.sakaiproject.api.app.messagecenter.bundle.Messages";
private static final String INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS = "cdfm_insufficient_privileges";
private static final String INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE = "cdfm_insufficient_privileges";
private static final String INSUFFICIENT_PRIVILEAGES_TO="cdfm_insufficient_privileages_to";
private static final String INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM="cdfm_insufficient_privileges_change_forum";
private static final String INSUFFICIENT_PRIVILEGES_NEW_TOPIC = "cdfm_insufficient_privileges_new_topic";
private static final String INSUFFICIENT_PRIVILEGES_CREATE_TOPIC="cdfm_insufficient_privileges_create_topic";
private static final String USER_NOT_ALLOWED_CREATE_FORUM="cdfm_user_not_allowed_create_forum";
private static final String INSUFFICIENT_PRIVILEGES_TO_DELETE_FORUM="cdfm_insufficient_privileges_delete_forum";
private static final String SHORT_DESC_TOO_LONG = "cdfm_short_desc_too_long";
private static final String LAST_REVISE_BY = "cdfm_last_revise_msg";
private static final String LAST_REVISE_ON = "cdfm_last_revise_msg_on";
private static final String VALID_FORUM_TITLE_WARN = "cdfm_valid_forum_title_warn";
private static final String VALID_TOPIC_TITLE_WARN = "cdfm_valid_topic_title_warn";
private static final String INVALID_SELECTED_FORUM ="cdfm_invalid_selected_forum";
private static final String FORUM_NOT_FOUND = "cdfm_forum_not_found";
private static final String SELECTED_FORUM_NOT_FOUND = "cdfm_selected_forum_not_found";
private static final String FAILED_NEW_TOPIC ="cdfm_failed_new_topic";
private static final String TOPIC_WITH_ID = "cdfm_topic_with_id";
private static final String MESSAGE_WITH_ID = "cdfm_message_with_id";
private static final String NOT_FOUND_WITH_QUOTE = "cdfm_not_found_quote";
private static final String PARENT_FORUM_NOT_FOUND = "cdfm_parent_forum_not_found";
private static final String NOT_FOUND_REDIRECT_PAGE = "cdfm_not_found_redirect_page";
private static final String MESSAGE_REFERENCE_NOT_FOUND = "cdfm_message_reference_not_found";
private static final String TOPC_REFERENCE_NOT_FOUND = "cdfm_topic_reference_not_found";
private static final String UNABLE_RETRIEVE_TOPIC = "cdfm_unable_retrieve_topic";
private static final String PARENT_TOPIC_NOT_FOUND = "cdfm_parent_topic_not_found";
private static final String FAILED_CREATE_TOPIC = "cdfm_failed_create_topic";
private static final String FAILED_REND_MESSAGE = "cdfm_failed_rend_message";
private static final String VIEW_UNDER_CONSTRUCT = "cdfm_view_under_construct";
private static final String LOST_ASSOCIATE = "cdfm_lost_association";
private static final String NO_MARKED_READ_MESSAGE = "cdfm_no_message_mark_read";
private static final String GRADE_SUCCESSFUL = "cdfm_grade_successful";
private static final String GRADE_GREATER_ZERO = "cdfm_grade_greater_than_zero";
private static final String GRADE_DECIMAL_WARN = "cdfm_grade_decimal_warn";
private static final String ALERT = "cdfm_alert";
private static final String SELECT_ASSIGN = "cdfm_select_assign";
private static final String INVALID_COMMENT = "cdfm_add_comment_invalid";
private static final String INSUFFICIENT_PRIVILEGES_TO_ADD_COMMENT = "cdfm_insufficient_privileges_add_comment";
private static final String MOD_COMMENT_TEXT = "cdfm_moderator_comment_text";
private static final String NO_MSG_SEL_FOR_APPROVAL = "cdfm_no_message_mark_approved";
private static final String MSGS_APPROVED = "cdfm_approve_msgs_success";
private static final String MSGS_DENIED = "cdfm_deny_msgs_success";
private static final String MSG_REPLY_PREFIX = "cdfm_reply_prefix";
private static final String NO_GRADE_PTS = "cdfm_no_points_for_grade";
private static final String NO_ASSGN = "cdfm_no_assign_for_grade";
private static final String FROM_PAGE = "msgForum:mainOrForumOrTopic";
private String fromPage = null; // keep track of originating page for common functions
private List forums = new ArrayList();
private List pendingMsgs = new ArrayList();
// compose
private MessageForumsMessageManager messageManager;
private String composeTitle;
private String composeBody;
private String composeLabel;
private String searchText = "";
private String selectedMessageView = ALL_MESSAGES;
private String selectedMessageShow = SUBJECT_ONLY;
private String selectedMessageOrganize = "thread";
private String threadAnchorMessageId = null;
private boolean deleteMsg;
private boolean displayUnreadOnly;
private boolean errorSynch = false;
// attachment
private ArrayList attachments = new ArrayList();
private ArrayList prepareRemoveAttach = new ArrayList();
// private boolean attachCaneled = false;
// private ArrayList oldAttachments = new ArrayList();
// private List allAttachments = new ArrayList();
private boolean threaded = true;
private boolean expandedView = false;
private String expanded = "false";
private boolean orderAsc = true;
private boolean disableLongDesc = false;
private boolean isDisplaySearchedMessages;
private List siteMembers = new ArrayList();
private String selectedRole;
private String moderatorComments;
private boolean editMode = true;
private String permissionMode;
//grading
private boolean gradeNotify = false;
private List assignments = new ArrayList();
private String selectedAssign = "Default_0";
private String gradePoint = "";
private String gradeComment;
private boolean gradebookExist = false;
private boolean displayDeniedMsg = false;
/**
* Dependency Injected
*/
private DiscussionForumManager forumManager;
private UIPermissionsManager uiPermissionsManager;
private MessageForumsTypeManager typeManager;
private MembershipManager membershipManager;
private PermissionLevelManager permissionLevelManager;
/**
*
*/
public DiscussionForumTool()
{
LOG.debug("DiscussionForumTool()");
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.threadedview")))
{
threaded = true;
selectedMessageView = THREADED_VIEW;
}
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.disableLongDesc")))
{
disableLongDesc = true;
}
}
/**
* @param forumManager
*/
public void setForumManager(DiscussionForumManager forumManager)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setForumManager(DiscussionForumManager " + forumManager + ")");
}
this.forumManager = forumManager;
}
/**
* @param uiPermissionsManager
* The uiPermissionsManager to set.
*/
public void setUiPermissionsManager(UIPermissionsManager uiPermissionsManager)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setUiPermissionsManager(UIPermissionsManager "
+ uiPermissionsManager + ")");
}
this.uiPermissionsManager = uiPermissionsManager;
}
/**
* @param typeManager The typeManager to set.
*/
public void setTypeManager(MessageForumsTypeManager typeManager)
{
this.typeManager = typeManager;
}
/**
* @param membershipManager The membershipManager to set.
*/
public void setMembershipManager(MembershipManager membershipManager)
{
this.membershipManager = membershipManager;
}
/**
* @return
*/
public String processActionHome()
{
LOG.debug("processActionHome()");
reset();
return gotoMain();
}
/**
* @return
*/
public boolean isInstructor()
{
LOG.debug("isInstructor()");
return forumManager.isInstructor();
}
/**
* @return List of SelectItem
*/
public List getForumSelectItems()
{
List f = getForums();
int num = (f == null) ? 0 : f.size();
List retSort = new ArrayList();
for(int i = 1; i <= num; i++) {
Integer index = new Integer(i);
retSort.add(new SelectItem(index, index.toString()));
}
return retSort;
}
/**
* @return List of DiscussionForumBean
*/
public List getForums()
{
LOG.debug("getForums()");
if (forums == null || forums.size() < 1)
{
try
{
assignments = new ArrayList();
SelectItem item = new SelectItem("Default_0", getResourceBundleString(SELECT_ASSIGN));
assignments.add(item);
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
if(getGradebookExist())
{
List gradeAssignmentsBeforeFilter = gradebookService.getAssignments(ToolManager.getCurrentPlacement().getContext());
List gradeAssignments = new ArrayList();
for(int i=0; i<gradeAssignmentsBeforeFilter.size(); i++)
{
Assignment thisAssign = (Assignment) gradeAssignmentsBeforeFilter.get(i);
if(!thisAssign.isExternallyMaintained())
{
gradeAssignments.add(thisAssign);
}
}
for(int i=0; i<gradeAssignments.size(); i++)
{
try
{
Assignment thisAssign = (Assignment) gradeAssignments.get(i);
String assignName = thisAssign.getName();
item = new SelectItem((new Integer(i+1)).toString(), assignName);
assignments.add(item);
}
catch(Exception e)
{
LOG.error("DiscussionForumTool - processDfMsgGrd:" + e);
e.printStackTrace();
}
}
}
}
catch(SecurityException se)
{
// ignore - don't want to print out stacktrace every time a non-admin user uses MC
}
catch(Exception e1)
{
LOG.error("DiscussionForumTool&processDfMsgGrad:" + e1);
e1.printStackTrace();
}
forums = new ArrayList();
//List tempForum = forumManager.getDiscussionForums();
List tempForum = forumManager.getDiscussionForumsWithTopics();
if (tempForum == null)
{
return null;
}
Iterator iterForum = tempForum.iterator();
Map unreadMap = new HashMap();
List msgIds = new ArrayList();
while (iterForum.hasNext())
{
DiscussionForum forum = (DiscussionForum) iterForum.next();
if(forum != null)
{
List topicList = forum.getTopics();
if(topicList != null)
{
for(int i=0; i<topicList.size(); i++)
{
Topic thisTopic = (Topic) topicList.get(i);
if(thisTopic != null)
{
List msgList = thisTopic.getMessages();
if(msgList != null)
{
for(int j=0; j<msgList.size(); j++)
{
Message tempMsg = (Message)msgList.get(j);
if(tempMsg != null && !tempMsg.getDraft().booleanValue())
{
msgIds.add(tempMsg.getId());
}
}
}
}
}
}
}
}
unreadMap = forumManager.getReadStatusForMessagesWithId(msgIds, getUserId());
iterForum = tempForum.iterator();
while (iterForum.hasNext())
{
DiscussionForum forum = (DiscussionForum) iterForum.next();
if (forum == null)
{
return forums;
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return forums;
}
// TODO: put this logic in database layer
if (forum.getDraft().equals(Boolean.FALSE)||(forum.getDraft().equals(Boolean.TRUE)&& forum.getCreatedBy().equals(SessionManager.getCurrentSessionUserId())
)||SecurityService.isSuperUser()
||isInstructor()
||forum.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
//DiscussionForumBean decoForum = getDecoratedForum(forum);
DiscussionForumBean decoForum = getDecoratedForumWithPersistentForumAndTopics(forum, unreadMap);
decoForum.setGradeAssign("Default_0");
for(int i=0; i<assignments.size(); i++)
{
if(((String)((SelectItem)assignments.get(i)).getLabel()).equals(forum.getDefaultAssignName()))
{
decoForum.setGradeAssign(new Integer(i).toString());
break;
}
}
forums.add(decoForum);
}
}
}
return forums;
}
/**
* @return Returns the selectedForum.
*/
public DiscussionForumBean getSelectedForum()
{
LOG.debug("getSelectedForum()");
return selectedForum;
}
/**
* @return
*/
public String processActionOrganize()
{
LOG.debug("processActionOrganize()");
return MAIN;
}
/**
* @return
*/
public String processActionStatistics()
{
LOG.debug("processActionStatistics()");
return FORUM_STATISTICS;
}
/**
* @return
*/
public String processActionTemplateSettings()
{
LOG.debug("processActionTemplateSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
template = new DiscussionAreaBean(areaManager.getDiscusionArea());
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
return TEMPLATE_SETTING;
}
/**
* @return
*/
public String processActionTemplateOrganize()
{
LOG.debug("processActionTemplateOrganize()");
setEditMode(false);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE));
return gotoMain();
}
return TEMPLATE_ORGANIZE;
}
/**
* @return
*/
public List getPermissions()
{
if (permissions == null)
{
siteMembers=null;
getSiteRoles();
}
return permissions;
}
/**
* @return
*/
public void setPermissions(List permissions)
{
this.permissions = permissions;
}
// /**
// * @return Returns the templateMessagePermissions.
// */
// public List getTemplateMessagePermissions()
// {
// if (templateMessagePermissions == null)
// {
// templateMessagePermissions = forumManager.getAreaMessagePermissions();
// }
// return templateMessagePermissions;
// }
//
// /**
// * @param templateMessagePermissions
// * The templateMessagePermissions to set.
// */
// public void setTemplateMessagePermissions(List templateMessagePermissions)
// {
// this.templateMessagePermissions = templateMessagePermissions;
// }
/*/**
* @return
*/
/*public String processActionReviseTemplateSettings()
{
if (LOG.isDebugEnabled()){
LOG.debug("processActionReviseTemplateSettings()");
}
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
return TEMPLATE_SETTING;
}*/
/**
* @return
*/
public String processActionSaveTemplateSettings()
{
LOG.debug("processActionSaveTemplateSettings()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
setObjectPermissions(template.getArea());
areaManager.saveArea(template.getArea());
return gotoMain();
}
/**
* @return
*/
public String processActionSaveTemplateOrganization()
{
LOG.debug("processActionSaveTemplateOrganization()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE));
return gotoMain();
}
for(Iterator i = forums.iterator(); i.hasNext(); ) {
DiscussionForumBean forum = (DiscussionForumBean)i.next();
// because there is no straight up save forum function we need to retain the draft status
if(forum.getForum().getDraft().booleanValue())
forumManager.saveForumAsDraft(forum.getForum());
else
forumManager.saveForum(forum.getForum());
}
//reload the forums so they change position in the list
forums = null;
return gotoMain();
}
/**
* @return
*/
public String processActionRestoreDefaultTemplate()
{
LOG.debug("processActionRestoreDefaultTemplate()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
Area area = null;
if ((area = areaManager.getDiscusionArea()) != null){
area.setMembershipItemSet(new HashSet());
area.setModerated(Boolean.FALSE);
areaManager.saveArea(area);
permissions = null;
}
else{
throw new IllegalStateException("Could not obtain area for site: " + getContextSiteId());
}
return TEMPLATE_SETTING;
}
/**
* Check out if the user is allowed to create new forum
*
* @return
*/
public boolean getNewForum()
{
LOG.debug("getNewForum()");
return uiPermissionsManager.isNewForum();
}
/**
* Display Individual forum
*
* @return
*/
public String processActionDisplayForum()
{
LOG.debug("processDisplayForum()");
if (getDecoratedForum() == null)
{
LOG.error("Forum not found");
return gotoMain();
}
return FORUM_DETAILS;
}
/**
* Forward to delete forum confirmation screen
*
* @return
*/
public String processActionDeleteForumConfirm()
{
LOG.debug("processActionDeleteForumConfirm()");
if (selectedForum == null)
{
LOG.debug("There is no forum selected for deletion");
return gotoMain();
}
// TODO:
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_DELETE_FORUM));
return gotoMain();
}
selectedForum.setMarkForDeletion(true);
return FORUM_SETTING;
}
/**
* @return
*/
public String processActionDeleteForum()
{
if (selectedForum == null)
{
LOG.debug("There is no forum selected for deletion");
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEAGES_TO));
return gotoMain();
}
forumManager.deleteForum(selectedForum.getForum());
reset();
return gotoMain();
}
/**
* @return
*/
public String processActionNewForum()
{
LOG.debug("processActionNewForum()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
if (getNewForum())
{
DiscussionForum forum = forumManager.createForum();
forum.setModerated(areaManager.getDiscusionArea().getModerated()); // default to template setting
selectedForum = null;
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setNewForumBeanAssign();
return FORUM_SETTING_REVISE;
}
else
{
setErrorMessage(getResourceBundleString(USER_NOT_ALLOWED_CREATE_FORUM));
return gotoMain();
}
}
/**
* @return
*/
public String processActionForumSettings()
{
LOG.debug("processForumSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
String forumId = getExternalParameterByKey(FORUM_ID);
if ((forumId) == null)
{
setErrorMessage(getResourceBundleString(INVALID_SELECTED_FORUM));
return gotoMain();
}
DiscussionForum forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(forum))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
List attachList = forum.getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
setFromMainOrForumOrTopic();
return FORUM_SETTING_REVISE;
}
/**
* @return
*/
/*public String processActionReviseForumSettings()
{
LOG.debug("processActionReviseForumSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
if ((selectedForum) == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
List attachList = selectedForum.getForum().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setFromMainOrForumOrTopic();
return FORUM_SETTING_REVISE; //
}*/
/**
* @return
*/
public String processActionSaveForumAndAddTopic()
{
LOG.debug("processActionSaveForumAndAddTopic()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
DiscussionForum forum = saveForumSettings(false);
if(!uiPermissionsManager.isNewTopic(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CREATE_TOPIC));
return gotoMain();
}
selectedTopic = createTopic(forum.getId());
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveForumSettings()
{
LOG.debug("processActionSaveForumSettings()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
saveForumSettings(false);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
/**
* @return
*/
public String processActionSaveForumAsDraft()
{
LOG.debug("processActionSaveForumAsDraft()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
saveForumSettings(true);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
private DiscussionForum saveForumSettings(boolean draft)
{
LOG.debug("saveForumSettings(boolean " + draft + ")");
if (selectedForum == null)
{
setErrorMessage(getResourceBundleString(SELECTED_FORUM_NOT_FOUND));
return null;
}
DiscussionForum forum = selectedForum.getForum();
if (forum == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return null;
}
saveForumSelectedAssignment(forum);
saveForumAttach(forum);
setObjectPermissions(forum);
if (draft)
forumManager.saveForumAsDraft(forum);
else
forumManager.saveForum(forum);
//forumManager.saveForumControlPermissions(forum, forumControlPermissions);
//forumManager.saveForumMessagePermissions(forum, forumMessagePermissions);
if (forum.getId() == null)
{
String forumUuid = forum.getUuid();
forum = null;
forum = forumManager.getForumByUuid(forumUuid);
}
return forum;
}
/**
* @return Returns the selectedTopic.
*/
public DiscussionTopicBean getSelectedTopic()
{
//if(threaded)
//{
rearrageTopicMsgsThreaded();
//}
setMessageBeanPreNextStatus();
return selectedTopic;
}
/**
* @return Returns the selected Area
*/
public DiscussionAreaBean getTemplate()
{
return template;
}
/**
* @return
*/
public String processActionNewTopic()
{
LOG.debug("processActionNewTopic()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TOPIC);
selectedTopic = createTopic();
setNewTopicBeanAssign();
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
if(!uiPermissionsManager.isNewTopic(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CREATE_TOPIC));
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
setFromMainOrForumOrTopic();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionReviseTopicSettings()
{
LOG.debug("processActionReviseTopicSettings()");
setPermissionMode(PERMISSION_MODE_TOPIC);
setEditMode(true);
DiscussionTopic topic = selectedTopic.getTopic();
if (topic == null)
{
topic = forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
}
if (topic == null)
{
setErrorMessage(getResourceBundleString(TOPIC_WITH_ID) + getExternalParameterByKey(TOPIC_ID)
+ getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
List attachList = selectedTopic.getTopic().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setFromMainOrForumOrTopic();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveTopicAndAddTopic()
{
LOG.debug("processActionSaveTopicAndAddTopic()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
// if the topic is not moderated (and already exists), all of the pending messages must be approved
if (selectedTopic != null && selectedTopic.getTopic() != null &&
!selectedTopic.isTopicModerated() && selectedTopic.getTopic().getId() != null)
{
forumManager.approveAllPendingMessages(selectedTopic.getTopic().getId());
}
saveTopicSettings(false);
Long forumId = selectedForum.getForum().getId();
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_FORUM_NOT_FOUND));
return gotoMain();
}
selectedTopic = null;
selectedTopic = createTopic(forumId);
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveTopicSettings()
{
LOG.debug("processActionSaveTopicSettings()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
// if the topic is not moderated, all of the messages must be approved
if (selectedTopic != null && selectedTopic.getTopic().getId() != null &&
!selectedTopic.isTopicModerated())
{
forumManager.approveAllPendingMessages(selectedTopic.getTopic().getId());
}
saveTopicSettings(false);
return processReturnToOriginatingPage();
//reset();
//return MAIN;
}
/**
* @return
*/
public String processActionSaveTopicAsDraft()
{
LOG.debug("processActionSaveTopicAsDraft()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
saveTopicSettings(true);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
private String saveTopicSettings(boolean draft)
{
LOG.debug("saveTopicSettings(" + draft + ")");
setPermissionMode(PERMISSION_MODE_TOPIC);
if (selectedTopic != null)
{
DiscussionTopic topic = selectedTopic.getTopic();
if (selectedForum != null)
{
topic.setBaseForum(selectedForum.getForum());
saveTopicSelectedAssignment(topic);
saveTopicAttach(topic);
setObjectPermissions(topic);
if (draft)
{
forumManager.saveTopicAsDraft(topic);
}
else
{
forumManager.saveTopic(topic);
}
//forumManager
// .saveTopicControlPermissions(topic, topicControlPermissions);
//forumManager
// .saveTopicMessagePermissions(topic, topicMessagePermissions);
}
}
return gotoMain();
}
/**
* @return
*/
public String processActionDeleteTopicConfirm()
{
LOG.debug("processActionDeleteTopicConfirm()");
if (selectedTopic == null)
{
LOG.debug("There is no topic selected for deletion");
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
selectedTopic.setMarkForDeletion(true);
return TOPIC_SETTING;
}
/**
* @return
*/
public String processActionDeleteTopic()
{
LOG.debug("processActionDeleteTopic()");
if (selectedTopic == null)
{
LOG.debug("There is no topic selected for deletion");
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
forumManager.deleteTopic(selectedTopic.getTopic());
reset();
return gotoMain();
}
/**
* @return
*/
public String processActionTopicSettings()
{
LOG.debug("processActionTopicSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TOPIC);
DiscussionTopic topic = null;
if(getExternalParameterByKey(TOPIC_ID) != ""){
topic = (DiscussionTopic) forumManager
.getTopicByIdWithAttachments(new Long(
getExternalParameterByKey(TOPIC_ID)));
} else if(selectedTopic != null) {
topic = selectedTopic.getTopic();
}
if (topic == null)
{
return gotoMain();
}
setSelectedForumForCurrentTopic(topic);
if(!uiPermissionsManager.isChangeSettings(topic,selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
List attachList = selectedTopic.getTopic().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setTopicBeanAssign();
setFromMainOrForumOrTopic();
//return TOPIC_SETTING;
return TOPIC_SETTING_REVISE;
}
public String processActionToggleDisplayForumExtendedDescription()
{
LOG.debug("processActionToggleDisplayForumExtendedDescription()");
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
if (redirectTo == null)
{
setErrorMessage(getResourceBundleString(NOT_FOUND_REDIRECT_PAGE));
return gotoMain();
}
if (redirectTo.equals("displayHome"))
{
displayHomeWithExtendedForumDescription();
return gotoMain();
}
if (redirectTo.equals("processActionDisplayForum"))
{
if (selectedForum.isReadFullDesciption())
{
selectedForum.setReadFullDesciption(false);
}
else
{
selectedForum.setReadFullDesciption(true);
}
return FORUM_DETAILS;
}
return gotoMain();
}
/**
* @return
*/
public String processActionToggleDisplayExtendedDescription()
{
LOG.debug("processActionToggleDisplayExtendedDescription()");
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
if (redirectTo == null)
{
setErrorMessage(getResourceBundleString(NOT_FOUND_REDIRECT_PAGE));
return gotoMain();
}
if (redirectTo.equals("displayHome"))
{
return displayHomeWithExtendedTopicDescription();
}
if (redirectTo.equals("processActionDisplayTopic"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return ALL_MESSAGES;
}
if (redirectTo.equals("processActionDisplayMessage"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return MESSAGE_VIEW;
}
if (redirectTo.equals("processActionGradeMessage"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return GRADE_MESSAGE;
}
return gotoMain();
}
/**
* @return
*/
public String processActionDisplayTopic()
{
LOG.debug("processActionDisplayTopic()");
return displayTopicById(TOPIC_ID);
}
/**
* @return
*/
public String processActionDisplayNextTopic()
{
LOG.debug("processActionDisplayNextTopic()");
return displayTopicById("nextTopicId");
}
/**
* @return
*/
public String processActionDisplayPreviousTopic()
{
LOG.debug("processActionDisplayNextTopic()");
return displayTopicById("previousTopicId");
}
/**
* @return Returns the selectedMessage.
*/
public DiscussionMessageBean getSelectedMessage()
{
return selectedMessage;
}
/**
* @return Returns the selectedThread.
*/
public DiscussionMessageBean getSelectedThreadHead()
{
return selectedThreadHead;
}
/**
* @return Returns an array of Messages for the current selected thread
*/
public List getSelectedThread()
{
List returnArray = new ArrayList();
returnArray = selectedThread;
if(displayUnreadOnly){
ArrayList tempmes = new ArrayList();
for(int i = returnArray.size()-1; i >= 0; i--){
if(!((DiscussionMessageBean)returnArray.get(i)).isRead()){
tempmes.add(returnArray.get(i));
}
}
returnArray = tempmes;
}
if (!orderAsc){
ArrayList tempmes = new ArrayList();
for(int i = returnArray.size()-1; i >= 0; i--){
tempmes.add(returnArray.get(i));
}
return tempmes;
} else
return returnArray;
}
/**
* @return
*/
public String processActionDisplayFlatView()
{
return FLAT_VIEW;
}
/**
* @return
*/
public String processActionDisplayThreadedView()
{
return ALL_MESSAGES;
}
public String processActionGetDisplayThread()
{
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
setTopicBeanAssign();
getSelectedTopic();
List msgsList = selectedTopic.getMessages();
if (msgsList != null && !msgsList.isEmpty())
msgsList = filterModeratedMessages(msgsList, selectedTopic.getTopic(), (DiscussionForum) selectedTopic.getTopic().getBaseForum());
List orderedList = new ArrayList();
selectedThread = new ArrayList();
Boolean foundHead = false;
Boolean foundAfterHead = false;
for(int i=0; i<msgsList.size(); i++){
if(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId().equals(selectedThreadHead.getMessage().getId())){
((DiscussionMessageBean) msgsList.get(i)).setDepth(0);
selectedThread.add((DiscussionMessageBean)msgsList.get(i));
foundHead = true;
}
else if(((DiscussionMessageBean)msgsList.get(i)).getMessage().getInReplyTo() == null && foundHead && !foundAfterHead) {
selectedThreadHead.setHasNextThread(true);
selectedThreadHead.setNextThreadId(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId());
foundAfterHead = true;
}
else if (((DiscussionMessageBean)msgsList.get(i)).getMessage().getInReplyTo() == null && !foundHead) {
selectedThreadHead.setHasPreThread(true);
selectedThreadHead.setPreThreadId(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId());
}
}
recursiveGetThreadedMsgs(msgsList, orderedList, selectedThreadHead);
selectedThread.addAll(orderedList);
return THREAD_VIEW;
}
/**
* @return
*/
public String processActionDisplayThread()
{
LOG.debug("processActionDisplayThread()");
threadAnchorMessageId = null;
String threadId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (threadId == "")
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == "")
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message threadMessage = messageManager.getMessageByIdWithAttachments(new Long(
threadId));
if (threadMessage == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + threadId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
//threadMessage = messageManager.getMessageByIdWithAttachments(threadMessage.getId());
selectedThreadHead = new DiscussionMessageBean(threadMessage, messageManager);
//make sure we have the thread head of depth 0
while(selectedThreadHead.getMessage().getInReplyTo() != null){
threadMessage = messageManager.getMessageByIdWithAttachments(selectedThreadHead.getMessage().getInReplyTo().getId());
selectedThreadHead = new DiscussionMessageBean(
threadMessage, messageManager);
}
DiscussionTopic topic=forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
selectedMessage = selectedThreadHead;
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
String currentForumId = getExternalParameterByKey(FORUM_ID);
if (currentForumId != null && (!currentForumId.trim().equals(""))
&& (!currentForumId.trim().equals("null")))
{
DiscussionForum forum = forumManager
.getForumById(new Long(currentForumId));
selectedForum = getDecoratedForum(forum);
setForumBeanAssign();
selectedTopic.getTopic().setBaseForum(forum);
}
selectedTopic = getDecoratedTopic(forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID))));
return processActionGetDisplayThread();
}
/**
* @return
*/
public String processActionDisplayThreadAnchor()
{
String returnString = processActionDisplayThread();
threadAnchorMessageId = getExternalParameterByKey(MESSAGE_ID);
return returnString;
}
/**
* @return
*/
public String processActionDisplayMessage()
{
LOG.debug("processActionDisplayMessage()");
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
DiscussionTopic topic=forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
String currentForumId = getExternalParameterByKey(FORUM_ID);
if (currentForumId != null && (!currentForumId.trim().equals(""))
&& (!currentForumId.trim().equals("null")))
{
DiscussionForum forum = forumManager
.getForumById(new Long(currentForumId));
selectedForum = getDecoratedForum(forum);
setForumBeanAssign();
selectedTopic.getTopic().setBaseForum(forum);
}
selectedTopic = getDecoratedTopic(forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID))));
setTopicBeanAssign();
getSelectedTopic();
//get thread from message
getThreadFromMessage();
// selectedTopic= new DiscussionTopicBean(message.getTopic());
return MESSAGE_VIEW;
}
public void getThreadFromMessage()
{
Message mes = selectedMessage.getMessage();
String messageId = mes.getId().toString();
while( mes.getInReplyTo() != null) {
mes = messageManager.getMessageById(mes.getInReplyTo().getId());
}
selectedThreadHead = new DiscussionMessageBean(mes, messageManager);
List tempMsgs = selectedTopic.getMessages();
Boolean foundHead = false;
Boolean foundAfterHead = false;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId().toString().equals(messageId))
{
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
foundHead = true;
}
else if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getInReplyTo() == null && foundHead && !foundAfterHead) {
selectedThreadHead.setHasNextThread(true);
selectedThreadHead.setNextThreadId(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId());
foundAfterHead = true;
}
else if (((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getInReplyTo() == null && !foundHead) {
selectedThreadHead.setHasPreThread(true);
selectedThreadHead.setPreThreadId(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId());
}
}
}
}
public String processDisplayPreviousMsg()
{
List tempMsgs = selectedTopic.getMessages();
int currentMsgPosition = -1;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(selectedMessage.getMessage().getId().equals(thisDmb.getMessage().getId()))
{
currentMsgPosition = i;
break;
}
}
}
if(currentMsgPosition > 0)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(currentMsgPosition-1);
Message message = messageManager.getMessageByIdWithAttachments(thisDmb.getMessage().getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(),
selectedMessage.getMessage().getId(), true);
}
return null;
}
public String processDfDisplayNextMsg()
{
List tempMsgs = selectedTopic.getMessages();
int currentMsgPosition = -1;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(selectedMessage.getMessage().getId().equals(thisDmb.getMessage().getId()))
{
currentMsgPosition = i;
break;
}
}
}
if(currentMsgPosition > -2 && currentMsgPosition < (tempMsgs.size()-1))
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(currentMsgPosition+1);
Message message = messageManager.getMessageByIdWithAttachments(thisDmb.getMessage().getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(),
selectedMessage.getMessage().getId(), true);
}
return null;
}
// **************************************** helper methods**********************************
private String getExternalParameterByKey(String parameterId)
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
Map paramMap = context.getRequestParameterMap();
return (String) paramMap.get(parameterId);
}
/**
* @param forum
* @return List of DiscussionTopicBean
*/
private DiscussionForumBean getDecoratedForum(DiscussionForum forum)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedForum(DiscussionForum" + forum + ")");
}
forum = forumManager.getForumByIdWithTopics(forum.getId());
DiscussionForumBean decoForum = new DiscussionForumBean(forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoForum.setReadFullDesciption(true);
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return decoForum;
}
Iterator iter = temp_topics.iterator();
while (iter.hasNext())
{
DiscussionTopic topic = (DiscussionTopic) iter.next();
// TODO: put this logic in database layer
if (topic.getDraft().equals(Boolean.FALSE)||
(topic.getDraft().equals(Boolean.TRUE)&&topic.getCreatedBy().equals(SessionManager.getCurrentSessionUserId()))
||isInstructor()
||SecurityService.isSuperUser()||topic.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
topic = (DiscussionTopic) forumManager.getTopicByIdWithAttachments(topic
.getId());
if (topic != null)
{
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic, forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
if (uiPermissionsManager.isModeratePostings(topic, forum))
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoForum.addTopic(decoTopic);
}
}
}
return decoForum;
}
private DiscussionForumBean getDecoratedForumWithPersistentForumAndTopics(DiscussionForum forum, Map unreadMap)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedForum(DiscussionForum" + forum + ")");
}
DiscussionForumBean decoForum = new DiscussionForumBean(forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoForum.setReadFullDesciption(true);
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return decoForum;
}
Iterator iter = temp_topics.iterator();
while (iter.hasNext())
{
DiscussionTopic topic = (DiscussionTopic) iter.next();
// TODO: put this logic in database layer
if (topic.getDraft().equals(Boolean.FALSE)||
(topic.getDraft().equals(Boolean.TRUE)&&topic.getCreatedBy().equals(SessionManager.getCurrentSessionUserId()))
||isInstructor()
||SecurityService.isSuperUser()||topic.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
if (topic != null)
{
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic, forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
/*int totalMsgNumber = 0;
int readMsgNumber = 0;
if(topic.getMessages() != null)
{
List thisMessageList = topic.getMessages();
for(int i=0; i<thisMessageList.size(); i++)
{
Message thisMsg = (Message)thisMessageList.get(i);
if(thisMsg != null && !thisMsg.getDraft().booleanValue())
{
totalMsgNumber++;
if(unreadMap.get(thisMsg.getId()) != null && ((Boolean)unreadMap.get(thisMsg.getId())).booleanValue())
{
readMsgNumber++;
}
}
}
}
if(totalMsgNumber > 0 )
{
decoTopic.setTotalNoMessages(totalMsgNumber);
decoTopic.setUnreadNoMessages(totalMsgNumber -readMsgNumber);
}
//decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
//decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));*/
if (uiPermissionsManager.isModeratePostings(topic, forum))
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoForum.addTopic(decoTopic);
}
}
}
return decoForum;
}
/**
* @return DiscussionForumBean
*/
private DiscussionForumBean getDecoratedForum()
{
LOG.debug("decorateSelectedForum()");
String forumId = getExternalParameterByKey(FORUM_ID);
if ((forumId) != null)
{
DiscussionForum forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
return null;
}
selectedForum = getDecoratedForum(forum);
return selectedForum;
}
return null;
}
/**
* @return
*/
private String displayHomeWithExtendedForumDescription()
{
LOG.debug("displayHomeWithExtendedForumDescription()");
List tmpForums = getForums();
if (tmpForums != null)
{
Iterator iter = tmpForums.iterator();
while (iter.hasNext())
{
DiscussionForumBean decoForumBean = (DiscussionForumBean) iter.next();
if (decoForumBean != null)
{
// if this forum is selected to display full desciption
if (getExternalParameterByKey("forumId_displayExtended") != null
&& getExternalParameterByKey("forumId_displayExtended")
.trim().length() > 0
&& decoForumBean
.getForum()
.getId()
.equals(
new Long(
getExternalParameterByKey("forumId_displayExtended"))))
{
decoForumBean.setReadFullDesciption(true);
}
// if this topic is selected to display hide extended desciption
if (getExternalParameterByKey("forumId_hideExtended") != null
&& getExternalParameterByKey("forumId_hideExtended").trim()
.length() > 0
&& decoForumBean.getForum().getId().equals(
new Long(
getExternalParameterByKey("forumId_hideExtended"))))
{
decoForumBean.setReadFullDesciption(false);
}
}
}
}
return gotoMain();
}
/**
* @return
*/
private String displayHomeWithExtendedTopicDescription()
{
LOG.debug("displayHomeWithExtendedTopicDescription()");
List tmpForums = getForums();
if (tmpForums != null)
{
Iterator iter = tmpForums.iterator();
while (iter.hasNext())
{
DiscussionForumBean decoForumBean = (DiscussionForumBean) iter.next();
if (decoForumBean != null)
{
List tmpTopics = decoForumBean.getTopics();
Iterator iter2 = tmpTopics.iterator();
while (iter2.hasNext())
{
DiscussionTopicBean decoTopicBean = (DiscussionTopicBean) iter2
.next();
if (decoTopicBean != null)
{
// if this topic is selected to display full desciption
if (getExternalParameterByKey("topicId_displayExtended") != null
&& getExternalParameterByKey("topicId_displayExtended")
.trim().length() > 0
&& decoTopicBean
.getTopic()
.getId()
.equals(
new Long(
getExternalParameterByKey("topicId_displayExtended"))))
{
decoTopicBean.setReadFullDesciption(true);
}
// if this topic is selected to display hide extended desciption
if (getExternalParameterByKey("topicId_hideExtended") != null
&& getExternalParameterByKey("topicId_hideExtended").trim()
.length() > 0
&& decoTopicBean.getTopic().getId().equals(
new Long(
getExternalParameterByKey("topicId_hideExtended"))))
{
decoTopicBean.setReadFullDesciption(false);
}
}
}
}
}
}
return gotoMain();
}
/**
* @param topic
* @return
*/
private DiscussionTopicBean getDecoratedTopic(DiscussionTopic topic)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedTopic(DiscussionTopic " + topic + ")");
}
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic,
selectedForum.getForum(), uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
if (!decoTopic.isTopicModerated() || decoTopic.getIsModeratedAndHasPerm())
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoTopic.setHasNextTopic(forumManager.hasNextTopic(topic));
decoTopic.setHasPreviousTopic(forumManager.hasPreviousTopic(topic));
if (forumManager.hasNextTopic(topic))
{
DiscussionTopic nextTopic= forumManager.getNextTopic(topic);
decoTopic.setNextTopicId(nextTopic.getId());
}
if (forumManager.hasPreviousTopic(topic))
{
decoTopic
.setPreviousTopicId(forumManager.getPreviousTopic(topic).getId());
}
List temp_messages = forumManager.getTopicByIdWithMessages(topic.getId())
.getMessages();
if (temp_messages == null || temp_messages.size() < 1)
{
return decoTopic;
}
Iterator iter = temp_messages.iterator();
final boolean isRead = decoTopic.getIsRead();
final boolean isNewResponse = decoTopic.getIsNewResponse();
while (iter.hasNext())
{
Message message = (Message) iter.next();
if (topic != null)
{
if (message != null)
{
DiscussionMessageBean decoMsg = new DiscussionMessageBean(message,
messageManager);
if(isRead || (isNewResponse && decoMsg.getIsOwn()))
{
decoMsg.setRead(messageManager.isMessageReadForUser(topic.getId(),
message.getId()));
decoTopic.addMessage(decoMsg);
}
}
}
}
return decoTopic;
}
private Boolean resetTopicById(String externalTopicId)
{
String topicId = null;
//threaded = true;
selectedTopic = null;
try
{
topicId = getExternalParameterByKey(externalTopicId);
if (topicId != null)
{
DiscussionTopic topic = null;
try
{
Long.parseLong(topicId);
topic = forumManager.getTopicById(new Long(topicId));
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(getResourceBundleString(UNABLE_RETRIEVE_TOPIC));
return false;
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
else
{
LOG.error("Topic with id '" + externalTopicId + "' not found");
setErrorMessage(getResourceBundleString(TOPIC_WITH_ID) + externalTopicId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return false;
}
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return false;
}
return true;
}
/**
* @param externalTopicId
* @return
*/
private String displayTopicById(String externalTopicId)
{
if (LOG.isDebugEnabled())
{
LOG.debug("processActionDisplayTopicById(String" + externalTopicId + ")");
}
if(resetTopicById(externalTopicId)){
return ALL_MESSAGES;
} else {
return gotoMain();
}
}
private void reset()
{
this.forums = null;
this.selectedForum = null;
this.selectedTopic = null;
this.selectedMessage = null;
// this.templateControlPermissions = null;
// this.templateMessagePermissions = null;
this.permissions=null;
this.errorSynch = false;
this.siteMembers=null;
attachments.clear();
prepareRemoveAttach.clear();
assignments.clear();
}
/**
* @return newly created topic
*/
private DiscussionTopicBean createTopic()
{
String forumId = getExternalParameterByKey(FORUM_ID);
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
return createTopic(new Long(forumId));
}
/**
* @param forumID
* @return
*/
private DiscussionTopicBean createTopic(Long forumId)
{
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
DiscussionForum forum = forumManager.getForumById(forumId);
if (forum == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
DiscussionTopic topic = forumManager.createTopic(forum);
if (topic == null)
{
setErrorMessage(getResourceBundleString(FAILED_CREATE_TOPIC));
return null;
}
selectedTopic = new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
selectedTopic.setModerated(selectedForum.getModerated()); // default to parent forum's setting
setNewTopicBeanAssign();
DiscussionTopicBean thisDTB = new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
thisDTB.setReadFullDesciption(true);
}
setNewTopicBeanAssign(selectedForum, thisDTB);
return thisDTB;
//return new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
}
// compose
public String processAddMessage()
{
return MESSAGE_COMPOSE;
}
public String processAddAttachmentRedirect()
{
LOG.debug("processAddAttachmentRedirect()");
try
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
context.redirect("sakai.filepicker.helper/tool");
return null;
}
catch (Exception e)
{
return null;
}
}
public void setMessageManager(MessageForumsMessageManager messageManager)
{
this.messageManager = messageManager;
}
public String getComposeTitle()
{
return composeTitle;
}
public void setComposeTitle(String composeTitle)
{
this.composeTitle = composeTitle;
}
public String getComposeBody()
{
return composeBody;
}
public void setComposeBody(String composeBody)
{
this.composeBody = composeBody;
}
public String getComposeLabel()
{
return composeLabel;
}
public void setComposeLabel(String composeLabel)
{
this.composeLabel = composeLabel;
}
public ArrayList getAttachments()
{
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null
&& session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null)
{
List refs = (List) session
.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if(refs != null && refs.size()>0)
{
Reference ref = (Reference) refs.get(0);
for (int i = 0; i < refs.size(); i++)
{
ref = (Reference) refs.get(i);
Attachment thisAttach = messageManager.createAttachment();
thisAttach.setAttachmentName(ref.getProperties().getProperty(
ref.getProperties().getNamePropDisplayName()));
thisAttach.setAttachmentSize(ref.getProperties().getProperty(
ref.getProperties().getNamePropContentLength()));
thisAttach.setAttachmentType(ref.getProperties().getProperty(
ref.getProperties().getNamePropContentType()));
thisAttach.setAttachmentId(ref.getId());
//thisAttach.setAttachmentUrl(ref.getUrl());
thisAttach.setAttachmentUrl("/url");
attachments.add(new DecoratedAttachment(thisAttach));
}
}
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
return attachments;
}
public void setAttachments(ArrayList attachments)
{
this.attachments = attachments;
}
public String processDeleteAttach()
{
LOG.debug("processDeleteAttach()");
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
attachments.remove(i);
break;
}
}
}
return null;
}
public String processDfMsgCancel()
{
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfMsgPost()
{
Message dMsg = constructMessage();
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
/** mark message creator as having read the message */
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(), dMsg.getId(), true);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
// refresh page with unread status
selectedTopic = getDecoratedTopic(forumManager.getTopicById(selectedTopic.getTopic().getId()));
return ALL_MESSAGES;
}
public String processDfMsgSaveDraft()
{
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public Message constructMessage()
{
Message aMsg;
aMsg = messageManager.createDiscussionMessage();
if (aMsg != null)
{
aMsg.setTitle(getComposeTitle());
aMsg.setBody(getComposeBody());
aMsg.setAuthor(getUserNameOrEid());
aMsg.setDraft(Boolean.FALSE);
// if the topic is moderated, we want to leave approval null.
// if the topic is not moderated, all msgs are approved
// if the author has moderator perm, the msg is automatically approved
if (!selectedTopic.isTopicModerated() || selectedTopic.getIsModeratedAndHasPerm())
{
aMsg.setApproved(Boolean.TRUE);
}
aMsg.setTopic(selectedTopic.getTopic());
}
for (int i = 0; i < attachments.size(); i++)
{
aMsg.addAttachment(((DecoratedAttachment) attachments.get(i)).getAttachment());
}
attachments.clear();
// oldAttachments.clear();
return aMsg;
}
public String processDfComposeToggle()
{
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
String expand = getExternalParameterByKey("composeExpand");
if (redirectTo == null)
{
return gotoMain();
}
if (redirectTo.equals("dfCompose"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return MESSAGE_COMPOSE;
}
if (redirectTo.equals("dfViewMessage"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return MESSAGE_VIEW;
}
if (redirectTo.equals("dfTopicReply"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return "dfTopicReply";
}
return gotoMain();
}
public String getUserId()
{
return SessionManager.getCurrentSessionUserId();
}
public boolean getFullAccess()
{
return forumManager.isInstructor();
}
/**
* @return
*/
public String processDfMsgMarkMsgAsRead()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
if(resetTopicById(TOPIC_ID)){ // reconstruct topic again;
return null;
} else {
return gotoMain();
}
}
/**
* @return
*/
public String processDfMsgMarkMsgAsReadFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
return processActionGetDisplayThread(); // reconstruct thread again;
}
public String processDfMsgReplyMsgFromEntire()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgReplyMsg();
}
public String processDfMsgReplyMsg()
{
if(selectedMessage.getMessage().getTitle() != null && !selectedMessage.getMessage().getTitle().startsWith(getResourceBundleString(MSG_REPLY_PREFIX)))
this.composeTitle = getResourceBundleString(MSG_REPLY_PREFIX) + " " + selectedMessage.getMessage().getTitle() + " ";
else
this.composeTitle = selectedMessage.getMessage().getTitle();
return "dfMessageReply";
}
public String processDfMsgReplyThread()
{
//we have to get the depth 0 message that this is in response to
DiscussionMessageBean cur = selectedMessage;
int depth = 0;
long messageId = 0;
while(cur.getDepth() > 0){
messageId = cur.getMessage().getInReplyTo().getId();
depth = cur.getDepth();
cur = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(cur.getMessage().getInReplyTo().getId()), messageManager);
cur.setDepth(--depth);
}
selectedMessage = cur;
List tempMsgs = selectedTopic.getMessages();
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId().toString().equals(messageId))
{
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
break;
}
}
}
composeTitle = getResourceBundleString(MSG_REPLY_PREFIX) + " " + selectedMessage.getMessage().getTitle();
return "dfMessageReplyThread";
}
public String processDfMsgReplyTp()
{
return "dfTopicReply";
}
public String processDfMsgGrdFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgGrd();
}
public String processDfMsgGrd()
{
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
try
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String createdById = UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId();
String gradebookUid = ToolManager.getCurrentPlacement().getContext();
String msgAssignmentName = selectedMessage.getMessage().getGradeAssignmentName();
String topicDefaultAssignment = selectedTopic.getTopic().getDefaultAssignName();
String forumDefaultAssignment = selectedForum.getForum().getDefaultAssignName();
if(msgAssignmentName !=null && msgAssignmentName.trim().length()>0)
{
if((gradebookService.getAssignmentScore(gradebookUid,
msgAssignmentName, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
msgAssignmentName, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, msgAssignmentName, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(msgAssignmentName);
}
}
else if(topicDefaultAssignment != null &&
topicDefaultAssignment.trim().length() > 0)
{
if((gradebookService.getAssignmentScore(gradebookUid,
topicDefaultAssignment, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
topicDefaultAssignment, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, topicDefaultAssignment, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(topicDefaultAssignment);
}
else
{
gradePoint = "";
setSelectedAssignForMessage(topicDefaultAssignment);
}
}
else if(forumDefaultAssignment != null &&
forumDefaultAssignment.trim().length() > 0)
{
if( (gradebookService.getAssignmentScore(gradebookUid,
forumDefaultAssignment, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
forumDefaultAssignment, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, forumDefaultAssignment, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(forumDefaultAssignment);
}
else
{
gradePoint = "";
setSelectedAssignForMessage(topicDefaultAssignment);
}
}
}
catch(Exception e)
{
LOG.error("processDfMsgGrd in DiscussionFOrumTool - " + e);
e.printStackTrace();
return null;
}
return "dfMsgGrade";
}
public String processDfMsgRvsFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgRvs();
}
public String processDfMsgRvs()
{
attachments.clear();
composeBody = selectedMessage.getMessage().getBody();
composeLabel = selectedMessage.getMessage().getLabel();
composeTitle = selectedMessage.getMessage().getTitle();
List attachList = selectedMessage.getMessage().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment) attachList.get(i)));
}
}
return "dfMsgRevise";
}
public String processDfMsgMove()
{
List childMsgs = new ArrayList();
messageManager
.getChildMsgs(selectedMessage.getMessage().getId(), childMsgs);
// selectedMessage.getMessage().setTopic(selectedTopic.getTopic());
return null;
}
public String processDfMsgDeleteConfirm()
{
deleteMsg = true;
return null;
}
public String processDfReplyMsgPost()
{
List tempList = forumManager.getMessagesByTopicId(selectedTopic.getTopic().getId());
if(tempList != null)
{
boolean existed = false;
for(int i=0; i<tempList.size(); i++)
{
Message tempMsg = (Message)tempList.get(i);
if(tempMsg.getId().equals(selectedMessage.getMessage().getId()))
{
existed = true;
break;
}
}
if(!existed)
{
this.errorSynch = true;
return null;
}
}
else
{
this.errorSynch = true;
return null;
}
Message dMsg = constructMessage();
dMsg.setInReplyTo(selectedMessage.getMessage());
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(), dMsg.getId(), true);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
//return ALL_MESSAGES;
return processActionGetDisplayThread();
}
public String processDfReplyMsgSaveDraft()
{
List tempList = forumManager.getMessagesByTopicId(selectedTopic.getTopic().getId());
if(tempList != null)
{
boolean existed = false;
for(int i=0; i<tempList.size(); i++)
{
Message tempMsg = (Message)tempList.get(i);
if(tempMsg.getId().equals(selectedMessage.getMessage().getId()))
{
existed = true;
break;
}
}
if(!existed)
{
this.errorSynch = true;
return null;
}
}
else
{
this.errorSynch = true;
return null;
}
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
dMsg.setInReplyTo(selectedMessage.getMessage());
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return processActionGetDisplayThread();
}
public String processDeleteAttachRevise()
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
prepareRemoveAttach.add((DecoratedAttachment) attachments.get(i));
attachments.remove(i);
break;
}
}
}
return null;
}
public String processDfMsgRevisedCancel()
{
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfMsgRevisedPost()
{
Message dMsg = selectedMessage.getMessage();
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
dMsg.removeAttachment(removeAttach.getAttachment());
}
List oldList = dMsg.getAttachments();
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId()
.equals(thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
dMsg.addAttachment(thisAttach.getAttachment());
}
}
String currentBody = getComposeBody();
String revisedInfo = getResourceBundleString(LAST_REVISE_BY);
revisedInfo += getUserNameOrEid();
revisedInfo += " " + getResourceBundleString(LAST_REVISE_ON);
Date now = new Date();
revisedInfo += now.toString() + " <br/> ";
/* if(currentBody != null && currentBody.length()>0 && currentBody.startsWith("Last Revised By "))
{
if(currentBody.lastIndexOf(" <br/> ") > 0)
{
currentBody = currentBody.substring(currentBody.lastIndexOf(" <br/> ") + 7);
}
}*/
revisedInfo = revisedInfo.concat(currentBody);
dMsg.setTitle(getComposeTitle());
dMsg.setBody(revisedInfo);
dMsg.setDraft(Boolean.FALSE);
dMsg.setModified(new Date());
dMsg.setModifiedBy(getUserNameOrEid());
if (!selectedTopic.isTopicModerated() || selectedTopic.getIsModeratedAndHasPerm())
{
dMsg.setApproved(Boolean.TRUE);
}
else
{
dMsg.setApproved(null);
}
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
dMsg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
// Topic currentTopic = forumManager.getTopicByIdWithMessagesAndAttachments(dMsg.getTopic().getId());
// dMsg.getTopic().setBaseForum(currentTopic.getBaseForum());
//dMsg.getTopic().setBaseForum(selectedTopic.getTopic().getBaseForum());
forumManager.saveMessage(dMsg);
List messageList = selectedTopic.getMessages();
for (int i = 0; i < messageList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean) messageList.get(i);
if (dmb.getMessage().getId().equals(dMsg.getId()))
{
selectedTopic.getMessages().set(i,
new DiscussionMessageBean(dMsg, messageManager));
}
}
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return null;
}
prepareRemoveAttach.clear();
composeBody = null;
composeLabel = null;
composeTitle = null;
attachments.clear();
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfMsgSaveRevisedDraft()
{
Message dMsg = selectedMessage.getMessage();
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
dMsg.removeAttachment(removeAttach.getAttachment());
}
List oldList = dMsg.getAttachments();
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId()
.equals(thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
dMsg.addAttachment(thisAttach.getAttachment());
}
}
String currentBody = getComposeBody();
String revisedInfo = getResourceBundleString(LAST_REVISE_BY);
revisedInfo += getUserNameOrEid();
revisedInfo += " " + getResourceBundleString(LAST_REVISE_ON);
Date now = new Date();
revisedInfo += now.toString() + " <br/> ";
revisedInfo = revisedInfo.concat(currentBody);
dMsg.setTitle(getComposeTitle());
dMsg.setBody(revisedInfo);
dMsg.setDraft(Boolean.TRUE);
dMsg.setModified(new Date());
dMsg.setModifiedBy(getUserNameOrEid());
// if the topic is moderated, we want to leave approval null.
// if the topic is not moderated, all msgs are approved
if (!selectedTopic.isTopicModerated())
{
dMsg.setApproved(Boolean.TRUE);
}
// setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
// .getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.setTopic((DiscussionTopic) forumManager
// .getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
dMsg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
//dMsg.getTopic().setBaseForum(selectedTopic.getTopic().getBaseForum());
forumManager.saveMessage(dMsg);
List messageList = selectedTopic.getMessages();
for (int i = 0; i < messageList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean) messageList.get(i);
if (dmb.getMessage().getId().equals(dMsg.getId()))
{
selectedTopic.getMessages().set(i,
new DiscussionMessageBean(dMsg, messageManager));
}
}
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return null;
}
prepareRemoveAttach.clear();
composeBody = null;
composeLabel = null;
composeTitle = null;
attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyMsgCancel()
{
this.errorSynch = false;
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfReplyThreadCancel()
{
this.errorSynch = false;
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return processActionGetDisplayThread();
}
public String processDfReplyTopicPost()
{
Message dMsg = constructMessage();
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyTopicSaveDraft()
{
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyTopicCancel()
{
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public boolean getDeleteMsg()
{
return deleteMsg;
}
public String processDfMsgDeleteConfirmYes()
{
List delList = new ArrayList();
messageManager.getChildMsgs(selectedMessage.getMessage().getId(), delList);
if(delList.size() > 0)
{
if(!selectedTopic.getIsDeleteAny())
{
errorSynch = true;
return null;
}
}
selectedTopic.removeMessage(selectedMessage);
Topic tempTopic = forumManager.getTopicByIdWithMessages(selectedTopic
.getTopic().getId());
tempTopic.removeMessage(selectedMessage.getMessage());
// selectedTopic.getTopic().removeMessage(selectedMessage.getMessage());
for (int i = 0; i < delList.size(); i++)
{
selectedTopic.removeMessage(new DiscussionMessageBean((Message) delList
.get(i), messageManager));
// tempTopic.removeMessage((Message) delList.get(i));
// selectedTopic.getTopic().removeMessage((Message) delList.get(i));
}
messageManager.deleteMsgWithChild(selectedMessage.getMessage().getId());
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
this.deleteMsg = false;
return gotoMain();
}
this.deleteMsg = false;
return ALL_MESSAGES;
}
public String processDfMsgDeleteCancel()
{
this.deleteMsg = false;
this.errorSynch = false;
return null;
}
/**
* A moderator view of all msgs pending approval
* @return
*/
public String processPendingMsgQueue()
{
return PENDING_MSG_QUEUE;
}
/**
* "Pending Messages" link will be displayed if current user
* has moderate perm for at least one moderated topic in site.
* Also sets number of pending msgs
* @return
*/
public boolean isDisplayPendingMsgQueue()
{
List membershipList = uiPermissionsManager.getCurrentUserMemberships();
int numModTopicWithPerm = forumManager.getNumModTopicsWithModPermission(membershipList);
if (numModTopicWithPerm < 1)
return false;
if (refreshPendingMsgs)
{
refreshPendingMessages();
}
return true;
}
public int getNumPendingMessages()
{
return numPendingMessages;
}
public void setNumPendingMessages(int numPendingMessages)
{
this.numPendingMessages = numPendingMessages;
}
/**
* Retrieve pending msgs from db and make DiscussionMessageBeans
*
*/
private void refreshPendingMessages()
{
pendingMsgs = new ArrayList();
numPendingMessages = 0;
List messages = forumManager.getPendingMsgsInSiteByMembership(uiPermissionsManager.getCurrentUserMemberships());
if (messages != null && !messages.isEmpty())
{
messages = messageManager.sortMessageByDate(messages, false);
Iterator msgIter = messages.iterator();
while (msgIter.hasNext())
{
Message msg = (Message) msgIter.next();
DiscussionMessageBean decoMsg = new DiscussionMessageBean(msg, messageManager);
pendingMsgs.add(decoMsg);
numPendingMessages++;
}
}
refreshPendingMsgs = false;
}
/**
* returns all messages in the site that are pending and curr user has
* moderate perm to view
* @return
*/
public List getPendingMessages()
{
if (refreshPendingMsgs)
{
refreshPendingMessages();
}
return pendingMsgs;
}
/**
* Will approve all "selected" messags
* @return
*/
public String markCheckedAsApproved()
{
approveOrDenySelectedMsgs(true);
if (numPendingMessages > 0)
return PENDING_MSG_QUEUE;
return processActionHome();
}
/**
* Will deny all "selected" messages
* @return
*/
public String markCheckedAsDenied()
{
approveOrDenySelectedMsgs(false);
if (numPendingMessages > 0)
return PENDING_MSG_QUEUE;
return processActionHome();
}
/**
* Mark selected msgs as denied or approved
* @param approved
*/
private void approveOrDenySelectedMsgs(boolean approved)
{
if (pendingMsgs == null || pendingMsgs.isEmpty())
{
return;
}
int numSelected = 0;
Iterator iter = pendingMsgs.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
if (decoMessage.isSelected())
{
Message msg = decoMessage.getMessage();
messageManager.markMessageApproval(msg.getId(), approved);
messageManager.markMessageReadForUser(msg.getTopic().getId(), msg.getId(), true);
numSelected++;
numPendingMessages--;
}
}
if (numSelected < 1)
setErrorMessage(getResourceBundleString(NO_MSG_SEL_FOR_APPROVAL));
else
{
if (approved)
setSuccessMessage(getResourceBundleString(MSGS_APPROVED));
else
setSuccessMessage(getResourceBundleString(MSGS_DENIED));
}
refreshPendingMsgs = true;
}
/**
* Deny a message
* @return
*/
public String processDfMsgDeny()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, false);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
}
refreshPendingMsgs = true;
return MESSAGE_VIEW;
}
/**
* Deny a message and return to comment page
* @return
*/
public String processDfMsgDenyAndComment()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, false);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
displayDeniedMsg = true;
}
refreshPendingMsgs = true;
return ADD_COMMENT;
}
/**
* Approve a message
* @return
*/
public String processDfMsgApprove()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, true);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
setSuccessMessage(getResourceBundleString("cdfm_approved_alert"));
}
refreshPendingMsgs = true;
return MESSAGE_VIEW;
}
/**
* @return
*/
public String processDfMsgAddComment()
{
moderatorComments = "";
return ADD_COMMENT;
}
/**
*
* @return
*/
public String processCancelAddComment()
{
if (displayDeniedMsg) // only displayed if from Deny & Comment path
{
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
displayDeniedMsg = false;
}
return MESSAGE_VIEW;
}
/**
* Moderators may add a comment that is prepended to the text
* of the denied msg
* @return
*/
public String processAddCommentToDeniedMsg()
{
if (!selectedTopic.getIsModeratedAndHasPerm())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_ADD_COMMENT));
return ADD_COMMENT;
}
if (moderatorComments == null || moderatorComments.trim().length() < 1)
{
setErrorMessage(getResourceBundleString(INVALID_COMMENT));
return ADD_COMMENT;
}
Message currMessage = selectedMessage.getMessage();
StringBuffer sb = new StringBuffer();
sb.append("<div style=\"font-style:italic; padding-bottom: 1.0em;\">");
sb.append("<div style=\"font-weight:bold;\">");
sb.append(getResourceBundleString(MOD_COMMENT_TEXT) + " ");
sb.append(UserDirectoryService.getCurrentUser().getDisplayName());
sb.append("</div>");
sb.append(moderatorComments);
sb.append("</div>");
String originalText = currMessage.getBody();
currMessage.setBody(sb.toString() + originalText);
currMessage.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
forumManager.saveMessage(currMessage);
if (displayDeniedMsg) // only displayed if from Deny & Comment path
{
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
displayDeniedMsg = false;
}
// we also must mark this message as unread for the author to let them
// know there is a comment
forumManager.markMessageReadStatusForUser(currMessage, false, currMessage.getCreatedBy());
return MESSAGE_VIEW;
}
/**
* Approve option is displayed if:
* 1) topic is moderated
* 2) user has moderate perm
* 3) message has not been approved
* @return
*/
public boolean isAllowedToApproveMsg()
{
return selectedTopic.getIsModeratedAndHasPerm() && !selectedMessage.isMsgApproved();
}
/**
* Deny option is displayed if:
* 1) topic is moderated
* 2) user has moderate perm
* 3) message has not been denied
* 4) message has no responses
* @return
*/
public boolean isAllowedToDenyMsg()
{
return selectedTopic.getIsModeratedAndHasPerm() && !selectedMessage.isMsgDenied() && !selectedMessage.getHasChild();
}
public void setNewForumBeanAssign()
{
selectedForum.setGradeAssign("Default_0");
}
public void setNewTopicBeanAssign()
{
if(selectedForum !=null && selectedForum.getGradeAssign() != null && selectedForum.getForum() != null)
{
selectedTopic.setGradeAssign(selectedForum.getGradeAssign());
selectedTopic.getTopic().setDefaultAssignName(selectedForum.getForum().getDefaultAssignName());
}
}
public void setNewTopicBeanAssign(DiscussionForumBean dfb, DiscussionTopicBean dtb)
{
if(dfb !=null && dfb.getGradeAssign() != null && dfb.getForum() != null)
{
dtb.setGradeAssign(dfb.getGradeAssign());
dtb.getTopic().setDefaultAssignName(dfb.getForum().getDefaultAssignName());
}
}
public void setForumBeanAssign()
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(selectedForum.getForum().getDefaultAssignName()))
{
selectedForum.setGradeAssign((String)((SelectItem)assignments.get(i)).getValue());
break;
}
}
}
}
public void setTopicBeanAssign()
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(selectedTopic.getTopic().getDefaultAssignName()))
{
selectedTopic.setGradeAssign((String)((SelectItem)assignments.get(i)).getValue());
break;
}
}
}
}
public void setSelectedAssignForMessage(String assignName)
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(assignName))
{
this.selectedAssign = (String)((SelectItem)assignments.get(i)).getValue();
break;
}
}
}
}
public void saveForumSelectedAssignment(DiscussionForum forum)
{
if(selectedForum.getGradeAssign() != null && !selectedForum.getGradeAssign().equals("Default_0"))
{
forum.setDefaultAssignName( ((SelectItem)assignments.get( new Integer(selectedForum.getGradeAssign()).intValue())).getLabel());
}
}
public void saveForumAttach(DiscussionForum forum)
{
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
List oldList = forum.getAttachments();
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
removeAttach.getAttachment().getAttachmentId()))
{
forum.removeAttachment(removeAttach.getAttachment());
break;
}
}
}
List oldList = forum.getAttachments();
if (oldList != null)
{
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
forum.addAttachment(thisAttach.getAttachment());
}
}
}
prepareRemoveAttach.clear();
attachments.clear();
}
public void saveTopicSelectedAssignment(DiscussionTopic topic)
{
if(selectedTopic.getGradeAssign() != null && !selectedTopic.getGradeAssign().equals("Default_0"))
{
topic.setDefaultAssignName( ((SelectItem)assignments.get( new Integer(selectedTopic.getGradeAssign()).intValue())).getLabel());
}
}
public void saveTopicAttach(DiscussionTopic topic)
{
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
List oldList = topic.getAttachments();
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
removeAttach.getAttachment().getAttachmentId()))
{
topic.removeAttachment(removeAttach.getAttachment());
break;
}
}
}
List oldList = topic.getAttachments();
if (oldList != null)
{
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
topic.addAttachment(thisAttach.getAttachment());
}
}
}
prepareRemoveAttach.clear();
attachments.clear();
}
public String processDeleteAttachSetting()
{
LOG.debug("processDeleteAttach()");
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
prepareRemoveAttach.add((DecoratedAttachment) attachments.get(i));
attachments.remove(i);
break;
}
}
}
return null;
}
public boolean getThreaded()
{
return threaded;
}
public void setThreaded(boolean threaded)
{
this.threaded = threaded;
}
public String getExpanded()
{
return expanded;
}
public boolean getExpandedView()
{
return expandedView;
}
public void setExpanded(String expanded)
{
this.expanded = expanded;
}
public void setGradeNotify(boolean gradeNotify)
{
this.gradeNotify = gradeNotify;
}
public boolean getGradeNotify()
{
return gradeNotify;
}
public String getSelectedAssign()
{
return selectedAssign;
}
public void setSelectedAssign(String selectedAssign)
{
this.selectedAssign = selectedAssign;
}
public void setGradePoint(String gradePoint)
{
this.gradePoint = gradePoint;
}
public String getGradePoint()
{
return gradePoint;
}
public List getAssignments()
{
return assignments;
}
public void setAssignments(List assignments)
{
this.assignments = assignments;
}
public void setGradeComment(String gradeComment)
{
this.gradeComment = gradeComment;
}
public String getGradeComment()
{
return gradeComment;
}
public void rearrageTopicMsgsThreaded()
{
List msgsList = selectedTopic.getMessages();
if (msgsList != null && !msgsList.isEmpty())
msgsList = filterModeratedMessages(msgsList, selectedTopic.getTopic(), (DiscussionForum)selectedTopic.getTopic().getBaseForum());
List orderedList = new ArrayList();
List threadList = new ArrayList();
if(msgsList != null)
{
for(int i=0; i<msgsList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean)msgsList.get(i);
if(dmb.getMessage().getInReplyTo() == null)
{
threadList.add(dmb);
dmb.setDepth(0);
orderedList.add(dmb);
//for performance speed - operate with existing selectedTopic msgs instead of getting from manager through DB again
//recursiveGetThreadedMsgs(msgsList, orderedList, dmb);
//use arrays so as to pass by reference during recursion
recursiveGetThreadedMsgsFromListWithCounts(msgsList, orderedList, dmb, new int[1], new int[1]);
}
}
}
selectedTopic.setMessages(orderedList);
}
public void recursiveGetThreadedMsgs(List msgsList, List returnList,
DiscussionMessageBean currentMsg)
{
List childList = messageManager.getFirstLevelChildMsgs(currentMsg.getMessage().getId());
for(int j=0; j<childList.size(); j++)
{
Message currentChild = (Message)childList.get(j);
for(int k=0; k<msgsList.size(); k++)
{
Message existedMsg = ((DiscussionMessageBean)msgsList.get(k)).getMessage();
if(currentChild.getId().equals(existedMsg.getId()))
{
DiscussionMessageBean dmb = new DiscussionMessageBean(currentChild, messageManager);
/* dmb.setDepth(currentMsg.getDepth() + 1);
returnList.add(dmb);*/
((DiscussionMessageBean)msgsList.get(k)).setDepth(currentMsg.getDepth() + 1);
returnList.add(((DiscussionMessageBean)msgsList.get(k)));
recursiveGetThreadedMsgs(msgsList, returnList, ((DiscussionMessageBean)msgsList.get(k)));
break;
}
}
}
}
private void recursiveGetThreadedMsgsFromList(List msgsList, List returnList,
DiscussionMessageBean currentMsg)
{
for (int i = 0; i < msgsList.size(); i++)
{
DiscussionMessageBean thisMsgBean = (DiscussionMessageBean) msgsList
.get(i);
Message thisMsg = thisMsgBean.getMessage();
if (thisMsg.getInReplyTo() != null
&& thisMsg.getInReplyTo().getId().equals(
currentMsg.getMessage().getId()))
{
/*
* DiscussionMessageBean dmb = new DiscussionMessageBean(thisMsg, messageManager);
* dmb.setDepth(currentMsg.getDepth() + 1); returnList.add(dmb);
* this.recursiveGetThreadedMsgsFromList(msgsList, returnList, dmb);
*/
thisMsgBean.setDepth(currentMsg.getDepth() + 1);
returnList.add(thisMsgBean);
this
.recursiveGetThreadedMsgsFromList(msgsList, returnList, thisMsgBean);
}
}
}
private void recursiveGetThreadedMsgsFromListWithCounts(List msgsList, List returnList,
DiscussionMessageBean currentMsg, int[] childCount, int[] childUnread)
{
for (int i = 0; i < msgsList.size(); i++)
{
DiscussionMessageBean thisMsgBean = (DiscussionMessageBean) msgsList
.get(i);
Message thisMsg = thisMsgBean.getMessage();
if (thisMsg.getInReplyTo() != null
&& thisMsg.getInReplyTo().getId().equals(
currentMsg.getMessage().getId()))
{
/*
* DiscussionMessageBean dmb = new DiscussionMessageBean(thisMsg, messageManager);
* dmb.setDepth(currentMsg.getDepth() + 1); returnList.add(dmb);
* this.recursiveGetThreadedMsgsFromList(msgsList, returnList, dmb);
*/
childCount[0]++;
if(!thisMsgBean.isRead()){
childUnread[0]++;
}
thisMsgBean.setDepth(currentMsg.getDepth() + 1);
returnList.add(thisMsgBean);
this
.recursiveGetThreadedMsgsFromListWithCounts(msgsList, returnList, thisMsgBean, childCount, childUnread);
}
}
currentMsg.setChildCount(childCount[0]);
currentMsg.setChildUnread(childUnread[0]);
}
public String processDfGradeCancel()
{
gradeNotify = false;
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processGradeAssignChange(ValueChangeEvent vce)
{
String changeAssign = (String) vce.getNewValue();
if (changeAssign == null)
{
return null;
}
else
{
try
{
selectedAssign = changeAssign;
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
if((!selectedAssign.equalsIgnoreCase("Default_0"))
&& ((gradebookService.getAssignmentScore(ToolManager.getCurrentPlacement().getContext(),
((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel(),
UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId())) != null))
{
gradePoint = (gradebookService.getAssignmentScore(ToolManager.getCurrentPlacement().getContext(),
((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel(),
UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId())).toString();
}
else
{
gradePoint = "";
}
return "dfMsgGrade";
}
catch(Exception e)
{
LOG.error("processGradeAssignChange in DiscussionFOrumTool - " + e);
e.printStackTrace();
return null;
}
}
}
public boolean isNumber(String validateString)
{
try
{
double d = Double.valueOf(validateString).doubleValue();
if(d >= 0)
return true;
else
return false;
}
catch (NumberFormatException e)
{
e.printStackTrace();
return false;
}
}
public boolean isFewerDigit(String validateString)
{
String stringValue = new Double(validateString).toString();
if(stringValue.lastIndexOf(".") >= 0)
{
String subString = stringValue.substring(stringValue.lastIndexOf("."));
if(subString != null && subString.length() > 3)
return false;
}
return true;
}
private boolean validateGradeInput()
{
if(!isNumber(gradePoint))
{
FacesContext currentContext = FacesContext.getCurrentInstance();
String uiComponentId = "msgForum:dfMsgGradeGradePoint";
FacesMessage validateMessage = new FacesMessage(getResourceBundleString(GRADE_GREATER_ZERO));
validateMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
currentContext.addMessage(uiComponentId, validateMessage);
return false;
}
else if(!isFewerDigit(gradePoint))
{
FacesContext currentContext = FacesContext.getCurrentInstance();
String uiComponentId = "msgForum:dfMsgGradeGradePoint";
FacesMessage validateMessage = new FacesMessage(getResourceBundleString(GRADE_DECIMAL_WARN));
validateMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
currentContext.addMessage(uiComponentId, validateMessage);
return false;
}
return true;
}
public String processDfGradeSubmit()
{
if(gradePoint == null || gradePoint.trim().length()==0)
{
setErrorMessage(getResourceBundleString(NO_GRADE_PTS));
return null;
}
if(selectedAssign == null || selectedAssign.trim().length()==0 || selectedAssign.equalsIgnoreCase("Default_0"))
{
setErrorMessage(getResourceBundleString(NO_ASSGN));
return null;
}
if(!validateGradeInput())
return null;
try
{
if(selectedAssign != null && selectedAssign.trim().length()>0)
{
if(!selectedAssign.equalsIgnoreCase("Default_0"))
{
if(gradePoint != null && gradePoint.trim().length()>0)
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String selectedAssignName = ((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel();
String gradebookUuid = ToolManager.getCurrentPlacement().getContext();
String studentUid = UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId();
gradebookService.setAssignmentScore(gradebookUuid,
selectedAssignName, studentUid, new Double(gradePoint), "");
if (gradeComment != null && gradeComment.trim().length() > 0)
{
gradebookService.setAssignmentScoreComment(gradebookUuid,
selectedAssignName, studentUid, gradeComment);
}
Message msg = selectedMessage.getMessage();
msg.setGradeAssignmentName(selectedAssignName);
msg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
forumManager.saveMessage(msg);
setSuccessMessage(getResourceBundleString(GRADE_SUCCESSFUL));
}
}
}
}
catch(Exception e)
{
LOG.error("DiscussionForumTool - processDfGradeSubmit:" + e);
e.printStackTrace();
}
gradeNotify = false;
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processCheckAll()
{
for(int i=0; i<selectedTopic.getMessages().size(); i++)
{
((DiscussionMessageBean)selectedTopic.getMessages().get(i)).setSelected(true);
}
return null;
}
private void setMessageBeanPreNextStatus()
{
if(selectedTopic != null)
{
if(selectedTopic.getMessages() != null)
{
List tempMsgs = selectedTopic.getMessages();
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean)tempMsgs.get(i);
if(i==0)
{
dmb.setHasPre(false);
if(i==(tempMsgs.size()-1))
{
dmb.setHasNext(false);
}
else
{
dmb.setHasNext(true);
}
}
else if(i==(tempMsgs.size()-1))
{
dmb.setHasPre(true);
dmb.setHasNext(false);
}
else
{
dmb.setHasNext(true);
dmb.setHasPre(true);
}
}
}
}
}
/**
* @return Returns the selectedMessageView.
*/
public String getSelectedMessageView()
{
return selectedMessageView;
}
/**
* @param selectedMessageView
* The selectedMessageView to set.
*/
public void setSelectedMessageView(String selectedMessageView)
{
this.selectedMessageView = selectedMessageView;
}
/**
* @return Returns the selectedMessageShow.
*/
public String getSelectedMessageShow()
{
return selectedMessageShow;
}
/**
* @param selectedMessageShow
* The selectedMessageShow to set.
*/
public void setSelectedMessageShow(String selectedMessageShow)
{
this.selectedMessageShow = selectedMessageShow;
}
/**
* @return Returns the selectedMessagOrganize.
*/
public String getSelectedMessageOrganize()
{
return selectedMessageOrganize;
}
/**
* @param selectedMessageOrganize
* The selectedMessageOrganize to set.
*/
public void setSelectedMessageOrganize(String selectedMessageOrganize)
{
this.selectedMessageOrganize = selectedMessageOrganize;
}
public String getThreadAnchorMessageId()
{
return threadAnchorMessageId;
}
public void setThreadAnchorMessageId(String newValue)
{
threadAnchorMessageId = newValue;
}
/**
* @return Returns the displayUnreadOnly.
*/
public boolean getDisplayUnreadOnly()
{
return displayUnreadOnly;
}
public void processActionToggleExpanded()
{
if(expanded.equals("true")){
expanded = "false";
} else {
expanded = "true";
}
}
/**
* @param vce
*/
public void processValueChangeForMessageView(ValueChangeEvent vce)
{
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
String changeView = (String) vce.getNewValue();
this.displayUnreadOnly = false;
//expandedView = false;
if (changeView == null)
{
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if (changeView.equals(ALL_MESSAGES))
{
//threaded = false;
setSelectedMessageView(ALL_MESSAGES);
DiscussionTopic topic = null;
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
return;
}
else
if (changeView.equals(UNREAD_VIEW))
{
//threaded = false;
this.displayUnreadOnly = true;
return;
}
/*
else
if (changeView.equals(EXPANDED_VIEW))
{
threaded = false;
expandedView = true;
return;
}
else
if (changeView.equals(THREADED_VIEW))
{
threaded = true;
expanded = "true";
return;
}
else
if (changeView.equals("expand"))
{
threaded = true;
expanded = "true";
return;
}
else
if (changeView.equals("collapse"))
{
threaded = true;
expanded = "false";
return;
}
*/
else
{
//threaded = false;
setErrorMessage(getResourceBundleString(VIEW_UNDER_CONSTRUCT));
return;
}
}
public void processValueChangedForMessageShow(ValueChangeEvent vce){
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
String changeShow = (String) vce.getNewValue();
if (changeShow == null){
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if (changeShow.equals(ENTIRE_MSG)){
//threaded = false;
selectedMessageShow = ENTIRE_MSG;
expandedView = true;
return;
}
else {
selectedMessageShow = SUBJECT_ONLY;
expandedView = false;
return;
}
}
public void processValueChangedForMessageOrganize(ValueChangeEvent vce){
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
//expanded="false";
String changeOrganize = (String) vce.getNewValue();
threadAnchorMessageId = null;
DiscussionTopic topic = null;
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
if (changeOrganize == null){
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if(changeOrganize.equals("thread")){
threaded = true;
orderAsc = true;
displayUnreadOnly = false;
} else if(changeOrganize.equals("date_desc")){
threaded = false;
orderAsc = false;
displayUnreadOnly = false;
} else if(changeOrganize.equals("date")){
orderAsc = true;
threaded = false;
displayUnreadOnly = false;
} else if (changeOrganize.equals("unread")){
orderAsc = true;
threaded = false;
displayUnreadOnly = true;
}
return;
}
public boolean getErrorSynch()
{
return errorSynch;
}
public void setErrorSynch(boolean errorSynch)
{
this.errorSynch = errorSynch;
}
/**
* @return
*/
public String processActionSearch()
{
LOG.debug("processActionSearch()");
// //TODO : should be fetched via a query in db
// //Subject, Authored By, Date,
// isDisplaySearchedMessages=true;
//
// if(searchText==null || searchText.trim().length()<1)
// {
// setErrorMessage("Invalid search criteria");
// return ALL_MESSAGES;
// }
// if(selectedTopic == null)
// {
// setErrorMessage("There is no topic selected for search");
// return ALL_MESSAGES;
// }
// searchResults=new DiscussionTopicBean(selectedTopic.getTopic(),selectedForum.getForum() ,uiPermissionsManager);
// if(selectedTopic.getMessages()!=null)
// {
// Iterator iter = selectedTopic.getMessages().iterator();
//
// while (iter.hasNext())
// {
// DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
// if((decoMessage.getMessage()!= null && (decoMessage.getMessage().getTitle().matches(".*"+searchText+".*") ||
// decoMessage.getMessage().getCreatedBy().matches(".*"+searchText+".*") ||
// decoMessage.getMessage().getCreated().toString().matches(".*"+searchText+".*") )))
// {
// searchResults.addMessage(decoMessage);
// }
// }
// }
return ALL_MESSAGES;
}
/**
* @return
*/
public String processActionMarkAllAsRead()
{
return markAllMessages(true);
}
/**
* @return
*/
public String processActionMarkAllThreadAsRead()
{
return markAllThreadAsRead(true);
}
/**
* @return
*/
public String processActionMarkCheckedAsRead()
{
return markCheckedMessages(true);
}
/**
* @return
*/
public String processActionMarkCheckedAsUnread()
{
return markCheckedMessages(false);
}
private String markCheckedMessages(boolean readStatus)
{
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
List messages = selectedTopic.getMessages();
if (messages == null || messages.size() < 1)
{
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = messages.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
if (decoMessage.isSelected())
{
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
}
return displayTopicById(TOPIC_ID); // reconstruct topic again;
}
private String markAllMessages(boolean readStatus)
{
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
List messages = selectedTopic.getMessages();
if (messages == null || messages.size() < 1)
{
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = messages.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
//return displayTopicById(TOPIC_ID); // reconstruct topic again;
setSelectedForumForCurrentTopic(selectedTopic.getTopic());
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
return processActionDisplayFlatView();
}
private String markAllThreadAsRead(boolean readStatus)
{
if(selectedThreadHead == null){
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
if(selectedThread == null || selectedThread.size() < 1){
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = selectedThread.iterator();
while (iter.hasNext()){
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
return processActionGetDisplayThread();
}
/**
* @return Returns the isDisplaySearchedMessages.
*/
public boolean getIsDisplaySearchedMessages()
{
return isDisplaySearchedMessages;
}
/**
* @return Returns the searchText.
*/
public String getSearchText()
{
return searchText;
}
/**
* @param searchText
* The searchText to set.
*/
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public List getSiteMembers()
{
return getSiteMembers(true);
}
public List getSiteRoles()
{
//for group awareness
//return getSiteMembers(false);
return getSiteMembers(true);
}
public List getSiteMembers(boolean includeGroup)
{
LOG.debug("getSiteMembers()");
if(siteMembers!=null && siteMembers.size()>0)
{
return siteMembers;
}
permissions=new ArrayList();
Set membershipItems = null;
if (PERMISSION_MODE_TEMPLATE.equals(getPermissionMode())){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
membershipItems = uiPermissionsManager.getAreaItemsSet(forumManager.getDiscussionForumArea());
}
else if (PERMISSION_MODE_FORUM.equals(getPermissionMode())){
//membershipItems = selectedForum.getForum().getMembershipItemSet();
membershipItems = uiPermissionsManager.getForumItemsSet(selectedForum.getForum());
if (membershipItems == null || membershipItems.size() == 0){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
membershipItems = uiPermissionsManager.getAreaItemsSet(forumManager.getDiscussionForumArea());
}
}
else if (PERMISSION_MODE_TOPIC.equals(getPermissionMode())){
//membershipItems = selectedTopic.getTopic().getMembershipItemSet();
membershipItems = uiPermissionsManager.getTopicItemsSet(selectedTopic.getTopic());
if (membershipItems == null || membershipItems.size() == 0){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
if (selectedForum != null && selectedForum.getForum() != null){
//membershipItems = selectedForum.getForum().getMembershipItemSet();
membershipItems = uiPermissionsManager.getForumItemsSet(selectedForum.getForum());
}
}
}
siteMembers=new ArrayList();
// get Roles
AuthzGroup realm;
Site currentSite = null;
int i=0;
try
{
realm = AuthzGroupService.getAuthzGroup(getContextSiteId());
Set roles1 = realm.getRoles();
if (roles1 != null && roles1.size() > 0)
{
List rolesList = sortRoles(roles1);
Iterator roleIter = rolesList.iterator();
while (roleIter.hasNext())
{
Role role = (Role) roleIter.next();
if (role != null)
{
if(i==0)
{
selectedRole = role.getId();
i=1;
}
DBMembershipItem item = forumManager.getAreaDBMember(membershipItems, role.getId(), DBMembershipItem.TYPE_ROLE);
siteMembers.add(new SelectItem(role.getId(), role.getId() + " ("+item.getPermissionLevelName()+")"));
permissions.add(new PermissionBean(item, permissionLevelManager));
}
}
}
if(includeGroup)
{
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Collection groups = currentSite.getGroups();
groups = sortGroups(groups);
for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext();)
{
Group currentGroup = (Group) groupIterator.next();
DBMembershipItem item = forumManager.getAreaDBMember(membershipItems,currentGroup.getTitle(), DBMembershipItem.TYPE_GROUP);
siteMembers.add(new SelectItem(currentGroup.getTitle(), currentGroup.getTitle() + " ("+item.getPermissionLevel().getName()+")"));
permissions.add(new PermissionBean(item, permissionLevelManager));
}
}
}
catch (IdUnusedException e)
{
LOG.error(e.getMessage(), e);
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return siteMembers;
}
/**
* Takes roles defined and sorts them alphabetically by id
* so when displayed will be in order.
*
* @param roles
* Set of defined roles
*
* @return
* Set of defined roles sorted
*/
private List sortRoles(Set roles) {
final List rolesList = new ArrayList();
rolesList.addAll(roles);
final AuthzGroupComparator authzGroupComparator = new AuthzGroupComparator("id", true);
Collections.sort(rolesList, authzGroupComparator);
return rolesList;
}
/**
* Takes groups defined and sorts them alphabetically by title
* so will be in some order when displayed on permission widget.
*
* @param groups
* Collection of groups to be sorted
*
* @return
* Collection of groups in sorted order
*/
private Collection sortGroups(Collection groups) {
List sortGroupsList = new ArrayList();
sortGroupsList.addAll(groups);
final GroupComparator groupComparator = new GroupComparator("title", true);
Collections.sort(sortGroupsList, groupComparator);
groups.clear();
groups.addAll(sortGroupsList);
return groups;
}
/**
* @return siteId
*/
private String getContextSiteId()
{
LOG.debug("getContextSiteId()");
return ("/site/" + ToolManager.getCurrentPlacement().getContext());
}
/**
* @param topic
*/
private void setSelectedForumForCurrentTopic(DiscussionTopic topic)
{
if (selectedForum != null)
{
return;
}
DiscussionForum forum = (DiscussionForum) topic.getBaseForum();
if (forum == null)
{
String forumId = getExternalParameterByKey(FORUM_ID);
if (forumId == null || forumId.trim().length() < 1)
{
selectedForum = null;
return;
}
forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
selectedForum = null;
return;
}
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
}
/**
* @param errorMsg
*/
private void setErrorMessage(String errorMsg)
{
LOG.debug("setErrorMessage(String " + errorMsg + ")");
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, getResourceBundleString(ALERT) + errorMsg, null));
}
private void setSuccessMessage(String successMsg)
{
LOG.debug("setSuccessMessage(String " + successMsg + ")");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, successMsg, null));
}
public void processPost(){
}
public String generatePermissionScript(){
PermissionLevel ownerLevel = permissionLevelManager.getDefaultOwnerPermissionLevel();
PermissionLevel authorLevel = permissionLevelManager.getDefaultAuthorPermissionLevel();
PermissionLevel noneditingAuthorLevel = permissionLevelManager.getDefaultNoneditingAuthorPermissionLevel();
PermissionLevel reviewerLevel = permissionLevelManager.getDefaultReviewerPermissionLevel();
PermissionLevel noneLevel = permissionLevelManager.getDefaultNonePermissionLevel();
PermissionLevel contributorLevel = permissionLevelManager.getDefaultContributorPermissionLevel();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("<script type=\"text/javascript\">\n");
sBuffer.append("var ownerLevelArray = " + ownerLevel + ";\n");
sBuffer.append("var authorLevelArray = " + authorLevel + ";\n");
sBuffer.append("var noneditingAuthorLevelArray = " + noneditingAuthorLevel + ";\n");
sBuffer.append("var reviewerLevelArray = " + reviewerLevel + ";\n");
sBuffer.append("var noneLevelArray = " + noneLevel + ";\n");
sBuffer.append("var contributorLevelArray = " + contributorLevel + ";\n");
sBuffer.append("var owner = 'Owner';\n");
sBuffer.append("var author = 'Author';\n");
sBuffer.append("var nonEditingAuthor = 'Nonediting Author';\n");
sBuffer.append("var reviewer = 'Reviewer';\n");
sBuffer.append("var none = 'None';\n");
sBuffer.append("var contributor = 'Contributor';\n");
sBuffer.append("var custom = 'Custom';\n");
sBuffer.append("var all = 'All';\n");
sBuffer.append("var own = 'Own';\n");
sBuffer.append("function checkLevel(selectedLevel){\n" +
" var ownerVal = true;\n" +
" var authorVal = true;\n" +
" var noneditingAuthorVal = true;\n" +
" var reviewerVal = true;\n" +
" var noneVal = true;\n" +
" var contributorVal = true;\n\n" +
" for (var i = 0; i < selectedLevel.length; i++){\n" +
" if (ownerVal && ownerLevelArray[i] != selectedLevel[i])\n" +
" ownerVal = false;\n" +
" if (authorVal && authorLevelArray[i] != selectedLevel[i])\n" +
" authorVal = false;\n" +
" if (noneditingAuthorVal && noneditingAuthorLevelArray[i] != selectedLevel[i])\n" +
" noneditingAuthorVal = false;\n" +
" if (reviewerVal && reviewerLevelArray[i] != selectedLevel[i])\n" +
" reviewerVal = false;\n" +
" if (noneVal && noneLevelArray[i] != selectedLevel[i])\n" +
" noneVal = false;\n" +
" if (contributorVal && contributorLevelArray[i] != selectedLevel[i])\n" +
" contributorVal = false;\n" +
" }\n\n" +
" if (ownerVal)\n" +
" return 'Owner';\n" +
" else if (authorVal)\n" +
" return 'Author';\n" +
" else if (noneditingAuthorVal)\n" +
" return 'Nonediting Author';\n" +
" else if (reviewerVal)\n" +
" return 'Reviewer';\n" +
" else if (noneVal)\n" +
" return 'None';\n" +
" else if (contributorVal)\n" +
" return 'Contributor';\n" +
" else return 'Custom';\n" +
"}\n"
);
sBuffer.append("</script>");
return sBuffer.toString();
}
public void setObjectPermissions(Object target){
Set membershipItemSet = null;
Set oldMembershipItemSet = null;
DiscussionForum forum = null;
Area area = null;
//Topic topic = null;
DiscussionTopic topic = null;
/** get membership item set */
if (target instanceof DiscussionForum){
forum = ((DiscussionForum) target);
//membershipItemSet = forum.getMembershipItemSet();
//membershipItemSet = uiPermissionsManager.getForumItemsSet(forum);
oldMembershipItemSet = uiPermissionsManager.getForumItemsSet(forum);
}
else if (target instanceof Area){
area = ((Area) target);
//membershipItemSet = area.getMembershipItemSet();
//membershipItemSet = uiPermissionsManager.getAreaItemsSet();
oldMembershipItemSet = uiPermissionsManager.getAreaItemsSet(area);
}
else if (target instanceof Topic){
//topic = ((Topic) target);
//membershipItemSet = topic.getMembershipItemSet();
topic = ((DiscussionTopic) target);
//membershipItemSet = uiPermissionsManager.getTopicItemsSet(topic);
oldMembershipItemSet = uiPermissionsManager.getTopicItemsSet(topic);
}
if (membershipItemSet != null){
membershipItemSet.clear();
}
else{
membershipItemSet = new HashSet();
}
if(permissions!=null ){
Iterator iter = permissions.iterator();
while (iter.hasNext())
{
PermissionBean permBean = (PermissionBean) iter.next();
//for group awareness
//DBMembershipItem membershipItem = permissionLevelManager.createDBMembershipItem(permBean.getItem().getName(), permBean.getSelectedLevel(), DBMembershipItem.TYPE_ROLE);
DBMembershipItem membershipItem = permissionLevelManager.createDBMembershipItem(permBean.getItem().getName(), permBean.getSelectedLevel(), permBean.getItem().getType());
if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM.equals(membershipItem.getPermissionLevelName())){
PermissionsMask mask = new PermissionsMask();
mask.put(PermissionLevel.NEW_FORUM, new Boolean(permBean.getNewForum()));
mask.put(PermissionLevel.NEW_TOPIC, new Boolean(permBean.getNewTopic()));
mask.put(PermissionLevel.NEW_RESPONSE, new Boolean(permBean.getNewResponse()));
mask.put(PermissionLevel.NEW_RESPONSE_TO_RESPONSE, new Boolean(permBean.getResponseToResponse()));
mask.put(PermissionLevel.MOVE_POSTING, new Boolean(permBean.getMovePosting()));
mask.put(PermissionLevel.CHANGE_SETTINGS,new Boolean(permBean.getChangeSettings()));
mask.put(PermissionLevel.POST_TO_GRADEBOOK, new Boolean(permBean.getPostToGradebook()));
mask.put(PermissionLevel.READ, new Boolean(permBean.getRead()));
mask.put(PermissionLevel.MARK_AS_READ,new Boolean(permBean.getMarkAsRead()));
mask.put(PermissionLevel.MODERATE_POSTINGS, new Boolean(permBean.getModeratePostings()));
mask.put(PermissionLevel.DELETE_OWN, new Boolean(permBean.getDeleteOwn()));
mask.put(PermissionLevel.DELETE_ANY, new Boolean(permBean.getDeleteAny()));
mask.put(PermissionLevel.REVISE_OWN, new Boolean(permBean.getReviseOwn()));
mask.put(PermissionLevel.REVISE_ANY, new Boolean(permBean.getReviseAny()));
PermissionLevel level = permissionLevelManager.createPermissionLevel(permBean.getSelectedLevel(), typeManager.getCustomLevelType(), mask);
membershipItem.setPermissionLevel(level);
}
// save DBMembershiptItem here to get an id so we can add to the set
permissionLevelManager.saveDBMembershipItem(membershipItem);
membershipItemSet.add(membershipItem);
}
if( ((area != null && area.getId() != null) ||
(forum != null && forum.getId() != null) ||
(topic != null && topic.getId() != null))
&& oldMembershipItemSet != null)
permissionLevelManager.deleteMembershipItems(oldMembershipItemSet);
if (target instanceof DiscussionForum){
forum.setMembershipItemSet(membershipItemSet);
//forumManager.saveForum(forum);
}
else if (area != null){
area.setMembershipItemSet(membershipItemSet);
//areaManager.saveArea(area);
}
else if (topic != null){
topic.setMembershipItemSet(membershipItemSet);
//forumManager.saveTopic((DiscussionTopic) topic);
}
}
siteMembers = null;
}
/**
* processActionAddGroupsUsers
* @return navigation String
*/
public String processActionAddGroupsUsers(){
totalGroupsUsersList = null;
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
String attr = null;
if (session != null){
/** get navigation string of previous navigation (set by navigation handler) */
attr = (String) session.getAttribute("MC_PREVIOUS_NAV");
}
/** store caller navigation string in session (used to return from add groups/users) */
session.setAttribute("MC_ADD_GROUPS_USERS_CALLER", attr);
return "addGroupsUsers";
}
/**
* processAddGroupsUsersSubmit
* @return navigation String
*/
public String processAddGroupsUsersSubmit(){
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
/** get navigation string of previous navigation (set by navigation handler) */
return (String) session.getAttribute("MC_ADD_GROUPS_USERS_CALLER");
}
/**
* processAddGroupsUsersCancel
* @return navigation String
*/
public String processAddGroupsUsersCancel(){
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
/** get navigation string of previous navigation (set by navigation handler) */
return (String) session.getAttribute("MC_ADD_GROUPS_USERS_CALLER");
}
public List getTotalGroupsUsersList()
{
/** protect from jsf calling multiple times */
if (totalGroupsUsersList != null){
return totalGroupsUsersList;
}
courseMemberMap = membershipManager.getAllCourseMembers(true, false, false);
List members = membershipManager.convertMemberMapToList(courseMemberMap);
totalGroupsUsersList = new ArrayList();
/** create a list of SelectItem elements */
for (Iterator i = members.iterator(); i.hasNext();){
MembershipItem item = (MembershipItem) i.next();
totalGroupsUsersList.add(
new SelectItem(item.getId(), item.getName()));
}
return totalGroupsUsersList;
}
public void setPermissionLevelManager(
PermissionLevelManager permissionLevelManager) {
this.permissionLevelManager = permissionLevelManager;
}
public List getPostingOptions()
{
List postingOptions = new ArrayList();
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.NONE),
PermissionBean.getResourceBundleString(PermissionBean.NONE)));
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.OWN),
PermissionBean.getResourceBundleString(PermissionBean.OWN)));
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.ALL),
PermissionBean.getResourceBundleString(PermissionBean.ALL)));
return postingOptions;
}
/**
* @return Returns the levels.
*/
public List getLevels()
{
boolean hasCustom = false;
if (levels == null || levels.size() == 0)
{
levels = new ArrayList();
List origLevels = permissionLevelManager.getOrderedPermissionLevelNames();
if (origLevels != null)
{
Iterator iter = origLevels.iterator();
while (iter.hasNext())
{
String level = (String) iter.next();
levels.add(new SelectItem(level));
if(level.equals("Custom"))
{
hasCustom =true;
}
}
}
if(!hasCustom)
{
levels.add(new SelectItem("Custom"));
}
}
return levels;
}
/**
* @param areaManager The areaManager to set.
*/
public void setAreaManager(AreaManager areaManager)
{
this.areaManager = areaManager;
}
/**
* @return Returns the selectedRole.
*/
public String getSelectedRole()
{
return selectedRole;
}
/**
* @param selectedRole The selectedRole to set.
*/
public void setSelectedRole(String selectedRole)
{
this.selectedRole = selectedRole;
}
public boolean getEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
public String getPermissionMode() {
return permissionMode;
}
public void setPermissionMode(String permissionMode) {
this.permissionMode = permissionMode;
}
public List getSelectedGroupsUsersList() {
return selectedGroupsUsersList;
}
public void setSelectedGroupsUsersList(List selectedGroupsUsersList) {
this.selectedGroupsUsersList = selectedGroupsUsersList;
}
public void setTotalGroupsUsersList(List totalGroupsUsersList) {
this.totalGroupsUsersList = totalGroupsUsersList;
}
/**
* Pulls messages from bundle
*
* @param key
* Key of message to get
*
* @return
* String for key passed in or [missing: key] if not found
*/
public static String getResourceBundleString(String key)
{
final ResourceBundle rb = ResourceBundle.getBundle(MESSAGECENTER_BUNDLE);
return rb.getString(key);
}
public boolean getGradebookExist()
{
try
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
gradebookExist = gradebookService.isGradebookDefined(ToolManager.getCurrentPlacement().getContext());
return gradebookExist;
}
catch(Exception e)
{
gradebookExist = false;
return gradebookExist;
}
}
public void setGradebookExist(boolean gradebookExist)
{
this.gradebookExist = gradebookExist;
}
public String getUserNameOrEid()
{
try
{
String currentUserId = getUserId();
if(!"false".equalsIgnoreCase(ServerConfigurationService.getString
("[email protected]")))
{
String userString = "";
String userLastName = UserDirectoryService.getUser(currentUserId).getLastName();
String userFirstName = UserDirectoryService.getUser(currentUserId).getFirstName();
if((userLastName != null && userLastName.length() > 0) ||
(userFirstName != null && userFirstName.length() > 0))
{
userString += userLastName + ", ";
userString += userFirstName;
return userString;
}
else
{
return UserDirectoryService.getUserEid(currentUserId);
}
}
else
{
String userString = "";
String userLastName = UserDirectoryService.getUser(currentUserId).getLastName();
String userFirstName = UserDirectoryService.getUser(currentUserId).getFirstName();
if((userLastName != null && userLastName.length() > 0) ||
(userFirstName != null && userFirstName.length() > 0))
{
userString += userLastName + ", ";
userString += userFirstName;
return userString;
}
else
{
return UserDirectoryService.getUserEid(currentUserId);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return getUserId();
}
public boolean isDisableLongDesc()
{
return disableLongDesc;
}
/**
* Determines current level (template, forum, or topic) and
* returns boolean indicating whether moderating is enabled or not.
* @return
*/
public boolean isDisableModeratePerm()
{
if (permissionMode == null)
return true;
else if (permissionMode.equals(PERMISSION_MODE_TEMPLATE) && template != null)
return !template.isAreaModerated();
else if (permissionMode.equals(PERMISSION_MODE_FORUM) && selectedForum != null)
return !selectedForum.isForumModerated();
else if (permissionMode.equals(PERMISSION_MODE_TOPIC) && selectedTopic != null)
return !selectedTopic.isTopicModerated();
else
return true;
}
public List getMessages() {
List messages = new ArrayList();
//if(displayUnreadOnly)
// messages = selectedTopic.getUnreadMessages();
//else
messages = selectedTopic.getMessages();
if (messages != null && !messages.isEmpty())
messages = filterModeratedMessages(messages, selectedTopic.getTopic(), selectedForum.getForum());
return messages;
}
/**
* Given a list of messages, will return all messages that meet at
* least one of the following criteria:
* 1) message is approved
* 2) message was written by current user
* 3) current user has moderator perm
*/
private List filterModeratedMessages(List messages, DiscussionTopic topic, DiscussionForum forum)
{
List viewableMsgs = new ArrayList();
if (messages != null || messages.size() > 0)
{
boolean hasModeratePerm = uiPermissionsManager.isModeratePostings(topic, forum);
if (hasModeratePerm)
return messages;
Iterator msgIter = messages.iterator();
while (msgIter.hasNext())
{
DiscussionMessageBean msg = (DiscussionMessageBean) msgIter.next();
if (msg.isMsgApproved() || msg.getIsOwn())
viewableMsgs.add(msg);
}
}
return viewableMsgs;
}
public String getModeratorComments()
{
return moderatorComments;
}
public void setModeratorComments(String moderatorComments)
{
this.moderatorComments = moderatorComments;
}
public UIData getForumTable(){
return forumTable;
}
public void setForumTable(UIData forumTable){
this.forumTable=forumTable;
}
public String processReturnToOriginatingPage()
{
LOG.debug("processReturnToOriginatingPage()");
if(fromPage != null)
{
String returnToPage = fromPage;
fromPage = "";
if(returnToPage.equals(ALL_MESSAGES) && selectedTopic != null)
{
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
return ALL_MESSAGES;
}
if(returnToPage.equals(FORUM_DETAILS) && selectedForum != null)
{
selectedForum = getDecoratedForum(selectedForum.getForum());
return FORUM_DETAILS;
}
}
return processActionHome();
}
private void setFromMainOrForumOrTopic()
{
String originatingPage = getExternalParameterByKey(FROM_PAGE);
if(originatingPage != null && (originatingPage.equals(MAIN) || originatingPage.equals(ALL_MESSAGES) || originatingPage.equals(FORUM_DETAILS)
|| originatingPage.equals(THREAD_VIEW) || originatingPage.equals(FLAT_VIEW)))
{
fromPage = originatingPage;
}
}
/**
* @return TRUE if within Messages & Forums tool, FALSE otherwise
*/
public boolean isMessagesandForums() {
return messageManager.currentToolMatch(MESSAGECENTER_TOOL_ID);
}
/**
* @return TRUE if within Forums tool, FALSE otherwise
*/
public boolean isForumsTool() {
return messageManager.currentToolMatch(FORUMS_TOOL_ID);
}
private String gotoMain() {
if (isForumsTool()) {
return FORUMS_MAIN;
}
else {
return MAIN;
}
}
/**
* @return TRUE if Messages & Forums (Message Center) exists in this site,
* FALSE otherwise
*/
private boolean isMessageForumsPageInSite(String siteId) {
return messageManager.isToolInSite(siteId, MESSAGECENTER_TOOL_ID);
}
/**
* @return TRUE if Messages & Forums (Message Center) exists in this site,
* FALSE otherwise
*/
private boolean isForumsPageInSite(String siteId) {
return messageManager.isToolInSite(siteId, FORUMS_TOOL_ID);
}
public String getPrintFriendlyUrl()
{
return ServerConfigurationService.getToolUrl() + Entity.SEPARATOR
+ ToolManager.getCurrentPlacement().getId() + Entity.SEPARATOR + "discussionForum"
+ Entity.SEPARATOR + "message" + Entity.SEPARATOR
+ "printFriendly";
}
public String getPrintFriendlyUrlThread()
{
return ServerConfigurationService.getToolUrl() + Entity.SEPARATOR
+ ToolManager.getCurrentPlacement().getId() + Entity.SEPARATOR + "discussionForum"
+ Entity.SEPARATOR + "message" + Entity.SEPARATOR
+ "printFriendlyThread";
}
public Boolean isMessageReadForUser(Long topicId, Long messageId)
{
return messageManager.isMessageReadForUser(topicId, messageId);
}
public void markMessageReadForUser(Long topicId, Long messageId, Boolean read)
{
messageManager.markMessageReadForUser(topicId, messageId, read);
if(selectedThreadHead != null){
//reset the thread to show unread
processActionGetDisplayThread();
}
//also go ahead and reset the the topic
DiscussionTopic topic = forumManager.getTopicById(new Long(topicId));
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
setTopicBeanAssign();
getSelectedTopic();
}
} | msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java $
* $Id: DiscussionForumTool.java 9227 2006-05-15 15:02:42Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.tool.messageforums;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIData;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.Area;
import org.sakaiproject.api.app.messageforums.AreaManager;
import org.sakaiproject.api.app.messageforums.Attachment;
import org.sakaiproject.api.app.messageforums.DBMembershipItem;
import org.sakaiproject.api.app.messageforums.DiscussionForum;
import org.sakaiproject.api.app.messageforums.DiscussionTopic;
import org.sakaiproject.api.app.messageforums.MembershipManager;
import org.sakaiproject.api.app.messageforums.Message;
import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager;
import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager;
import org.sakaiproject.api.app.messageforums.OpenForum;
import org.sakaiproject.api.app.messageforums.PermissionLevel;
import org.sakaiproject.api.app.messageforums.PermissionLevelManager;
import org.sakaiproject.api.app.messageforums.PermissionsMask;
import org.sakaiproject.api.app.messageforums.PrivateMessage;
import org.sakaiproject.api.app.messageforums.Topic;
import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager;
import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager;
import org.sakaiproject.api.app.messageforums.ui.UIPermissionsManager;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.component.app.messageforums.MembershipItem;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.CommentDefinition;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.messageforums.ui.DecoratedAttachment;
import org.sakaiproject.tool.messageforums.ui.DiscussionAreaBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionForumBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionMessageBean;
import org.sakaiproject.tool.messageforums.ui.DiscussionTopicBean;
import org.sakaiproject.tool.messageforums.ui.PermissionBean;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
/**
* @author <a href="mailto:[email protected]">Rashmi Shastri</a>
* @author Chen wen
*/
public class DiscussionForumTool
{
private static final Log LOG = LogFactory.getLog(DiscussionForumTool.class);
/**
* List individual forum details
*/
private static final String MAIN = "main";
private static final String FORUMS_MAIN = "forumsMain";
private static final String TEMPLATE_SETTING = "dfTemplateSettings";
private static final String TEMPLATE_ORGANIZE = "dfTemplateOrganize";
private static final String FORUM_DETAILS = "dfForumDetail";
private static final String FORUM_SETTING = "dfForumSettings";
private static final String FORUM_SETTING_REVISE = "dfReviseForumSettings";
private static final String TOPIC_SETTING = "dfTopicSettings";
private static final String TOPIC_SETTING_REVISE = "dfReviseTopicSettings";
private static final String MESSAGE_COMPOSE = "dfCompose";
private static final String MESSAGE_VIEW = "dfViewMessage";
private static final String THREAD_VIEW = "dfViewThread";
private static final String ALL_MESSAGES = "dfAllMessages";
private static final String SUBJECT_ONLY = "dfSubjectOnly";
private static final String ENTIRE_MSG = "dfEntireMsg";
private static final String EXPANDED_VIEW = "dfExpandAllView";
private static final String THREADED_VIEW = "dfThreadedView";
private static final String FLAT_VIEW = "dfFlatView";
private static final String UNREAD_VIEW = "dfUnreadView";
private static final String GRADE_MESSAGE = "dfMsgGrade";
private static final String FORUM_STATISTICS = "dfStatisticsList";
private static final String FORUM_STATISTICS_USER = "dfStatisticsUser";
private static final String ADD_COMMENT = "dfMsgAddComment";
private static final String PENDING_MSG_QUEUE = "dfPendingMessages";
private static final String PERMISSION_MODE_TEMPLATE = "template";
private static final String PERMISSION_MODE_FORUM = "forum";
private static final String PERMISSION_MODE_TOPIC = "topic";
private DiscussionForumBean selectedForum;
private DiscussionTopicBean selectedTopic;
private DiscussionTopicBean searchResults;
private DiscussionMessageBean selectedMessage;
private DiscussionAreaBean template;
private DiscussionMessageBean selectedThreadHead;
private List selectedThread = new ArrayList();
private UIData forumTable;
private List groupsUsersList;
private List totalGroupsUsersList;
private List selectedGroupsUsersList;
private Map courseMemberMap;
private List permissions;
private List levels;
private AreaManager areaManager;
private int numPendingMessages = 0;
private boolean refreshPendingMsgs = true;
private static final String TOPIC_ID = "topicId";
private static final String FORUM_ID = "forumId";
private static final String MESSAGE_ID = "messageId";
private static final String REDIRECT_PROCESS_ACTION = "redirectToProcessAction";
private static final String MESSAGECENTER_TOOL_ID = "sakai.messagecenter";
private static final String FORUMS_TOOL_ID = "sakai.forums";
private static final String MESSAGECENTER_BUNDLE = "org.sakaiproject.api.app.messagecenter.bundle.Messages";
private static final String INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS = "cdfm_insufficient_privileges";
private static final String INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE = "cdfm_insufficient_privileges";
private static final String INSUFFICIENT_PRIVILEAGES_TO="cdfm_insufficient_privileages_to";
private static final String INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM="cdfm_insufficient_privileges_change_forum";
private static final String INSUFFICIENT_PRIVILEGES_NEW_TOPIC = "cdfm_insufficient_privileges_new_topic";
private static final String INSUFFICIENT_PRIVILEGES_CREATE_TOPIC="cdfm_insufficient_privileges_create_topic";
private static final String USER_NOT_ALLOWED_CREATE_FORUM="cdfm_user_not_allowed_create_forum";
private static final String INSUFFICIENT_PRIVILEGES_TO_DELETE_FORUM="cdfm_insufficient_privileges_delete_forum";
private static final String SHORT_DESC_TOO_LONG = "cdfm_short_desc_too_long";
private static final String LAST_REVISE_BY = "cdfm_last_revise_msg";
private static final String LAST_REVISE_ON = "cdfm_last_revise_msg_on";
private static final String VALID_FORUM_TITLE_WARN = "cdfm_valid_forum_title_warn";
private static final String VALID_TOPIC_TITLE_WARN = "cdfm_valid_topic_title_warn";
private static final String INVALID_SELECTED_FORUM ="cdfm_invalid_selected_forum";
private static final String FORUM_NOT_FOUND = "cdfm_forum_not_found";
private static final String SELECTED_FORUM_NOT_FOUND = "cdfm_selected_forum_not_found";
private static final String FAILED_NEW_TOPIC ="cdfm_failed_new_topic";
private static final String TOPIC_WITH_ID = "cdfm_topic_with_id";
private static final String MESSAGE_WITH_ID = "cdfm_message_with_id";
private static final String NOT_FOUND_WITH_QUOTE = "cdfm_not_found_quote";
private static final String PARENT_FORUM_NOT_FOUND = "cdfm_parent_forum_not_found";
private static final String NOT_FOUND_REDIRECT_PAGE = "cdfm_not_found_redirect_page";
private static final String MESSAGE_REFERENCE_NOT_FOUND = "cdfm_message_reference_not_found";
private static final String TOPC_REFERENCE_NOT_FOUND = "cdfm_topic_reference_not_found";
private static final String UNABLE_RETRIEVE_TOPIC = "cdfm_unable_retrieve_topic";
private static final String PARENT_TOPIC_NOT_FOUND = "cdfm_parent_topic_not_found";
private static final String FAILED_CREATE_TOPIC = "cdfm_failed_create_topic";
private static final String FAILED_REND_MESSAGE = "cdfm_failed_rend_message";
private static final String VIEW_UNDER_CONSTRUCT = "cdfm_view_under_construct";
private static final String LOST_ASSOCIATE = "cdfm_lost_association";
private static final String NO_MARKED_READ_MESSAGE = "cdfm_no_message_mark_read";
private static final String GRADE_SUCCESSFUL = "cdfm_grade_successful";
private static final String GRADE_GREATER_ZERO = "cdfm_grade_greater_than_zero";
private static final String GRADE_DECIMAL_WARN = "cdfm_grade_decimal_warn";
private static final String ALERT = "cdfm_alert";
private static final String SELECT_ASSIGN = "cdfm_select_assign";
private static final String INVALID_COMMENT = "cdfm_add_comment_invalid";
private static final String INSUFFICIENT_PRIVILEGES_TO_ADD_COMMENT = "cdfm_insufficient_privileges_add_comment";
private static final String MOD_COMMENT_TEXT = "cdfm_moderator_comment_text";
private static final String NO_MSG_SEL_FOR_APPROVAL = "cdfm_no_message_mark_approved";
private static final String MSGS_APPROVED = "cdfm_approve_msgs_success";
private static final String MSGS_DENIED = "cdfm_deny_msgs_success";
private static final String MSG_REPLY_PREFIX = "cdfm_reply_prefix";
private static final String NO_GRADE_PTS = "cdfm_no_points_for_grade";
private static final String NO_ASSGN = "cdfm_no_assign_for_grade";
private static final String FROM_PAGE = "msgForum:mainOrForumOrTopic";
private String fromPage = null; // keep track of originating page for common functions
private List forums = new ArrayList();
private List pendingMsgs = new ArrayList();
// compose
private MessageForumsMessageManager messageManager;
private String composeTitle;
private String composeBody;
private String composeLabel;
private String searchText = "";
private String selectedMessageView = ALL_MESSAGES;
private String selectedMessageShow = SUBJECT_ONLY;
private String selectedMessageOrganize = "thread";
private String threadAnchorMessageId = null;
private boolean deleteMsg;
private boolean displayUnreadOnly;
private boolean errorSynch = false;
// attachment
private ArrayList attachments = new ArrayList();
private ArrayList prepareRemoveAttach = new ArrayList();
// private boolean attachCaneled = false;
// private ArrayList oldAttachments = new ArrayList();
// private List allAttachments = new ArrayList();
private boolean threaded = true;
private boolean expandedView = false;
private String expanded = "false";
private boolean orderAsc = true;
private boolean disableLongDesc = false;
private boolean isDisplaySearchedMessages;
private List siteMembers = new ArrayList();
private String selectedRole;
private String moderatorComments;
private boolean editMode = true;
private String permissionMode;
//grading
private boolean gradeNotify = false;
private List assignments = new ArrayList();
private String selectedAssign = "Default_0";
private String gradePoint = "";
private String gradeComment;
private boolean gradebookExist = false;
private boolean displayDeniedMsg = false;
/**
* Dependency Injected
*/
private DiscussionForumManager forumManager;
private UIPermissionsManager uiPermissionsManager;
private MessageForumsTypeManager typeManager;
private MembershipManager membershipManager;
private PermissionLevelManager permissionLevelManager;
/**
*
*/
public DiscussionForumTool()
{
LOG.debug("DiscussionForumTool()");
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.threadedview")))
{
threaded = true;
selectedMessageView = THREADED_VIEW;
}
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.disableLongDesc")))
{
disableLongDesc = true;
}
}
/**
* @param forumManager
*/
public void setForumManager(DiscussionForumManager forumManager)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setForumManager(DiscussionForumManager " + forumManager + ")");
}
this.forumManager = forumManager;
}
/**
* @param uiPermissionsManager
* The uiPermissionsManager to set.
*/
public void setUiPermissionsManager(UIPermissionsManager uiPermissionsManager)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setUiPermissionsManager(UIPermissionsManager "
+ uiPermissionsManager + ")");
}
this.uiPermissionsManager = uiPermissionsManager;
}
/**
* @param typeManager The typeManager to set.
*/
public void setTypeManager(MessageForumsTypeManager typeManager)
{
this.typeManager = typeManager;
}
/**
* @param membershipManager The membershipManager to set.
*/
public void setMembershipManager(MembershipManager membershipManager)
{
this.membershipManager = membershipManager;
}
/**
* @return
*/
public String processActionHome()
{
LOG.debug("processActionHome()");
reset();
return gotoMain();
}
/**
* @return
*/
public boolean isInstructor()
{
LOG.debug("isInstructor()");
return forumManager.isInstructor();
}
/**
* @return List of SelectItem
*/
public List getForumSelectItems()
{
List f = getForums();
int num = (f == null) ? 0 : f.size();
List retSort = new ArrayList();
for(int i = 1; i <= num; i++) {
Integer index = new Integer(i);
retSort.add(new SelectItem(index, index.toString()));
}
return retSort;
}
/**
* @return List of DiscussionForumBean
*/
public List getForums()
{
LOG.debug("getForums()");
if (forums == null || forums.size() < 1)
{
try
{
assignments = new ArrayList();
SelectItem item = new SelectItem("Default_0", getResourceBundleString(SELECT_ASSIGN));
assignments.add(item);
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
if(getGradebookExist())
{
List gradeAssignmentsBeforeFilter = gradebookService.getAssignments(ToolManager.getCurrentPlacement().getContext());
List gradeAssignments = new ArrayList();
for(int i=0; i<gradeAssignmentsBeforeFilter.size(); i++)
{
Assignment thisAssign = (Assignment) gradeAssignmentsBeforeFilter.get(i);
if(!thisAssign.isExternallyMaintained())
{
gradeAssignments.add(thisAssign);
}
}
for(int i=0; i<gradeAssignments.size(); i++)
{
try
{
Assignment thisAssign = (Assignment) gradeAssignments.get(i);
String assignName = thisAssign.getName();
item = new SelectItem((new Integer(i+1)).toString(), assignName);
assignments.add(item);
}
catch(Exception e)
{
LOG.error("DiscussionForumTool - processDfMsgGrd:" + e);
e.printStackTrace();
}
}
}
}
catch(SecurityException se)
{
// ignore - don't want to print out stacktrace every time a non-admin user uses MC
}
catch(Exception e1)
{
LOG.error("DiscussionForumTool&processDfMsgGrad:" + e1);
e1.printStackTrace();
}
forums = new ArrayList();
//List tempForum = forumManager.getDiscussionForums();
List tempForum = forumManager.getDiscussionForumsWithTopics();
if (tempForum == null)
{
return null;
}
Iterator iterForum = tempForum.iterator();
Map unreadMap = new HashMap();
List msgIds = new ArrayList();
while (iterForum.hasNext())
{
DiscussionForum forum = (DiscussionForum) iterForum.next();
if(forum != null)
{
List topicList = forum.getTopics();
if(topicList != null)
{
for(int i=0; i<topicList.size(); i++)
{
Topic thisTopic = (Topic) topicList.get(i);
if(thisTopic != null)
{
List msgList = thisTopic.getMessages();
if(msgList != null)
{
for(int j=0; j<msgList.size(); j++)
{
Message tempMsg = (Message)msgList.get(j);
if(tempMsg != null && !tempMsg.getDraft().booleanValue())
{
msgIds.add(tempMsg.getId());
}
}
}
}
}
}
}
}
unreadMap = forumManager.getReadStatusForMessagesWithId(msgIds, getUserId());
iterForum = tempForum.iterator();
while (iterForum.hasNext())
{
DiscussionForum forum = (DiscussionForum) iterForum.next();
if (forum == null)
{
return forums;
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return forums;
}
// TODO: put this logic in database layer
if (forum.getDraft().equals(Boolean.FALSE)||(forum.getDraft().equals(Boolean.TRUE)&& forum.getCreatedBy().equals(SessionManager.getCurrentSessionUserId())
)||SecurityService.isSuperUser()
||isInstructor()
||forum.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
//DiscussionForumBean decoForum = getDecoratedForum(forum);
DiscussionForumBean decoForum = getDecoratedForumWithPersistentForumAndTopics(forum, unreadMap);
decoForum.setGradeAssign("Default_0");
for(int i=0; i<assignments.size(); i++)
{
if(((String)((SelectItem)assignments.get(i)).getLabel()).equals(forum.getDefaultAssignName()))
{
decoForum.setGradeAssign(new Integer(i).toString());
break;
}
}
forums.add(decoForum);
}
}
}
return forums;
}
/**
* @return Returns the selectedForum.
*/
public DiscussionForumBean getSelectedForum()
{
LOG.debug("getSelectedForum()");
return selectedForum;
}
/**
* @return
*/
public String processActionOrganize()
{
LOG.debug("processActionOrganize()");
return MAIN;
}
/**
* @return
*/
public String processActionStatistics()
{
LOG.debug("processActionStatistics()");
return FORUM_STATISTICS;
}
/**
* @return
*/
public String processActionTemplateSettings()
{
LOG.debug("processActionTemplateSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
template = new DiscussionAreaBean(areaManager.getDiscusionArea());
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
return TEMPLATE_SETTING;
}
/**
* @return
*/
public String processActionTemplateOrganize()
{
LOG.debug("processActionTemplateOrganize()");
setEditMode(false);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE));
return gotoMain();
}
return TEMPLATE_ORGANIZE;
}
/**
* @return
*/
public List getPermissions()
{
if (permissions == null)
{
siteMembers=null;
getSiteRoles();
}
return permissions;
}
/**
* @return
*/
public void setPermissions(List permissions)
{
this.permissions = permissions;
}
// /**
// * @return Returns the templateMessagePermissions.
// */
// public List getTemplateMessagePermissions()
// {
// if (templateMessagePermissions == null)
// {
// templateMessagePermissions = forumManager.getAreaMessagePermissions();
// }
// return templateMessagePermissions;
// }
//
// /**
// * @param templateMessagePermissions
// * The templateMessagePermissions to set.
// */
// public void setTemplateMessagePermissions(List templateMessagePermissions)
// {
// this.templateMessagePermissions = templateMessagePermissions;
// }
/*/**
* @return
*/
/*public String processActionReviseTemplateSettings()
{
if (LOG.isDebugEnabled()){
LOG.debug("processActionReviseTemplateSettings()");
}
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TEMPLATE);
return TEMPLATE_SETTING;
}*/
/**
* @return
*/
public String processActionSaveTemplateSettings()
{
LOG.debug("processActionSaveTemplateSettings()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
setObjectPermissions(template.getArea());
areaManager.saveArea(template.getArea());
return gotoMain();
}
/**
* @return
*/
public String processActionSaveTemplateOrganization()
{
LOG.debug("processActionSaveTemplateOrganization()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_ORGANIZE));
return gotoMain();
}
for(Iterator i = forums.iterator(); i.hasNext(); ) {
DiscussionForumBean forum = (DiscussionForumBean)i.next();
// because there is no straight up save forum function we need to retain the draft status
if(forum.getForum().getDraft().booleanValue())
forumManager.saveForumAsDraft(forum.getForum());
else
forumManager.saveForum(forum.getForum());
}
//reload the forums so they change position in the list
forums = null;
return gotoMain();
}
/**
* @return
*/
public String processActionRestoreDefaultTemplate()
{
LOG.debug("processActionRestoreDefaultTemplate()");
if(!isInstructor())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_EDIT_TEMPLATE_SETTINGS));
return gotoMain();
}
Area area = null;
if ((area = areaManager.getDiscusionArea()) != null){
area.setMembershipItemSet(new HashSet());
area.setModerated(Boolean.FALSE);
areaManager.saveArea(area);
permissions = null;
}
else{
throw new IllegalStateException("Could not obtain area for site: " + getContextSiteId());
}
return TEMPLATE_SETTING;
}
/**
* Check out if the user is allowed to create new forum
*
* @return
*/
public boolean getNewForum()
{
LOG.debug("getNewForum()");
return uiPermissionsManager.isNewForum();
}
/**
* Display Individual forum
*
* @return
*/
public String processActionDisplayForum()
{
LOG.debug("processDisplayForum()");
if (getDecoratedForum() == null)
{
LOG.error("Forum not found");
return gotoMain();
}
return FORUM_DETAILS;
}
/**
* Forward to delete forum confirmation screen
*
* @return
*/
public String processActionDeleteForumConfirm()
{
LOG.debug("processActionDeleteForumConfirm()");
if (selectedForum == null)
{
LOG.debug("There is no forum selected for deletion");
return gotoMain();
}
// TODO:
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_DELETE_FORUM));
return gotoMain();
}
selectedForum.setMarkForDeletion(true);
return FORUM_SETTING;
}
/**
* @return
*/
public String processActionDeleteForum()
{
if (selectedForum == null)
{
LOG.debug("There is no forum selected for deletion");
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEAGES_TO));
return gotoMain();
}
forumManager.deleteForum(selectedForum.getForum());
reset();
return gotoMain();
}
/**
* @return
*/
public String processActionNewForum()
{
LOG.debug("processActionNewForum()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
if (getNewForum())
{
DiscussionForum forum = forumManager.createForum();
forum.setModerated(areaManager.getDiscusionArea().getModerated()); // default to template setting
selectedForum = null;
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setNewForumBeanAssign();
return FORUM_SETTING_REVISE;
}
else
{
setErrorMessage(getResourceBundleString(USER_NOT_ALLOWED_CREATE_FORUM));
return gotoMain();
}
}
/**
* @return
*/
public String processActionForumSettings()
{
LOG.debug("processForumSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
String forumId = getExternalParameterByKey(FORUM_ID);
if ((forumId) == null)
{
setErrorMessage(getResourceBundleString(INVALID_SELECTED_FORUM));
return gotoMain();
}
DiscussionForum forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(forum))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
List attachList = forum.getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
setFromMainOrForumOrTopic();
return FORUM_SETTING_REVISE;
}
/**
* @return
*/
/*public String processActionReviseForumSettings()
{
LOG.debug("processActionReviseForumSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_FORUM);
if ((selectedForum) == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
List attachList = selectedForum.getForum().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setFromMainOrForumOrTopic();
return FORUM_SETTING_REVISE; //
}*/
/**
* @return
*/
public String processActionSaveForumAndAddTopic()
{
LOG.debug("processActionSaveForumAndAddTopic()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
DiscussionForum forum = saveForumSettings(false);
if(!uiPermissionsManager.isNewTopic(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CREATE_TOPIC));
return gotoMain();
}
selectedTopic = createTopic(forum.getId());
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveForumSettings()
{
LOG.debug("processActionSaveForumSettings()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
saveForumSettings(false);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
/**
* @return
*/
public String processActionSaveForumAsDraft()
{
LOG.debug("processActionSaveForumAsDraft()");
if(selectedForum !=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getShortDescription()!=null) &&
(selectedForum.getForum().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
if(!uiPermissionsManager.isChangeSettings(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CHAGNE_FORUM));
return gotoMain();
}
if(selectedForum!=null && selectedForum.getForum()!=null &&
(selectedForum.getForum().getTitle()==null
||selectedForum.getForum().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_FORUM_TITLE_WARN));
return FORUM_SETTING_REVISE;
}
saveForumSettings(true);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
private DiscussionForum saveForumSettings(boolean draft)
{
LOG.debug("saveForumSettings(boolean " + draft + ")");
if (selectedForum == null)
{
setErrorMessage(getResourceBundleString(SELECTED_FORUM_NOT_FOUND));
return null;
}
DiscussionForum forum = selectedForum.getForum();
if (forum == null)
{
setErrorMessage(getResourceBundleString(FORUM_NOT_FOUND));
return null;
}
saveForumSelectedAssignment(forum);
saveForumAttach(forum);
setObjectPermissions(forum);
if (draft)
forumManager.saveForumAsDraft(forum);
else
forumManager.saveForum(forum);
//forumManager.saveForumControlPermissions(forum, forumControlPermissions);
//forumManager.saveForumMessagePermissions(forum, forumMessagePermissions);
if (forum.getId() == null)
{
String forumUuid = forum.getUuid();
forum = null;
forum = forumManager.getForumByUuid(forumUuid);
}
return forum;
}
/**
* @return Returns the selectedTopic.
*/
public DiscussionTopicBean getSelectedTopic()
{
//if(threaded)
//{
rearrageTopicMsgsThreaded();
//}
setMessageBeanPreNextStatus();
return selectedTopic;
}
/**
* @return Returns the selected Area
*/
public DiscussionAreaBean getTemplate()
{
return template;
}
/**
* @return
*/
public String processActionNewTopic()
{
LOG.debug("processActionNewTopic()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TOPIC);
selectedTopic = createTopic();
setNewTopicBeanAssign();
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
if(!uiPermissionsManager.isNewTopic(selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_CREATE_TOPIC));
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
setFromMainOrForumOrTopic();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionReviseTopicSettings()
{
LOG.debug("processActionReviseTopicSettings()");
setPermissionMode(PERMISSION_MODE_TOPIC);
setEditMode(true);
DiscussionTopic topic = selectedTopic.getTopic();
if (topic == null)
{
topic = forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
}
if (topic == null)
{
setErrorMessage(getResourceBundleString(TOPIC_WITH_ID) + getExternalParameterByKey(TOPIC_ID)
+ getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
List attachList = selectedTopic.getTopic().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setFromMainOrForumOrTopic();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveTopicAndAddTopic()
{
LOG.debug("processActionSaveTopicAndAddTopic()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
// if the topic is not moderated (and already exists), all of the pending messages must be approved
if (selectedTopic != null && selectedTopic.getTopic() != null &&
!selectedTopic.isTopicModerated() && selectedTopic.getTopic().getId() != null)
{
forumManager.approveAllPendingMessages(selectedTopic.getTopic().getId());
}
saveTopicSettings(false);
Long forumId = selectedForum.getForum().getId();
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_FORUM_NOT_FOUND));
return gotoMain();
}
selectedTopic = null;
selectedTopic = createTopic(forumId);
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(FAILED_NEW_TOPIC));
attachments.clear();
prepareRemoveAttach.clear();
return gotoMain();
}
attachments.clear();
prepareRemoveAttach.clear();
return TOPIC_SETTING_REVISE;
}
/**
* @return
*/
public String processActionSaveTopicSettings()
{
LOG.debug("processActionSaveTopicSettings()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
// if the topic is not moderated, all of the messages must be approved
if (selectedTopic != null && selectedTopic.getTopic().getId() != null &&
!selectedTopic.isTopicModerated())
{
forumManager.approveAllPendingMessages(selectedTopic.getTopic().getId());
}
saveTopicSettings(false);
return processReturnToOriginatingPage();
//reset();
//return MAIN;
}
/**
* @return
*/
public String processActionSaveTopicAsDraft()
{
LOG.debug("processActionSaveTopicAsDraft()");
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getShortDescription()!=null) &&
(selectedTopic.getTopic().getShortDescription().length() > 255))
{
setErrorMessage(getResourceBundleString(SHORT_DESC_TOO_LONG));
return null;
}
setPermissionMode(PERMISSION_MODE_TOPIC);
if(selectedTopic!=null && selectedTopic.getTopic()!=null &&
(selectedTopic.getTopic().getTitle()==null
||selectedTopic.getTopic().getTitle().trim().length()<1 ))
{
setErrorMessage(getResourceBundleString(VALID_TOPIC_TITLE_WARN));
return TOPIC_SETTING_REVISE;
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
saveTopicSettings(true);
//reset();
//return MAIN;
return processReturnToOriginatingPage();
}
private String saveTopicSettings(boolean draft)
{
LOG.debug("saveTopicSettings(" + draft + ")");
setPermissionMode(PERMISSION_MODE_TOPIC);
if (selectedTopic != null)
{
DiscussionTopic topic = selectedTopic.getTopic();
if (selectedForum != null)
{
topic.setBaseForum(selectedForum.getForum());
saveTopicSelectedAssignment(topic);
saveTopicAttach(topic);
setObjectPermissions(topic);
if (draft)
{
forumManager.saveTopicAsDraft(topic);
}
else
{
forumManager.saveTopic(topic);
}
//forumManager
// .saveTopicControlPermissions(topic, topicControlPermissions);
//forumManager
// .saveTopicMessagePermissions(topic, topicMessagePermissions);
}
}
return gotoMain();
}
/**
* @return
*/
public String processActionDeleteTopicConfirm()
{
LOG.debug("processActionDeleteTopicConfirm()");
if (selectedTopic == null)
{
LOG.debug("There is no topic selected for deletion");
return gotoMain();
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
selectedTopic.setMarkForDeletion(true);
return TOPIC_SETTING;
}
/**
* @return
*/
public String processActionDeleteTopic()
{
LOG.debug("processActionDeleteTopic()");
if (selectedTopic == null)
{
LOG.debug("There is no topic selected for deletion");
}
if(!uiPermissionsManager.isChangeSettings(selectedTopic.getTopic(),selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
forumManager.deleteTopic(selectedTopic.getTopic());
reset();
return gotoMain();
}
/**
* @return
*/
public String processActionTopicSettings()
{
LOG.debug("processActionTopicSettings()");
setEditMode(true);
setPermissionMode(PERMISSION_MODE_TOPIC);
DiscussionTopic topic = null;
if(getExternalParameterByKey(TOPIC_ID) != ""){
topic = (DiscussionTopic) forumManager
.getTopicByIdWithAttachments(new Long(
getExternalParameterByKey(TOPIC_ID)));
} else if(selectedTopic != null) {
topic = selectedTopic.getTopic();
}
if (topic == null)
{
return gotoMain();
}
setSelectedForumForCurrentTopic(topic);
if(!uiPermissionsManager.isChangeSettings(topic,selectedForum.getForum()))
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_NEW_TOPIC));
return gotoMain();
}
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
List attachList = selectedTopic.getTopic().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment)attachList.get(i)));
}
}
setTopicBeanAssign();
setFromMainOrForumOrTopic();
//return TOPIC_SETTING;
return TOPIC_SETTING_REVISE;
}
public String processActionToggleDisplayForumExtendedDescription()
{
LOG.debug("processActionToggleDisplayForumExtendedDescription()");
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
if (redirectTo == null)
{
setErrorMessage(getResourceBundleString(NOT_FOUND_REDIRECT_PAGE));
return gotoMain();
}
if (redirectTo.equals("displayHome"))
{
displayHomeWithExtendedForumDescription();
return gotoMain();
}
if (redirectTo.equals("processActionDisplayForum"))
{
if (selectedForum.isReadFullDesciption())
{
selectedForum.setReadFullDesciption(false);
}
else
{
selectedForum.setReadFullDesciption(true);
}
return FORUM_DETAILS;
}
return gotoMain();
}
/**
* @return
*/
public String processActionToggleDisplayExtendedDescription()
{
LOG.debug("processActionToggleDisplayExtendedDescription()");
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
if (redirectTo == null)
{
setErrorMessage(getResourceBundleString(NOT_FOUND_REDIRECT_PAGE));
return gotoMain();
}
if (redirectTo.equals("displayHome"))
{
return displayHomeWithExtendedTopicDescription();
}
if (redirectTo.equals("processActionDisplayTopic"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return ALL_MESSAGES;
}
if (redirectTo.equals("processActionDisplayMessage"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return MESSAGE_VIEW;
}
if (redirectTo.equals("processActionGradeMessage"))
{
if (selectedTopic.isReadFullDesciption())
{
selectedTopic.setReadFullDesciption(false);
}
else
{
selectedTopic.setReadFullDesciption(true);
}
return GRADE_MESSAGE;
}
return gotoMain();
}
/**
* @return
*/
public String processActionDisplayTopic()
{
LOG.debug("processActionDisplayTopic()");
return displayTopicById(TOPIC_ID);
}
/**
* @return
*/
public String processActionDisplayNextTopic()
{
LOG.debug("processActionDisplayNextTopic()");
return displayTopicById("nextTopicId");
}
/**
* @return
*/
public String processActionDisplayPreviousTopic()
{
LOG.debug("processActionDisplayNextTopic()");
return displayTopicById("previousTopicId");
}
/**
* @return Returns the selectedMessage.
*/
public DiscussionMessageBean getSelectedMessage()
{
return selectedMessage;
}
/**
* @return Returns the selectedThread.
*/
public DiscussionMessageBean getSelectedThreadHead()
{
return selectedThreadHead;
}
/**
* @return Returns an array of Messages for the current selected thread
*/
public List getSelectedThread()
{
List returnArray = new ArrayList();
returnArray = selectedThread;
if(displayUnreadOnly){
ArrayList tempmes = new ArrayList();
for(int i = returnArray.size()-1; i >= 0; i--){
if(!((DiscussionMessageBean)returnArray.get(i)).isRead()){
tempmes.add(returnArray.get(i));
}
}
returnArray = tempmes;
}
if (!orderAsc){
ArrayList tempmes = new ArrayList();
for(int i = returnArray.size()-1; i >= 0; i--){
tempmes.add(returnArray.get(i));
}
return tempmes;
} else
return returnArray;
}
/**
* @return
*/
public String processActionDisplayFlatView()
{
return FLAT_VIEW;
}
/**
* @return
*/
public String processActionDisplayThreadedView()
{
return ALL_MESSAGES;
}
public String processActionGetDisplayThread()
{
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
setTopicBeanAssign();
getSelectedTopic();
List msgsList = selectedTopic.getMessages();
if (msgsList != null && !msgsList.isEmpty())
msgsList = filterModeratedMessages(msgsList, selectedTopic.getTopic(), (DiscussionForum) selectedTopic.getTopic().getBaseForum());
List orderedList = new ArrayList();
selectedThread = new ArrayList();
Boolean foundHead = false;
Boolean foundAfterHead = false;
for(int i=0; i<msgsList.size(); i++){
if(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId().equals(selectedThreadHead.getMessage().getId())){
((DiscussionMessageBean) msgsList.get(i)).setDepth(0);
selectedThread.add((DiscussionMessageBean)msgsList.get(i));
foundHead = true;
}
else if(((DiscussionMessageBean)msgsList.get(i)).getMessage().getInReplyTo() == null && foundHead && !foundAfterHead) {
selectedThreadHead.setHasNextThread(true);
selectedThreadHead.setNextThreadId(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId());
foundAfterHead = true;
}
else if (((DiscussionMessageBean)msgsList.get(i)).getMessage().getInReplyTo() == null && !foundHead) {
selectedThreadHead.setHasPreThread(true);
selectedThreadHead.setPreThreadId(((DiscussionMessageBean)msgsList.get(i)).getMessage().getId());
}
}
recursiveGetThreadedMsgs(msgsList, orderedList, selectedThreadHead);
selectedThread.addAll(orderedList);
return THREAD_VIEW;
}
/**
* @return
*/
public String processActionDisplayThread()
{
LOG.debug("processActionDisplayThread()");
threadAnchorMessageId = null;
String threadId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (threadId == "")
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == "")
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message threadMessage = messageManager.getMessageByIdWithAttachments(new Long(
threadId));
if (threadMessage == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + threadId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
//threadMessage = messageManager.getMessageByIdWithAttachments(threadMessage.getId());
selectedThreadHead = new DiscussionMessageBean(threadMessage, messageManager);
//make sure we have the thread head of depth 0
while(selectedThreadHead.getMessage().getInReplyTo() != null){
threadMessage = messageManager.getMessageByIdWithAttachments(selectedThreadHead.getMessage().getInReplyTo().getId());
selectedThreadHead = new DiscussionMessageBean(
threadMessage, messageManager);
}
DiscussionTopic topic=forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
selectedMessage = selectedThreadHead;
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
String currentForumId = getExternalParameterByKey(FORUM_ID);
if (currentForumId != null && (!currentForumId.trim().equals(""))
&& (!currentForumId.trim().equals("null")))
{
DiscussionForum forum = forumManager
.getForumById(new Long(currentForumId));
selectedForum = getDecoratedForum(forum);
setForumBeanAssign();
selectedTopic.getTopic().setBaseForum(forum);
}
selectedTopic = getDecoratedTopic(forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID))));
return processActionGetDisplayThread();
}
/**
* @return
*/
public String processActionDisplayThreadAnchor()
{
String returnString = processActionDisplayThread();
threadAnchorMessageId = getExternalParameterByKey(MESSAGE_ID);
return returnString;
}
/**
* @return
*/
public String processActionDisplayMessage()
{
LOG.debug("processActionDisplayMessage()");
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
DiscussionTopic topic=forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID)));
setSelectedForumForCurrentTopic(topic);
selectedTopic = new DiscussionTopicBean(topic, selectedForum.getForum(),
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
setTopicBeanAssign();
String currentForumId = getExternalParameterByKey(FORUM_ID);
if (currentForumId != null && (!currentForumId.trim().equals(""))
&& (!currentForumId.trim().equals("null")))
{
DiscussionForum forum = forumManager
.getForumById(new Long(currentForumId));
selectedForum = getDecoratedForum(forum);
setForumBeanAssign();
selectedTopic.getTopic().setBaseForum(forum);
}
selectedTopic = getDecoratedTopic(forumManager.getTopicById(new Long(
getExternalParameterByKey(TOPIC_ID))));
setTopicBeanAssign();
getSelectedTopic();
//get thread from message
getThreadFromMessage();
// selectedTopic= new DiscussionTopicBean(message.getTopic());
return MESSAGE_VIEW;
}
public void getThreadFromMessage()
{
Message mes = selectedMessage.getMessage();
String messageId = mes.getId().toString();
while( mes.getInReplyTo() != null) {
mes = messageManager.getMessageById(mes.getInReplyTo().getId());
}
selectedThreadHead = new DiscussionMessageBean(mes, messageManager);
List tempMsgs = selectedTopic.getMessages();
Boolean foundHead = false;
Boolean foundAfterHead = false;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId().toString().equals(messageId))
{
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
foundHead = true;
}
else if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getInReplyTo() == null && foundHead && !foundAfterHead) {
selectedThreadHead.setHasNextThread(true);
selectedThreadHead.setNextThreadId(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId());
foundAfterHead = true;
}
else if (((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getInReplyTo() == null && !foundHead) {
selectedThreadHead.setHasPreThread(true);
selectedThreadHead.setPreThreadId(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId());
}
}
}
}
public String processDisplayPreviousMsg()
{
List tempMsgs = selectedTopic.getMessages();
int currentMsgPosition = -1;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(selectedMessage.getMessage().getId().equals(thisDmb.getMessage().getId()))
{
currentMsgPosition = i;
break;
}
}
}
if(currentMsgPosition > 0)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(currentMsgPosition-1);
Message message = messageManager.getMessageByIdWithAttachments(thisDmb.getMessage().getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(),
selectedMessage.getMessage().getId(), true);
}
return null;
}
public String processDfDisplayNextMsg()
{
List tempMsgs = selectedTopic.getMessages();
int currentMsgPosition = -1;
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(selectedMessage.getMessage().getId().equals(thisDmb.getMessage().getId()))
{
currentMsgPosition = i;
break;
}
}
}
if(currentMsgPosition > -2 && currentMsgPosition < (tempMsgs.size()-1))
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(currentMsgPosition+1);
Message message = messageManager.getMessageByIdWithAttachments(thisDmb.getMessage().getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(),
selectedMessage.getMessage().getId(), true);
}
return null;
}
// **************************************** helper methods**********************************
private String getExternalParameterByKey(String parameterId)
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
Map paramMap = context.getRequestParameterMap();
return (String) paramMap.get(parameterId);
}
/**
* @param forum
* @return List of DiscussionTopicBean
*/
private DiscussionForumBean getDecoratedForum(DiscussionForum forum)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedForum(DiscussionForum" + forum + ")");
}
forum = forumManager.getForumByIdWithTopics(forum.getId());
DiscussionForumBean decoForum = new DiscussionForumBean(forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoForum.setReadFullDesciption(true);
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return decoForum;
}
Iterator iter = temp_topics.iterator();
while (iter.hasNext())
{
DiscussionTopic topic = (DiscussionTopic) iter.next();
// TODO: put this logic in database layer
if (topic.getDraft().equals(Boolean.FALSE)||
(topic.getDraft().equals(Boolean.TRUE)&&topic.getCreatedBy().equals(SessionManager.getCurrentSessionUserId()))
||isInstructor()
||SecurityService.isSuperUser()||topic.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
topic = (DiscussionTopic) forumManager.getTopicByIdWithAttachments(topic
.getId());
if (topic != null)
{
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic, forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
if (uiPermissionsManager.isModeratePostings(topic, forum))
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoForum.addTopic(decoTopic);
}
}
}
return decoForum;
}
private DiscussionForumBean getDecoratedForumWithPersistentForumAndTopics(DiscussionForum forum, Map unreadMap)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedForum(DiscussionForum" + forum + ")");
}
DiscussionForumBean decoForum = new DiscussionForumBean(forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoForum.setReadFullDesciption(true);
}
List temp_topics = forum.getTopics();
if (temp_topics == null)
{
return decoForum;
}
Iterator iter = temp_topics.iterator();
while (iter.hasNext())
{
DiscussionTopic topic = (DiscussionTopic) iter.next();
// TODO: put this logic in database layer
if (topic.getDraft().equals(Boolean.FALSE)||
(topic.getDraft().equals(Boolean.TRUE)&&topic.getCreatedBy().equals(SessionManager.getCurrentSessionUserId()))
||isInstructor()
||SecurityService.isSuperUser()||topic.getCreatedBy().equals(
SessionManager.getCurrentSessionUserId()))
{
if (topic != null)
{
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic, forum,
uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
/*int totalMsgNumber = 0;
int readMsgNumber = 0;
if(topic.getMessages() != null)
{
List thisMessageList = topic.getMessages();
for(int i=0; i<thisMessageList.size(); i++)
{
Message thisMsg = (Message)thisMessageList.get(i);
if(thisMsg != null && !thisMsg.getDraft().booleanValue())
{
totalMsgNumber++;
if(unreadMap.get(thisMsg.getId()) != null && ((Boolean)unreadMap.get(thisMsg.getId())).booleanValue())
{
readMsgNumber++;
}
}
}
}
if(totalMsgNumber > 0 )
{
decoTopic.setTotalNoMessages(totalMsgNumber);
decoTopic.setUnreadNoMessages(totalMsgNumber -readMsgNumber);
}
//decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
//decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));*/
if (uiPermissionsManager.isModeratePostings(topic, forum))
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoForum.addTopic(decoTopic);
}
}
}
return decoForum;
}
/**
* @return DiscussionForumBean
*/
private DiscussionForumBean getDecoratedForum()
{
LOG.debug("decorateSelectedForum()");
String forumId = getExternalParameterByKey(FORUM_ID);
if ((forumId) != null)
{
DiscussionForum forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
return null;
}
selectedForum = getDecoratedForum(forum);
return selectedForum;
}
return null;
}
/**
* @return
*/
private String displayHomeWithExtendedForumDescription()
{
LOG.debug("displayHomeWithExtendedForumDescription()");
List tmpForums = getForums();
if (tmpForums != null)
{
Iterator iter = tmpForums.iterator();
while (iter.hasNext())
{
DiscussionForumBean decoForumBean = (DiscussionForumBean) iter.next();
if (decoForumBean != null)
{
// if this forum is selected to display full desciption
if (getExternalParameterByKey("forumId_displayExtended") != null
&& getExternalParameterByKey("forumId_displayExtended")
.trim().length() > 0
&& decoForumBean
.getForum()
.getId()
.equals(
new Long(
getExternalParameterByKey("forumId_displayExtended"))))
{
decoForumBean.setReadFullDesciption(true);
}
// if this topic is selected to display hide extended desciption
if (getExternalParameterByKey("forumId_hideExtended") != null
&& getExternalParameterByKey("forumId_hideExtended").trim()
.length() > 0
&& decoForumBean.getForum().getId().equals(
new Long(
getExternalParameterByKey("forumId_hideExtended"))))
{
decoForumBean.setReadFullDesciption(false);
}
}
}
}
return gotoMain();
}
/**
* @return
*/
private String displayHomeWithExtendedTopicDescription()
{
LOG.debug("displayHomeWithExtendedTopicDescription()");
List tmpForums = getForums();
if (tmpForums != null)
{
Iterator iter = tmpForums.iterator();
while (iter.hasNext())
{
DiscussionForumBean decoForumBean = (DiscussionForumBean) iter.next();
if (decoForumBean != null)
{
List tmpTopics = decoForumBean.getTopics();
Iterator iter2 = tmpTopics.iterator();
while (iter2.hasNext())
{
DiscussionTopicBean decoTopicBean = (DiscussionTopicBean) iter2
.next();
if (decoTopicBean != null)
{
// if this topic is selected to display full desciption
if (getExternalParameterByKey("topicId_displayExtended") != null
&& getExternalParameterByKey("topicId_displayExtended")
.trim().length() > 0
&& decoTopicBean
.getTopic()
.getId()
.equals(
new Long(
getExternalParameterByKey("topicId_displayExtended"))))
{
decoTopicBean.setReadFullDesciption(true);
}
// if this topic is selected to display hide extended desciption
if (getExternalParameterByKey("topicId_hideExtended") != null
&& getExternalParameterByKey("topicId_hideExtended").trim()
.length() > 0
&& decoTopicBean.getTopic().getId().equals(
new Long(
getExternalParameterByKey("topicId_hideExtended"))))
{
decoTopicBean.setReadFullDesciption(false);
}
}
}
}
}
}
return gotoMain();
}
/**
* @param topic
* @return
*/
private DiscussionTopicBean getDecoratedTopic(DiscussionTopic topic)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getDecoratedTopic(DiscussionTopic " + topic + ")");
}
DiscussionTopicBean decoTopic = new DiscussionTopicBean(topic,
selectedForum.getForum(), uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
decoTopic.setReadFullDesciption(true);
}
if (!decoTopic.isTopicModerated() || decoTopic.getIsModeratedAndHasPerm())
{
decoTopic.setTotalNoMessages(forumManager.getTotalNoMessages(topic));
decoTopic.setUnreadNoMessages(forumManager.getUnreadNoMessages(topic));
}
else
{
decoTopic.setTotalNoMessages(forumManager.getTotalViewableMessagesWhenMod(topic));
decoTopic.setUnreadNoMessages(forumManager.getNumUnreadViewableMessagesWhenMod(topic));
}
decoTopic.setHasNextTopic(forumManager.hasNextTopic(topic));
decoTopic.setHasPreviousTopic(forumManager.hasPreviousTopic(topic));
if (forumManager.hasNextTopic(topic))
{
DiscussionTopic nextTopic= forumManager.getNextTopic(topic);
decoTopic.setNextTopicId(nextTopic.getId());
}
if (forumManager.hasPreviousTopic(topic))
{
decoTopic
.setPreviousTopicId(forumManager.getPreviousTopic(topic).getId());
}
List temp_messages = forumManager.getTopicByIdWithMessages(topic.getId())
.getMessages();
if (temp_messages == null || temp_messages.size() < 1)
{
return decoTopic;
}
Iterator iter = temp_messages.iterator();
final boolean isRead = decoTopic.getIsRead();
final boolean isNewResponse = decoTopic.getIsNewResponse();
while (iter.hasNext())
{
Message message = (Message) iter.next();
if (topic != null)
{
if (message != null)
{
DiscussionMessageBean decoMsg = new DiscussionMessageBean(message,
messageManager);
if(isRead || (isNewResponse && decoMsg.getIsOwn()))
{
decoMsg.setRead(messageManager.isMessageReadForUser(topic.getId(),
message.getId()));
decoTopic.addMessage(decoMsg);
}
}
}
}
return decoTopic;
}
private Boolean resetTopicById(String externalTopicId)
{
String topicId = null;
//threaded = true;
selectedTopic = null;
try
{
topicId = getExternalParameterByKey(externalTopicId);
if (topicId != null)
{
DiscussionTopic topic = null;
try
{
Long.parseLong(topicId);
topic = forumManager.getTopicById(new Long(topicId));
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(getResourceBundleString(UNABLE_RETRIEVE_TOPIC));
return false;
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
else
{
LOG.error("Topic with id '" + externalTopicId + "' not found");
setErrorMessage(getResourceBundleString(TOPIC_WITH_ID) + externalTopicId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return false;
}
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return false;
}
return true;
}
/**
* @param externalTopicId
* @return
*/
private String displayTopicById(String externalTopicId)
{
if (LOG.isDebugEnabled())
{
LOG.debug("processActionDisplayTopicById(String" + externalTopicId + ")");
}
if(resetTopicById(externalTopicId)){
return ALL_MESSAGES;
} else {
return gotoMain();
}
}
private void reset()
{
this.forums = null;
this.selectedForum = null;
this.selectedTopic = null;
this.selectedMessage = null;
// this.templateControlPermissions = null;
// this.templateMessagePermissions = null;
this.permissions=null;
this.errorSynch = false;
this.siteMembers=null;
attachments.clear();
prepareRemoveAttach.clear();
assignments.clear();
}
/**
* @return newly created topic
*/
private DiscussionTopicBean createTopic()
{
String forumId = getExternalParameterByKey(FORUM_ID);
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
return createTopic(new Long(forumId));
}
/**
* @param forumID
* @return
*/
private DiscussionTopicBean createTopic(Long forumId)
{
if (forumId == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
DiscussionForum forum = forumManager.getForumById(forumId);
if (forum == null)
{
setErrorMessage(getResourceBundleString(PARENT_TOPIC_NOT_FOUND));
return null;
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
DiscussionTopic topic = forumManager.createTopic(forum);
if (topic == null)
{
setErrorMessage(getResourceBundleString(FAILED_CREATE_TOPIC));
return null;
}
selectedTopic = new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedTopic.setReadFullDesciption(true);
}
selectedTopic.setModerated(selectedForum.getModerated()); // default to parent forum's setting
setNewTopicBeanAssign();
DiscussionTopicBean thisDTB = new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
thisDTB.setReadFullDesciption(true);
}
setNewTopicBeanAssign(selectedForum, thisDTB);
return thisDTB;
//return new DiscussionTopicBean(topic, forum, uiPermissionsManager, forumManager);
}
// compose
public String processAddMessage()
{
return MESSAGE_COMPOSE;
}
public String processAddAttachmentRedirect()
{
LOG.debug("processAddAttachmentRedirect()");
try
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
context.redirect("sakai.filepicker.helper/tool");
return null;
}
catch (Exception e)
{
return null;
}
}
public void setMessageManager(MessageForumsMessageManager messageManager)
{
this.messageManager = messageManager;
}
public String getComposeTitle()
{
return composeTitle;
}
public void setComposeTitle(String composeTitle)
{
this.composeTitle = composeTitle;
}
public String getComposeBody()
{
return composeBody;
}
public void setComposeBody(String composeBody)
{
this.composeBody = composeBody;
}
public String getComposeLabel()
{
return composeLabel;
}
public void setComposeLabel(String composeLabel)
{
this.composeLabel = composeLabel;
}
public ArrayList getAttachments()
{
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null
&& session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null)
{
List refs = (List) session
.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if(refs != null && refs.size()>0)
{
Reference ref = (Reference) refs.get(0);
for (int i = 0; i < refs.size(); i++)
{
ref = (Reference) refs.get(i);
Attachment thisAttach = messageManager.createAttachment();
thisAttach.setAttachmentName(ref.getProperties().getProperty(
ref.getProperties().getNamePropDisplayName()));
thisAttach.setAttachmentSize(ref.getProperties().getProperty(
ref.getProperties().getNamePropContentLength()));
thisAttach.setAttachmentType(ref.getProperties().getProperty(
ref.getProperties().getNamePropContentType()));
thisAttach.setAttachmentId(ref.getId());
//thisAttach.setAttachmentUrl(ref.getUrl());
thisAttach.setAttachmentUrl("/url");
attachments.add(new DecoratedAttachment(thisAttach));
}
}
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
return attachments;
}
public void setAttachments(ArrayList attachments)
{
this.attachments = attachments;
}
public String processDeleteAttach()
{
LOG.debug("processDeleteAttach()");
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
attachments.remove(i);
break;
}
}
}
return null;
}
public String processDfMsgCancel()
{
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfMsgPost()
{
Message dMsg = constructMessage();
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
/** mark message creator as having read the message */
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(), dMsg.getId(), true);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
// refresh page with unread status
selectedTopic = getDecoratedTopic(forumManager.getTopicById(selectedTopic.getTopic().getId()));
return ALL_MESSAGES;
}
public String processDfMsgSaveDraft()
{
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public Message constructMessage()
{
Message aMsg;
aMsg = messageManager.createDiscussionMessage();
if (aMsg != null)
{
aMsg.setTitle(getComposeTitle());
aMsg.setBody(getComposeBody());
aMsg.setAuthor(getUserNameOrEid());
aMsg.setDraft(Boolean.FALSE);
// if the topic is moderated, we want to leave approval null.
// if the topic is not moderated, all msgs are approved
// if the author has moderator perm, the msg is automatically approved
if (!selectedTopic.isTopicModerated() || selectedTopic.getIsModeratedAndHasPerm())
{
aMsg.setApproved(Boolean.TRUE);
}
aMsg.setTopic(selectedTopic.getTopic());
}
for (int i = 0; i < attachments.size(); i++)
{
aMsg.addAttachment(((DecoratedAttachment) attachments.get(i)).getAttachment());
}
attachments.clear();
// oldAttachments.clear();
return aMsg;
}
public String processDfComposeToggle()
{
String redirectTo = getExternalParameterByKey(REDIRECT_PROCESS_ACTION);
String expand = getExternalParameterByKey("composeExpand");
if (redirectTo == null)
{
return gotoMain();
}
if (redirectTo.equals("dfCompose"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return MESSAGE_COMPOSE;
}
if (redirectTo.equals("dfViewMessage"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return MESSAGE_VIEW;
}
if (redirectTo.equals("dfTopicReply"))
{
if ((expand != null) && (expand.equalsIgnoreCase("true")))
{
selectedTopic.setReadFullDesciption(true);
}
else
{
selectedTopic.setReadFullDesciption(false);
}
return "dfTopicReply";
}
return gotoMain();
}
public String getUserId()
{
return SessionManager.getCurrentSessionUserId();
}
public boolean getFullAccess()
{
return forumManager.isInstructor();
}
/**
* @return
*/
public String processDfMsgMarkMsgAsRead()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
if(resetTopicById(TOPIC_ID)){ // reconstruct topic again;
return null;
} else {
return gotoMain();
}
}
/**
* @return
*/
public String processDfMsgMarkMsgAsReadFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
return processActionGetDisplayThread(); // reconstruct thread again;
}
public String processDfMsgReplyMsgFromEntire()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
messageManager.markMessageReadForUser(new Long(topicId),
new Long(messageId), true);
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgReplyMsg();
}
public String processDfMsgReplyMsg()
{
if(selectedMessage.getMessage().getTitle() != null && !selectedMessage.getMessage().getTitle().startsWith(getResourceBundleString(MSG_REPLY_PREFIX)))
this.composeTitle = getResourceBundleString(MSG_REPLY_PREFIX) + " " + selectedMessage.getMessage().getTitle() + " ";
else
this.composeTitle = selectedMessage.getMessage().getTitle();
return "dfMessageReply";
}
public String processDfMsgReplyThread()
{
//we have to get the depth 0 message that this is in response to
DiscussionMessageBean cur = selectedMessage;
int depth = 0;
long messageId = 0;
while(cur.getDepth() > 0){
messageId = cur.getMessage().getInReplyTo().getId();
depth = cur.getDepth();
cur = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(cur.getMessage().getInReplyTo().getId()), messageManager);
cur.setDepth(--depth);
}
selectedMessage = cur;
List tempMsgs = selectedTopic.getMessages();
if(tempMsgs != null)
{
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean thisDmb = (DiscussionMessageBean)tempMsgs.get(i);
if(((DiscussionMessageBean)tempMsgs.get(i)).getMessage().getId().toString().equals(messageId))
{
selectedMessage.setDepth(thisDmb.getDepth());
selectedMessage.setHasNext(thisDmb.getHasNext());
selectedMessage.setHasPre(thisDmb.getHasPre());
break;
}
}
}
composeTitle = getResourceBundleString(MSG_REPLY_PREFIX) + " " + selectedMessage.getMessage().getTitle();
return "dfMessageReplyThread";
}
public String processDfMsgReplyTp()
{
return "dfTopicReply";
}
public String processDfMsgGrdFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgGrd();
}
public String processDfMsgGrd()
{
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
try
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String createdById = UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId();
String gradebookUid = ToolManager.getCurrentPlacement().getContext();
String msgAssignmentName = selectedMessage.getMessage().getGradeAssignmentName();
String topicDefaultAssignment = selectedTopic.getTopic().getDefaultAssignName();
String forumDefaultAssignment = selectedForum.getForum().getDefaultAssignName();
if(msgAssignmentName !=null && msgAssignmentName.trim().length()>0)
{
if((gradebookService.getAssignmentScore(gradebookUid,
msgAssignmentName, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
msgAssignmentName, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, msgAssignmentName, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(msgAssignmentName);
}
}
else if(topicDefaultAssignment != null &&
topicDefaultAssignment.trim().length() > 0)
{
if((gradebookService.getAssignmentScore(gradebookUid,
topicDefaultAssignment, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
topicDefaultAssignment, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, topicDefaultAssignment, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(topicDefaultAssignment);
}
else
{
gradePoint = "";
setSelectedAssignForMessage(topicDefaultAssignment);
}
}
else if(forumDefaultAssignment != null &&
forumDefaultAssignment.trim().length() > 0)
{
if( (gradebookService.getAssignmentScore(gradebookUid,
forumDefaultAssignment, createdById)) != null)
{
gradePoint = (gradebookService.getAssignmentScore(gradebookUid,
forumDefaultAssignment, createdById)).toString();
gradePoint = new Double(gradePoint).toString();
CommentDefinition assgnComment = gradebookService.getAssignmentScoreComment(gradebookUid, forumDefaultAssignment, createdById);
if (assgnComment != null)
gradeComment = assgnComment.getCommentText();
setSelectedAssignForMessage(forumDefaultAssignment);
}
else
{
gradePoint = "";
setSelectedAssignForMessage(topicDefaultAssignment);
}
}
}
catch(Exception e)
{
LOG.error("processDfMsgGrd in DiscussionFOrumTool - " + e);
e.printStackTrace();
return null;
}
return "dfMsgGrade";
}
public String processDfMsgRvsFromThread()
{
String messageId = getExternalParameterByKey(MESSAGE_ID);
String topicId = getExternalParameterByKey(TOPIC_ID);
if (messageId == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_REFERENCE_NOT_FOUND));
return gotoMain();
}
if (topicId == null)
{
setErrorMessage(getResourceBundleString(TOPC_REFERENCE_NOT_FOUND));
return gotoMain();
}
// Message message=forumManager.getMessageById(new Long(messageId));
Message message = messageManager.getMessageByIdWithAttachments(new Long(
messageId));
if (message == null)
{
setErrorMessage(getResourceBundleString(MESSAGE_WITH_ID) + messageId + getResourceBundleString(NOT_FOUND_WITH_QUOTE));
return gotoMain();
}
message = messageManager.getMessageByIdWithAttachments(message.getId());
selectedMessage = new DiscussionMessageBean(message, messageManager);
return processDfMsgRvs();
}
public String processDfMsgRvs()
{
attachments.clear();
composeBody = selectedMessage.getMessage().getBody();
composeLabel = selectedMessage.getMessage().getLabel();
composeTitle = selectedMessage.getMessage().getTitle();
List attachList = selectedMessage.getMessage().getAttachments();
if (attachList != null)
{
for (int i = 0; i < attachList.size(); i++)
{
attachments.add(new DecoratedAttachment((Attachment) attachList.get(i)));
}
}
return "dfMsgRevise";
}
public String processDfMsgMove()
{
List childMsgs = new ArrayList();
messageManager
.getChildMsgs(selectedMessage.getMessage().getId(), childMsgs);
// selectedMessage.getMessage().setTopic(selectedTopic.getTopic());
return null;
}
public String processDfMsgDeleteConfirm()
{
deleteMsg = true;
return null;
}
public String processDfReplyMsgPost()
{
List tempList = forumManager.getMessagesByTopicId(selectedTopic.getTopic().getId());
if(tempList != null)
{
boolean existed = false;
for(int i=0; i<tempList.size(); i++)
{
Message tempMsg = (Message)tempList.get(i);
if(tempMsg.getId().equals(selectedMessage.getMessage().getId()))
{
existed = true;
break;
}
}
if(!existed)
{
this.errorSynch = true;
return null;
}
}
else
{
this.errorSynch = true;
return null;
}
Message dMsg = constructMessage();
dMsg.setInReplyTo(selectedMessage.getMessage());
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
messageManager.markMessageReadForUser(selectedTopic.getTopic().getId(), dMsg.getId(), true);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
//return ALL_MESSAGES;
return processActionGetDisplayThread();
}
public String processDfReplyMsgSaveDraft()
{
List tempList = forumManager.getMessagesByTopicId(selectedTopic.getTopic().getId());
if(tempList != null)
{
boolean existed = false;
for(int i=0; i<tempList.size(); i++)
{
Message tempMsg = (Message)tempList.get(i);
if(tempMsg.getId().equals(selectedMessage.getMessage().getId()))
{
existed = true;
break;
}
}
if(!existed)
{
this.errorSynch = true;
return null;
}
}
else
{
this.errorSynch = true;
return null;
}
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
dMsg.setInReplyTo(selectedMessage.getMessage());
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return processActionGetDisplayThread();
}
public String processDeleteAttachRevise()
{
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
prepareRemoveAttach.add((DecoratedAttachment) attachments.get(i));
attachments.remove(i);
break;
}
}
}
return null;
}
public String processDfMsgRevisedCancel()
{
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfMsgRevisedPost()
{
Message dMsg = selectedMessage.getMessage();
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
dMsg.removeAttachment(removeAttach.getAttachment());
}
List oldList = dMsg.getAttachments();
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId()
.equals(thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
dMsg.addAttachment(thisAttach.getAttachment());
}
}
String currentBody = getComposeBody();
String revisedInfo = getResourceBundleString(LAST_REVISE_BY);
revisedInfo += getUserNameOrEid();
revisedInfo += " " + getResourceBundleString(LAST_REVISE_ON);
Date now = new Date();
revisedInfo += now.toString() + " <br/> ";
/* if(currentBody != null && currentBody.length()>0 && currentBody.startsWith("Last Revised By "))
{
if(currentBody.lastIndexOf(" <br/> ") > 0)
{
currentBody = currentBody.substring(currentBody.lastIndexOf(" <br/> ") + 7);
}
}*/
revisedInfo = revisedInfo.concat(currentBody);
dMsg.setTitle(getComposeTitle());
dMsg.setBody(revisedInfo);
dMsg.setDraft(Boolean.FALSE);
dMsg.setModified(new Date());
dMsg.setModifiedBy(getUserNameOrEid());
if (!selectedTopic.isTopicModerated() || selectedTopic.getIsModeratedAndHasPerm())
{
dMsg.setApproved(Boolean.TRUE);
}
else
{
dMsg.setApproved(null);
}
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
dMsg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
// Topic currentTopic = forumManager.getTopicByIdWithMessagesAndAttachments(dMsg.getTopic().getId());
// dMsg.getTopic().setBaseForum(currentTopic.getBaseForum());
//dMsg.getTopic().setBaseForum(selectedTopic.getTopic().getBaseForum());
forumManager.saveMessage(dMsg);
List messageList = selectedTopic.getMessages();
for (int i = 0; i < messageList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean) messageList.get(i);
if (dmb.getMessage().getId().equals(dMsg.getId()))
{
selectedTopic.getMessages().set(i,
new DiscussionMessageBean(dMsg, messageManager));
}
}
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return null;
}
prepareRemoveAttach.clear();
composeBody = null;
composeLabel = null;
composeTitle = null;
attachments.clear();
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfMsgSaveRevisedDraft()
{
Message dMsg = selectedMessage.getMessage();
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
dMsg.removeAttachment(removeAttach.getAttachment());
}
List oldList = dMsg.getAttachments();
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId()
.equals(thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
dMsg.addAttachment(thisAttach.getAttachment());
}
}
String currentBody = getComposeBody();
String revisedInfo = getResourceBundleString(LAST_REVISE_BY);
revisedInfo += getUserNameOrEid();
revisedInfo += " " + getResourceBundleString(LAST_REVISE_ON);
Date now = new Date();
revisedInfo += now.toString() + " <br/> ";
revisedInfo = revisedInfo.concat(currentBody);
dMsg.setTitle(getComposeTitle());
dMsg.setBody(revisedInfo);
dMsg.setDraft(Boolean.TRUE);
dMsg.setModified(new Date());
dMsg.setModifiedBy(getUserNameOrEid());
// if the topic is moderated, we want to leave approval null.
// if the topic is not moderated, all msgs are approved
if (!selectedTopic.isTopicModerated())
{
dMsg.setApproved(Boolean.TRUE);
}
// setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
// .getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.setTopic((DiscussionTopic) forumManager
// .getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
// selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
dMsg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
//dMsg.getTopic().setBaseForum(selectedTopic.getTopic().getBaseForum());
forumManager.saveMessage(dMsg);
List messageList = selectedTopic.getMessages();
for (int i = 0; i < messageList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean) messageList.get(i);
if (dmb.getMessage().getId().equals(dMsg.getId()))
{
selectedTopic.getMessages().set(i,
new DiscussionMessageBean(dMsg, messageManager));
}
}
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
return null;
}
prepareRemoveAttach.clear();
composeBody = null;
composeLabel = null;
composeTitle = null;
attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyMsgCancel()
{
this.errorSynch = false;
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processDfReplyThreadCancel()
{
this.errorSynch = false;
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return processActionGetDisplayThread();
}
public String processDfReplyTopicPost()
{
Message dMsg = constructMessage();
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyTopicSaveDraft()
{
Message dMsg = constructMessage();
dMsg.setDraft(Boolean.TRUE);
forumManager.saveMessage(dMsg);
setSelectedForumForCurrentTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
selectedTopic.getTopic().setBaseForum(selectedForum.getForum());
//selectedTopic.addMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.insertMessage(new DiscussionMessageBean(dMsg, messageManager));
selectedTopic.getTopic().addMessage(dMsg);
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public String processDfReplyTopicCancel()
{
this.composeBody = null;
this.composeLabel = null;
this.composeTitle = null;
this.attachments.clear();
return ALL_MESSAGES;
}
public boolean getDeleteMsg()
{
return deleteMsg;
}
public String processDfMsgDeleteConfirmYes()
{
List delList = new ArrayList();
messageManager.getChildMsgs(selectedMessage.getMessage().getId(), delList);
if(delList.size() > 0)
{
if(!selectedTopic.getIsDeleteAny())
{
errorSynch = true;
return null;
}
}
selectedTopic.removeMessage(selectedMessage);
Topic tempTopic = forumManager.getTopicByIdWithMessages(selectedTopic
.getTopic().getId());
tempTopic.removeMessage(selectedMessage.getMessage());
// selectedTopic.getTopic().removeMessage(selectedMessage.getMessage());
for (int i = 0; i < delList.size(); i++)
{
selectedTopic.removeMessage(new DiscussionMessageBean((Message) delList
.get(i), messageManager));
// tempTopic.removeMessage((Message) delList.get(i));
// selectedTopic.getTopic().removeMessage((Message) delList.get(i));
}
messageManager.deleteMsgWithChild(selectedMessage.getMessage().getId());
try
{
DiscussionTopic topic = null;
try
{
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
}
catch (NumberFormatException e)
{
LOG.error(e.getMessage(), e);
}
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
setErrorMessage(e.getMessage());
this.deleteMsg = false;
return gotoMain();
}
this.deleteMsg = false;
return ALL_MESSAGES;
}
public String processDfMsgDeleteCancel()
{
this.deleteMsg = false;
this.errorSynch = false;
return null;
}
/**
* A moderator view of all msgs pending approval
* @return
*/
public String processPendingMsgQueue()
{
return PENDING_MSG_QUEUE;
}
/**
* "Pending Messages" link will be displayed if current user
* has moderate perm for at least one moderated topic in site.
* Also sets number of pending msgs
* @return
*/
public boolean isDisplayPendingMsgQueue()
{
List membershipList = uiPermissionsManager.getCurrentUserMemberships();
int numModTopicWithPerm = forumManager.getNumModTopicsWithModPermission(membershipList);
if (numModTopicWithPerm < 1)
return false;
if (refreshPendingMsgs)
{
refreshPendingMessages();
}
return true;
}
public int getNumPendingMessages()
{
return numPendingMessages;
}
public void setNumPendingMessages(int numPendingMessages)
{
this.numPendingMessages = numPendingMessages;
}
/**
* Retrieve pending msgs from db and make DiscussionMessageBeans
*
*/
private void refreshPendingMessages()
{
pendingMsgs = new ArrayList();
numPendingMessages = 0;
List messages = forumManager.getPendingMsgsInSiteByMembership(uiPermissionsManager.getCurrentUserMemberships());
if (messages != null && !messages.isEmpty())
{
messages = messageManager.sortMessageByDate(messages, false);
Iterator msgIter = messages.iterator();
while (msgIter.hasNext())
{
Message msg = (Message) msgIter.next();
DiscussionMessageBean decoMsg = new DiscussionMessageBean(msg, messageManager);
pendingMsgs.add(decoMsg);
numPendingMessages++;
}
}
refreshPendingMsgs = false;
}
/**
* returns all messages in the site that are pending and curr user has
* moderate perm to view
* @return
*/
public List getPendingMessages()
{
if (refreshPendingMsgs)
{
refreshPendingMessages();
}
return pendingMsgs;
}
/**
* Will approve all "selected" messags
* @return
*/
public String markCheckedAsApproved()
{
approveOrDenySelectedMsgs(true);
if (numPendingMessages > 0)
return PENDING_MSG_QUEUE;
return processActionHome();
}
/**
* Will deny all "selected" messages
* @return
*/
public String markCheckedAsDenied()
{
approveOrDenySelectedMsgs(false);
if (numPendingMessages > 0)
return PENDING_MSG_QUEUE;
return processActionHome();
}
/**
* Mark selected msgs as denied or approved
* @param approved
*/
private void approveOrDenySelectedMsgs(boolean approved)
{
if (pendingMsgs == null || pendingMsgs.isEmpty())
{
return;
}
int numSelected = 0;
Iterator iter = pendingMsgs.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
if (decoMessage.isSelected())
{
Message msg = decoMessage.getMessage();
messageManager.markMessageApproval(msg.getId(), approved);
messageManager.markMessageReadForUser(msg.getTopic().getId(), msg.getId(), true);
numSelected++;
numPendingMessages--;
}
}
if (numSelected < 1)
setErrorMessage(getResourceBundleString(NO_MSG_SEL_FOR_APPROVAL));
else
{
if (approved)
setSuccessMessage(getResourceBundleString(MSGS_APPROVED));
else
setSuccessMessage(getResourceBundleString(MSGS_DENIED));
}
refreshPendingMsgs = true;
}
/**
* Deny a message
* @return
*/
public String processDfMsgDeny()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, false);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
}
refreshPendingMsgs = true;
return MESSAGE_VIEW;
}
/**
* Deny a message and return to comment page
* @return
*/
public String processDfMsgDenyAndComment()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, false);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
displayDeniedMsg = true;
}
refreshPendingMsgs = true;
return ADD_COMMENT;
}
/**
* Approve a message
* @return
*/
public String processDfMsgApprove()
{
Long msgId = selectedMessage.getMessage().getId();
if (msgId != null)
{
messageManager.markMessageApproval(msgId, true);
selectedMessage = new DiscussionMessageBean(messageManager.getMessageByIdWithAttachments(msgId), messageManager);
setSuccessMessage(getResourceBundleString("cdfm_approved_alert"));
}
refreshPendingMsgs = true;
return MESSAGE_VIEW;
}
/**
* @return
*/
public String processDfMsgAddComment()
{
moderatorComments = "";
return ADD_COMMENT;
}
/**
*
* @return
*/
public String processCancelAddComment()
{
if (displayDeniedMsg) // only displayed if from Deny & Comment path
{
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
displayDeniedMsg = false;
}
return MESSAGE_VIEW;
}
/**
* Moderators may add a comment that is prepended to the text
* of the denied msg
* @return
*/
public String processAddCommentToDeniedMsg()
{
if (!selectedTopic.getIsModeratedAndHasPerm())
{
setErrorMessage(getResourceBundleString(INSUFFICIENT_PRIVILEGES_TO_ADD_COMMENT));
return ADD_COMMENT;
}
if (moderatorComments == null || moderatorComments.trim().length() < 1)
{
setErrorMessage(getResourceBundleString(INVALID_COMMENT));
return ADD_COMMENT;
}
Message currMessage = selectedMessage.getMessage();
StringBuffer sb = new StringBuffer();
sb.append("<div style=\"font-style:italic; padding-bottom: 1.0em;\">");
sb.append("<div style=\"font-weight:bold;\">");
sb.append(getResourceBundleString(MOD_COMMENT_TEXT) + " ");
sb.append(UserDirectoryService.getCurrentUser().getDisplayName());
sb.append("</div>");
sb.append(moderatorComments);
sb.append("</div>");
String originalText = currMessage.getBody();
currMessage.setBody(sb.toString() + originalText);
currMessage.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
forumManager.saveMessage(currMessage);
if (displayDeniedMsg) // only displayed if from Deny & Comment path
{
setSuccessMessage(getResourceBundleString("cdfm_denied_alert"));
displayDeniedMsg = false;
}
// we also must mark this message as unread for the author to let them
// know there is a comment
forumManager.markMessageReadStatusForUser(currMessage, false, currMessage.getCreatedBy());
return MESSAGE_VIEW;
}
/**
* Approve option is displayed if:
* 1) topic is moderated
* 2) user has moderate perm
* 3) message has not been approved
* @return
*/
public boolean isAllowedToApproveMsg()
{
return selectedTopic.getIsModeratedAndHasPerm() && !selectedMessage.isMsgApproved();
}
/**
* Deny option is displayed if:
* 1) topic is moderated
* 2) user has moderate perm
* 3) message has not been denied
* 4) message has no responses
* @return
*/
public boolean isAllowedToDenyMsg()
{
return selectedTopic.getIsModeratedAndHasPerm() && !selectedMessage.isMsgDenied() && !selectedMessage.getHasChild();
}
public void setNewForumBeanAssign()
{
selectedForum.setGradeAssign("Default_0");
}
public void setNewTopicBeanAssign()
{
if(selectedForum !=null && selectedForum.getGradeAssign() != null && selectedForum.getForum() != null)
{
selectedTopic.setGradeAssign(selectedForum.getGradeAssign());
selectedTopic.getTopic().setDefaultAssignName(selectedForum.getForum().getDefaultAssignName());
}
}
public void setNewTopicBeanAssign(DiscussionForumBean dfb, DiscussionTopicBean dtb)
{
if(dfb !=null && dfb.getGradeAssign() != null && dfb.getForum() != null)
{
dtb.setGradeAssign(dfb.getGradeAssign());
dtb.getTopic().setDefaultAssignName(dfb.getForum().getDefaultAssignName());
}
}
public void setForumBeanAssign()
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(selectedForum.getForum().getDefaultAssignName()))
{
selectedForum.setGradeAssign((String)((SelectItem)assignments.get(i)).getValue());
break;
}
}
}
}
public void setTopicBeanAssign()
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(selectedTopic.getTopic().getDefaultAssignName()))
{
selectedTopic.setGradeAssign((String)((SelectItem)assignments.get(i)).getValue());
break;
}
}
}
}
public void setSelectedAssignForMessage(String assignName)
{
if(assignments != null)
{
for(int i=0; i<assignments.size(); i++)
{
if(((SelectItem)assignments.get(i)).getLabel().equals(assignName))
{
this.selectedAssign = (String)((SelectItem)assignments.get(i)).getValue();
break;
}
}
}
}
public void saveForumSelectedAssignment(DiscussionForum forum)
{
if(selectedForum.getGradeAssign() != null && !selectedForum.getGradeAssign().equals("Default_0"))
{
forum.setDefaultAssignName( ((SelectItem)assignments.get( new Integer(selectedForum.getGradeAssign()).intValue())).getLabel());
}
}
public void saveForumAttach(DiscussionForum forum)
{
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
List oldList = forum.getAttachments();
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
removeAttach.getAttachment().getAttachmentId()))
{
forum.removeAttachment(removeAttach.getAttachment());
break;
}
}
}
List oldList = forum.getAttachments();
if (oldList != null)
{
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
forum.addAttachment(thisAttach.getAttachment());
}
}
}
prepareRemoveAttach.clear();
attachments.clear();
}
public void saveTopicSelectedAssignment(DiscussionTopic topic)
{
if(selectedTopic.getGradeAssign() != null && !selectedTopic.getGradeAssign().equals("Default_0"))
{
topic.setDefaultAssignName( ((SelectItem)assignments.get( new Integer(selectedTopic.getGradeAssign()).intValue())).getLabel());
}
}
public void saveTopicAttach(DiscussionTopic topic)
{
for (int i = 0; i < prepareRemoveAttach.size(); i++)
{
DecoratedAttachment removeAttach = (DecoratedAttachment) prepareRemoveAttach.get(i);
List oldList = topic.getAttachments();
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
removeAttach.getAttachment().getAttachmentId()))
{
topic.removeAttachment(removeAttach.getAttachment());
break;
}
}
}
List oldList = topic.getAttachments();
if (oldList != null)
{
for (int i = 0; i < attachments.size(); i++)
{
DecoratedAttachment thisAttach = (DecoratedAttachment) attachments.get(i);
boolean existed = false;
for (int j = 0; j < oldList.size(); j++)
{
Attachment existedAttach = (Attachment) oldList.get(j);
if (existedAttach.getAttachmentId().equals(
thisAttach.getAttachment().getAttachmentId()))
{
existed = true;
break;
}
}
if (!existed)
{
topic.addAttachment(thisAttach.getAttachment());
}
}
}
prepareRemoveAttach.clear();
attachments.clear();
}
public String processDeleteAttachSetting()
{
LOG.debug("processDeleteAttach()");
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String attachId = null;
Map paramMap = context.getRequestParameterMap();
Iterator itr = paramMap.keySet().iterator();
while (itr.hasNext())
{
Object key = itr.next();
if (key instanceof String)
{
String name = (String) key;
int pos = name.lastIndexOf("dfmsg_current_attach");
if (pos >= 0 && name.length() == pos + "dfmsg_current_attach".length())
{
attachId = (String) paramMap.get(key);
break;
}
}
}
if ((attachId != null) && (!attachId.equals("")))
{
for (int i = 0; i < attachments.size(); i++)
{
if (attachId.equalsIgnoreCase(((DecoratedAttachment) attachments.get(i)).getAttachment()
.getAttachmentId()))
{
prepareRemoveAttach.add((DecoratedAttachment) attachments.get(i));
attachments.remove(i);
break;
}
}
}
return null;
}
public boolean getThreaded()
{
return threaded;
}
public void setThreaded(boolean threaded)
{
this.threaded = threaded;
}
public String getExpanded()
{
return expanded;
}
public boolean getExpandedView()
{
return expandedView;
}
public void setExpanded(String expanded)
{
this.expanded = expanded;
}
public void setGradeNotify(boolean gradeNotify)
{
this.gradeNotify = gradeNotify;
}
public boolean getGradeNotify()
{
return gradeNotify;
}
public String getSelectedAssign()
{
return selectedAssign;
}
public void setSelectedAssign(String selectedAssign)
{
this.selectedAssign = selectedAssign;
}
public void setGradePoint(String gradePoint)
{
this.gradePoint = gradePoint;
}
public String getGradePoint()
{
return gradePoint;
}
public List getAssignments()
{
return assignments;
}
public void setAssignments(List assignments)
{
this.assignments = assignments;
}
public void setGradeComment(String gradeComment)
{
this.gradeComment = gradeComment;
}
public String getGradeComment()
{
return gradeComment;
}
public void rearrageTopicMsgsThreaded()
{
List msgsList = selectedTopic.getMessages();
if (msgsList != null && !msgsList.isEmpty())
msgsList = filterModeratedMessages(msgsList, selectedTopic.getTopic(), (DiscussionForum)selectedTopic.getTopic().getBaseForum());
List orderedList = new ArrayList();
List threadList = new ArrayList();
if(msgsList != null)
{
for(int i=0; i<msgsList.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean)msgsList.get(i);
if(dmb.getMessage().getInReplyTo() == null)
{
threadList.add(dmb);
dmb.setDepth(0);
orderedList.add(dmb);
//for performance speed - operate with existing selectedTopic msgs instead of getting from manager through DB again
//recursiveGetThreadedMsgs(msgsList, orderedList, dmb);
//use arrays so as to pass by reference during recursion
recursiveGetThreadedMsgsFromListWithCounts(msgsList, orderedList, dmb, new int[1], new int[1]);
}
}
}
selectedTopic.setMessages(orderedList);
}
public void recursiveGetThreadedMsgs(List msgsList, List returnList,
DiscussionMessageBean currentMsg)
{
List childList = messageManager.getFirstLevelChildMsgs(currentMsg.getMessage().getId());
for(int j=0; j<childList.size(); j++)
{
Message currentChild = (Message)childList.get(j);
for(int k=0; k<msgsList.size(); k++)
{
Message existedMsg = ((DiscussionMessageBean)msgsList.get(k)).getMessage();
if(currentChild.getId().equals(existedMsg.getId()))
{
DiscussionMessageBean dmb = new DiscussionMessageBean(currentChild, messageManager);
/* dmb.setDepth(currentMsg.getDepth() + 1);
returnList.add(dmb);*/
((DiscussionMessageBean)msgsList.get(k)).setDepth(currentMsg.getDepth() + 1);
returnList.add(((DiscussionMessageBean)msgsList.get(k)));
recursiveGetThreadedMsgs(msgsList, returnList, ((DiscussionMessageBean)msgsList.get(k)));
break;
}
}
}
}
private void recursiveGetThreadedMsgsFromList(List msgsList, List returnList,
DiscussionMessageBean currentMsg)
{
for (int i = 0; i < msgsList.size(); i++)
{
DiscussionMessageBean thisMsgBean = (DiscussionMessageBean) msgsList
.get(i);
Message thisMsg = thisMsgBean.getMessage();
if (thisMsg.getInReplyTo() != null
&& thisMsg.getInReplyTo().getId().equals(
currentMsg.getMessage().getId()))
{
/*
* DiscussionMessageBean dmb = new DiscussionMessageBean(thisMsg, messageManager);
* dmb.setDepth(currentMsg.getDepth() + 1); returnList.add(dmb);
* this.recursiveGetThreadedMsgsFromList(msgsList, returnList, dmb);
*/
thisMsgBean.setDepth(currentMsg.getDepth() + 1);
returnList.add(thisMsgBean);
this
.recursiveGetThreadedMsgsFromList(msgsList, returnList, thisMsgBean);
}
}
}
private void recursiveGetThreadedMsgsFromListWithCounts(List msgsList, List returnList,
DiscussionMessageBean currentMsg, int[] childCount, int[] childUnread)
{
for (int i = 0; i < msgsList.size(); i++)
{
DiscussionMessageBean thisMsgBean = (DiscussionMessageBean) msgsList
.get(i);
Message thisMsg = thisMsgBean.getMessage();
if (thisMsg.getInReplyTo() != null
&& thisMsg.getInReplyTo().getId().equals(
currentMsg.getMessage().getId()))
{
/*
* DiscussionMessageBean dmb = new DiscussionMessageBean(thisMsg, messageManager);
* dmb.setDepth(currentMsg.getDepth() + 1); returnList.add(dmb);
* this.recursiveGetThreadedMsgsFromList(msgsList, returnList, dmb);
*/
childCount[0]++;
if(!thisMsgBean.isRead()){
childUnread[0]++;
}
thisMsgBean.setDepth(currentMsg.getDepth() + 1);
returnList.add(thisMsgBean);
this
.recursiveGetThreadedMsgsFromListWithCounts(msgsList, returnList, thisMsgBean, childCount, childUnread);
}
}
currentMsg.setChildCount(childCount[0]);
currentMsg.setChildUnread(childUnread[0]);
}
public String processDfGradeCancel()
{
gradeNotify = false;
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processGradeAssignChange(ValueChangeEvent vce)
{
String changeAssign = (String) vce.getNewValue();
if (changeAssign == null)
{
return null;
}
else
{
try
{
selectedAssign = changeAssign;
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
if((!selectedAssign.equalsIgnoreCase("Default_0"))
&& ((gradebookService.getAssignmentScore(ToolManager.getCurrentPlacement().getContext(),
((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel(),
UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId())) != null))
{
gradePoint = (gradebookService.getAssignmentScore(ToolManager.getCurrentPlacement().getContext(),
((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel(),
UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId())).toString();
}
else
{
gradePoint = "";
}
return "dfMsgGrade";
}
catch(Exception e)
{
LOG.error("processGradeAssignChange in DiscussionFOrumTool - " + e);
e.printStackTrace();
return null;
}
}
}
public boolean isNumber(String validateString)
{
try
{
double d = Double.valueOf(validateString).doubleValue();
if(d >= 0)
return true;
else
return false;
}
catch (NumberFormatException e)
{
e.printStackTrace();
return false;
}
}
public boolean isFewerDigit(String validateString)
{
String stringValue = new Double(validateString).toString();
if(stringValue.lastIndexOf(".") >= 0)
{
String subString = stringValue.substring(stringValue.lastIndexOf("."));
if(subString != null && subString.length() > 3)
return false;
}
return true;
}
private boolean validateGradeInput()
{
if(!isNumber(gradePoint))
{
FacesContext currentContext = FacesContext.getCurrentInstance();
String uiComponentId = "msgForum:dfMsgGradeGradePoint";
FacesMessage validateMessage = new FacesMessage(getResourceBundleString(GRADE_GREATER_ZERO));
validateMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
currentContext.addMessage(uiComponentId, validateMessage);
return false;
}
else if(!isFewerDigit(gradePoint))
{
FacesContext currentContext = FacesContext.getCurrentInstance();
String uiComponentId = "msgForum:dfMsgGradeGradePoint";
FacesMessage validateMessage = new FacesMessage(getResourceBundleString(GRADE_DECIMAL_WARN));
validateMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
currentContext.addMessage(uiComponentId, validateMessage);
return false;
}
return true;
}
public String processDfGradeSubmit()
{
if(gradePoint == null || gradePoint.trim().length()==0)
{
setErrorMessage(getResourceBundleString(NO_GRADE_PTS));
return null;
}
if(selectedAssign == null || selectedAssign.trim().length()==0 || selectedAssign.equalsIgnoreCase("Default_0"))
{
setErrorMessage(getResourceBundleString(NO_ASSGN));
return null;
}
if(!validateGradeInput())
return null;
try
{
if(selectedAssign != null && selectedAssign.trim().length()>0)
{
if(!selectedAssign.equalsIgnoreCase("Default_0"))
{
if(gradePoint != null && gradePoint.trim().length()>0)
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String selectedAssignName = ((SelectItem)assignments.get((new Integer(selectedAssign)).intValue())).getLabel();
String gradebookUuid = ToolManager.getCurrentPlacement().getContext();
String studentUid = UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId();
gradebookService.setAssignmentScore(gradebookUuid,
selectedAssignName, studentUid, new Double(gradePoint), "");
if (gradeComment != null && gradeComment.trim().length() > 0)
{
gradebookService.setAssignmentScoreComment(gradebookUuid,
selectedAssignName, studentUid, gradeComment);
}
Message msg = selectedMessage.getMessage();
msg.setGradeAssignmentName(selectedAssignName);
msg.setTopic((DiscussionTopic) forumManager
.getTopicByIdWithMessages(selectedTopic.getTopic().getId()));
forumManager.saveMessage(msg);
setSuccessMessage(getResourceBundleString(GRADE_SUCCESSFUL));
}
}
}
}
catch(Exception e)
{
LOG.error("DiscussionForumTool - processDfGradeSubmit:" + e);
e.printStackTrace();
}
gradeNotify = false;
selectedAssign = "Default_0";
gradePoint = "";
gradeComment = "";
getThreadFromMessage();
return MESSAGE_VIEW;
}
public String processCheckAll()
{
for(int i=0; i<selectedTopic.getMessages().size(); i++)
{
((DiscussionMessageBean)selectedTopic.getMessages().get(i)).setSelected(true);
}
return null;
}
private void setMessageBeanPreNextStatus()
{
if(selectedTopic != null)
{
if(selectedTopic.getMessages() != null)
{
List tempMsgs = selectedTopic.getMessages();
for(int i=0; i<tempMsgs.size(); i++)
{
DiscussionMessageBean dmb = (DiscussionMessageBean)tempMsgs.get(i);
if(i==0)
{
dmb.setHasPre(false);
if(i==(tempMsgs.size()-1))
{
dmb.setHasNext(false);
}
else
{
dmb.setHasNext(true);
}
}
else if(i==(tempMsgs.size()-1))
{
dmb.setHasPre(true);
dmb.setHasNext(false);
}
else
{
dmb.setHasNext(true);
dmb.setHasPre(true);
}
}
}
}
}
/**
* @return Returns the selectedMessageView.
*/
public String getSelectedMessageView()
{
return selectedMessageView;
}
/**
* @param selectedMessageView
* The selectedMessageView to set.
*/
public void setSelectedMessageView(String selectedMessageView)
{
this.selectedMessageView = selectedMessageView;
}
/**
* @return Returns the selectedMessageShow.
*/
public String getSelectedMessageShow()
{
return selectedMessageShow;
}
/**
* @param selectedMessageShow
* The selectedMessageShow to set.
*/
public void setSelectedMessageShow(String selectedMessageShow)
{
this.selectedMessageShow = selectedMessageShow;
}
/**
* @return Returns the selectedMessagOrganize.
*/
public String getSelectedMessageOrganize()
{
return selectedMessageOrganize;
}
/**
* @param selectedMessageOrganize
* The selectedMessageOrganize to set.
*/
public void setSelectedMessageOrganize(String selectedMessageOrganize)
{
this.selectedMessageOrganize = selectedMessageOrganize;
}
public String getThreadAnchorMessageId()
{
return threadAnchorMessageId;
}
public void setThreadAnchorMessageId(String newValue)
{
threadAnchorMessageId = newValue;
}
/**
* @return Returns the displayUnreadOnly.
*/
public boolean getDisplayUnreadOnly()
{
return displayUnreadOnly;
}
public void processActionToggleExpanded()
{
if(expanded.equals("true")){
expanded = "false";
} else {
expanded = "true";
}
}
/**
* @param vce
*/
public void processValueChangeForMessageView(ValueChangeEvent vce)
{
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
String changeView = (String) vce.getNewValue();
this.displayUnreadOnly = false;
//expandedView = false;
if (changeView == null)
{
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if (changeView.equals(ALL_MESSAGES))
{
//threaded = false;
setSelectedMessageView(ALL_MESSAGES);
DiscussionTopic topic = null;
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
return;
}
else
if (changeView.equals(UNREAD_VIEW))
{
//threaded = false;
this.displayUnreadOnly = true;
return;
}
/*
else
if (changeView.equals(EXPANDED_VIEW))
{
threaded = false;
expandedView = true;
return;
}
else
if (changeView.equals(THREADED_VIEW))
{
threaded = true;
expanded = "true";
return;
}
else
if (changeView.equals("expand"))
{
threaded = true;
expanded = "true";
return;
}
else
if (changeView.equals("collapse"))
{
threaded = true;
expanded = "false";
return;
}
*/
else
{
//threaded = false;
setErrorMessage(getResourceBundleString(VIEW_UNDER_CONSTRUCT));
return;
}
}
public void processValueChangedForMessageShow(ValueChangeEvent vce){
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
String changeShow = (String) vce.getNewValue();
if (changeShow == null){
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if (changeShow.equals(ENTIRE_MSG)){
//threaded = false;
selectedMessageShow = ENTIRE_MSG;
expandedView = true;
return;
}
else {
selectedMessageShow = SUBJECT_ONLY;
expandedView = false;
return;
}
}
public void processValueChangedForMessageOrganize(ValueChangeEvent vce){
if (LOG.isDebugEnabled())
LOG.debug("processValueChangeForMessageView(ValueChangeEvent " + vce
+ ")");
isDisplaySearchedMessages=false;
searchText="";
//expanded="false";
String changeOrganize = (String) vce.getNewValue();
threadAnchorMessageId = null;
DiscussionTopic topic = null;
topic = forumManager.getTopicById(selectedTopic.getTopic().getId());
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
if (changeOrganize == null){
//threaded = false;
setErrorMessage(getResourceBundleString(FAILED_REND_MESSAGE));
return;
}
if(changeOrganize.equals("thread")){
threaded = true;
orderAsc = true;
displayUnreadOnly = false;
} else if(changeOrganize.equals("date_desc")){
threaded = false;
orderAsc = false;
displayUnreadOnly = false;
} else if(changeOrganize.equals("date")){
orderAsc = true;
threaded = false;
displayUnreadOnly = false;
} else if (changeOrganize.equals("unread")){
orderAsc = true;
threaded = false;
displayUnreadOnly = true;
}
return;
}
public boolean getErrorSynch()
{
return errorSynch;
}
public void setErrorSynch(boolean errorSynch)
{
this.errorSynch = errorSynch;
}
/**
* @return
*/
public String processActionSearch()
{
LOG.debug("processActionSearch()");
// //TODO : should be fetched via a query in db
// //Subject, Authored By, Date,
// isDisplaySearchedMessages=true;
//
// if(searchText==null || searchText.trim().length()<1)
// {
// setErrorMessage("Invalid search criteria");
// return ALL_MESSAGES;
// }
// if(selectedTopic == null)
// {
// setErrorMessage("There is no topic selected for search");
// return ALL_MESSAGES;
// }
// searchResults=new DiscussionTopicBean(selectedTopic.getTopic(),selectedForum.getForum() ,uiPermissionsManager);
// if(selectedTopic.getMessages()!=null)
// {
// Iterator iter = selectedTopic.getMessages().iterator();
//
// while (iter.hasNext())
// {
// DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
// if((decoMessage.getMessage()!= null && (decoMessage.getMessage().getTitle().matches(".*"+searchText+".*") ||
// decoMessage.getMessage().getCreatedBy().matches(".*"+searchText+".*") ||
// decoMessage.getMessage().getCreated().toString().matches(".*"+searchText+".*") )))
// {
// searchResults.addMessage(decoMessage);
// }
// }
// }
return ALL_MESSAGES;
}
/**
* @return
*/
public String processActionMarkAllAsRead()
{
return markAllMessages(true);
}
/**
* @return
*/
public String processActionMarkAllThreadAsRead()
{
return markAllThreadAsRead(true);
}
/**
* @return
*/
public String processActionMarkCheckedAsRead()
{
return markCheckedMessages(true);
}
/**
* @return
*/
public String processActionMarkCheckedAsUnread()
{
return markCheckedMessages(false);
}
private String markCheckedMessages(boolean readStatus)
{
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
List messages = selectedTopic.getMessages();
if (messages == null || messages.size() < 1)
{
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = messages.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
if (decoMessage.isSelected())
{
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
}
return displayTopicById(TOPIC_ID); // reconstruct topic again;
}
private String markAllMessages(boolean readStatus)
{
if (selectedTopic == null)
{
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
List messages = selectedTopic.getMessages();
if (messages == null || messages.size() < 1)
{
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = messages.iterator();
while (iter.hasNext())
{
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
//return displayTopicById(TOPIC_ID); // reconstruct topic again;
setSelectedForumForCurrentTopic(selectedTopic.getTopic());
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
return processActionDisplayFlatView();
}
private String markAllThreadAsRead(boolean readStatus)
{
if(selectedThreadHead == null){
setErrorMessage(getResourceBundleString(LOST_ASSOCIATE));
return ALL_MESSAGES;
}
if(selectedThread == null || selectedThread.size() < 1){
setErrorMessage(getResourceBundleString(NO_MARKED_READ_MESSAGE));
return ALL_MESSAGES;
}
Iterator iter = selectedThread.iterator();
while (iter.hasNext()){
DiscussionMessageBean decoMessage = (DiscussionMessageBean) iter.next();
forumManager.markMessageAs(decoMessage.getMessage(), readStatus);
}
return processActionGetDisplayThread();
}
/**
* @return Returns the isDisplaySearchedMessages.
*/
public boolean getIsDisplaySearchedMessages()
{
return isDisplaySearchedMessages;
}
/**
* @return Returns the searchText.
*/
public String getSearchText()
{
return searchText;
}
/**
* @param searchText
* The searchText to set.
*/
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public List getSiteMembers()
{
return getSiteMembers(true);
}
public List getSiteRoles()
{
//for group awareness
//return getSiteMembers(false);
return getSiteMembers(true);
}
public List getSiteMembers(boolean includeGroup)
{
LOG.debug("getSiteMembers()");
if(siteMembers!=null && siteMembers.size()>0)
{
return siteMembers;
}
permissions=new ArrayList();
Set membershipItems = null;
if (PERMISSION_MODE_TEMPLATE.equals(getPermissionMode())){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
membershipItems = uiPermissionsManager.getAreaItemsSet(forumManager.getDiscussionForumArea());
}
else if (PERMISSION_MODE_FORUM.equals(getPermissionMode())){
//membershipItems = selectedForum.getForum().getMembershipItemSet();
membershipItems = uiPermissionsManager.getForumItemsSet(selectedForum.getForum());
if (membershipItems == null || membershipItems.size() == 0){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
membershipItems = uiPermissionsManager.getAreaItemsSet(forumManager.getDiscussionForumArea());
}
}
else if (PERMISSION_MODE_TOPIC.equals(getPermissionMode())){
//membershipItems = selectedTopic.getTopic().getMembershipItemSet();
membershipItems = uiPermissionsManager.getTopicItemsSet(selectedTopic.getTopic());
if (membershipItems == null || membershipItems.size() == 0){
//membershipItems = forumManager.getDiscussionForumArea().getMembershipItemSet();
if (selectedForum != null && selectedForum.getForum() != null){
//membershipItems = selectedForum.getForum().getMembershipItemSet();
membershipItems = uiPermissionsManager.getForumItemsSet(selectedForum.getForum());
}
}
}
siteMembers=new ArrayList();
// get Roles
AuthzGroup realm;
Site currentSite = null;
int i=0;
try
{
realm = AuthzGroupService.getAuthzGroup(getContextSiteId());
Set roles1 = realm.getRoles();
if (roles1 != null && roles1.size() > 0)
{
List rolesList = sortRoles(roles1);
Iterator roleIter = rolesList.iterator();
while (roleIter.hasNext())
{
Role role = (Role) roleIter.next();
if (role != null)
{
if(i==0)
{
selectedRole = role.getId();
i=1;
}
DBMembershipItem item = forumManager.getAreaDBMember(membershipItems, role.getId(), DBMembershipItem.TYPE_ROLE);
siteMembers.add(new SelectItem(role.getId(), role.getId() + " ("+item.getPermissionLevelName()+")"));
permissions.add(new PermissionBean(item, permissionLevelManager));
}
}
}
if(includeGroup)
{
currentSite = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Collection groups = currentSite.getGroups();
groups = sortGroups(groups);
for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext();)
{
Group currentGroup = (Group) groupIterator.next();
DBMembershipItem item = forumManager.getAreaDBMember(membershipItems,currentGroup.getTitle(), DBMembershipItem.TYPE_GROUP);
siteMembers.add(new SelectItem(currentGroup.getTitle(), currentGroup.getTitle() + " ("+item.getPermissionLevel().getName()+")"));
permissions.add(new PermissionBean(item, permissionLevelManager));
}
}
}
catch (IdUnusedException e)
{
LOG.error(e.getMessage(), e);
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return siteMembers;
}
/**
* Takes roles defined and sorts them alphabetically by id
* so when displayed will be in order.
*
* @param roles
* Set of defined roles
*
* @return
* Set of defined roles sorted
*/
private List sortRoles(Set roles) {
final List rolesList = new ArrayList();
rolesList.addAll(roles);
final AuthzGroupComparator authzGroupComparator = new AuthzGroupComparator("id", true);
Collections.sort(rolesList, authzGroupComparator);
return rolesList;
}
/**
* Takes groups defined and sorts them alphabetically by title
* so will be in some order when displayed on permission widget.
*
* @param groups
* Collection of groups to be sorted
*
* @return
* Collection of groups in sorted order
*/
private Collection sortGroups(Collection groups) {
List sortGroupsList = new ArrayList();
sortGroupsList.addAll(groups);
final GroupComparator groupComparator = new GroupComparator("title", true);
Collections.sort(sortGroupsList, groupComparator);
groups.clear();
groups.addAll(sortGroupsList);
return groups;
}
/**
* @return siteId
*/
private String getContextSiteId()
{
LOG.debug("getContextSiteId()");
return ("/site/" + ToolManager.getCurrentPlacement().getContext());
}
/**
* @param topic
*/
private void setSelectedForumForCurrentTopic(DiscussionTopic topic)
{
if (selectedForum != null)
{
return;
}
DiscussionForum forum = (DiscussionForum) topic.getBaseForum();
if (forum == null)
{
String forumId = getExternalParameterByKey(FORUM_ID);
if (forumId == null || forumId.trim().length() < 1)
{
selectedForum = null;
return;
}
forum = forumManager.getForumById(new Long(forumId));
if (forum == null)
{
selectedForum = null;
return;
}
}
selectedForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager);
if("true".equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")))
{
selectedForum.setReadFullDesciption(true);
}
setForumBeanAssign();
}
/**
* @param errorMsg
*/
private void setErrorMessage(String errorMsg)
{
LOG.debug("setErrorMessage(String " + errorMsg + ")");
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, getResourceBundleString(ALERT) + errorMsg, null));
}
private void setSuccessMessage(String successMsg)
{
LOG.debug("setSuccessMessage(String " + successMsg + ")");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, successMsg, null));
}
public void processPost(){
}
public String generatePermissionScript(){
PermissionLevel ownerLevel = permissionLevelManager.getDefaultOwnerPermissionLevel();
PermissionLevel authorLevel = permissionLevelManager.getDefaultAuthorPermissionLevel();
PermissionLevel noneditingAuthorLevel = permissionLevelManager.getDefaultNoneditingAuthorPermissionLevel();
PermissionLevel reviewerLevel = permissionLevelManager.getDefaultReviewerPermissionLevel();
PermissionLevel noneLevel = permissionLevelManager.getDefaultNonePermissionLevel();
PermissionLevel contributorLevel = permissionLevelManager.getDefaultContributorPermissionLevel();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("<script type=\"text/javascript\">\n");
sBuffer.append("var ownerLevelArray = " + ownerLevel + ";\n");
sBuffer.append("var authorLevelArray = " + authorLevel + ";\n");
sBuffer.append("var noneditingAuthorLevelArray = " + noneditingAuthorLevel + ";\n");
sBuffer.append("var reviewerLevelArray = " + reviewerLevel + ";\n");
sBuffer.append("var noneLevelArray = " + noneLevel + ";\n");
sBuffer.append("var contributorLevelArray = " + contributorLevel + ";\n");
sBuffer.append("var owner = 'Owner';\n");
sBuffer.append("var author = 'Author';\n");
sBuffer.append("var nonEditingAuthor = 'Nonediting Author';\n");
sBuffer.append("var reviewer = 'Reviewer';\n");
sBuffer.append("var none = 'None';\n");
sBuffer.append("var contributor = 'Contributor';\n");
sBuffer.append("var custom = 'Custom';\n");
sBuffer.append("var all = 'All';\n");
sBuffer.append("var own = 'Own';\n");
sBuffer.append("function checkLevel(selectedLevel){\n" +
" var ownerVal = true;\n" +
" var authorVal = true;\n" +
" var noneditingAuthorVal = true;\n" +
" var reviewerVal = true;\n" +
" var noneVal = true;\n" +
" var contributorVal = true;\n\n" +
" for (var i = 0; i < selectedLevel.length; i++){\n" +
" if (ownerVal && ownerLevelArray[i] != selectedLevel[i])\n" +
" ownerVal = false;\n" +
" if (authorVal && authorLevelArray[i] != selectedLevel[i])\n" +
" authorVal = false;\n" +
" if (noneditingAuthorVal && noneditingAuthorLevelArray[i] != selectedLevel[i])\n" +
" noneditingAuthorVal = false;\n" +
" if (reviewerVal && reviewerLevelArray[i] != selectedLevel[i])\n" +
" reviewerVal = false;\n" +
" if (noneVal && noneLevelArray[i] != selectedLevel[i])\n" +
" noneVal = false;\n" +
" if (contributorVal && contributorLevelArray[i] != selectedLevel[i])\n" +
" contributorVal = false;\n" +
" }\n\n" +
" if (ownerVal)\n" +
" return 'Owner';\n" +
" else if (authorVal)\n" +
" return 'Author';\n" +
" else if (noneditingAuthorVal)\n" +
" return 'Nonediting Author';\n" +
" else if (reviewerVal)\n" +
" return 'Reviewer';\n" +
" else if (noneVal)\n" +
" return 'None';\n" +
" else if (contributorVal)\n" +
" return 'Contributor';\n" +
" else return 'Custom';\n" +
"}\n"
);
sBuffer.append("</script>");
return sBuffer.toString();
}
public void setObjectPermissions(Object target){
Set membershipItemSet = null;
Set oldMembershipItemSet = null;
DiscussionForum forum = null;
Area area = null;
//Topic topic = null;
DiscussionTopic topic = null;
/** get membership item set */
if (target instanceof DiscussionForum){
forum = ((DiscussionForum) target);
//membershipItemSet = forum.getMembershipItemSet();
//membershipItemSet = uiPermissionsManager.getForumItemsSet(forum);
oldMembershipItemSet = uiPermissionsManager.getForumItemsSet(forum);
}
else if (target instanceof Area){
area = ((Area) target);
//membershipItemSet = area.getMembershipItemSet();
//membershipItemSet = uiPermissionsManager.getAreaItemsSet();
oldMembershipItemSet = uiPermissionsManager.getAreaItemsSet(area);
}
else if (target instanceof Topic){
//topic = ((Topic) target);
//membershipItemSet = topic.getMembershipItemSet();
topic = ((DiscussionTopic) target);
//membershipItemSet = uiPermissionsManager.getTopicItemsSet(topic);
oldMembershipItemSet = uiPermissionsManager.getTopicItemsSet(topic);
}
if (membershipItemSet != null){
membershipItemSet.clear();
}
else{
membershipItemSet = new HashSet();
}
if(permissions!=null ){
Iterator iter = permissions.iterator();
while (iter.hasNext())
{
PermissionBean permBean = (PermissionBean) iter.next();
//for group awareness
//DBMembershipItem membershipItem = permissionLevelManager.createDBMembershipItem(permBean.getItem().getName(), permBean.getSelectedLevel(), DBMembershipItem.TYPE_ROLE);
DBMembershipItem membershipItem = permissionLevelManager.createDBMembershipItem(permBean.getItem().getName(), permBean.getSelectedLevel(), permBean.getItem().getType());
if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM.equals(membershipItem.getPermissionLevelName())){
PermissionsMask mask = new PermissionsMask();
mask.put(PermissionLevel.NEW_FORUM, new Boolean(permBean.getNewForum()));
mask.put(PermissionLevel.NEW_TOPIC, new Boolean(permBean.getNewTopic()));
mask.put(PermissionLevel.NEW_RESPONSE, new Boolean(permBean.getNewResponse()));
mask.put(PermissionLevel.NEW_RESPONSE_TO_RESPONSE, new Boolean(permBean.getResponseToResponse()));
mask.put(PermissionLevel.MOVE_POSTING, new Boolean(permBean.getMovePosting()));
mask.put(PermissionLevel.CHANGE_SETTINGS,new Boolean(permBean.getChangeSettings()));
mask.put(PermissionLevel.POST_TO_GRADEBOOK, new Boolean(permBean.getPostToGradebook()));
mask.put(PermissionLevel.READ, new Boolean(permBean.getRead()));
mask.put(PermissionLevel.MARK_AS_READ,new Boolean(permBean.getMarkAsRead()));
mask.put(PermissionLevel.MODERATE_POSTINGS, new Boolean(permBean.getModeratePostings()));
mask.put(PermissionLevel.DELETE_OWN, new Boolean(permBean.getDeleteOwn()));
mask.put(PermissionLevel.DELETE_ANY, new Boolean(permBean.getDeleteAny()));
mask.put(PermissionLevel.REVISE_OWN, new Boolean(permBean.getReviseOwn()));
mask.put(PermissionLevel.REVISE_ANY, new Boolean(permBean.getReviseAny()));
PermissionLevel level = permissionLevelManager.createPermissionLevel(permBean.getSelectedLevel(), typeManager.getCustomLevelType(), mask);
membershipItem.setPermissionLevel(level);
}
// save DBMembershiptItem here to get an id so we can add to the set
permissionLevelManager.saveDBMembershipItem(membershipItem);
membershipItemSet.add(membershipItem);
}
if( ((area != null && area.getId() != null) ||
(forum != null && forum.getId() != null) ||
(topic != null && topic.getId() != null))
&& oldMembershipItemSet != null)
permissionLevelManager.deleteMembershipItems(oldMembershipItemSet);
if (target instanceof DiscussionForum){
forum.setMembershipItemSet(membershipItemSet);
//forumManager.saveForum(forum);
}
else if (area != null){
area.setMembershipItemSet(membershipItemSet);
//areaManager.saveArea(area);
}
else if (topic != null){
topic.setMembershipItemSet(membershipItemSet);
//forumManager.saveTopic((DiscussionTopic) topic);
}
}
siteMembers = null;
}
/**
* processActionAddGroupsUsers
* @return navigation String
*/
public String processActionAddGroupsUsers(){
totalGroupsUsersList = null;
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
String attr = null;
if (session != null){
/** get navigation string of previous navigation (set by navigation handler) */
attr = (String) session.getAttribute("MC_PREVIOUS_NAV");
}
/** store caller navigation string in session (used to return from add groups/users) */
session.setAttribute("MC_ADD_GROUPS_USERS_CALLER", attr);
return "addGroupsUsers";
}
/**
* processAddGroupsUsersSubmit
* @return navigation String
*/
public String processAddGroupsUsersSubmit(){
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
/** get navigation string of previous navigation (set by navigation handler) */
return (String) session.getAttribute("MC_ADD_GROUPS_USERS_CALLER");
}
/**
* processAddGroupsUsersCancel
* @return navigation String
*/
public String processAddGroupsUsersCancel(){
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) exContext.getSession(false);
/** get navigation string of previous navigation (set by navigation handler) */
return (String) session.getAttribute("MC_ADD_GROUPS_USERS_CALLER");
}
public List getTotalGroupsUsersList()
{
/** protect from jsf calling multiple times */
if (totalGroupsUsersList != null){
return totalGroupsUsersList;
}
courseMemberMap = membershipManager.getAllCourseMembers(true, false, false);
List members = membershipManager.convertMemberMapToList(courseMemberMap);
totalGroupsUsersList = new ArrayList();
/** create a list of SelectItem elements */
for (Iterator i = members.iterator(); i.hasNext();){
MembershipItem item = (MembershipItem) i.next();
totalGroupsUsersList.add(
new SelectItem(item.getId(), item.getName()));
}
return totalGroupsUsersList;
}
public void setPermissionLevelManager(
PermissionLevelManager permissionLevelManager) {
this.permissionLevelManager = permissionLevelManager;
}
public List getPostingOptions()
{
List postingOptions = new ArrayList();
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.NONE),
PermissionBean.getResourceBundleString(PermissionBean.NONE)));
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.OWN),
PermissionBean.getResourceBundleString(PermissionBean.OWN)));
postingOptions.add(new SelectItem(PermissionBean.getResourceBundleString(PermissionBean.ALL),
PermissionBean.getResourceBundleString(PermissionBean.ALL)));
return postingOptions;
}
/**
* @return Returns the levels.
*/
public List getLevels()
{
boolean hasCustom = false;
if (levels == null || levels.size() == 0)
{
levels = new ArrayList();
List origLevels = permissionLevelManager.getOrderedPermissionLevelNames();
if (origLevels != null)
{
Iterator iter = origLevels.iterator();
while (iter.hasNext())
{
String level = (String) iter.next();
levels.add(new SelectItem(level));
if(level.equals("Custom"))
{
hasCustom =true;
}
}
}
if(!hasCustom)
{
levels.add(new SelectItem("Custom"));
}
}
return levels;
}
/**
* @param areaManager The areaManager to set.
*/
public void setAreaManager(AreaManager areaManager)
{
this.areaManager = areaManager;
}
/**
* @return Returns the selectedRole.
*/
public String getSelectedRole()
{
return selectedRole;
}
/**
* @param selectedRole The selectedRole to set.
*/
public void setSelectedRole(String selectedRole)
{
this.selectedRole = selectedRole;
}
public boolean getEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
public String getPermissionMode() {
return permissionMode;
}
public void setPermissionMode(String permissionMode) {
this.permissionMode = permissionMode;
}
public List getSelectedGroupsUsersList() {
return selectedGroupsUsersList;
}
public void setSelectedGroupsUsersList(List selectedGroupsUsersList) {
this.selectedGroupsUsersList = selectedGroupsUsersList;
}
public void setTotalGroupsUsersList(List totalGroupsUsersList) {
this.totalGroupsUsersList = totalGroupsUsersList;
}
/**
* Pulls messages from bundle
*
* @param key
* Key of message to get
*
* @return
* String for key passed in or [missing: key] if not found
*/
public static String getResourceBundleString(String key)
{
final ResourceBundle rb = ResourceBundle.getBundle(MESSAGECENTER_BUNDLE);
return rb.getString(key);
}
public boolean getGradebookExist()
{
try
{
GradebookService gradebookService = (org.sakaiproject.service.gradebook.shared.GradebookService)
ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
gradebookExist = gradebookService.isGradebookDefined(ToolManager.getCurrentPlacement().getContext());
return gradebookExist;
}
catch(Exception e)
{
gradebookExist = false;
return gradebookExist;
}
}
public void setGradebookExist(boolean gradebookExist)
{
this.gradebookExist = gradebookExist;
}
public String getUserNameOrEid()
{
try
{
String currentUserId = getUserId();
if(!"false".equalsIgnoreCase(ServerConfigurationService.getString
("[email protected]")))
{
String userString = "";
String userLastName = UserDirectoryService.getUser(currentUserId).getLastName();
String userFirstName = UserDirectoryService.getUser(currentUserId).getFirstName();
if((userLastName != null && userLastName.length() > 0) ||
(userFirstName != null && userFirstName.length() > 0))
{
userString += userLastName + ", ";
userString += userFirstName;
return userString;
}
else
{
return UserDirectoryService.getUserEid(currentUserId);
}
}
else
{
String userString = "";
String userLastName = UserDirectoryService.getUser(currentUserId).getLastName();
String userFirstName = UserDirectoryService.getUser(currentUserId).getFirstName();
if((userLastName != null && userLastName.length() > 0) ||
(userFirstName != null && userFirstName.length() > 0))
{
userString += userLastName + ", ";
userString += userFirstName;
return userString;
}
else
{
return UserDirectoryService.getUserEid(currentUserId);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return getUserId();
}
public boolean isDisableLongDesc()
{
return disableLongDesc;
}
/**
* Determines current level (template, forum, or topic) and
* returns boolean indicating whether moderating is enabled or not.
* @return
*/
public boolean isDisableModeratePerm()
{
if (permissionMode == null)
return true;
else if (permissionMode.equals(PERMISSION_MODE_TEMPLATE) && template != null)
return !template.isAreaModerated();
else if (permissionMode.equals(PERMISSION_MODE_FORUM) && selectedForum != null)
return !selectedForum.isForumModerated();
else if (permissionMode.equals(PERMISSION_MODE_TOPIC) && selectedTopic != null)
return !selectedTopic.isTopicModerated();
else
return true;
}
public List getMessages() {
List messages = new ArrayList();
if(displayUnreadOnly)
messages = selectedTopic.getUnreadMessages();
else
messages = selectedTopic.getMessages();
if (messages != null && !messages.isEmpty())
messages = filterModeratedMessages(messages, selectedTopic.getTopic(), selectedForum.getForum());
return messages;
}
/**
* Given a list of messages, will return all messages that meet at
* least one of the following criteria:
* 1) message is approved
* 2) message was written by current user
* 3) current user has moderator perm
*/
private List filterModeratedMessages(List messages, DiscussionTopic topic, DiscussionForum forum)
{
List viewableMsgs = new ArrayList();
if (messages != null || messages.size() > 0)
{
boolean hasModeratePerm = uiPermissionsManager.isModeratePostings(topic, forum);
if (hasModeratePerm)
return messages;
Iterator msgIter = messages.iterator();
while (msgIter.hasNext())
{
DiscussionMessageBean msg = (DiscussionMessageBean) msgIter.next();
if (msg.isMsgApproved() || msg.getIsOwn())
viewableMsgs.add(msg);
}
}
return viewableMsgs;
}
public String getModeratorComments()
{
return moderatorComments;
}
public void setModeratorComments(String moderatorComments)
{
this.moderatorComments = moderatorComments;
}
public UIData getForumTable(){
return forumTable;
}
public void setForumTable(UIData forumTable){
this.forumTable=forumTable;
}
public String processReturnToOriginatingPage()
{
LOG.debug("processReturnToOriginatingPage()");
if(fromPage != null)
{
String returnToPage = fromPage;
fromPage = "";
if(returnToPage.equals(ALL_MESSAGES) && selectedTopic != null)
{
selectedTopic = getDecoratedTopic(selectedTopic.getTopic());
return ALL_MESSAGES;
}
if(returnToPage.equals(FORUM_DETAILS) && selectedForum != null)
{
selectedForum = getDecoratedForum(selectedForum.getForum());
return FORUM_DETAILS;
}
}
return processActionHome();
}
private void setFromMainOrForumOrTopic()
{
String originatingPage = getExternalParameterByKey(FROM_PAGE);
if(originatingPage != null && (originatingPage.equals(MAIN) || originatingPage.equals(ALL_MESSAGES) || originatingPage.equals(FORUM_DETAILS)
|| originatingPage.equals(THREAD_VIEW) || originatingPage.equals(FLAT_VIEW)))
{
fromPage = originatingPage;
}
}
/**
* @return TRUE if within Messages & Forums tool, FALSE otherwise
*/
public boolean isMessagesandForums() {
return messageManager.currentToolMatch(MESSAGECENTER_TOOL_ID);
}
/**
* @return TRUE if within Forums tool, FALSE otherwise
*/
public boolean isForumsTool() {
return messageManager.currentToolMatch(FORUMS_TOOL_ID);
}
private String gotoMain() {
if (isForumsTool()) {
return FORUMS_MAIN;
}
else {
return MAIN;
}
}
/**
* @return TRUE if Messages & Forums (Message Center) exists in this site,
* FALSE otherwise
*/
private boolean isMessageForumsPageInSite(String siteId) {
return messageManager.isToolInSite(siteId, MESSAGECENTER_TOOL_ID);
}
/**
* @return TRUE if Messages & Forums (Message Center) exists in this site,
* FALSE otherwise
*/
private boolean isForumsPageInSite(String siteId) {
return messageManager.isToolInSite(siteId, FORUMS_TOOL_ID);
}
public String getPrintFriendlyUrl()
{
return ServerConfigurationService.getToolUrl() + Entity.SEPARATOR
+ ToolManager.getCurrentPlacement().getId() + Entity.SEPARATOR + "discussionForum"
+ Entity.SEPARATOR + "message" + Entity.SEPARATOR
+ "printFriendly";
}
public String getPrintFriendlyUrlThread()
{
return ServerConfigurationService.getToolUrl() + Entity.SEPARATOR
+ ToolManager.getCurrentPlacement().getId() + Entity.SEPARATOR + "discussionForum"
+ Entity.SEPARATOR + "message" + Entity.SEPARATOR
+ "printFriendlyThread";
}
public Boolean isMessageReadForUser(Long topicId, Long messageId)
{
return messageManager.isMessageReadForUser(topicId, messageId);
}
public void markMessageReadForUser(Long topicId, Long messageId, Boolean read)
{
messageManager.markMessageReadForUser(topicId, messageId, read);
if(selectedThreadHead != null){
//reset the thread to show unread
processActionGetDisplayThread();
}
//also go ahead and reset the the topic
DiscussionTopic topic = forumManager.getTopicById(new Long(topicId));
setSelectedForumForCurrentTopic(topic);
selectedTopic = getDecoratedTopic(topic);
setTopicBeanAssign();
getSelectedTopic();
}
} | SAK-8903
http://bugs.sakaiproject.org/jira/browse/SAK-8903
Forums - Thread View "unread" affecting Topic
git-svn-id: 65c85f73e8ce8bfb0e9a03896276dfceee826a06@27648 66ffb92e-73f9-0310-93c1-f5514f145a0a
| msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java | SAK-8903 http://bugs.sakaiproject.org/jira/browse/SAK-8903 Forums - Thread View "unread" affecting Topic |
|
Java | apache-2.0 | 414f0907da1991f72252830d69edbb7aa763c749 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2004 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.springframework.remoting.jaxrpc;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.rmi.RmiClientInterceptorUtils;
/**
* Interceptor for accessing a specific port of a JAX-RPC service.
* Uses either LocalJaxRpcServiceFactory's facilities underneath,
* or takes an explicit reference to an existing JAX-RPC Service instance
* (for example looked up via JndiObjectFactoryBean).
*
* <p>Allows to set JAX-RPC's standard stub properties directly, via the
* "username", "password", "endpointAddress" and "maintainSession" properties.
* For typical usage, it is not necessary to specify those, though.
*
* <p>This invoker is typically used with an RMI service interface. Alternatively,
* this invoker can also proxy a JAX-RPC service with a matching non-RMI business
* interface, i.e. an interface that mirrors the RMI service methods but does not
* declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the
* JAX-RPC stub will automatically get converted to Spring's unchecked
* RemoteAccessException.
*
* <p>If exposing the JAX-RPC port interface (i.e. an RMI interface) directly,
* setting "serviceInterface" is sufficient. If exposing a non-RMI business
* interface, the business interface needs to be set as "serviceInterface",
* and the JAX-RPC port interface as "portInterface".
*
* @author Juergen Hoeller
* @since 15.12.2003
* @see #setPortName
* @see #setServiceInterface
* @see #setPortInterface
* @see javax.xml.rpc.Service#getPort
* @see javax.xml.rpc.Stub
* @see org.springframework.remoting.RemoteAccessException
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
implements MethodInterceptor, InitializingBean {
private Service jaxRpcService;
private String portName;
private String username;
private String password;
private String endpointAddress;
private boolean maintainSession;
private Properties customProperties;
private Class serviceInterface;
private Class portInterface;
private QName portQName;
private Remote portStub;
/**
* Set a reference to an existing JAX-RPC Service instance,
* for example looked up via JndiObjectFactoryBean.
* If not set, LocalJaxRpcServiceFactory's properties have to be specified.
* @see #setServiceFactoryClass
* @see #setWsdlDocumentUrl
* @see #setNamespaceUri
* @see #setServiceName
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public void setJaxRpcService(Service jaxRpcService) {
this.jaxRpcService = jaxRpcService;
}
/**
* Return a reference to an existing JAX-RPC Service instance, if any.
*/
public Service getJaxRpcService() {
return jaxRpcService;
}
/**
* Set the name of the port.
* Corresponds to the "wsdl:port" name.
*/
public void setPortName(String portName) {
this.portName = portName;
}
/**
* Return the name of the port.
*/
public String getPortName() {
return portName;
}
/**
* Set the username to specify on the stub or call.
* @see javax.xml.rpc.Stub#USERNAME_PROPERTY
* @see javax.xml.rpc.Call#USERNAME_PROPERTY
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Return the username to specify on the stub or call.
*/
public String getUsername() {
return username;
}
/**
* Set the password to specify on the stub or call.
* @see javax.xml.rpc.Stub#PASSWORD_PROPERTY
* @see javax.xml.rpc.Call#PASSWORD_PROPERTY
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Return the password to specify on the stub or call.
*/
public String getPassword() {
return password;
}
/**
* Set the endpoint address to specify on the stub or call.
* @see javax.xml.rpc.Stub#ENDPOINT_ADDRESS_PROPERTY
* @see javax.xml.rpc.Call#setTargetEndpointAddress
*/
public void setEndpointAddress(String endpointAddress) {
this.endpointAddress = endpointAddress;
}
/**
* Return the endpoint address to specify on the stub or call.
*/
public String getEndpointAddress() {
return endpointAddress;
}
/**
* Set the maintain session flag to specify on the stub or call.
* @see javax.xml.rpc.Stub#SESSION_MAINTAIN_PROPERTY
* @see javax.xml.rpc.Call#SESSION_MAINTAIN_PROPERTY
*/
public void setMaintainSession(boolean maintainSession) {
this.maintainSession = maintainSession;
}
/**
* Return the maintain session flag to specify on the stub or call.
*/
public boolean isMaintainSession() {
return maintainSession;
}
/**
* Set custom properties to be set on the stub or call.
* @see javax.xml.rpc.Stub#_setProperty
* @see javax.xml.rpc.Call#setProperty
*/
public void setCustomProperties(Properties customProperties) {
this.customProperties = customProperties;
}
/**
* Return custom properties to be set on the stub or call.
*/
public Properties getCustomProperties() {
return customProperties;
}
/**
* Set the interface of the service that this factory should create a proxy for.
* This will typically be a non-RMI business interface, although you can also
* use an RMI port interface as recommended by JAX-RPC here.
* <p>If the specified service interface is a non-RMI business interface,
* invocations will either be translated to the underlying RMI port interface
* (in case of a "portInterface" being specified) or to JAX-RPC dynamic calls.
* <p>The dynamic call mechanism has the advantage that you don't need to
* maintain an RMI port interface in addition to an existing non-RMI business
* interface. In terms of configuration, specifying the business interface
* as "serviceInterface" will be enough; this interceptor will automatically
* switch to dynamic calls in such a scenario.
* @see #setPortInterface
*/
public void setServiceInterface(Class serviceInterface) {
if (serviceInterface != null && !serviceInterface.isInterface()) {
throw new IllegalArgumentException("serviceInterface must be an interface");
}
this.serviceInterface = serviceInterface;
}
/**
* Return the interface of the service that this factory should create a proxy for.
*/
public Class getServiceInterface() {
return serviceInterface;
}
/**
* Set the JAX-RPC port interface to use. Only needs to be set if the exposed
* service interface is different from the port interface, i.e. when using
* a non-RMI business interface as service interface for exposed proxies,
* and if the JAX-RPC dynamic call mechanism is not desirable. See the
* javadoc of the "serviceInterface" property for more details.
* <p>The interface must be suitable for a JAX-RPC port, i.e. it must be an
* RMI service interface (that extends <code>java.rmi.Remote</code>).
* @see #setServiceInterface
* @see java.rmi.Remote
*/
public void setPortInterface(Class portInterface) {
if (portInterface != null &&
(!portInterface.isInterface() || !Remote.class.isAssignableFrom(portInterface))) {
throw new IllegalArgumentException(
"portInterface must be an interface derived from [java.rmi.Remote]");
}
this.portInterface = portInterface;
}
/**
* Return the JAX-RPC port interface to use.
*/
public Class getPortInterface() {
return portInterface;
}
public void afterPropertiesSet() throws ServiceException {
prepare();
}
/**
* Create and initialize the JAX-RPC service for the specified port.
* <p>Prepares a JAX-RPC stub if possible (if an RMI interface is available);
* falls back to JAX-RPC dynamic calls else. Using dynamic calls can be
* enforced through overriding <code>alwaysUseJaxRpcCall</code> to return true.
* <p><code>postProcessJaxRpcService</code> and <code>postProcessPortStub</code>
* hooks are available for customization in subclasses. When using dynamic calls,
* each can be post-processed via <code>postProcessJaxRpcCall</code>.
* @see #alwaysUseJaxRpcCall
* @see #postProcessJaxRpcService
* @see #postProcessPortStub
* @see #postProcessJaxRpcCall
*/
public void prepare() throws ServiceException {
if (this.portName == null) {
throw new IllegalArgumentException("portName is required");
}
if (this.jaxRpcService == null) {
this.jaxRpcService = createJaxRpcService();
}
// Cache the QName for the port.
this.portQName = getQName(this.portName);
// Determine interface to use at the JAX-RPC port level:
// Use portInterface if specified, else fall back to serviceInterface.
Class actualInterface = (this.portInterface != null ? this.portInterface : this.serviceInterface);
if (actualInterface != null && Remote.class.isAssignableFrom(actualInterface) &&
!alwaysUseJaxRpcCall()) {
// JAX-RPC-compliant port interface -> using JAX-RPC stub for port.
if (logger.isInfoEnabled()) {
logger.info("Creating JAX-RPC proxy for JAX-RPC port [" + this.portQName +
"], using port interface [" + actualInterface.getName() + "]");
}
Remote remoteObj = this.jaxRpcService.getPort(this.portQName, actualInterface);
if (logger.isInfoEnabled()) {
if (this.serviceInterface != null) {
boolean isImpl = this.serviceInterface.isInstance(remoteObj);
logger.info("Using service interface [" + this.serviceInterface.getName() + "] for JAX-RPC port [" +
this.portQName + "] - " + (!isImpl ? "not" : "") + " directly implemented");
}
}
if (!(remoteObj instanceof Stub)) {
throw new ServiceException("Port stub of class [" + remoteObj.getClass().getName() +
"] is not a valid JAX-RPC stub: it does not implement interface [javax.xml.rpc.Stub]");
}
Stub stub = (Stub) remoteObj;
// Apply properties to JAX-RPC stub.
preparePortStub(stub);
// Allow for custom post-processing in subclasses.
postProcessPortStub(stub);
this.portStub = remoteObj;
}
else {
// No JAX-RPC-compliant port interface -> using JAX-RPC dynamic calls.
if (logger.isInfoEnabled()) {
logger.info("Using JAX-RPC dynamic calls for JAX-RPC port [" + this.portQName + "]");
}
}
}
/**
* Return the prepared QName for the port.
* @see #setPortName
* @see #getQName
*/
protected QName getPortQName() {
return portQName;
}
/**
* Return whether to always use JAX-RPC dynamic calls.
* Called by <code>afterPropertiesSet</code>.
* <p>Default is false; if an RMI interface is specified as "portInterface"
* or "serviceInterface", it will be used to create a JAX-RPC port stub.
* <p>Can be overridden to enforce the use of the JAX-RPC Call API,
* for example if there is a need to customize at the Call level.
* This just necessary if you you want to use an RMI interface as
* "serviceInterface", though; in case of only a non-RMI interface being
* available, this interceptor will fall back to the Call API anyway.
* @see #postProcessJaxRpcCall
*/
protected boolean alwaysUseJaxRpcCall() {
return false;
}
/**
* Prepare the given JAX-RPC port stub, applying properties to it.
* Called by <code>afterPropertiesSet</code>.
* <p>Just applied when actually creating a JAX-RPC port stub,
* in case of a specified JAX-RPC-compliant port interface.
* Else, JAX-RPC dynamic calls will be used.
* @param stub the current JAX-RPC port stub
* @see #afterPropertiesSet
* @see #setUsername
* @see #setPassword
* @see #setEndpointAddress
* @see #setMaintainSession
* @see #setCustomProperties
* @see #setPortInterface
* @see #prepareJaxRpcCall
*/
protected void preparePortStub(Stub stub) {
if (this.username != null) {
stub._setProperty(Stub.USERNAME_PROPERTY, this.username);
}
if (this.password != null) {
stub._setProperty(Stub.PASSWORD_PROPERTY, this.password);
}
if (this.endpointAddress != null) {
stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, this.endpointAddress);
}
if (this.maintainSession) {
stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, new Boolean(this.maintainSession));
}
if (this.customProperties != null) {
Enumeration en = this.customProperties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
stub._setProperty(key, this.customProperties.getProperty(key));
}
}
}
/**
* Post-process the given JAX-RPC port stub.
* Default implementation is empty. Called by <code>prepare</code>.
* <p>Just applied when actually creating a JAX-RPC port stub,
* in case of a specified JAX-RPC-compliant port interface.
* Else, JAX-RPC dynamic calls will be used.
* @param stub the current JAX-RPC port stub
* (can be cast to an implementation-specific class if necessary)
* @see #prepare
* @see #setPortInterface
* @see #postProcessJaxRpcCall
*/
protected void postProcessPortStub(Stub stub) {
}
/**
* Return the underlying JAX-RPC port stub that this interceptor delegates to
* for each method invocation on the proxy.
*/
protected Remote getPortStub() {
return portStub;
}
public Object invoke(MethodInvocation invocation) throws Throwable {
if (AopUtils.isToStringMethod(invocation.getMethod())) {
return "JAX-RPC proxy for port [" + getPortName() + "] of service [" +
getJaxRpcService().getServiceName() + "]";
}
Remote stub = getPortStub();
if (stub != null) {
// JAX-RPC stub available -> traditional RMI stub invocation.
if (logger.isDebugEnabled()) {
logger.debug("Invoking operation '" + invocation.getMethod().getName() +
"' on JAX-RPC port stub");
}
return RmiClientInterceptorUtils.invoke(invocation, stub, getPortQName().toString());
}
else {
// No JAX-RPC stub -> using JAX-RPC dynamic calls.
if (logger.isDebugEnabled()) {
logger.debug("Invoking operation '" + invocation.getMethod().getName() +
"' as JAX-RPC dynamic call");
}
return performJaxRpcCall(invocation);
}
}
/**
* Perform a JAX-RPC dynamic call for the given AOP method invocation.
* Delegates to <code>prepareJaxRpcCall</code> and
* <code>postProcessJaxRpcCall</code> for setting up the call object.
* <p>Default implementation uses method name as JAX-RPC operation name
* and method arguments as arguments for the JAX-RPC call. Can be
* overridden in subclasses for custom operation names and/or arguments.
* @param invocation the current AOP MethodInvocation that should
* be converted to a JAX-RPC call
* @return the return value of the invocation, if any
* @throws Throwable the exception thrown by the invocation, if any
* @see #getJaxRpcService
* @see #getPortQName
* @see #prepareJaxRpcCall
* @see #postProcessJaxRpcCall
*/
protected Object performJaxRpcCall(MethodInvocation invocation) throws Throwable {
Service service = getJaxRpcService();
if (service == null) {
throw new IllegalStateException("JaxRpcClientInterceptor is not properly initialized - " +
"invoke 'prepare' before attempting any operations");
}
QName portQName = getPortQName();
// Create JAX-RPC call object, using the method name as operation name.
Call call = service.createCall(portQName, invocation.getMethod().getName());
// Apply properties to JAX-RPC stub.
prepareJaxRpcCall(call);
// Allow for custom post-processing in subclasses.
postProcessJaxRpcCall(call, invocation);
// Perform actual invocation.
try {
return call.invoke(invocation.getArguments());
}
catch (RemoteException ex) {
throw RmiClientInterceptorUtils.convertRmiAccessException(
invocation.getMethod(), ex, portQName.toString());
}
}
/**
* Prepare the given JAX-RPC call, applying properties to it.
* Called by <code>invoke</code>.
* <p>Just applied when actually using JAX-RPC dynamic calls,
* i.e. if no JAX-RPC-compliant port interface was specified.
* Else, a JAX-RPC port stub will be used.
* @param call the current JAX-RPC call object
* @see #invoke
* @see #setUsername
* @see #setPassword
* @see #setEndpointAddress
* @see #setMaintainSession
* @see #setCustomProperties
* @see #setPortInterface
* @see #preparePortStub
*/
protected void prepareJaxRpcCall(Call call) {
if (this.username != null) {
call.setProperty(Call.USERNAME_PROPERTY, this.username);
}
if (this.password != null) {
call.setProperty(Call.PASSWORD_PROPERTY, this.password);
}
if (this.endpointAddress != null) {
call.setTargetEndpointAddress(this.endpointAddress);
}
if (this.maintainSession) {
call.setProperty(Call.SESSION_MAINTAIN_PROPERTY, new Boolean(this.maintainSession));
}
if (this.customProperties != null) {
Enumeration en = this.customProperties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
call.setProperty(key, this.customProperties.getProperty(key));
}
}
}
/**
* Post-process the given JAX-RPC call.
* Default implementation is empty. Called by <code>invoke</code>.
* <p>Just applied when actually using JAX-RPC dynamic calls,
* i.e. if no JAX-RPC-compliant port interface was specified.
* Else, a JAX-RPC port stub will be used.
* @param call the current JAX-RPC call object
* (can be cast to an implementation-specific class if necessary)
* @param invocation the current AOP MethodInvocation that the call was
* created for (can be used to check method name, method parameters
* and/or passed-in arguments)
* @see #invoke
* @see #setPortInterface
* @see #postProcessPortStub
*/
protected void postProcessJaxRpcCall(Call call, MethodInvocation invocation) {
}
}
| src/org/springframework/remoting/jaxrpc/JaxRpcPortClientInterceptor.java | /*
* Copyright 2002-2004 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.springframework.remoting.jaxrpc;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.rmi.RmiClientInterceptorUtils;
/**
* Interceptor for accessing a specific port of a JAX-RPC service.
* Uses either LocalJaxRpcServiceFactory's facilities underneath,
* or takes an explicit reference to an existing JAX-RPC Service instance
* (for example looked up via JndiObjectFactoryBean).
*
* <p>Allows to set JAX-RPC's standard stub properties directly, via the
* "username", "password", "endpointAddress" and "maintainSession" properties.
* For typical usage, it is not necessary to specify those, though.
*
* <p>This invoker is typically used with an RMI service interface. Alternatively,
* this invoker can also proxy a JAX-RPC service with a matching non-RMI business
* interface, i.e. an interface that mirrors the RMI service methods but does not
* declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the
* JAX-RPC stub will automatically get converted to Spring's unchecked
* RemoteAccessException.
*
* <p>If exposing the JAX-RPC port interface (i.e. an RMI interface) directly,
* setting "serviceInterface" is sufficient. If exposing a non-RMI business
* interface, the business interface needs to be set as "serviceInterface",
* and the JAX-RPC port interface as "portInterface".
*
* @author Juergen Hoeller
* @since 15.12.2003
* @see #setPortName
* @see #setServiceInterface
* @see #setPortInterface
* @see javax.xml.rpc.Service#getPort
* @see javax.xml.rpc.Stub
* @see org.springframework.remoting.RemoteAccessException
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
implements MethodInterceptor, InitializingBean {
private Service jaxRpcService;
private String portName;
private String username;
private String password;
private String endpointAddress;
private boolean maintainSession;
private Properties customProperties;
private Class serviceInterface;
private Class portInterface;
private QName portQName;
private Remote portStub;
/**
* Set a reference to an existing JAX-RPC Service instance,
* for example looked up via JndiObjectFactoryBean.
* If not set, LocalJaxRpcServiceFactory's properties have to be specified.
* @see #setServiceFactoryClass
* @see #setWsdlDocumentUrl
* @see #setNamespaceUri
* @see #setServiceName
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public void setJaxRpcService(Service jaxRpcService) {
this.jaxRpcService = jaxRpcService;
}
/**
* Return a reference to an existing JAX-RPC Service instance, if any.
*/
public Service getJaxRpcService() {
return jaxRpcService;
}
/**
* Set the name of the port.
* Corresponds to the "wsdl:port" name.
*/
public void setPortName(String portName) {
this.portName = portName;
}
/**
* Return the name of the port.
*/
public String getPortName() {
return portName;
}
/**
* Set the username to specify on the stub or call.
* @see javax.xml.rpc.Stub#USERNAME_PROPERTY
* @see javax.xml.rpc.Call#USERNAME_PROPERTY
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Return the username to specify on the stub or call.
*/
public String getUsername() {
return username;
}
/**
* Set the password to specify on the stub or call.
* @see javax.xml.rpc.Stub#PASSWORD_PROPERTY
* @see javax.xml.rpc.Call#PASSWORD_PROPERTY
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Return the password to specify on the stub or call.
*/
public String getPassword() {
return password;
}
/**
* Set the endpoint address to specify on the stub or call.
* @see javax.xml.rpc.Stub#ENDPOINT_ADDRESS_PROPERTY
* @see javax.xml.rpc.Call#setTargetEndpointAddress
*/
public void setEndpointAddress(String endpointAddress) {
this.endpointAddress = endpointAddress;
}
/**
* Return the endpoint address to specify on the stub or call.
*/
public String getEndpointAddress() {
return endpointAddress;
}
/**
* Set the maintain session flag to specify on the stub or call.
* @see javax.xml.rpc.Stub#SESSION_MAINTAIN_PROPERTY
* @see javax.xml.rpc.Call#SESSION_MAINTAIN_PROPERTY
*/
public void setMaintainSession(boolean maintainSession) {
this.maintainSession = maintainSession;
}
/**
* Return the maintain session flag to specify on the stub or call.
*/
public boolean isMaintainSession() {
return maintainSession;
}
/**
* Set custom properties to be set on the stub or call.
* @see javax.xml.rpc.Stub#_setProperty
* @see javax.xml.rpc.Call#setProperty
*/
public void setCustomProperties(Properties customProperties) {
this.customProperties = customProperties;
}
/**
* Return custom properties to be set on the stub or call.
*/
public Properties getCustomProperties() {
return customProperties;
}
/**
* Set the interface of the service that this factory should create a proxy for.
* This will typically be a non-RMI business interface, although you can also
* use an RMI port interface as recommended by JAX-RPC here.
* <p>If the specified service interface is a non-RMI business interface,
* invocations will either be translated to the underlying RMI port interface
* (in case of a "portInterface" being specified) or to JAX-RPC dynamic calls.
* <p>The dynamic call mechanism has the advantage that you don't need to
* maintain an RMI port interface in addition to an existing non-RMI business
* interface. In terms of configuration, specifying the business interface
* as "serviceInterface" will be enough; this interceptor will automatically
* switch to dynamic calls in such a scenario.
* @see #setPortInterface
*/
public void setServiceInterface(Class serviceInterface) {
if (serviceInterface != null && !serviceInterface.isInterface()) {
throw new IllegalArgumentException("serviceInterface must be an interface");
}
this.serviceInterface = serviceInterface;
}
/**
* Return the interface of the service that this factory should create a proxy for.
*/
public Class getServiceInterface() {
return serviceInterface;
}
/**
* Set the JAX-RPC port interface to use. Only needs to be set if the exposed
* service interface is different from the port interface, i.e. when using
* a non-RMI business interface as service interface for exposed proxies,
* and if the JAX-RPC dynamic call mechanism is not desirable. See the
* javadoc of the "serviceInterface" property for more details.
* <p>The interface must be suitable for a JAX-RPC port, i.e. it must be an
* RMI service interface (that extends <code>java.rmi.Remote</code>).
* @see #setServiceInterface
* @see java.rmi.Remote
*/
public void setPortInterface(Class portInterface) {
if (portInterface != null &&
(!portInterface.isInterface() || !Remote.class.isAssignableFrom(portInterface))) {
throw new IllegalArgumentException(
"portInterface must be an interface derived from [java.rmi.Remote]");
}
this.portInterface = portInterface;
}
/**
* Return the JAX-RPC port interface to use.
*/
public Class getPortInterface() {
return portInterface;
}
public void afterPropertiesSet() throws ServiceException {
prepare();
}
/**
* Create and initialize the JAX-RPC service for the specified port.
* <p>Prepares a JAX-RPC stub if possible (if an RMI interface is available);
* falls back to JAX-RPC dynamic calls else. Using dynamic calls can be
* enforced through overriding <code>alwaysUseJaxRpcCall</code> to return true.
* <p><code>postProcessJaxRpcService</code> and <code>postProcessPortStub</code>
* hooks are available for customization in subclasses. When using dynamic calls,
* each can be post-processed via <code>postProcessJaxRpcCall</code>.
* @see #alwaysUseJaxRpcCall
* @see #postProcessJaxRpcService
* @see #postProcessPortStub
* @see #postProcessJaxRpcCall
*/
public void prepare() throws ServiceException {
if (this.portName == null) {
throw new IllegalArgumentException("portName is required");
}
if (this.jaxRpcService == null) {
this.jaxRpcService = createJaxRpcService();
}
// Cache the QName for the port.
this.portQName = getQName(this.portName);
// Determine interface to use at the JAX-RPC port level:
// Use portInterface if specified, else fall back to serviceInterface.
Class actualInterface = (this.portInterface != null ? this.portInterface : this.serviceInterface);
if (actualInterface != null && Remote.class.isAssignableFrom(actualInterface) &&
!alwaysUseJaxRpcCall()) {
// JAX-RPC-compliant port interface -> using JAX-RPC stub for port.
if (logger.isInfoEnabled()) {
logger.info("Creating JAX-RPC proxy for JAX-RPC port [" + this.portQName +
"], using port interface [" + actualInterface.getName() + "]");
}
Remote remoteObj = this.jaxRpcService.getPort(this.portQName, actualInterface);
if (logger.isInfoEnabled()) {
if (this.serviceInterface != null) {
boolean isImpl = this.serviceInterface.isInstance(remoteObj);
logger.info("Using service interface [" + this.serviceInterface.getName() + "] for JAX-RPC port [" +
this.portQName + "] - " + (!isImpl ? "not" : "") + " directly implemented");
}
}
if (!(remoteObj instanceof Stub)) {
throw new ServiceException("Port stub of class [" + remoteObj.getClass().getName() +
"] is not a valid JAX-RPC stub: it does not implement interface [javax.xml.rpc.Stub]");
}
Stub stub = (Stub) remoteObj;
// Apply properties to JAX-RPC stub.
preparePortStub(stub);
// Allow for custom post-processing in subclasses.
postProcessPortStub(stub);
this.portStub = remoteObj;
}
else {
// No JAX-RPC-compliant port interface -> using JAX-RPC dynamic calls.
if (logger.isInfoEnabled()) {
logger.info("Using JAX-RPC dynamic calls for JAX-RPC port [" + this.portQName + "]");
}
}
}
/**
* Return the prepared QName for the port.
* @see #setPortName
* @see #getQName
*/
protected QName getPortQName() {
return portQName;
}
/**
* Return whether to always use JAX-RPC dynamic calls.
* Called by <code>afterPropertiesSet</code>.
* <p>Default is false; if an RMI interface is specified as "portInterface"
* or "serviceInterface", it will be used to create a JAX-RPC port stub.
* <p>Can be overridden to enforce the use of the JAX-RPC Call API,
* for example if there is a need to customize at the Call level.
* This just necessary if you you want to use an RMI interface as
* "serviceInterface", though; in case of only a non-RMI interface being
* available, this interceptor will fall back to the Call API anyway.
* @see #postProcessJaxRpcCall
*/
protected boolean alwaysUseJaxRpcCall() {
return false;
}
/**
* Prepare the given JAX-RPC port stub, applying properties to it.
* Called by <code>afterPropertiesSet</code>.
* <p>Just applied when actually creating a JAX-RPC port stub,
* in case of a specified JAX-RPC-compliant port interface.
* Else, JAX-RPC dynamic calls will be used.
* @param stub the current JAX-RPC port stub
* @see #afterPropertiesSet
* @see #setUsername
* @see #setPassword
* @see #setEndpointAddress
* @see #setMaintainSession
* @see #setCustomProperties
* @see #setPortInterface
* @see #prepareJaxRpcCall
*/
protected void preparePortStub(Stub stub) {
if (this.username != null) {
stub._setProperty(Stub.USERNAME_PROPERTY, this.username);
}
if (this.password != null) {
stub._setProperty(Stub.PASSWORD_PROPERTY, this.password);
}
if (this.endpointAddress != null) {
stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, this.endpointAddress);
}
if (this.maintainSession) {
stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, new Boolean(this.maintainSession));
}
if (this.customProperties != null) {
Enumeration en = this.customProperties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
stub._setProperty(key, this.customProperties.getProperty(key));
}
}
}
/**
* Post-process the given JAX-RPC port stub.
* Default implementation is empty. Called by <code>prepare</code>.
* <p>Just applied when actually creating a JAX-RPC port stub,
* in case of a specified JAX-RPC-compliant port interface.
* Else, JAX-RPC dynamic calls will be used.
* @param stub the current JAX-RPC port stub
* (can be cast to an implementation-specific class if necessary)
* @see #prepare
* @see #setPortInterface
* @see #postProcessJaxRpcCall
*/
protected void postProcessPortStub(Stub stub) {
}
/**
* Return the underlying JAX-RPC port stub that this interceptor delegates to
* for each method invocation on the proxy.
*/
protected Remote getPortStub() {
return portStub;
}
public Object invoke(MethodInvocation invocation) throws Throwable {
Remote stub = getPortStub();
if (stub != null) {
// JAX-RPC stub available -> traditional RMI stub invocation.
if (logger.isDebugEnabled()) {
logger.debug("Invoking operation '" + invocation.getMethod().getName() +
"' on JAX-RPC port stub");
}
return RmiClientInterceptorUtils.invoke(invocation, stub, getPortQName().toString());
}
else {
// No JAX-RPC stub -> using JAX-RPC dynamic calls.
if (logger.isDebugEnabled()) {
logger.debug("Invoking operation '" + invocation.getMethod().getName() +
"' as JAX-RPC dynamic call");
}
return performJaxRpcCall(invocation);
}
}
/**
* Perform a JAX-RPC dynamic call for the given AOP method invocation.
* Delegates to <code>prepareJaxRpcCall</code> and
* <code>postProcessJaxRpcCall</code> for setting up the call object.
* <p>Default implementation uses method name as JAX-RPC operation name
* and method arguments as arguments for the JAX-RPC call. Can be
* overridden in subclasses for custom operation names and/or arguments.
* @param invocation the current AOP MethodInvocation that should
* be converted to a JAX-RPC call
* @return the return value of the invocation, if any
* @throws Throwable the exception thrown by the invocation, if any
* @see #getJaxRpcService
* @see #getPortQName
* @see #prepareJaxRpcCall
* @see #postProcessJaxRpcCall
*/
protected Object performJaxRpcCall(MethodInvocation invocation) throws Throwable {
Service service = getJaxRpcService();
if (service == null) {
throw new IllegalStateException("JaxRpcClientInterceptor is not properly initialized - " +
"invoke 'prepare' before attempting any operations");
}
QName portQName = getPortQName();
// Create JAX-RPC call object, using the method name as operation name.
Call call = service.createCall(portQName, invocation.getMethod().getName());
// Apply properties to JAX-RPC stub.
prepareJaxRpcCall(call);
// Allow for custom post-processing in subclasses.
postProcessJaxRpcCall(call, invocation);
// Perform actual invocation.
try {
return call.invoke(invocation.getArguments());
}
catch (RemoteException ex) {
throw RmiClientInterceptorUtils.convertRmiAccessException(
invocation.getMethod(), ex, portQName.toString());
}
}
/**
* Prepare the given JAX-RPC call, applying properties to it.
* Called by <code>invoke</code>.
* <p>Just applied when actually using JAX-RPC dynamic calls,
* i.e. if no JAX-RPC-compliant port interface was specified.
* Else, a JAX-RPC port stub will be used.
* @param call the current JAX-RPC call object
* @see #invoke
* @see #setUsername
* @see #setPassword
* @see #setEndpointAddress
* @see #setMaintainSession
* @see #setCustomProperties
* @see #setPortInterface
* @see #preparePortStub
*/
protected void prepareJaxRpcCall(Call call) {
if (this.username != null) {
call.setProperty(Call.USERNAME_PROPERTY, this.username);
}
if (this.password != null) {
call.setProperty(Call.PASSWORD_PROPERTY, this.password);
}
if (this.endpointAddress != null) {
call.setTargetEndpointAddress(this.endpointAddress);
}
if (this.maintainSession) {
call.setProperty(Call.SESSION_MAINTAIN_PROPERTY, new Boolean(this.maintainSession));
}
if (this.customProperties != null) {
Enumeration en = this.customProperties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
call.setProperty(key, this.customProperties.getProperty(key));
}
}
}
/**
* Post-process the given JAX-RPC call.
* Default implementation is empty. Called by <code>invoke</code>.
* <p>Just applied when actually using JAX-RPC dynamic calls,
* i.e. if no JAX-RPC-compliant port interface was specified.
* Else, a JAX-RPC port stub will be used.
* @param call the current JAX-RPC call object
* (can be cast to an implementation-specific class if necessary)
* @param invocation the current AOP MethodInvocation that the call was
* created for (can be used to check method name, method parameters
* and/or passed-in arguments)
* @see #invoke
* @see #setPortInterface
* @see #postProcessPortStub
*/
protected void postProcessJaxRpcCall(Call call, MethodInvocation invocation) {
}
}
| returns own proxy description on "toString" (to avoid "toString" failure on Axis)
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@4760 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| src/org/springframework/remoting/jaxrpc/JaxRpcPortClientInterceptor.java | returns own proxy description on "toString" (to avoid "toString" failure on Axis) |
|
Java | apache-2.0 | 894c60fde7152cd3ad30ca90c038be2c26526da5 | 0 | Overseas-Student-Living/jackrabbit,tripodsan/jackrabbit,bartosz-grabski/jackrabbit,Kast0rTr0y/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,Kast0rTr0y/jackrabbit,bartosz-grabski/jackrabbit,bartosz-grabski/jackrabbit,kigsmtua/jackrabbit,Overseas-Student-Living/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,SylvesterAbreu/jackrabbit,SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,sdmcraft/jackrabbit,tripodsan/jackrabbit,SylvesterAbreu/jackrabbit,tripodsan/jackrabbit,afilimonov/jackrabbit,sdmcraft/jackrabbit | /*
* 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.jackrabbit.commons.observation;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.nanoTime;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import org.apache.jackrabbit.api.jmx.EventListenerMBean;
import org.apache.jackrabbit.api.observation.JackrabbitEvent;
import org.apache.jackrabbit.commons.iterator.EventIteratorAdapter;
/**
* Tracks event deliveries to an event listener and the way the listener
* processes the events. The collected information is made available through
* the {@link EventListenerMBean} interface.
*/
public class ListenerTracker {
private final EventListener listener;
private final int eventTypes;
private final String absPath;
private final boolean isDeep;
private final String[] uuid;
private final String[] nodeTypeName;
private final boolean noLocal;
protected final Exception initStackTrace =
new Exception("The event listener was registered here:");
private final long startTime = currentTimeMillis();
private final AtomicLong eventDeliveries = new AtomicLong();
private final AtomicLong eventsDelivered = new AtomicLong();
private final AtomicLong eventDeliveryTime = new AtomicLong();
final AtomicBoolean userInfoAccessedWithoutExternalsCheck =
new AtomicBoolean();
final AtomicBoolean userInfoAccessedFromExternalEvent =
new AtomicBoolean();
final AtomicBoolean dateAccessedWithoutExternalsCheck =
new AtomicBoolean();
final AtomicBoolean dateAccessedFromExternalEvent =
new AtomicBoolean();
public ListenerTracker(
EventListener listener,
int eventTypes, String absPath, boolean isDeep,
String[] uuid, String[] nodeTypeName, boolean noLocal) {
this.listener = listener;
this.eventTypes = eventTypes;
this.absPath = absPath;
this.isDeep = isDeep;
this.uuid = copy(uuid);
this.nodeTypeName = copy(nodeTypeName);
this.noLocal = noLocal;
}
/**
* Called to log a deprecation warning about the detected behavior of
* the decorated listener. Subclasses should override this method that
* by default does nothing.
*
* @param message warning message
*/
protected void warn(String message) {
// do nothing
}
public EventListener getTrackedListener() {
return new EventListener() {
@Override
public void onEvent(EventIterator events) {
eventDeliveries.incrementAndGet();
long start = nanoTime();
try {
listener.onEvent(new EventIteratorAdapter(events) {
@Override
public Object next() {
eventsDelivered.incrementAndGet();
Object object = super.next();
if (object instanceof JackrabbitEvent) {
object = new JackrabbitEventTracker(
ListenerTracker.this,
(JackrabbitEvent) object);
} else if (object instanceof Event) {
object = new EventTracker(
ListenerTracker.this, (Event) object);
}
return object;
}
});
} finally {
eventDeliveryTime.addAndGet(nanoTime() - start);
}
}
};
}
public EventListenerMBean getListenerMBean() {
return new EventListenerMBean() {
@Override
public String getClassName() {
return listener.getClass().getName();
}
@Override
public String getInitStackTrace() {
StringWriter writer = new StringWriter();
initStackTrace.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
@Override
public int getEventTypes() {
return eventTypes;
}
@Override
public String getAbsPath() {
return absPath;
}
@Override
public boolean isDeep() {
return isDeep;
}
@Override
public String[] getUuid() {
return copy(uuid);
}
@Override
public String[] getNodeTypeName() {
return copy(nodeTypeName);
}
@Override
public boolean isNoLocal() {
return noLocal;
}
@Override
public long getEventDeliveries() {
return eventDeliveries.get();
}
@Override
public long getEventDeliveriesPerHour() {
return TimeUnit.HOURS.toMillis(getEventDeliveries())
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public long getMicrosecondsPerEventDelivery() {
return TimeUnit.NANOSECONDS.toMicros(eventDeliveryTime.get())
/ Math.max(getEventDeliveries(), 1);
}
@Override
public long getEventsDelivered() {
return eventsDelivered.get();
}
@Override
public long getEventsDeliveredPerHour() {
return TimeUnit.HOURS.toMillis(getEventsDelivered())
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public long getMicrosecondsPerEventDelivered() {
return TimeUnit.NANOSECONDS.toMicros(eventDeliveryTime.get())
/ Math.max(getEventsDelivered(), 1);
}
@Override
public double getRatioOfTimeSpentProcessingEvents() {
double timeSpentProcessingEvents =
TimeUnit.NANOSECONDS.toMillis(eventDeliveryTime.get());
return timeSpentProcessingEvents
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public boolean isUserInfoAccessedWithoutExternalsCheck() {
return userInfoAccessedWithoutExternalsCheck.get();
}
@Override
public synchronized boolean isUserInfoAccessedFromExternalEvent() {
return userInfoAccessedFromExternalEvent.get();
}
@Override
public synchronized boolean isDateAccessedWithoutExternalsCheck() {
return dateAccessedWithoutExternalsCheck.get();
}
@Override
public synchronized boolean isDateAccessedFromExternalEvent() {
return dateAccessedFromExternalEvent.get();
}
};
}
//------------------------------------------------------------< Object >--
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (absPath != null) {
builder.append(absPath);
}
if (isDeep) {
builder.append("//*");
} else {
builder.append("/*");
}
builder.append('[');
builder.append(Integer.toBinaryString(eventTypes));
builder.append('b');
if (uuid != null) {
for (String id : uuid) {
builder.append(", ");
builder.append(id);
}
}
if (nodeTypeName != null) {
for (String name : nodeTypeName) {
builder.append(", ");
builder.append(name);
}
}
if (noLocal) {
builder.append(", local");
}
builder.append(']');
return listener.getClass().getSimpleName();
}
//-----------------------------------------------------------< private >--
private static String[] copy(String[] array) {
if (array != null && array.length > 0) {
String[] copy = new String[array.length];
System.arraycopy(array, 0, copy, 0, array.length);
return copy;
} else {
return array;
}
}
}
| jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/observation/ListenerTracker.java | /*
* 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.jackrabbit.commons.observation;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.nanoTime;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import org.apache.jackrabbit.api.jmx.EventListenerMBean;
import org.apache.jackrabbit.api.observation.JackrabbitEvent;
import org.apache.jackrabbit.commons.iterator.EventIteratorAdapter;
/**
* Tracks event deliveries to an event listener and the way the listener
* processes the events. The collected information is made available through
* the {@link EventListenerMBean} interface.
*/
public class ListenerTracker {
private final EventListener listener;
private final int eventTypes;
private final String absPath;
private final boolean isDeep;
private final String[] uuid;
private final String[] nodeTypeName;
private final boolean noLocal;
protected final Exception initStackTrace =
new Exception("The event listener was registered here:");
private final long startTime = currentTimeMillis();
private final AtomicLong eventDeliveries = new AtomicLong();
private final AtomicLong eventsDelivered = new AtomicLong();
private final AtomicLong eventDeliveryTime = new AtomicLong();
final AtomicBoolean userInfoAccessedWithoutExternalsCheck =
new AtomicBoolean();
final AtomicBoolean userInfoAccessedFromExternalEvent =
new AtomicBoolean();
final AtomicBoolean dateAccessedWithoutExternalsCheck =
new AtomicBoolean();
final AtomicBoolean dateAccessedFromExternalEvent =
new AtomicBoolean();
public ListenerTracker(
EventListener listener,
int eventTypes, String absPath, boolean isDeep,
String[] uuid, String[] nodeTypeName, boolean noLocal) {
this.listener = listener;
this.eventTypes = eventTypes;
this.absPath = absPath;
this.isDeep = isDeep;
this.uuid = copy(uuid);
this.nodeTypeName = copy(nodeTypeName);
this.noLocal = noLocal;
}
/**
* Called to log a deprecation warning about the detected behavior of
* the decorated listener. Subclasses should override this method that
* by default does nothing.
*
* @param message warning message
*/
protected void warn(String message) {
// do nothing
}
public EventListener getTrackedListener() {
return new EventListener() {
@Override
public void onEvent(EventIterator events) {
eventDeliveries.incrementAndGet();
long start = nanoTime();
try {
listener.onEvent(new EventIteratorAdapter(events) {
@Override
public Object next() {
eventsDelivered.incrementAndGet();
Object object = super.next();
if (object instanceof JackrabbitEvent) {
object = new JackrabbitEventTracker(
ListenerTracker.this,
(JackrabbitEvent) object);
} else if (object instanceof Event) {
object = new EventTracker(
ListenerTracker.this, (Event) object);
}
return object;
}
});
} finally {
eventDeliveryTime.addAndGet(nanoTime() - start);
}
}
};
}
public EventListenerMBean getListenerMBean() {
return new EventListenerMBean() {
@Override
public String getClassName() {
return listener.getClass().getName();
}
@Override
public String getInitStackTrace() {
StringWriter writer = new StringWriter();
initStackTrace.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
@Override
public int getEventTypes() {
return eventTypes;
}
@Override
public String getAbsPath() {
return absPath;
}
@Override
public boolean isDeep() {
return isDeep;
}
@Override
public String[] getUuid() {
return copy(uuid);
}
@Override
public String[] getNodeTypeName() {
return copy(nodeTypeName);
}
@Override
public boolean isNoLocal() {
return noLocal;
}
@Override
public long getEventDeliveries() {
return eventDeliveries.get();
}
@Override
public long getEventDeliveriesPerHour() {
return TimeUnit.HOURS.toMillis(getEventDeliveries())
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public long getMicrosecondsPerEventDelivery() {
return TimeUnit.NANOSECONDS.toMicros(eventDeliveryTime.get())
/ Math.max(getEventDeliveries(), 1);
}
@Override
public long getEventsDelivered() {
return eventsDelivered.get();
}
@Override
public long getEventsDeliveredPerHour() {
return TimeUnit.HOURS.toMillis(getEventsDelivered())
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public long getMicrosecondsPerEventDelivered() {
return TimeUnit.NANOSECONDS.toMicros(eventDeliveryTime.get())
/ Math.max(getEventsDelivered(), 1);
}
@Override
public double getRatioOfTimeSpentProcessingEvents() {
double timeSpentProcessingEvents =
TimeUnit.NANOSECONDS.toMillis(eventDeliveryTime.get());
return timeSpentProcessingEvents
/ Math.max(currentTimeMillis() - startTime, 1);
}
@Override
public boolean isUserInfoAccessedWithoutExternalsCheck() {
return userInfoAccessedWithoutExternalsCheck.get();
}
@Override
public synchronized boolean isUserInfoAccessedFromExternalEvent() {
return userInfoAccessedFromExternalEvent.get();
}
@Override
public synchronized boolean isDateAccessedWithoutExternalsCheck() {
return dateAccessedWithoutExternalsCheck.get();
}
@Override
public synchronized boolean isDateAccessedFromExternalEvent() {
return dateAccessedFromExternalEvent.get();
}
};
}
//------------------------------------------------------------< Object >--
@Override
public String toString() {
return listener.getClass().getSimpleName();
}
//-----------------------------------------------------------< private >--
private static String[] copy(String[] array) {
if (array != null && array.length > 0) {
String[] copy = new String[array.length];
System.arraycopy(array, 0, copy, 0, array.length);
return copy;
} else {
return array;
}
}
}
| JCR-3608: MBeans for tracking event listeners
Better toString() method for the ListenerTracker
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1494169 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/observation/ListenerTracker.java | JCR-3608: MBeans for tracking event listeners |
|
Java | apache-2.0 | 2b1eef93fd2c0fe5049f79ad3fcb8778fbdbcb50 | 0 | xnslong/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2 | /*
* 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.log4j.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.appender.NullAppender;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.Strings;
/**
* Experimental parser for Log4j 1.2 properties configuration files.
*
* This class is not thread-safe.
*
* <p>
* From the Log4j 1.2 Javadocs:
* </p>
* <p>
* All option values admit variable substitution. The syntax of variable substitution is similar to that of Unix shells. The string between
* an opening "${" and closing "}" is interpreted as a key. The value of the substituted variable can be defined as a system property or in
* the configuration file itself. The value of the key is first searched in the system properties, and if not found there, it is then
* searched in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. For example, if java.home
* system property is set to /home/xyz, then every occurrence of the sequence ${java.home} will be interpreted as /home/xyz.
* </p>
*/
public class Log4j1ConfigurationParser {
private static final String COMMA_DELIMITED_RE = "\\s*,\\s*";
private static final String ROOTLOGGER = "rootLogger";
private static final String ROOTCATEGORY = "rootCategory";
private static final String TRUE = "true";
private static final String FALSE = "false";
private final Properties properties = new Properties();
private StrSubstitutor strSubstitutorProperties;
private StrSubstitutor strSubstitutorSystem;
private final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
.newConfigurationBuilder();
/**
* Parses a Log4j 1.2 properties configuration file in ISO 8859-1 encoding into a ConfigurationBuilder.
*
* @param input
* InputStream to read from is assumed to be ISO 8859-1, and will not be closed.
* @return the populated ConfigurationBuilder, never {@literal null}
* @throws IOException
* if unable to read the input
* @throws ConfigurationException
* if the input does not contain a valid configuration
*/
public ConfigurationBuilder<BuiltConfiguration> buildConfigurationBuilder(final InputStream input)
throws IOException {
try {
properties.load(input);
strSubstitutorProperties = new StrSubstitutor(properties);
strSubstitutorSystem = new StrSubstitutor(System.getProperties());
final String rootCategoryValue = getLog4jValue(ROOTCATEGORY);
final String rootLoggerValue = getLog4jValue(ROOTLOGGER);
if (rootCategoryValue == null && rootLoggerValue == null) {
// This is not a Log4j 1 properties configuration file.
warn("Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
// throw new ConfigurationException(
// "Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
}
builder.setConfigurationName("Log4j1");
// DEBUG
final String debugValue = getLog4jValue("debug");
if (Boolean.valueOf(debugValue)) {
builder.setStatusLevel(Level.DEBUG);
}
// Root
final String[] sortedAppenderNamesC = buildRootLogger(getLog4jValue(ROOTCATEGORY));
final String[] sortedAppenderNamesL = buildRootLogger(getLog4jValue(ROOTLOGGER));
final String[] sortedAppenderNames = sortedAppenderNamesL.length > 0 ? sortedAppenderNamesL
: sortedAppenderNamesC;
// Appenders
final Map<String, String> classNameToProperty = buildClassToPropertyPrefixMap(sortedAppenderNames);
for (final Map.Entry<String, String> entry : classNameToProperty.entrySet()) {
final String appenderName = entry.getKey();
final String appenderClass = entry.getValue();
buildAppender(appenderName, appenderClass);
}
// Loggers
buildLoggers("log4j.category.");
buildLoggers("log4j.logger.");
buildProperties();
return builder;
} catch (final IllegalArgumentException e) {
throw new ConfigurationException(e);
}
}
private void buildProperties() {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
final String key = entry.getKey().toString();
if (!key.startsWith("log4j.") && !key.equals(ROOTCATEGORY) && !key.equals(ROOTLOGGER)) {
builder.addProperty(key, Objects.toString(entry.getValue(), Strings.EMPTY));
}
}
}
private void warn(String string) {
System.err.println(string);
}
private Map<String, String> buildClassToPropertyPrefixMap(final String[] sortedAppenderNames) {
final String prefix = "log4j.appender.";
final int preLength = prefix.length();
final Map<String, String> map = new HashMap<>(sortedAppenderNames.length);
for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
final Object keyObj = entry.getKey();
if (keyObj != null) {
final String key = keyObj.toString();
if (key.startsWith(prefix)) {
if (key.indexOf('.', preLength) < 0) {
final String name = key.substring(preLength);
if (Arrays.binarySearch(sortedAppenderNames, name) == -1) {
final Object value = entry.getValue();
if (value != null) {
map.put(name, value.toString());
}
}
}
}
}
}
return map;
}
private void buildAppender(final String appenderName, final String appenderClass) {
switch (appenderClass) {
case "org.apache.log4j.ConsoleAppender":
buildConsoleAppender(appenderName);
break;
case "org.apache.log4j.FileAppender":
buildFileAppender(appenderName);
break;
case "org.apache.log4j.DailyRollingFileAppender":
buildDailyRollingFileAppender(appenderName);
break;
case "org.apache.log4j.RollingFileAppender":
buildRollingFileAppender(appenderName);
break;
case "org.apache.log4j.varia.NullAppender":
buildNullAppender(appenderName);
break;
default:
reportWarning("Unknown appender class: " + appenderClass + "; ignoring appender: " + appenderName);
}
}
private void buildConsoleAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, ConsoleAppender.PLUGIN_NAME);
final String targetValue = getLog4jAppenderValue(appenderName, "Target", "System.out");
if (targetValue != null) {
final ConsoleAppender.Target target;
switch (targetValue) {
case "System.out":
target = ConsoleAppender.Target.SYSTEM_OUT;
break;
case "System.err":
target = ConsoleAppender.Target.SYSTEM_ERR;
break;
default:
reportWarning("Unknown value for console Target: " + targetValue);
target = null;
}
if (target != null) {
appenderBuilder.addAttribute("target", target);
}
}
buildAttribute(appenderName, appenderBuilder, "Follow", "follow");
if (FALSE.equalsIgnoreCase(getLog4jAppenderValue(appenderName, "ImmediateFlush"))) {
reportWarning("ImmediateFlush=false is not supported on Console appender");
}
buildAppenderLayout(appenderName, appenderBuilder);
builder.add(appenderBuilder);
}
private void buildFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
builder.add(appenderBuilder);
}
private void buildFileAppender(final String appenderName, final AppenderComponentBuilder appenderBuilder) {
buildMandatoryAttribute(appenderName, appenderBuilder, "File", "fileName");
buildAttribute(appenderName, appenderBuilder, "Append", "append");
buildAttribute(appenderName, appenderBuilder, "BufferedIO", "bufferedIo");
buildAttribute(appenderName, appenderBuilder, "BufferSize", "bufferSize");
buildAttribute(appenderName, appenderBuilder, "ImmediateFlush", "immediateFlush");
buildAppenderLayout(appenderName, appenderBuilder);
}
private void buildDailyRollingFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
RollingFileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
final String fileName = getLog4jAppenderValue(appenderName, "File");
final String datePattern = getLog4jAppenderValue(appenderName, "DatePattern", fileName + "'.'yyyy-MM-dd");
appenderBuilder.addAttribute("filePattern", fileName + "%d{" + datePattern + "}");
final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies")
.addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("modulate", true));
appenderBuilder.addComponent(triggeringPolicy);
appenderBuilder
.addComponent(builder.newComponent("DefaultRolloverStrategy").addAttribute("max", Integer.MAX_VALUE));
builder.add(appenderBuilder);
}
private void buildRollingFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
RollingFileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
final String fileName = getLog4jAppenderValue(appenderName, "File");
appenderBuilder.addAttribute("filePattern", fileName + ".%i");
final String maxFileSizeString = getLog4jAppenderValue(appenderName, "MaxFileSize", "10485760");
final String maxBackupIndexString = getLog4jAppenderValue(appenderName, "MaxBackupIndex", "1");
final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies").addComponent(
builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", maxFileSizeString));
appenderBuilder.addComponent(triggeringPolicy);
appenderBuilder.addComponent(
builder.newComponent("DefaultRolloverStrategy").addAttribute("max", maxBackupIndexString));
builder.add(appenderBuilder);
}
private void buildAttribute(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName);
if (attributeValue != null) {
componentBuilder.addAttribute(targetAttributeName, attributeValue);
}
}
private void buildAttributeWithDefault(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName, final String defaultValue) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName, defaultValue);
componentBuilder.addAttribute(targetAttributeName, attributeValue);
}
private void buildMandatoryAttribute(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName);
if (attributeValue != null) {
componentBuilder.addAttribute(targetAttributeName, attributeValue);
} else {
reportWarning("Missing " + sourceAttributeName + " for " + componentName);
}
}
private void buildNullAppender(String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, NullAppender.PLUGIN_NAME);
builder.add(appenderBuilder);
}
private void buildAppenderLayout(final String name, final AppenderComponentBuilder appenderBuilder) {
final String layoutClass = getLog4jAppenderValue(name, "layout", null);
if (layoutClass != null) {
switch (layoutClass) {
case "org.apache.log4j.PatternLayout":
case "org.apache.log4j.EnhancedPatternLayout": {
final String pattern = getLog4jAppenderValue(name, "layout.ConversionPattern", null)
// Log4j 2's %x (NDC) is not compatible with Log4j 1's
// %x
// Log4j 1: "foo bar baz"
// Log4j 2: "[foo, bar, baz]"
// Use %ndc to get the Log4j 1 format
.replace("%x", "%ndc")
// Log4j 2's %X (MDC) is not compatible with Log4j 1's
// %X
// Log4j 1: "{{foo,bar}{hoo,boo}}"
// Log4j 2: "{foo=bar,hoo=boo}"
// Use %properties to get the Log4j 1 format
.replace("%X", "%properties");
appenderBuilder.add(newPatternLayout(pattern));
break;
}
case "org.apache.log4j.SimpleLayout": {
appenderBuilder.add(newPatternLayout("%level - %m%n"));
break;
}
case "org.apache.log4j.TTCCLayout": {
String pattern = "%r ";
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.ThreadPrinting", TRUE))) {
pattern += "[%t] ";
}
pattern += "%p ";
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.CategoryPrefixing", TRUE))) {
pattern += "%c ";
}
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.ContextPrinting", TRUE))) {
pattern += "%notEmpty{%ndc }";
}
pattern += "- %m%n";
appenderBuilder.add(newPatternLayout(pattern));
break;
}
case "org.apache.log4j.HTMLLayout": {
final LayoutComponentBuilder htmlLayout = builder.newLayout("HtmlLayout");
htmlLayout.addAttribute("title", getLog4jAppenderValue(name, "layout.Title", "Log4J Log Messages"));
htmlLayout.addAttribute("locationInfo",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.LocationInfo", FALSE)));
appenderBuilder.add(htmlLayout);
break;
}
case "org.apache.log4j.xml.XMLLayout": {
final LayoutComponentBuilder xmlLayout = builder.newLayout("Log4j1XmlLayout");
xmlLayout.addAttribute("locationInfo",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.LocationInfo", FALSE)));
xmlLayout.addAttribute("properties",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.Properties", FALSE)));
appenderBuilder.add(xmlLayout);
break;
}
default:
reportWarning("Unknown layout class: " + layoutClass);
}
}
}
private LayoutComponentBuilder newPatternLayout(final String pattern) {
final LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout");
if (pattern != null) {
layoutBuilder.addAttribute("pattern", pattern);
}
return layoutBuilder;
}
private String[] buildRootLogger(final String rootLoggerValue) {
if (rootLoggerValue == null) {
return new String[0];
}
final String[] rootLoggerParts = rootLoggerValue.split(COMMA_DELIMITED_RE);
final String rootLoggerLevel = getLevelString(rootLoggerParts, Level.ERROR.name());
final String[] sortedAppenderNames = Arrays.copyOfRange(rootLoggerParts, 1, rootLoggerParts.length);
Arrays.sort(sortedAppenderNames);
final RootLoggerComponentBuilder loggerBuilder = builder.newRootLogger(rootLoggerLevel);
for (final String appender : sortedAppenderNames) {
loggerBuilder.add(builder.newAppenderRef(appender));
}
builder.add(loggerBuilder);
return sortedAppenderNames;
}
private String getLevelString(final String[] loggerParts, final String defaultLevel) {
return loggerParts.length > 0 ? loggerParts[0] : defaultLevel;
}
private void buildLoggers(final String prefix) {
final int preLength = prefix.length();
for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
final Object keyObj = entry.getKey();
if (keyObj != null) {
final String key = keyObj.toString();
if (key.startsWith(prefix)) {
final String name = key.substring(preLength);
final Object value = entry.getValue();
if (value != null) {
// a Level may be followed by a list of Appender refs.
final String valueStr = value.toString();
final String[] split = valueStr.split(COMMA_DELIMITED_RE);
final String level = getLevelString(split, null);
if (level == null) {
warn("Level is missing for entry " + entry);
} else {
final LoggerComponentBuilder newLogger = builder.newLogger(name, level);
if (split.length > 1) {
// Add Appenders to this logger
for (int i = 1; i < split.length; i++) {
newLogger.add(builder.newAppenderRef(split[i]));
}
}
builder.add(newLogger);
}
}
}
}
}
}
private String getLog4jAppenderValue(final String appenderName, final String attributeName) {
return getProperty("log4j.appender." + appenderName + "." + attributeName);
}
private String getProperty(final String key) {
final String value = properties.getProperty(key);
final String sysValue = strSubstitutorSystem.replace(value);
return strSubstitutorProperties.replace(sysValue);
}
private String getProperty(final String key, String defaultValue) {
final String value = getProperty(key);
return value == null ? defaultValue : value;
}
private String getLog4jAppenderValue(final String appenderName, final String attributeName,
final String defaultValue) {
return getProperty("log4j.appender." + appenderName + "." + attributeName, defaultValue);
}
private String getLog4jValue(final String key) {
return getProperty("log4j." + key);
}
private void reportWarning(final String msg) {
StatusLogger.getLogger().warn("Log4j 1 configuration parser: " + msg);
}
}
| log4j-1.2-api/src/main/java/org/apache/log4j/config/Log4j1ConfigurationParser.java | /*
* 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.log4j.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import javax.swing.text.StyledEditorKit.ForegroundAction;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.appender.NullAppender;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.Strings;
import org.apache.velocity.runtime.directive.Foreach;
/**
* Experimental parser for Log4j 1.2 properties configuration files.
*
* This class is not thread-safe.
*
* <p>
* From the Log4j 1.2 Javadocs:
* </p>
* <p>
* All option values admit variable substitution. The syntax of variable substitution is similar to that of Unix shells. The string between
* an opening "${" and closing "}" is interpreted as a key. The value of the substituted variable can be defined as a system property or in
* the configuration file itself. The value of the key is first searched in the system properties, and if not found there, it is then
* searched in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. For example, if java.home
* system property is set to /home/xyz, then every occurrence of the sequence ${java.home} will be interpreted as /home/xyz.
* </p>
*/
public class Log4j1ConfigurationParser {
private static final String COMMA_DELIMITED_RE = "\\s*,\\s*";
private static final String ROOTLOGGER = "rootLogger";
private static final String ROOTCATEGORY = "rootCategory";
private static final String TRUE = "true";
private static final String FALSE = "false";
private final Properties properties = new Properties();
private StrSubstitutor strSubstitutorProperties;
private StrSubstitutor strSubstitutorSystem;
private final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
.newConfigurationBuilder();
/**
* Parses a Log4j 1.2 properties configuration file in ISO 8859-1 encoding into a ConfigurationBuilder.
*
* @param input
* InputStream to read from is assumed to be ISO 8859-1, and will not be closed.
* @return the populated ConfigurationBuilder, never {@literal null}
* @throws IOException
* if unable to read the input
* @throws ConfigurationException
* if the input does not contain a valid configuration
*/
public ConfigurationBuilder<BuiltConfiguration> buildConfigurationBuilder(final InputStream input)
throws IOException {
try {
properties.load(input);
strSubstitutorProperties = new StrSubstitutor(properties);
strSubstitutorSystem = new StrSubstitutor(System.getProperties());
final String rootCategoryValue = getLog4jValue(ROOTCATEGORY);
final String rootLoggerValue = getLog4jValue(ROOTLOGGER);
if (rootCategoryValue == null && rootLoggerValue == null) {
// This is not a Log4j 1 properties configuration file.
warn("Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
// throw new ConfigurationException(
// "Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
}
builder.setConfigurationName("Log4j1");
// DEBUG
final String debugValue = getLog4jValue("debug");
if (Boolean.valueOf(debugValue)) {
builder.setStatusLevel(Level.DEBUG);
}
// Root
final String[] sortedAppenderNamesC = buildRootLogger(getLog4jValue(ROOTCATEGORY));
final String[] sortedAppenderNamesL = buildRootLogger(getLog4jValue(ROOTLOGGER));
final String[] sortedAppenderNames = sortedAppenderNamesL.length > 0 ? sortedAppenderNamesL
: sortedAppenderNamesC;
// Appenders
final Map<String, String> classNameToProperty = buildClassToPropertyPrefixMap(sortedAppenderNames);
for (final Map.Entry<String, String> entry : classNameToProperty.entrySet()) {
final String appenderName = entry.getKey();
final String appenderClass = entry.getValue();
buildAppender(appenderName, appenderClass);
}
// Loggers
buildLoggers("log4j.category.");
buildLoggers("log4j.logger.");
buildProperties();
return builder;
} catch (final IllegalArgumentException e) {
throw new ConfigurationException(e);
}
}
private void buildProperties() {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
final String key = entry.getKey().toString();
if (!key.startsWith("log4j.") && !key.equals(ROOTCATEGORY) && !key.equals(ROOTLOGGER)) {
builder.addProperty(key, Objects.toString(entry.getValue(), Strings.EMPTY));
}
}
}
private void warn(String string) {
System.err.println(string);
}
private Map<String, String> buildClassToPropertyPrefixMap(final String[] sortedAppenderNames) {
final String prefix = "log4j.appender.";
final int preLength = prefix.length();
final Map<String, String> map = new HashMap<>(sortedAppenderNames.length);
for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
final Object keyObj = entry.getKey();
if (keyObj != null) {
final String key = keyObj.toString();
if (key.startsWith(prefix)) {
if (key.indexOf('.', preLength) < 0) {
final String name = key.substring(preLength);
if (Arrays.binarySearch(sortedAppenderNames, name) == -1) {
final Object value = entry.getValue();
if (value != null) {
map.put(name, value.toString());
}
}
}
}
}
}
return map;
}
private void buildAppender(final String appenderName, final String appenderClass) {
switch (appenderClass) {
case "org.apache.log4j.ConsoleAppender":
buildConsoleAppender(appenderName);
break;
case "org.apache.log4j.FileAppender":
buildFileAppender(appenderName);
break;
case "org.apache.log4j.DailyRollingFileAppender":
buildDailyRollingFileAppender(appenderName);
break;
case "org.apache.log4j.RollingFileAppender":
buildRollingFileAppender(appenderName);
break;
case "org.apache.log4j.varia.NullAppender":
buildNullAppender(appenderName);
break;
default:
reportWarning("Unknown appender class: " + appenderClass + "; ignoring appender: " + appenderName);
}
}
private void buildConsoleAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, ConsoleAppender.PLUGIN_NAME);
final String targetValue = getLog4jAppenderValue(appenderName, "Target", "System.out");
if (targetValue != null) {
final ConsoleAppender.Target target;
switch (targetValue) {
case "System.out":
target = ConsoleAppender.Target.SYSTEM_OUT;
break;
case "System.err":
target = ConsoleAppender.Target.SYSTEM_ERR;
break;
default:
reportWarning("Unknown value for console Target: " + targetValue);
target = null;
}
if (target != null) {
appenderBuilder.addAttribute("target", target);
}
}
buildAttribute(appenderName, appenderBuilder, "Follow", "follow");
if (FALSE.equalsIgnoreCase(getLog4jAppenderValue(appenderName, "ImmediateFlush"))) {
reportWarning("ImmediateFlush=false is not supported on Console appender");
}
buildAppenderLayout(appenderName, appenderBuilder);
builder.add(appenderBuilder);
}
private void buildFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
builder.add(appenderBuilder);
}
private void buildFileAppender(final String appenderName, final AppenderComponentBuilder appenderBuilder) {
buildMandatoryAttribute(appenderName, appenderBuilder, "File", "fileName");
buildAttribute(appenderName, appenderBuilder, "Append", "append");
buildAttribute(appenderName, appenderBuilder, "BufferedIO", "bufferedIo");
buildAttribute(appenderName, appenderBuilder, "BufferSize", "bufferSize");
buildAttribute(appenderName, appenderBuilder, "ImmediateFlush", "immediateFlush");
buildAppenderLayout(appenderName, appenderBuilder);
}
private void buildDailyRollingFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
RollingFileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
final String fileName = getLog4jAppenderValue(appenderName, "File");
final String datePattern = getLog4jAppenderValue(appenderName, "DatePattern", fileName + "'.'yyyy-MM-dd");
appenderBuilder.addAttribute("filePattern", fileName + "%d{" + datePattern + "}");
final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies")
.addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("modulate", true));
appenderBuilder.addComponent(triggeringPolicy);
appenderBuilder
.addComponent(builder.newComponent("DefaultRolloverStrategy").addAttribute("max", Integer.MAX_VALUE));
builder.add(appenderBuilder);
}
private void buildRollingFileAppender(final String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
RollingFileAppender.PLUGIN_NAME);
buildFileAppender(appenderName, appenderBuilder);
final String fileName = getLog4jAppenderValue(appenderName, "File");
appenderBuilder.addAttribute("filePattern", fileName + ".%i");
final String maxFileSizeString = getLog4jAppenderValue(appenderName, "MaxFileSize", "10485760");
final String maxBackupIndexString = getLog4jAppenderValue(appenderName, "MaxBackupIndex", "1");
final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies").addComponent(
builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", maxFileSizeString));
appenderBuilder.addComponent(triggeringPolicy);
appenderBuilder.addComponent(
builder.newComponent("DefaultRolloverStrategy").addAttribute("max", maxBackupIndexString));
builder.add(appenderBuilder);
}
private void buildAttribute(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName);
if (attributeValue != null) {
componentBuilder.addAttribute(targetAttributeName, attributeValue);
}
}
private void buildAttributeWithDefault(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName, final String defaultValue) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName, defaultValue);
componentBuilder.addAttribute(targetAttributeName, attributeValue);
}
private void buildMandatoryAttribute(final String componentName, final ComponentBuilder componentBuilder,
final String sourceAttributeName, final String targetAttributeName) {
final String attributeValue = getLog4jAppenderValue(componentName, sourceAttributeName);
if (attributeValue != null) {
componentBuilder.addAttribute(targetAttributeName, attributeValue);
} else {
reportWarning("Missing " + sourceAttributeName + " for " + componentName);
}
}
private void buildNullAppender(String appenderName) {
final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, NullAppender.PLUGIN_NAME);
builder.add(appenderBuilder);
}
private void buildAppenderLayout(final String name, final AppenderComponentBuilder appenderBuilder) {
final String layoutClass = getLog4jAppenderValue(name, "layout", null);
if (layoutClass != null) {
switch (layoutClass) {
case "org.apache.log4j.PatternLayout":
case "org.apache.log4j.EnhancedPatternLayout": {
final String pattern = getLog4jAppenderValue(name, "layout.ConversionPattern", null)
// Log4j 2's %x (NDC) is not compatible with Log4j 1's
// %x
// Log4j 1: "foo bar baz"
// Log4j 2: "[foo, bar, baz]"
// Use %ndc to get the Log4j 1 format
.replace("%x", "%ndc")
// Log4j 2's %X (MDC) is not compatible with Log4j 1's
// %X
// Log4j 1: "{{foo,bar}{hoo,boo}}"
// Log4j 2: "{foo=bar,hoo=boo}"
// Use %properties to get the Log4j 1 format
.replace("%X", "%properties");
appenderBuilder.add(newPatternLayout(pattern));
break;
}
case "org.apache.log4j.SimpleLayout": {
appenderBuilder.add(newPatternLayout("%level - %m%n"));
break;
}
case "org.apache.log4j.TTCCLayout": {
String pattern = "%r ";
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.ThreadPrinting", TRUE))) {
pattern += "[%t] ";
}
pattern += "%p ";
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.CategoryPrefixing", TRUE))) {
pattern += "%c ";
}
if (Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.ContextPrinting", TRUE))) {
pattern += "%notEmpty{%ndc }";
}
pattern += "- %m%n";
appenderBuilder.add(newPatternLayout(pattern));
break;
}
case "org.apache.log4j.HTMLLayout": {
final LayoutComponentBuilder htmlLayout = builder.newLayout("HtmlLayout");
htmlLayout.addAttribute("title", getLog4jAppenderValue(name, "layout.Title", "Log4J Log Messages"));
htmlLayout.addAttribute("locationInfo",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.LocationInfo", FALSE)));
appenderBuilder.add(htmlLayout);
break;
}
case "org.apache.log4j.xml.XMLLayout": {
final LayoutComponentBuilder xmlLayout = builder.newLayout("Log4j1XmlLayout");
xmlLayout.addAttribute("locationInfo",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.LocationInfo", FALSE)));
xmlLayout.addAttribute("properties",
Boolean.parseBoolean(getLog4jAppenderValue(name, "layout.Properties", FALSE)));
appenderBuilder.add(xmlLayout);
break;
}
default:
reportWarning("Unknown layout class: " + layoutClass);
}
}
}
private LayoutComponentBuilder newPatternLayout(final String pattern) {
final LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout");
if (pattern != null) {
layoutBuilder.addAttribute("pattern", pattern);
}
return layoutBuilder;
}
private String[] buildRootLogger(final String rootLoggerValue) {
if (rootLoggerValue == null) {
return new String[0];
}
final String[] rootLoggerParts = rootLoggerValue.split(COMMA_DELIMITED_RE);
final String rootLoggerLevel = getLevelString(rootLoggerParts, Level.ERROR.name());
final String[] sortedAppenderNames = Arrays.copyOfRange(rootLoggerParts, 1, rootLoggerParts.length);
Arrays.sort(sortedAppenderNames);
final RootLoggerComponentBuilder loggerBuilder = builder.newRootLogger(rootLoggerLevel);
for (final String appender : sortedAppenderNames) {
loggerBuilder.add(builder.newAppenderRef(appender));
}
builder.add(loggerBuilder);
return sortedAppenderNames;
}
private String getLevelString(final String[] loggerParts, final String defaultLevel) {
return loggerParts.length > 0 ? loggerParts[0] : defaultLevel;
}
private void buildLoggers(final String prefix) {
final int preLength = prefix.length();
for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
final Object keyObj = entry.getKey();
if (keyObj != null) {
final String key = keyObj.toString();
if (key.startsWith(prefix)) {
final String name = key.substring(preLength);
final Object value = entry.getValue();
if (value != null) {
// a Level may be followed by a list of Appender refs.
final String valueStr = value.toString();
final String[] split = valueStr.split(COMMA_DELIMITED_RE);
final String level = getLevelString(split, null);
if (level == null) {
warn("Level is missing for entry " + entry);
} else {
final LoggerComponentBuilder newLogger = builder.newLogger(name, level);
if (split.length > 1) {
// Add Appenders to this logger
for (int i = 1; i < split.length; i++) {
newLogger.add(builder.newAppenderRef(split[i]));
}
}
builder.add(newLogger);
}
}
}
}
}
}
private String getLog4jAppenderValue(final String appenderName, final String attributeName) {
return getProperty("log4j.appender." + appenderName + "." + attributeName);
}
private String getProperty(final String key) {
final String value = properties.getProperty(key);
final String sysValue = strSubstitutorSystem.replace(value);
return strSubstitutorProperties.replace(sysValue);
}
private String getProperty(final String key, String defaultValue) {
final String value = getProperty(key);
return value == null ? defaultValue : value;
}
private String getLog4jAppenderValue(final String appenderName, final String attributeName,
final String defaultValue) {
return getProperty("log4j.appender." + appenderName + "." + attributeName, defaultValue);
}
private String getLog4jValue(final String key) {
return getProperty("log4j." + key);
}
private void reportWarning(final String msg) {
StatusLogger.getLogger().warn("Log4j 1 configuration parser: " + msg);
}
}
| Remove unused import. | log4j-1.2-api/src/main/java/org/apache/log4j/config/Log4j1ConfigurationParser.java | Remove unused import. |
|
Java | apache-2.0 | 42765a3627fe61dc1891885eca036cbc9777db3a | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr | package org.apache.lucene.codecs.lucene41;
/*
* 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.
*/
import static org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat.BLOCK_SIZE;
import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_DATA_SIZE;
import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_ENCODED_SIZE;
import java.io.IOException;
import java.util.Arrays;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.index.TermState;
import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
/**
* Concrete class that reads docId(maybe frq,pos,offset,payloads) list
* with postings format.
*
* @see Lucene41SkipReader for details
* @lucene.experimental
*/
public final class Lucene41PostingsReader extends PostingsReaderBase {
private final IndexInput docIn;
private final IndexInput posIn;
private final IndexInput payIn;
private final ForUtil forUtil;
// public static boolean DEBUG = false;
/** Sole constructor. */
public Lucene41PostingsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo segmentInfo, IOContext ioContext, String segmentSuffix) throws IOException {
boolean success = false;
IndexInput docIn = null;
IndexInput posIn = null;
IndexInput payIn = null;
try {
docIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.DOC_EXTENSION),
ioContext);
CodecUtil.checkHeader(docIn,
Lucene41PostingsWriter.DOC_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
forUtil = new ForUtil(docIn);
if (fieldInfos.hasProx()) {
posIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.POS_EXTENSION),
ioContext);
CodecUtil.checkHeader(posIn,
Lucene41PostingsWriter.POS_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
if (fieldInfos.hasPayloads() || fieldInfos.hasOffsets()) {
payIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.PAY_EXTENSION),
ioContext);
CodecUtil.checkHeader(payIn,
Lucene41PostingsWriter.PAY_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
}
}
this.docIn = docIn;
this.posIn = posIn;
this.payIn = payIn;
success = true;
} finally {
if (!success) {
IOUtils.closeWhileHandlingException(docIn, posIn, payIn);
}
}
}
@Override
public void init(IndexInput termsIn) throws IOException {
// Make sure we are talking to the matching postings writer
CodecUtil.checkHeader(termsIn,
Lucene41PostingsWriter.TERMS_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
final int indexBlockSize = termsIn.readVInt();
if (indexBlockSize != BLOCK_SIZE) {
throw new IllegalStateException("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + BLOCK_SIZE + ")");
}
}
/**
* Read values that have been written using variable-length encoding instead of bit-packing.
*/
static void readVIntBlock(IndexInput docIn, int[] docBuffer,
int[] freqBuffer, int num, boolean indexHasFreq) throws IOException {
if (indexHasFreq) {
for(int i=0;i<num;i++) {
final int code = docIn.readVInt();
docBuffer[i] = code >>> 1;
if ((code & 1) != 0) {
freqBuffer[i] = 1;
} else {
freqBuffer[i] = docIn.readVInt();
}
}
} else {
for(int i=0;i<num;i++) {
docBuffer[i] = docIn.readVInt();
}
}
}
// Must keep final because we do non-standard clone
private final static class IntBlockTermState extends BlockTermState {
long docStartFP;
long posStartFP;
long payStartFP;
long skipOffset;
long lastPosBlockOffset;
// docid when there is a single pulsed posting, otherwise -1
// freq is always implicitly totalTermFreq in this case.
int singletonDocID;
// Only used by the "primary" TermState -- clones don't
// copy this (basically they are "transient"):
ByteArrayDataInput bytesReader; // TODO: should this NOT be in the TermState...?
byte[] bytes;
@Override
public IntBlockTermState clone() {
IntBlockTermState other = new IntBlockTermState();
other.copyFrom(this);
return other;
}
@Override
public void copyFrom(TermState _other) {
super.copyFrom(_other);
IntBlockTermState other = (IntBlockTermState) _other;
docStartFP = other.docStartFP;
posStartFP = other.posStartFP;
payStartFP = other.payStartFP;
lastPosBlockOffset = other.lastPosBlockOffset;
skipOffset = other.skipOffset;
singletonDocID = other.singletonDocID;
// Do not copy bytes, bytesReader (else TermState is
// very heavy, ie drags around the entire block's
// byte[]). On seek back, if next() is in fact used
// (rare!), they will be re-read from disk.
}
@Override
public String toString() {
return super.toString() + " docStartFP=" + docStartFP + " posStartFP=" + posStartFP + " payStartFP=" + payStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;
}
}
@Override
public IntBlockTermState newTermState() {
return new IntBlockTermState();
}
@Override
public void close() throws IOException {
IOUtils.close(docIn, posIn, payIn);
}
/* Reads but does not decode the byte[] blob holding
metadata for the current terms block */
@Override
public void readTermsBlock(IndexInput termsIn, FieldInfo fieldInfo, BlockTermState _termState) throws IOException {
final IntBlockTermState termState = (IntBlockTermState) _termState;
final int numBytes = termsIn.readVInt();
if (termState.bytes == null) {
termState.bytes = new byte[ArrayUtil.oversize(numBytes, 1)];
termState.bytesReader = new ByteArrayDataInput();
} else if (termState.bytes.length < numBytes) {
termState.bytes = new byte[ArrayUtil.oversize(numBytes, 1)];
}
termsIn.readBytes(termState.bytes, 0, numBytes);
termState.bytesReader.reset(termState.bytes, 0, numBytes);
}
@Override
public void nextTerm(FieldInfo fieldInfo, BlockTermState _termState)
throws IOException {
final IntBlockTermState termState = (IntBlockTermState) _termState;
final boolean isFirstTerm = termState.termBlockOrd == 0;
final boolean fieldHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
final boolean fieldHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
final boolean fieldHasPayloads = fieldInfo.hasPayloads();
final DataInput in = termState.bytesReader;
if (isFirstTerm) {
if (termState.docFreq == 1) {
termState.singletonDocID = in.readVInt();
termState.docStartFP = 0;
} else {
termState.singletonDocID = -1;
termState.docStartFP = in.readVLong();
}
if (fieldHasPositions) {
termState.posStartFP = in.readVLong();
if (termState.totalTermFreq > BLOCK_SIZE) {
termState.lastPosBlockOffset = in.readVLong();
} else {
termState.lastPosBlockOffset = -1;
}
if ((fieldHasPayloads || fieldHasOffsets) && termState.totalTermFreq >= BLOCK_SIZE) {
termState.payStartFP = in.readVLong();
} else {
termState.payStartFP = -1;
}
}
} else {
if (termState.docFreq == 1) {
termState.singletonDocID = in.readVInt();
} else {
termState.singletonDocID = -1;
termState.docStartFP += in.readVLong();
}
if (fieldHasPositions) {
termState.posStartFP += in.readVLong();
if (termState.totalTermFreq > BLOCK_SIZE) {
termState.lastPosBlockOffset = in.readVLong();
} else {
termState.lastPosBlockOffset = -1;
}
if ((fieldHasPayloads || fieldHasOffsets) && termState.totalTermFreq >= BLOCK_SIZE) {
long delta = in.readVLong();
if (termState.payStartFP == -1) {
termState.payStartFP = delta;
} else {
termState.payStartFP += delta;
}
}
}
}
if (termState.docFreq > BLOCK_SIZE) {
termState.skipOffset = in.readVLong();
} else {
termState.skipOffset = -1;
}
}
@Override
public DocsEnum docs(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
BlockDocsEnum docsEnum;
if (reuse instanceof BlockDocsEnum) {
docsEnum = (BlockDocsEnum) reuse;
if (!docsEnum.canReuse(docIn, fieldInfo)) {
docsEnum = new BlockDocsEnum(fieldInfo);
}
} else {
docsEnum = new BlockDocsEnum(fieldInfo);
}
return docsEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
}
// TODO: specialize to liveDocs vs not
@Override
public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs,
DocsAndPositionsEnum reuse, int flags)
throws IOException {
boolean indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
boolean indexHasPayloads = fieldInfo.hasPayloads();
if ((!indexHasOffsets || (flags & DocsAndPositionsEnum.FLAG_OFFSETS) == 0) &&
(!indexHasPayloads || (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) == 0)) {
BlockDocsAndPositionsEnum docsAndPositionsEnum;
if (reuse instanceof BlockDocsAndPositionsEnum) {
docsAndPositionsEnum = (BlockDocsAndPositionsEnum) reuse;
if (!docsAndPositionsEnum.canReuse(docIn, fieldInfo)) {
docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
}
} else {
docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
}
return docsAndPositionsEnum.reset(liveDocs, (IntBlockTermState) termState);
} else {
EverythingEnum everythingEnum;
if (reuse instanceof EverythingEnum) {
everythingEnum = (EverythingEnum) reuse;
if (!everythingEnum.canReuse(docIn, fieldInfo)) {
everythingEnum = new EverythingEnum(fieldInfo);
}
} else {
everythingEnum = new EverythingEnum(fieldInfo);
}
return everythingEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
}
}
final class BlockDocsEnum extends DocsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private int docBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final boolean indexHasFreq;
final boolean indexHasPos;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // sum of freqs in this posting list (or docFreq when omitted)
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
// docID for next skip point, we won't use skipper if
// target docID is not larger than this
private int nextSkipDoc;
private Bits liveDocs;
private boolean needsFreq; // true if the caller actually needs frequencies
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public BlockDocsEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
indexHasFreq = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
indexHasPos = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
indexHasPayloads = fieldInfo.hasPayloads();
encoded = new byte[MAX_ENCODED_SIZE];
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasFreq == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0) &&
indexHasPos == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public DocsEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
totalTermFreq = indexHasFreq ? termState.totalTermFreq : docFreq;
docTermStartFP = termState.docStartFP;
skipOffset = termState.skipOffset;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
doc = -1;
this.needsFreq = (flags & DocsEnum.FLAG_FREQS) != 0;
if (!indexHasFreq) {
Arrays.fill(freqBuffer, 1);
}
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1; // we won't skip if target is found in first block
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
if (indexHasFreq) {
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
if (needsFreq) {
forUtil.readBlock(docIn, encoded, freqBuffer);
} else {
forUtil.skipBlock(docIn); // skip over freqs
}
}
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// Read vInts:
// if (DEBUG) {
// System.out.println(" fill last vInt block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, indexHasFreq);
}
docBufferUpto = 0;
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println("\nFPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
// if (DEBUG) {
// System.out.println(" return doc=END");
// }
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
freq = freqBuffer[docBufferUpto];
docBufferUpto++;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq);
// }
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
docBufferUpto++;
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
// current skip docID < docIDs generated from current buffer <= next skip docID
// we don't need to skip if target is buffered already
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println("load skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
indexHasPos,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
skipper.init(docTermStartFP+skipOffset, docTermStartFP, 0, 0, docFreq);
skipped = true;
}
// always plus one to fix the result, since skip position in Lucene41SkipReader
// is a little different from MultiLevelSkipListReader
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println("skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer());
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc(); // actually, this is just lastSkipEntry
docIn.seek(skipper.getDocPointer()); // now point to the block we want to search
}
// next time we call advance, this is used to
// foresee whether skipper is necessary.
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan... this is an inlined/pared down version
// of nextDoc():
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
docUpto++;
if (accum >= target) {
break;
}
docBufferUpto++;
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
freq = freqBuffer[docBufferUpto];
docBufferUpto++;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
docBufferUpto++;
return nextDoc();
}
}
}
final class BlockDocsAndPositionsEnum extends DocsAndPositionsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
private int docBufferUpto;
private int posBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final IndexInput posIn;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // number of positions in this posting list
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
private int position; // current position
// how many positions "behind" we are; nextPosition must
// skip these to "catch up":
private int posPendingCount;
// Lazy pos seek: if != -1 then we must seek to this FP
// before reading positions:
private long posPendingFP;
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's postings start in the .pos file:
private long posTermStartFP;
// Where this term's payloads/offsets start in the .pay
// file:
private long payTermStartFP;
// File pointer where the last (vInt encoded) pos delta
// block is. We need this to know whether to bulk
// decode vs vInt decode the block:
private long lastPosBlockFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
private int nextSkipDoc;
private Bits liveDocs;
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public BlockDocsAndPositionsEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
this.posIn = Lucene41PostingsReader.this.posIn.clone();
encoded = new byte[MAX_ENCODED_SIZE];
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
indexHasPayloads = fieldInfo.hasPayloads();
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public DocsAndPositionsEnum reset(Bits liveDocs, IntBlockTermState termState) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
docTermStartFP = termState.docStartFP;
posTermStartFP = termState.posStartFP;
payTermStartFP = termState.payStartFP;
skipOffset = termState.skipOffset;
totalTermFreq = termState.totalTermFreq;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
posPendingFP = posTermStartFP;
posPendingCount = 0;
if (termState.totalTermFreq < BLOCK_SIZE) {
lastPosBlockFP = posTermStartFP;
} else if (termState.totalTermFreq == BLOCK_SIZE) {
lastPosBlockFP = -1;
} else {
lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
}
doc = -1;
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1;
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, freqBuffer);
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// Read vInts:
// if (DEBUG) {
// System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
}
docBufferUpto = 0;
}
private void refillPositions() throws IOException {
// if (DEBUG) {
// System.out.println(" refillPositions");
// }
if (posIn.getFilePointer() == lastPosBlockFP) {
// if (DEBUG) {
// System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
// }
final int count = (int) (totalTermFreq % BLOCK_SIZE);
int payloadLength = 0;
for(int i=0;i<count;i++) {
int code = posIn.readVInt();
if (indexHasPayloads) {
if ((code & 1) != 0) {
payloadLength = posIn.readVInt();
}
posDeltaBuffer[i] = code >>> 1;
if (payloadLength != 0) {
posIn.seek(posIn.getFilePointer() + payloadLength);
}
} else {
posDeltaBuffer[i] = code;
}
if (indexHasOffsets) {
if ((posIn.readVInt() & 1) != 0) {
// offset length changed
posIn.readVInt();
}
}
}
} else {
// if (DEBUG) {
// System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
// }
forUtil.readBlock(posIn, encoded, posDeltaBuffer);
}
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
position = 0;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
// }
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println(" try skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
// if (DEBUG) {
// System.out.println(" create skipper");
// }
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
true,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
// if (DEBUG) {
// System.out.println(" init skipper");
// }
skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
skipped = true;
}
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto());
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc();
docIn.seek(skipper.getDocPointer());
posPendingFP = skipper.getPosPointer();
posPendingCount = skipper.getPosBufferUpto();
}
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan... this is an inlined/pared down version
// of nextDoc():
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (accum >= target) {
break;
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
position = 0;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
return nextDoc();
}
}
// TODO: in theory we could avoid loading frq block
// when not needed, ie, use skip data to load how far to
// seek the pos pointer ... instead of having to load frq
// blocks only to sum up how many positions to skip
private void skipPositions() throws IOException {
// Skip positions now:
int toSkip = posPendingCount - freq;
// if (DEBUG) {
// System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
// }
final int leftInBlock = BLOCK_SIZE - posBufferUpto;
if (toSkip < leftInBlock) {
posBufferUpto += toSkip;
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
} else {
toSkip -= leftInBlock;
while(toSkip >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
// }
assert posIn.getFilePointer() != lastPosBlockFP;
forUtil.skipBlock(posIn);
toSkip -= BLOCK_SIZE;
}
refillPositions();
posBufferUpto = toSkip;
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
}
position = 0;
}
@Override
public int nextPosition() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto);
// }
if (posPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek to pendingFP=" + posPendingFP);
// }
posIn.seek(posPendingFP);
posPendingFP = -1;
// Force buffer refill:
posBufferUpto = BLOCK_SIZE;
}
if (posPendingCount > freq) {
skipPositions();
posPendingCount = freq;
}
if (posBufferUpto == BLOCK_SIZE) {
refillPositions();
posBufferUpto = 0;
}
position += posDeltaBuffer[posBufferUpto++];
posPendingCount--;
// if (DEBUG) {
// System.out.println(" return pos=" + position);
// }
return position;
}
@Override
public int startOffset() {
return -1;
}
@Override
public int endOffset() {
return -1;
}
@Override
public BytesRef getPayload() {
return null;
}
}
// Also handles payloads + offsets
final class EverythingEnum extends DocsAndPositionsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] payloadLengthBuffer;
private final int[] offsetStartDeltaBuffer;
private final int[] offsetLengthBuffer;
private byte[] payloadBytes;
private int payloadByteUpto;
private int payloadLength;
private int lastStartOffset;
private int startOffset;
private int endOffset;
private int docBufferUpto;
private int posBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final IndexInput posIn;
final IndexInput payIn;
final BytesRef payload;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // number of positions in this posting list
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
private int position; // current position
// how many positions "behind" we are; nextPosition must
// skip these to "catch up":
private int posPendingCount;
// Lazy pos seek: if != -1 then we must seek to this FP
// before reading positions:
private long posPendingFP;
// Lazy pay seek: if != -1 then we must seek to this FP
// before reading payloads/offsets:
private long payPendingFP;
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's postings start in the .pos file:
private long posTermStartFP;
// Where this term's payloads/offsets start in the .pay
// file:
private long payTermStartFP;
// File pointer where the last (vInt encoded) pos delta
// block is. We need this to know whether to bulk
// decode vs vInt decode the block:
private long lastPosBlockFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
private int nextSkipDoc;
private Bits liveDocs;
private boolean needsOffsets; // true if we actually need offsets
private boolean needsPayloads; // true if we actually need payloads
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public EverythingEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
this.posIn = Lucene41PostingsReader.this.posIn.clone();
this.payIn = Lucene41PostingsReader.this.payIn.clone();
encoded = new byte[MAX_ENCODED_SIZE];
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
if (indexHasOffsets) {
offsetStartDeltaBuffer = new int[MAX_DATA_SIZE];
offsetLengthBuffer = new int[MAX_DATA_SIZE];
} else {
offsetStartDeltaBuffer = null;
offsetLengthBuffer = null;
startOffset = -1;
endOffset = -1;
}
indexHasPayloads = fieldInfo.hasPayloads();
if (indexHasPayloads) {
payloadLengthBuffer = new int[MAX_DATA_SIZE];
payloadBytes = new byte[128];
payload = new BytesRef();
} else {
payloadLengthBuffer = null;
payloadBytes = null;
payload = null;
}
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public EverythingEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
docTermStartFP = termState.docStartFP;
posTermStartFP = termState.posStartFP;
payTermStartFP = termState.payStartFP;
skipOffset = termState.skipOffset;
totalTermFreq = termState.totalTermFreq;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
posPendingFP = posTermStartFP;
payPendingFP = payTermStartFP;
posPendingCount = 0;
if (termState.totalTermFreq < BLOCK_SIZE) {
lastPosBlockFP = posTermStartFP;
} else if (termState.totalTermFreq == BLOCK_SIZE) {
lastPosBlockFP = -1;
} else {
lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
}
this.needsOffsets = (flags & DocsAndPositionsEnum.FLAG_OFFSETS) != 0;
this.needsPayloads = (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) != 0;
doc = -1;
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1;
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, freqBuffer);
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// if (DEBUG) {
// System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
}
docBufferUpto = 0;
}
private void refillPositions() throws IOException {
// if (DEBUG) {
// System.out.println(" refillPositions");
// }
if (posIn.getFilePointer() == lastPosBlockFP) {
// if (DEBUG) {
// System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
// }
final int count = (int) (totalTermFreq % BLOCK_SIZE);
int payloadLength = 0;
int offsetLength = 0;
payloadByteUpto = 0;
for(int i=0;i<count;i++) {
int code = posIn.readVInt();
if (indexHasPayloads) {
if ((code & 1) != 0) {
payloadLength = posIn.readVInt();
}
// if (DEBUG) {
// System.out.println(" i=" + i + " payloadLen=" + payloadLength);
// }
payloadLengthBuffer[i] = payloadLength;
posDeltaBuffer[i] = code >>> 1;
if (payloadLength != 0) {
if (payloadByteUpto + payloadLength > payloadBytes.length) {
payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payloadLength);
}
//System.out.println(" read payload @ pos.fp=" + posIn.getFilePointer());
posIn.readBytes(payloadBytes, payloadByteUpto, payloadLength);
payloadByteUpto += payloadLength;
}
} else {
posDeltaBuffer[i] = code;
}
if (indexHasOffsets) {
// if (DEBUG) {
// System.out.println(" i=" + i + " read offsets from posIn.fp=" + posIn.getFilePointer());
// }
int deltaCode = posIn.readVInt();
if ((deltaCode & 1) != 0) {
offsetLength = posIn.readVInt();
}
offsetStartDeltaBuffer[i] = deltaCode >>> 1;
offsetLengthBuffer[i] = offsetLength;
// if (DEBUG) {
// System.out.println(" startOffDelta=" + offsetStartDeltaBuffer[i] + " offsetLen=" + offsetLengthBuffer[i]);
// }
}
}
payloadByteUpto = 0;
} else {
// if (DEBUG) {
// System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
// }
forUtil.readBlock(posIn, encoded, posDeltaBuffer);
if (indexHasPayloads) {
// if (DEBUG) {
// System.out.println(" bulk payload block @ pay.fp=" + payIn.getFilePointer());
// }
if (needsPayloads) {
forUtil.readBlock(payIn, encoded, payloadLengthBuffer);
int numBytes = payIn.readVInt();
// if (DEBUG) {
// System.out.println(" " + numBytes + " payload bytes @ pay.fp=" + payIn.getFilePointer());
// }
if (numBytes > payloadBytes.length) {
payloadBytes = ArrayUtil.grow(payloadBytes, numBytes);
}
payIn.readBytes(payloadBytes, 0, numBytes);
} else {
// this works, because when writing a vint block we always force the first length to be written
forUtil.skipBlock(payIn); // skip over lengths
int numBytes = payIn.readVInt(); // read length of payloadBytes
payIn.seek(payIn.getFilePointer() + numBytes); // skip over payloadBytes
}
payloadByteUpto = 0;
}
if (indexHasOffsets) {
// if (DEBUG) {
// System.out.println(" bulk offset block @ pay.fp=" + payIn.getFilePointer());
// }
if (needsOffsets) {
forUtil.readBlock(payIn, encoded, offsetStartDeltaBuffer);
forUtil.readBlock(payIn, encoded, offsetLengthBuffer);
} else {
// this works, because when writing a vint block we always force the first length to be written
forUtil.skipBlock(payIn); // skip over starts
forUtil.skipBlock(payIn); // skip over lengths
}
}
}
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
// }
position = 0;
lastStartOffset = 0;
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println(" try skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
// if (DEBUG) {
// System.out.println(" create skipper");
// }
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
true,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
// if (DEBUG) {
// System.out.println(" init skipper");
// }
skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
skipped = true;
}
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto() + " pay.fp=" + skipper.getPayPointer() + " lastStartOffset=" + lastStartOffset);
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc();
docIn.seek(skipper.getDocPointer());
posPendingFP = skipper.getPosPointer();
payPendingFP = skipper.getPayPointer();
posPendingCount = skipper.getPosBufferUpto();
lastStartOffset = 0; // new document
payloadByteUpto = skipper.getPayloadByteUpto();
}
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan:
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (accum >= target) {
break;
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
position = 0;
lastStartOffset = 0;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
return nextDoc();
}
}
// TODO: in theory we could avoid loading frq block
// when not needed, ie, use skip data to load how far to
// seek the pos pointer ... instead of having to load frq
// blocks only to sum up how many positions to skip
private void skipPositions() throws IOException {
// Skip positions now:
int toSkip = posPendingCount - freq;
// if (DEBUG) {
// System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
// }
final int leftInBlock = BLOCK_SIZE - posBufferUpto;
if (toSkip < leftInBlock) {
int end = posBufferUpto + toSkip;
while(posBufferUpto < end) {
if (indexHasPayloads) {
payloadByteUpto += payloadLengthBuffer[posBufferUpto];
}
posBufferUpto++;
}
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
} else {
toSkip -= leftInBlock;
while(toSkip >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
// }
assert posIn.getFilePointer() != lastPosBlockFP;
forUtil.skipBlock(posIn);
if (indexHasPayloads) {
// Skip payloadLength block:
forUtil.skipBlock(payIn);
// Skip payloadBytes block:
int numBytes = payIn.readVInt();
payIn.seek(payIn.getFilePointer() + numBytes);
}
if (indexHasOffsets) {
forUtil.skipBlock(payIn);
forUtil.skipBlock(payIn);
}
toSkip -= BLOCK_SIZE;
}
refillPositions();
payloadByteUpto = 0;
posBufferUpto = 0;
while(posBufferUpto < toSkip) {
if (indexHasPayloads) {
payloadByteUpto += payloadLengthBuffer[posBufferUpto];
}
posBufferUpto++;
}
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
}
position = 0;
lastStartOffset = 0;
}
@Override
public int nextPosition() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto + " payloadByteUpto=" + payloadByteUpto)// ;
// }
if (posPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek pos to pendingFP=" + posPendingFP);
// }
posIn.seek(posPendingFP);
posPendingFP = -1;
if (payPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek pay to pendingFP=" + payPendingFP);
// }
payIn.seek(payPendingFP);
payPendingFP = -1;
}
// Force buffer refill:
posBufferUpto = BLOCK_SIZE;
}
if (posPendingCount > freq) {
skipPositions();
posPendingCount = freq;
}
if (posBufferUpto == BLOCK_SIZE) {
refillPositions();
posBufferUpto = 0;
}
position += posDeltaBuffer[posBufferUpto];
if (indexHasPayloads) {
payloadLength = payloadLengthBuffer[posBufferUpto];
payload.bytes = payloadBytes;
payload.offset = payloadByteUpto;
payload.length = payloadLength;
payloadByteUpto += payloadLength;
}
if (indexHasOffsets) {
startOffset = lastStartOffset + offsetStartDeltaBuffer[posBufferUpto];
endOffset = startOffset + offsetLengthBuffer[posBufferUpto];
lastStartOffset = startOffset;
}
posBufferUpto++;
posPendingCount--;
// if (DEBUG) {
// System.out.println(" return pos=" + position);
// }
return position;
}
@Override
public int startOffset() {
return startOffset;
}
@Override
public int endOffset() {
return endOffset;
}
@Override
public BytesRef getPayload() {
// if (DEBUG) {
// System.out.println(" FPR.getPayload payloadLength=" + payloadLength + " payloadByteUpto=" + payloadByteUpto);
// }
if (payloadLength == 0) {
return null;
} else {
return payload;
}
}
}
}
| lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java | package org.apache.lucene.codecs.lucene41;
/*
* 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.
*/
import static org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat.BLOCK_SIZE;
import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_DATA_SIZE;
import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_ENCODED_SIZE;
import java.io.IOException;
import java.util.Arrays;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.index.TermState;
import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
/**
* Concrete class that reads docId(maybe frq,pos,offset,payloads) list
* with postings format.
*
* @see Lucene41SkipReader for details
* @lucene.experimental
*/
public final class Lucene41PostingsReader extends PostingsReaderBase {
private final IndexInput docIn;
private final IndexInput posIn;
private final IndexInput payIn;
private final ForUtil forUtil;
// public static boolean DEBUG = false;
/** Sole constructor. */
public Lucene41PostingsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo segmentInfo, IOContext ioContext, String segmentSuffix) throws IOException {
boolean success = false;
IndexInput docIn = null;
IndexInput posIn = null;
IndexInput payIn = null;
try {
docIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.DOC_EXTENSION),
ioContext);
CodecUtil.checkHeader(docIn,
Lucene41PostingsWriter.DOC_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
forUtil = new ForUtil(docIn);
if (fieldInfos.hasProx()) {
posIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.POS_EXTENSION),
ioContext);
CodecUtil.checkHeader(posIn,
Lucene41PostingsWriter.POS_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
if (fieldInfos.hasPayloads() || fieldInfos.hasOffsets()) {
payIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Lucene41PostingsFormat.PAY_EXTENSION),
ioContext);
CodecUtil.checkHeader(payIn,
Lucene41PostingsWriter.PAY_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
}
}
this.docIn = docIn;
this.posIn = posIn;
this.payIn = payIn;
success = true;
} finally {
if (!success) {
IOUtils.closeWhileHandlingException(docIn, posIn, payIn);
}
}
}
@Override
public void init(IndexInput termsIn) throws IOException {
// Make sure we are talking to the matching postings writer
CodecUtil.checkHeader(termsIn,
Lucene41PostingsWriter.TERMS_CODEC,
Lucene41PostingsWriter.VERSION_CURRENT,
Lucene41PostingsWriter.VERSION_CURRENT);
final int indexBlockSize = termsIn.readVInt();
if (indexBlockSize != BLOCK_SIZE) {
throw new IllegalStateException("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + BLOCK_SIZE + ")");
}
}
/**
* Read values that have been written using variable-length encoding instead of bit-packing.
*/
private static void readVIntBlock(IndexInput docIn, int[] docBuffer,
int[] freqBuffer, int num, boolean indexHasFreq) throws IOException {
if (indexHasFreq) {
for(int i=0;i<num;i++) {
final int code = docIn.readVInt();
docBuffer[i] = code >>> 1;
if ((code & 1) != 0) {
freqBuffer[i] = 1;
} else {
freqBuffer[i] = docIn.readVInt();
}
}
} else {
for(int i=0;i<num;i++) {
docBuffer[i] = docIn.readVInt();
}
}
}
// Must keep final because we do non-standard clone
private final static class IntBlockTermState extends BlockTermState {
long docStartFP;
long posStartFP;
long payStartFP;
long skipOffset;
long lastPosBlockOffset;
// docid when there is a single pulsed posting, otherwise -1
// freq is always implicitly totalTermFreq in this case.
int singletonDocID;
// Only used by the "primary" TermState -- clones don't
// copy this (basically they are "transient"):
ByteArrayDataInput bytesReader; // TODO: should this NOT be in the TermState...?
byte[] bytes;
@Override
public IntBlockTermState clone() {
IntBlockTermState other = new IntBlockTermState();
other.copyFrom(this);
return other;
}
@Override
public void copyFrom(TermState _other) {
super.copyFrom(_other);
IntBlockTermState other = (IntBlockTermState) _other;
docStartFP = other.docStartFP;
posStartFP = other.posStartFP;
payStartFP = other.payStartFP;
lastPosBlockOffset = other.lastPosBlockOffset;
skipOffset = other.skipOffset;
singletonDocID = other.singletonDocID;
// Do not copy bytes, bytesReader (else TermState is
// very heavy, ie drags around the entire block's
// byte[]). On seek back, if next() is in fact used
// (rare!), they will be re-read from disk.
}
@Override
public String toString() {
return super.toString() + " docStartFP=" + docStartFP + " posStartFP=" + posStartFP + " payStartFP=" + payStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;
}
}
@Override
public IntBlockTermState newTermState() {
return new IntBlockTermState();
}
@Override
public void close() throws IOException {
IOUtils.close(docIn, posIn, payIn);
}
/* Reads but does not decode the byte[] blob holding
metadata for the current terms block */
@Override
public void readTermsBlock(IndexInput termsIn, FieldInfo fieldInfo, BlockTermState _termState) throws IOException {
final IntBlockTermState termState = (IntBlockTermState) _termState;
final int numBytes = termsIn.readVInt();
if (termState.bytes == null) {
termState.bytes = new byte[ArrayUtil.oversize(numBytes, 1)];
termState.bytesReader = new ByteArrayDataInput();
} else if (termState.bytes.length < numBytes) {
termState.bytes = new byte[ArrayUtil.oversize(numBytes, 1)];
}
termsIn.readBytes(termState.bytes, 0, numBytes);
termState.bytesReader.reset(termState.bytes, 0, numBytes);
}
@Override
public void nextTerm(FieldInfo fieldInfo, BlockTermState _termState)
throws IOException {
final IntBlockTermState termState = (IntBlockTermState) _termState;
final boolean isFirstTerm = termState.termBlockOrd == 0;
final boolean fieldHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
final boolean fieldHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
final boolean fieldHasPayloads = fieldInfo.hasPayloads();
final DataInput in = termState.bytesReader;
if (isFirstTerm) {
if (termState.docFreq == 1) {
termState.singletonDocID = in.readVInt();
termState.docStartFP = 0;
} else {
termState.singletonDocID = -1;
termState.docStartFP = in.readVLong();
}
if (fieldHasPositions) {
termState.posStartFP = in.readVLong();
if (termState.totalTermFreq > BLOCK_SIZE) {
termState.lastPosBlockOffset = in.readVLong();
} else {
termState.lastPosBlockOffset = -1;
}
if ((fieldHasPayloads || fieldHasOffsets) && termState.totalTermFreq >= BLOCK_SIZE) {
termState.payStartFP = in.readVLong();
} else {
termState.payStartFP = -1;
}
}
} else {
if (termState.docFreq == 1) {
termState.singletonDocID = in.readVInt();
} else {
termState.singletonDocID = -1;
termState.docStartFP += in.readVLong();
}
if (fieldHasPositions) {
termState.posStartFP += in.readVLong();
if (termState.totalTermFreq > BLOCK_SIZE) {
termState.lastPosBlockOffset = in.readVLong();
} else {
termState.lastPosBlockOffset = -1;
}
if ((fieldHasPayloads || fieldHasOffsets) && termState.totalTermFreq >= BLOCK_SIZE) {
long delta = in.readVLong();
if (termState.payStartFP == -1) {
termState.payStartFP = delta;
} else {
termState.payStartFP += delta;
}
}
}
}
if (termState.docFreq > BLOCK_SIZE) {
termState.skipOffset = in.readVLong();
} else {
termState.skipOffset = -1;
}
}
@Override
public DocsEnum docs(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
BlockDocsEnum docsEnum;
if (reuse instanceof BlockDocsEnum) {
docsEnum = (BlockDocsEnum) reuse;
if (!docsEnum.canReuse(docIn, fieldInfo)) {
docsEnum = new BlockDocsEnum(fieldInfo);
}
} else {
docsEnum = new BlockDocsEnum(fieldInfo);
}
return docsEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
}
// TODO: specialize to liveDocs vs not
@Override
public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs,
DocsAndPositionsEnum reuse, int flags)
throws IOException {
boolean indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
boolean indexHasPayloads = fieldInfo.hasPayloads();
if ((!indexHasOffsets || (flags & DocsAndPositionsEnum.FLAG_OFFSETS) == 0) &&
(!indexHasPayloads || (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) == 0)) {
BlockDocsAndPositionsEnum docsAndPositionsEnum;
if (reuse instanceof BlockDocsAndPositionsEnum) {
docsAndPositionsEnum = (BlockDocsAndPositionsEnum) reuse;
if (!docsAndPositionsEnum.canReuse(docIn, fieldInfo)) {
docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
}
} else {
docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
}
return docsAndPositionsEnum.reset(liveDocs, (IntBlockTermState) termState);
} else {
EverythingEnum everythingEnum;
if (reuse instanceof EverythingEnum) {
everythingEnum = (EverythingEnum) reuse;
if (!everythingEnum.canReuse(docIn, fieldInfo)) {
everythingEnum = new EverythingEnum(fieldInfo);
}
} else {
everythingEnum = new EverythingEnum(fieldInfo);
}
return everythingEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
}
}
final class BlockDocsEnum extends DocsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private int docBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final boolean indexHasFreq;
final boolean indexHasPos;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // sum of freqs in this posting list (or docFreq when omitted)
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
// docID for next skip point, we won't use skipper if
// target docID is not larger than this
private int nextSkipDoc;
private Bits liveDocs;
private boolean needsFreq; // true if the caller actually needs frequencies
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public BlockDocsEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
indexHasFreq = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
indexHasPos = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
indexHasPayloads = fieldInfo.hasPayloads();
encoded = new byte[MAX_ENCODED_SIZE];
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasFreq == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0) &&
indexHasPos == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public DocsEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
totalTermFreq = indexHasFreq ? termState.totalTermFreq : docFreq;
docTermStartFP = termState.docStartFP;
skipOffset = termState.skipOffset;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
doc = -1;
this.needsFreq = (flags & DocsEnum.FLAG_FREQS) != 0;
if (!indexHasFreq) {
Arrays.fill(freqBuffer, 1);
}
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1; // we won't skip if target is found in first block
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
if (indexHasFreq) {
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
if (needsFreq) {
forUtil.readBlock(docIn, encoded, freqBuffer);
} else {
forUtil.skipBlock(docIn); // skip over freqs
}
}
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// Read vInts:
// if (DEBUG) {
// System.out.println(" fill last vInt block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, indexHasFreq);
}
docBufferUpto = 0;
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println("\nFPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
// if (DEBUG) {
// System.out.println(" return doc=END");
// }
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
freq = freqBuffer[docBufferUpto];
docBufferUpto++;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq);
// }
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
docBufferUpto++;
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
// current skip docID < docIDs generated from current buffer <= next skip docID
// we don't need to skip if target is buffered already
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println("load skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
indexHasPos,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
skipper.init(docTermStartFP+skipOffset, docTermStartFP, 0, 0, docFreq);
skipped = true;
}
// always plus one to fix the result, since skip position in Lucene41SkipReader
// is a little different from MultiLevelSkipListReader
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println("skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer());
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc(); // actually, this is just lastSkipEntry
docIn.seek(skipper.getDocPointer()); // now point to the block we want to search
}
// next time we call advance, this is used to
// foresee whether skipper is necessary.
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan... this is an inlined/pared down version
// of nextDoc():
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
docUpto++;
if (accum >= target) {
break;
}
docBufferUpto++;
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
freq = freqBuffer[docBufferUpto];
docBufferUpto++;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
docBufferUpto++;
return nextDoc();
}
}
}
final class BlockDocsAndPositionsEnum extends DocsAndPositionsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
private int docBufferUpto;
private int posBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final IndexInput posIn;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // number of positions in this posting list
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
private int position; // current position
// how many positions "behind" we are; nextPosition must
// skip these to "catch up":
private int posPendingCount;
// Lazy pos seek: if != -1 then we must seek to this FP
// before reading positions:
private long posPendingFP;
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's postings start in the .pos file:
private long posTermStartFP;
// Where this term's payloads/offsets start in the .pay
// file:
private long payTermStartFP;
// File pointer where the last (vInt encoded) pos delta
// block is. We need this to know whether to bulk
// decode vs vInt decode the block:
private long lastPosBlockFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
private int nextSkipDoc;
private Bits liveDocs;
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public BlockDocsAndPositionsEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
this.posIn = Lucene41PostingsReader.this.posIn.clone();
encoded = new byte[MAX_ENCODED_SIZE];
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
indexHasPayloads = fieldInfo.hasPayloads();
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public DocsAndPositionsEnum reset(Bits liveDocs, IntBlockTermState termState) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
docTermStartFP = termState.docStartFP;
posTermStartFP = termState.posStartFP;
payTermStartFP = termState.payStartFP;
skipOffset = termState.skipOffset;
totalTermFreq = termState.totalTermFreq;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
posPendingFP = posTermStartFP;
posPendingCount = 0;
if (termState.totalTermFreq < BLOCK_SIZE) {
lastPosBlockFP = posTermStartFP;
} else if (termState.totalTermFreq == BLOCK_SIZE) {
lastPosBlockFP = -1;
} else {
lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
}
doc = -1;
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1;
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, freqBuffer);
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// Read vInts:
// if (DEBUG) {
// System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
}
docBufferUpto = 0;
}
private void refillPositions() throws IOException {
// if (DEBUG) {
// System.out.println(" refillPositions");
// }
if (posIn.getFilePointer() == lastPosBlockFP) {
// if (DEBUG) {
// System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
// }
final int count = (int) (totalTermFreq % BLOCK_SIZE);
int payloadLength = 0;
for(int i=0;i<count;i++) {
int code = posIn.readVInt();
if (indexHasPayloads) {
if ((code & 1) != 0) {
payloadLength = posIn.readVInt();
}
posDeltaBuffer[i] = code >>> 1;
if (payloadLength != 0) {
posIn.seek(posIn.getFilePointer() + payloadLength);
}
} else {
posDeltaBuffer[i] = code;
}
if (indexHasOffsets) {
if ((posIn.readVInt() & 1) != 0) {
// offset length changed
posIn.readVInt();
}
}
}
} else {
// if (DEBUG) {
// System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
// }
forUtil.readBlock(posIn, encoded, posDeltaBuffer);
}
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
position = 0;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
// }
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println(" try skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
// if (DEBUG) {
// System.out.println(" create skipper");
// }
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
true,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
// if (DEBUG) {
// System.out.println(" init skipper");
// }
skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
skipped = true;
}
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto());
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc();
docIn.seek(skipper.getDocPointer());
posPendingFP = skipper.getPosPointer();
posPendingCount = skipper.getPosBufferUpto();
}
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan... this is an inlined/pared down version
// of nextDoc():
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (accum >= target) {
break;
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
position = 0;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
return nextDoc();
}
}
// TODO: in theory we could avoid loading frq block
// when not needed, ie, use skip data to load how far to
// seek the pos pointer ... instead of having to load frq
// blocks only to sum up how many positions to skip
private void skipPositions() throws IOException {
// Skip positions now:
int toSkip = posPendingCount - freq;
// if (DEBUG) {
// System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
// }
final int leftInBlock = BLOCK_SIZE - posBufferUpto;
if (toSkip < leftInBlock) {
posBufferUpto += toSkip;
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
} else {
toSkip -= leftInBlock;
while(toSkip >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
// }
assert posIn.getFilePointer() != lastPosBlockFP;
forUtil.skipBlock(posIn);
toSkip -= BLOCK_SIZE;
}
refillPositions();
posBufferUpto = toSkip;
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
}
position = 0;
}
@Override
public int nextPosition() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto);
// }
if (posPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek to pendingFP=" + posPendingFP);
// }
posIn.seek(posPendingFP);
posPendingFP = -1;
// Force buffer refill:
posBufferUpto = BLOCK_SIZE;
}
if (posPendingCount > freq) {
skipPositions();
posPendingCount = freq;
}
if (posBufferUpto == BLOCK_SIZE) {
refillPositions();
posBufferUpto = 0;
}
position += posDeltaBuffer[posBufferUpto++];
posPendingCount--;
// if (DEBUG) {
// System.out.println(" return pos=" + position);
// }
return position;
}
@Override
public int startOffset() {
return -1;
}
@Override
public int endOffset() {
return -1;
}
@Override
public BytesRef getPayload() {
return null;
}
}
// Also handles payloads + offsets
final class EverythingEnum extends DocsAndPositionsEnum {
private final byte[] encoded;
private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] freqBuffer = new int[MAX_DATA_SIZE];
private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
private final int[] payloadLengthBuffer;
private final int[] offsetStartDeltaBuffer;
private final int[] offsetLengthBuffer;
private byte[] payloadBytes;
private int payloadByteUpto;
private int payloadLength;
private int lastStartOffset;
private int startOffset;
private int endOffset;
private int docBufferUpto;
private int posBufferUpto;
private Lucene41SkipReader skipper;
private boolean skipped;
final IndexInput startDocIn;
IndexInput docIn;
final IndexInput posIn;
final IndexInput payIn;
final BytesRef payload;
final boolean indexHasOffsets;
final boolean indexHasPayloads;
private int docFreq; // number of docs in this posting list
private long totalTermFreq; // number of positions in this posting list
private int docUpto; // how many docs we've read
private int doc; // doc we last read
private int accum; // accumulator for doc deltas
private int freq; // freq we last read
private int position; // current position
// how many positions "behind" we are; nextPosition must
// skip these to "catch up":
private int posPendingCount;
// Lazy pos seek: if != -1 then we must seek to this FP
// before reading positions:
private long posPendingFP;
// Lazy pay seek: if != -1 then we must seek to this FP
// before reading payloads/offsets:
private long payPendingFP;
// Where this term's postings start in the .doc file:
private long docTermStartFP;
// Where this term's postings start in the .pos file:
private long posTermStartFP;
// Where this term's payloads/offsets start in the .pay
// file:
private long payTermStartFP;
// File pointer where the last (vInt encoded) pos delta
// block is. We need this to know whether to bulk
// decode vs vInt decode the block:
private long lastPosBlockFP;
// Where this term's skip data starts (after
// docTermStartFP) in the .doc file (or -1 if there is
// no skip data for this term):
private long skipOffset;
private int nextSkipDoc;
private Bits liveDocs;
private boolean needsOffsets; // true if we actually need offsets
private boolean needsPayloads; // true if we actually need payloads
private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
public EverythingEnum(FieldInfo fieldInfo) throws IOException {
this.startDocIn = Lucene41PostingsReader.this.docIn;
this.docIn = null;
this.posIn = Lucene41PostingsReader.this.posIn.clone();
this.payIn = Lucene41PostingsReader.this.payIn.clone();
encoded = new byte[MAX_ENCODED_SIZE];
indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
if (indexHasOffsets) {
offsetStartDeltaBuffer = new int[MAX_DATA_SIZE];
offsetLengthBuffer = new int[MAX_DATA_SIZE];
} else {
offsetStartDeltaBuffer = null;
offsetLengthBuffer = null;
startOffset = -1;
endOffset = -1;
}
indexHasPayloads = fieldInfo.hasPayloads();
if (indexHasPayloads) {
payloadLengthBuffer = new int[MAX_DATA_SIZE];
payloadBytes = new byte[128];
payload = new BytesRef();
} else {
payloadLengthBuffer = null;
payloadBytes = null;
payload = null;
}
}
public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
return docIn == startDocIn &&
indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
indexHasPayloads == fieldInfo.hasPayloads();
}
public EverythingEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
this.liveDocs = liveDocs;
// if (DEBUG) {
// System.out.println(" FPR.reset: termState=" + termState);
// }
docFreq = termState.docFreq;
docTermStartFP = termState.docStartFP;
posTermStartFP = termState.posStartFP;
payTermStartFP = termState.payStartFP;
skipOffset = termState.skipOffset;
totalTermFreq = termState.totalTermFreq;
singletonDocID = termState.singletonDocID;
if (docFreq > 1) {
if (docIn == null) {
// lazy init
docIn = startDocIn.clone();
}
docIn.seek(docTermStartFP);
}
posPendingFP = posTermStartFP;
payPendingFP = payTermStartFP;
posPendingCount = 0;
if (termState.totalTermFreq < BLOCK_SIZE) {
lastPosBlockFP = posTermStartFP;
} else if (termState.totalTermFreq == BLOCK_SIZE) {
lastPosBlockFP = -1;
} else {
lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
}
this.needsOffsets = (flags & DocsAndPositionsEnum.FLAG_OFFSETS) != 0;
this.needsPayloads = (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) != 0;
doc = -1;
accum = 0;
docUpto = 0;
nextSkipDoc = BLOCK_SIZE - 1;
docBufferUpto = BLOCK_SIZE;
skipped = false;
return this;
}
@Override
public int freq() throws IOException {
return freq;
}
@Override
public int docID() {
return doc;
}
private void refillDocs() throws IOException {
final int left = docFreq - docUpto;
assert left > 0;
if (left >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, docDeltaBuffer);
// if (DEBUG) {
// System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
// }
forUtil.readBlock(docIn, encoded, freqBuffer);
} else if (docFreq == 1) {
docDeltaBuffer[0] = singletonDocID;
freqBuffer[0] = (int) totalTermFreq;
} else {
// if (DEBUG) {
// System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
// }
readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
}
docBufferUpto = 0;
}
private void refillPositions() throws IOException {
// if (DEBUG) {
// System.out.println(" refillPositions");
// }
if (posIn.getFilePointer() == lastPosBlockFP) {
// if (DEBUG) {
// System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
// }
final int count = (int) (totalTermFreq % BLOCK_SIZE);
int payloadLength = 0;
int offsetLength = 0;
payloadByteUpto = 0;
for(int i=0;i<count;i++) {
int code = posIn.readVInt();
if (indexHasPayloads) {
if ((code & 1) != 0) {
payloadLength = posIn.readVInt();
}
// if (DEBUG) {
// System.out.println(" i=" + i + " payloadLen=" + payloadLength);
// }
payloadLengthBuffer[i] = payloadLength;
posDeltaBuffer[i] = code >>> 1;
if (payloadLength != 0) {
if (payloadByteUpto + payloadLength > payloadBytes.length) {
payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payloadLength);
}
//System.out.println(" read payload @ pos.fp=" + posIn.getFilePointer());
posIn.readBytes(payloadBytes, payloadByteUpto, payloadLength);
payloadByteUpto += payloadLength;
}
} else {
posDeltaBuffer[i] = code;
}
if (indexHasOffsets) {
// if (DEBUG) {
// System.out.println(" i=" + i + " read offsets from posIn.fp=" + posIn.getFilePointer());
// }
int deltaCode = posIn.readVInt();
if ((deltaCode & 1) != 0) {
offsetLength = posIn.readVInt();
}
offsetStartDeltaBuffer[i] = deltaCode >>> 1;
offsetLengthBuffer[i] = offsetLength;
// if (DEBUG) {
// System.out.println(" startOffDelta=" + offsetStartDeltaBuffer[i] + " offsetLen=" + offsetLengthBuffer[i]);
// }
}
}
payloadByteUpto = 0;
} else {
// if (DEBUG) {
// System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
// }
forUtil.readBlock(posIn, encoded, posDeltaBuffer);
if (indexHasPayloads) {
// if (DEBUG) {
// System.out.println(" bulk payload block @ pay.fp=" + payIn.getFilePointer());
// }
if (needsPayloads) {
forUtil.readBlock(payIn, encoded, payloadLengthBuffer);
int numBytes = payIn.readVInt();
// if (DEBUG) {
// System.out.println(" " + numBytes + " payload bytes @ pay.fp=" + payIn.getFilePointer());
// }
if (numBytes > payloadBytes.length) {
payloadBytes = ArrayUtil.grow(payloadBytes, numBytes);
}
payIn.readBytes(payloadBytes, 0, numBytes);
} else {
// this works, because when writing a vint block we always force the first length to be written
forUtil.skipBlock(payIn); // skip over lengths
int numBytes = payIn.readVInt(); // read length of payloadBytes
payIn.seek(payIn.getFilePointer() + numBytes); // skip over payloadBytes
}
payloadByteUpto = 0;
}
if (indexHasOffsets) {
// if (DEBUG) {
// System.out.println(" bulk offset block @ pay.fp=" + payIn.getFilePointer());
// }
if (needsOffsets) {
forUtil.readBlock(payIn, encoded, offsetStartDeltaBuffer);
forUtil.readBlock(payIn, encoded, offsetLengthBuffer);
} else {
// this works, because when writing a vint block we always force the first length to be written
forUtil.skipBlock(payIn); // skip over starts
forUtil.skipBlock(payIn); // skip over lengths
}
}
}
}
@Override
public int nextDoc() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextDoc");
// }
while (true) {
// if (DEBUG) {
// System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
// }
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// if (DEBUG) {
// System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (liveDocs == null || liveDocs.get(accum)) {
doc = accum;
// if (DEBUG) {
// System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
// }
position = 0;
lastStartOffset = 0;
return doc;
}
// if (DEBUG) {
// System.out.println(" doc=" + accum + " is deleted; try next doc");
// }
}
}
@Override
public int advance(int target) throws IOException {
// TODO: make frq block load lazy/skippable
// if (DEBUG) {
// System.out.println(" FPR.advance target=" + target);
// }
if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
// if (DEBUG) {
// System.out.println(" try skipper");
// }
if (skipper == null) {
// Lazy init: first time this enum has ever been used for skipping
// if (DEBUG) {
// System.out.println(" create skipper");
// }
skipper = new Lucene41SkipReader(docIn.clone(),
Lucene41PostingsWriter.maxSkipLevels,
BLOCK_SIZE,
true,
indexHasOffsets,
indexHasPayloads);
}
if (!skipped) {
assert skipOffset != -1;
// This is the first time this enum has skipped
// since reset() was called; load the skip data:
// if (DEBUG) {
// System.out.println(" init skipper");
// }
skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
skipped = true;
}
final int newDocUpto = skipper.skipTo(target) + 1;
if (newDocUpto > docUpto) {
// Skipper moved
// if (DEBUG) {
// System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto() + " pay.fp=" + skipper.getPayPointer() + " lastStartOffset=" + lastStartOffset);
// }
assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
docUpto = newDocUpto;
// Force to read next block
docBufferUpto = BLOCK_SIZE;
accum = skipper.getDoc();
docIn.seek(skipper.getDocPointer());
posPendingFP = skipper.getPosPointer();
payPendingFP = skipper.getPayPointer();
posPendingCount = skipper.getPosBufferUpto();
lastStartOffset = 0; // new document
payloadByteUpto = skipper.getPayloadByteUpto();
}
nextSkipDoc = skipper.getNextSkipDoc();
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
if (docBufferUpto == BLOCK_SIZE) {
refillDocs();
}
// Now scan:
while (true) {
// if (DEBUG) {
// System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
// }
accum += docDeltaBuffer[docBufferUpto];
freq = freqBuffer[docBufferUpto];
posPendingCount += freq;
docBufferUpto++;
docUpto++;
if (accum >= target) {
break;
}
if (docUpto == docFreq) {
return doc = NO_MORE_DOCS;
}
}
if (liveDocs == null || liveDocs.get(accum)) {
// if (DEBUG) {
// System.out.println(" return doc=" + accum);
// }
position = 0;
lastStartOffset = 0;
return doc = accum;
} else {
// if (DEBUG) {
// System.out.println(" now do nextDoc()");
// }
return nextDoc();
}
}
// TODO: in theory we could avoid loading frq block
// when not needed, ie, use skip data to load how far to
// seek the pos pointer ... instead of having to load frq
// blocks only to sum up how many positions to skip
private void skipPositions() throws IOException {
// Skip positions now:
int toSkip = posPendingCount - freq;
// if (DEBUG) {
// System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
// }
final int leftInBlock = BLOCK_SIZE - posBufferUpto;
if (toSkip < leftInBlock) {
int end = posBufferUpto + toSkip;
while(posBufferUpto < end) {
if (indexHasPayloads) {
payloadByteUpto += payloadLengthBuffer[posBufferUpto];
}
posBufferUpto++;
}
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
} else {
toSkip -= leftInBlock;
while(toSkip >= BLOCK_SIZE) {
// if (DEBUG) {
// System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
// }
assert posIn.getFilePointer() != lastPosBlockFP;
forUtil.skipBlock(posIn);
if (indexHasPayloads) {
// Skip payloadLength block:
forUtil.skipBlock(payIn);
// Skip payloadBytes block:
int numBytes = payIn.readVInt();
payIn.seek(payIn.getFilePointer() + numBytes);
}
if (indexHasOffsets) {
forUtil.skipBlock(payIn);
forUtil.skipBlock(payIn);
}
toSkip -= BLOCK_SIZE;
}
refillPositions();
payloadByteUpto = 0;
posBufferUpto = 0;
while(posBufferUpto < toSkip) {
if (indexHasPayloads) {
payloadByteUpto += payloadLengthBuffer[posBufferUpto];
}
posBufferUpto++;
}
// if (DEBUG) {
// System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
// }
}
position = 0;
lastStartOffset = 0;
}
@Override
public int nextPosition() throws IOException {
// if (DEBUG) {
// System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto + " payloadByteUpto=" + payloadByteUpto)// ;
// }
if (posPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek pos to pendingFP=" + posPendingFP);
// }
posIn.seek(posPendingFP);
posPendingFP = -1;
if (payPendingFP != -1) {
// if (DEBUG) {
// System.out.println(" seek pay to pendingFP=" + payPendingFP);
// }
payIn.seek(payPendingFP);
payPendingFP = -1;
}
// Force buffer refill:
posBufferUpto = BLOCK_SIZE;
}
if (posPendingCount > freq) {
skipPositions();
posPendingCount = freq;
}
if (posBufferUpto == BLOCK_SIZE) {
refillPositions();
posBufferUpto = 0;
}
position += posDeltaBuffer[posBufferUpto];
if (indexHasPayloads) {
payloadLength = payloadLengthBuffer[posBufferUpto];
payload.bytes = payloadBytes;
payload.offset = payloadByteUpto;
payload.length = payloadLength;
payloadByteUpto += payloadLength;
}
if (indexHasOffsets) {
startOffset = lastStartOffset + offsetStartDeltaBuffer[posBufferUpto];
endOffset = startOffset + offsetLengthBuffer[posBufferUpto];
lastStartOffset = startOffset;
}
posBufferUpto++;
posPendingCount--;
// if (DEBUG) {
// System.out.println(" return pos=" + position);
// }
return position;
}
@Override
public int startOffset() {
return startOffset;
}
@Override
public int endOffset() {
return endOffset;
}
@Override
public BytesRef getPayload() {
// if (DEBUG) {
// System.out.println(" FPR.getPayload payloadLength=" + payloadLength + " payloadByteUpto=" + payloadByteUpto);
// }
if (payloadLength == 0) {
return null;
} else {
return payload;
}
}
}
}
| make package private to avoid access$N at runtime
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1420488 13f79535-47bb-0310-9956-ffa450edef68
| lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java | make package private to avoid access$N at runtime |
|
Java | apache-2.0 | 3a6aa8d80cdca35bf293d48c9af21a3129e6bb4d | 0 | alex-bl/ivyDEextension,alex-bl/ivyDEextension,apache/ant-ivyde,apache/ant-ivyde | /*
* 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.ivyde.eclipse.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.ivy.core.module.descriptor.Configuration;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.TableColumn;
public class ConfTableViewer extends Composite {
private CheckboxTableViewer confTableViewer;
private final List listeners = new ArrayList();
private Button selectAll;
private Button up;
private Button down;
private Configuration[] orderedConfigurations = new Configuration[0];
private Button all;
private Button none;
public ConfTableViewer(Composite parent, int style) {
super(parent, style);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
setLayout(layout);
selectAll = new Button(this, SWT.CHECK);
selectAll.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
selectAll.setText("Select every configuration");
selectAll.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled = !selectAll.getSelection();
confTableViewer.getTable().setEnabled(enabled);
updateAllNoneEnableButtons(enabled);
updateUpDownEnableButtons(enabled);
confTableUpdated();
}
});
confTableViewer = CheckboxTableViewer.newCheckList(this, SWT.BORDER | SWT.H_SCROLL
| SWT.V_SCROLL);
confTableViewer.getTable().setHeaderVisible(true);
confTableViewer.getTable().setLayoutData(
new GridData(GridData.FILL, GridData.FILL, true, true));
TableColumn col1 = new TableColumn(confTableViewer.getTable(), SWT.NONE);
col1.setText("Name");
// CheckStyle:MagicNumber| OFF
col1.setWidth(100);
TableColumn col2 = new TableColumn(confTableViewer.getTable(), SWT.NONE);
col2.setText("Description");
col2.setWidth(300);
// CheckStyle:MagicNumber| ON
confTableViewer.setColumnProperties(new String[] {"Name", "Description"});
confTableViewer.getTable().setLayoutData(
new GridData(GridData.FILL, GridData.FILL, true, true));
confTableViewer.setContentProvider(ArrayContentProvider.getInstance());
confTableViewer.setLabelProvider(new ConfigurationLabelProvider());
confTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateUpDownEnableButtons(true);
updateAllNoneEnableButtons(true);
confTableUpdated();
}
});
Composite upDownButtons = new Composite(this, SWT.NONE);
upDownButtons.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, true));
upDownButtons.setLayout(new GridLayout());
all = new Button(upDownButtons, SWT.PUSH);
all.setText("All");
all.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
all.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
confTableViewer.setCheckedElements(orderedConfigurations);
updateAllNoneEnableButtons(true);
}
});
none = new Button(upDownButtons, SWT.PUSH);
none.setText("None");
none.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
none.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
confTableViewer.setCheckedElements(new Configuration[0]);
updateAllNoneEnableButtons(true);
}
});
up = new Button(upDownButtons, SWT.PUSH);
up.setText("Up");
up.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
up.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int i = getSelectedConfigurationIndex();
Configuration c = orderedConfigurations[i];
orderedConfigurations[i] = orderedConfigurations[i - 1];
orderedConfigurations[i - 1] = c;
confTableViewer.refresh();
updateUpDownEnableButtons(true);
}
});
down = new Button(upDownButtons, SWT.PUSH);
down.setText("Down");
down.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
down.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int i = getSelectedConfigurationIndex();
Configuration c = orderedConfigurations[i];
orderedConfigurations[i] = orderedConfigurations[i + 1];
orderedConfigurations[i + 1] = c;
confTableViewer.refresh();
updateUpDownEnableButtons(true);
}
});
}
private int getSelectedConfigurationIndex() {
IStructuredSelection selection = (IStructuredSelection) confTableViewer.getSelection();
Configuration c = (Configuration) selection.getFirstElement();
for (int i = 0; i < orderedConfigurations.length; i++) {
if (orderedConfigurations[i] == c) {
return i;
}
}
return -1;
}
private void updateUpDownEnableButtons(boolean enabled) {
boolean selected = confTableViewer.getTable().getSelectionCount() != 0;
int i = getSelectedConfigurationIndex();
up.setEnabled(enabled && selected && i > 0);
down.setEnabled(enabled && selected && i < orderedConfigurations.length - 1);
}
private void updateAllNoneEnableButtons(boolean enabled) {
int nbChecked = confTableViewer.getCheckedElements().length;
all.setEnabled(!selectAll.getSelection() && nbChecked != orderedConfigurations.length);
none.setEnabled(!selectAll.getSelection() && nbChecked > 0);
}
public void setModuleDescriptor(ModuleDescriptor md) {
if (md == null) {
orderedConfigurations = new Configuration[0];
} else {
orderedConfigurations = md.getConfigurations();
}
confTableViewer.setInput(orderedConfigurations);
}
public void init(List/* <String> */confs) {
boolean enabled;
if (confs.size() == 1 && "*".equals(confs.get(0))) {
enabled = true;
selectAll.setSelection(true);
for (int i = 0; i < orderedConfigurations.length; i++) {
confTableViewer.setChecked(orderedConfigurations[i], true);
}
} else {
enabled = false;
selectAll.setSelection(false);
for (int i = 0; i < confs.size(); i++) {
String c = (String) confs.get(i);
for (int j = 0; j < orderedConfigurations.length; j++) {
if (orderedConfigurations[j].getName().equals(c)) {
confTableViewer.setChecked(orderedConfigurations[j], true);
break;
}
}
}
}
confTableViewer.getTable().setEnabled(!selectAll.getSelection());
updateAllNoneEnableButtons(enabled);
updateUpDownEnableButtons(enabled);
}
public List getSelectedConfigurations() {
if (selectAll.getSelection()) {
return Arrays.asList(new String[] {"*"});
}
Object[] confs = confTableViewer.getCheckedElements();
List confList = new ArrayList();
for (int i = 0; i < confs.length; i++) {
Configuration c = (Configuration) confs[i];
confList.add(c.getName());
}
return confList;
}
static class ConfigurationLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (columnIndex == 0) {
return ((Configuration) element).getName();
}
return ((Configuration) element).getDescription();
}
}
public interface ConfTableListener {
void confTableUpdated(List confs);
}
public void addListener(ConfTableListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void remodeListener(ConfTableListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
void confTableUpdated() {
synchronized (listeners) {
Iterator it = listeners.iterator();
while (it.hasNext()) {
((ConfTableListener) it.next()).confTableUpdated(getSelectedConfigurations());
}
}
}
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
selectAll.setEnabled(enabled);
updateUpDownEnableButtons(enabled);
updateAllNoneEnableButtons(enabled);
}
}
| org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/ui/ConfTableViewer.java | /*
* 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.ivyde.eclipse.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.ivy.core.module.descriptor.Configuration;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableColumn;
public class ConfTableViewer extends Composite {
private CheckboxTableViewer confTableViewer;
private final List listeners = new ArrayList();
private Button selectAll;
private Button up;
private Button down;
private Configuration[] orderedConfigurations = new Configuration[0];
public ConfTableViewer(Composite parent, int style) {
super(parent, style);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
setLayout(layout);
selectAll = new Button(this, SWT.CHECK);
selectAll.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
selectAll.setText("Select every configuration");
selectAll.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
confTableViewer.getTable().setEnabled(!selectAll.getSelection());
confTableUpdated();
}
});
confTableViewer = CheckboxTableViewer.newCheckList(this, SWT.BORDER | SWT.H_SCROLL
| SWT.V_SCROLL);
confTableViewer.getTable().setHeaderVisible(true);
confTableViewer.getTable().setLayoutData(
new GridData(GridData.FILL, GridData.FILL, true, true));
TableColumn col1 = new TableColumn(confTableViewer.getTable(), SWT.NONE);
col1.setText("Name");
// CheckStyle:MagicNumber| OFF
col1.setWidth(100);
TableColumn col2 = new TableColumn(confTableViewer.getTable(), SWT.NONE);
col2.setText("Description");
col2.setWidth(300);
// CheckStyle:MagicNumber| ON
confTableViewer.setColumnProperties(new String[] {"Name", "Description"});
confTableViewer.getTable().setLayoutData(
new GridData(GridData.FILL, GridData.FILL, true, true));
confTableViewer.setContentProvider(ArrayContentProvider.getInstance());
confTableViewer.setLabelProvider(new ConfigurationLabelProvider());
confTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateUpDownEnableButtons();
confTableUpdated();
}
});
Composite upDownButtons = new Composite(this, SWT.NONE);
upDownButtons.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, true));
upDownButtons.setLayout(new GridLayout());
up = new Button(upDownButtons, SWT.PUSH);
up.setText("Up");
up.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
up.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int i = getSelectedConfigurationIndex();
Configuration c = orderedConfigurations[i];
orderedConfigurations[i] = orderedConfigurations[i - 1];
orderedConfigurations[i - 1] = c;
confTableViewer.refresh();
updateUpDownEnableButtons();
}
});
down = new Button(upDownButtons, SWT.PUSH);
down.setText("Down");
down.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
down.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int i = getSelectedConfigurationIndex();
Configuration c = orderedConfigurations[i];
orderedConfigurations[i] = orderedConfigurations[i + 1];
orderedConfigurations[i + 1] = c;
confTableViewer.refresh();
updateUpDownEnableButtons();
}
});
}
private int getSelectedConfigurationIndex() {
IStructuredSelection selection = (IStructuredSelection) confTableViewer.getSelection();
Configuration c = (Configuration) selection.getFirstElement();
for (int i = 0; i < orderedConfigurations.length; i++) {
if (orderedConfigurations[i] == c) {
return i;
}
}
return -1;
}
private void updateUpDownEnableButtons() {
boolean selected = confTableViewer.getTable().getSelectionCount() != 0;
int i = getSelectedConfigurationIndex();
up.setEnabled(selected && i > 0);
down.setEnabled(selected && i < orderedConfigurations.length - 1);
}
public void setModuleDescriptor(ModuleDescriptor md) {
if (md == null) {
orderedConfigurations = new Configuration[0];
} else {
orderedConfigurations = md.getConfigurations();
}
confTableViewer.setInput(orderedConfigurations);
}
public void init(List/* <String> */confs) {
if (confs.size() == 1 && "*".equals(confs.get(0))) {
selectAll.setSelection(true);
for (int i = 0; i < orderedConfigurations.length; i++) {
confTableViewer.setChecked(orderedConfigurations[i], true);
}
} else {
selectAll.setSelection(false);
for (int i = 0; i < confs.size(); i++) {
String c = (String) confs.get(i);
for (int j = 0; j < orderedConfigurations.length; j++) {
if (orderedConfigurations[j].getName().equals(c)) {
confTableViewer.setChecked(orderedConfigurations[j], true);
break;
}
}
}
}
confTableViewer.getTable().setEnabled(!selectAll.getSelection());
boolean selected = confTableViewer.getTable().getSelectionCount() != 0;
up.setEnabled(!selectAll.getSelection() && selected);
down.setEnabled(!selectAll.getSelection() && selected);
}
public List getSelectedConfigurations() {
if (selectAll.getSelection()) {
return Arrays.asList(new String[] {"*"});
}
Object[] confs = confTableViewer.getCheckedElements();
List confList = new ArrayList();
for (int i = 0; i < confs.length; i++) {
Configuration c = (Configuration) confs[i];
confList.add(c.getName());
}
return confList;
}
static class ConfigurationLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (columnIndex == 0) {
return ((Configuration) element).getName();
}
return ((Configuration) element).getDescription();
}
}
public interface ConfTableListener {
void confTableUpdated(List confs);
}
public void addListener(ConfTableListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void remodeListener(ConfTableListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
void confTableUpdated() {
synchronized (listeners) {
Iterator it = listeners.iterator();
while (it.hasNext()) {
((ConfTableListener) it.next()).confTableUpdated(getSelectedConfigurations());
}
}
}
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
confTableViewer.getTable().setEnabled(enabled && !selectAll.getSelection());
boolean selected = confTableViewer.getTable().getSelectionCount() != 0;
up.setEnabled(enabled && !selectAll.getSelection() && selected);
down.setEnabled(enabled && !selectAll.getSelection() && selected);
selectAll.setEnabled(enabled);
}
}
| IVYDE-286:
- add the All/None links back
git-svn-id: 804c0f3032317a396a1b8894d1ed8cc0b56e9f1c@1189870 13f79535-47bb-0310-9956-ffa450edef68
| org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/ui/ConfTableViewer.java | IVYDE-286: - add the All/None links back |
|
Java | apache-2.0 | a0f5208f10009b0e074b919a7fd301ae47e57115 | 0 | alfonsodou/jfootball | package org.javahispano.jfootball;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
public class Jfootball extends ApplicationAdapter {
public Environment environment;
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public AssetManager assets;
public OrthographicCamera orthoCam;
public SpriteBatch spriteBatch;
public BitmapFont font;
public StringBuilder stringBuilder = new StringBuilder();
private Vector3 position = new Vector3();
@Override
public void create() {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
modelBatch = new ModelBatch();
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(5, 20, 20);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 100f;
cam.update();
assets = new AssetManager();
assets.load("Ball.g3db", Model.class);
assets.finishLoading();
model = assets.get("Ball.g3db", Model.class);
for (float x = -30; x <= 10f; x += 20) {
for (float z = -30f; z <= 0f; z += 10f) {
ModelInstance instance = new ModelInstance(model);
instance.transform.setToTranslation(x, 0, z);
instances.add(instance);
}
}
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
orthoCam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
orthoCam.position.set(Gdx.graphics.getWidth() / 2f, Gdx.graphics.getHeight() / 2f, 0);
spriteBatch = new SpriteBatch();
font = new BitmapFont();
}
@Override
public void render() {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
int count = 0;
for (ModelInstance instance : instances) {
if (isVisible(cam, instance)) {
modelBatch.render(instance, environment);
count++;
}
}
modelBatch.end();
orthoCam.update();
spriteBatch.setProjectionMatrix(orthoCam.combined);
spriteBatch.begin();
stringBuilder.setLength(0);
stringBuilder.append("FPS: " + Gdx.graphics.getFramesPerSecond()).append("\n");
stringBuilder.append("Balls: " + count).append("\n");
stringBuilder.append("Total: " + instances.size).append("\n");
font.draw(spriteBatch, stringBuilder, 0, Gdx.graphics.getHeight());
spriteBatch.end();
}
@Override
public void dispose() {
modelBatch.dispose();
assets.dispose();
}
private boolean isVisible(final Camera cam, final ModelInstance instance) {
instance.transform.getTranslation(position);
return cam.frustum.pointInFrustum(position);
}
}
| core/src/org/javahispano/jfootball/Jfootball.java | package org.javahispano.jfootball;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
public class Jfootball extends ApplicationAdapter {
public Environment environment;
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public ModelInstance instance;
public AssetManager assets;
@Override
public void create() {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
modelBatch = new ModelBatch();
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(1, 1, 1);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
assets = new AssetManager();
assets.load("Ball.g3db", Model.class);
assets.finishLoading();
model = assets.get("Ball.g3db", Model.class);
instance = new ModelInstance(model);
/*
* ModelBuilder modelBuilder = new ModelBuilder(); model =
* modelBuilder.createSphere(2, 2, 2, 20, 20, new
* Material(ColorAttribute.createDiffuse(Color.YELLOW)), Usage.Position
* | Usage.Normal); instance = new ModelInstance(model);
*/
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
}
@Override
public void render() {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instance, environment);
modelBatch.end();
}
@Override
public void dispose() {
modelBatch.dispose();
assets.dispose();
// model.dispose();
}
}
| Creando varios objetos en la escena
| core/src/org/javahispano/jfootball/Jfootball.java | Creando varios objetos en la escena |
|
Java | apache-2.0 | b41f96a359514a63895d88c142bf8408936ed3c0 | 0 | MovingBlocks/DestinationSol,MovingBlocks/DestinationSol | /*
* Copyright 2017 MovingBlocks
*
* 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.destinationsol.game;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import org.destinationsol.common.Nullable;
import org.destinationsol.game.asteroid.Asteroid;
import org.destinationsol.game.drawables.Drawable;
import org.destinationsol.game.item.Loot;
import java.util.List;
/**
* Generally speaking, SolObjects are all the game's foreground objects that are in the proximity of player/visible screen.
* <p>
* {@code SolObject} can be generally crashed into. Background objects aren't usually {@code SolObject}s, but they are
* rather just sprites rendered using some background manager. {@code SolObject} that gets too far from player/camera is
* usually transformed to {@link FarObject}, which has less runtime executable code and thus is faster and can be
* recreated back into {@code SolObject}. Some gameplay-wise unimportant {@code SolObjects}s are also just removed when
* they get too far from player/camera, and new ones are generated as needed.
*/
public interface SolObject {
/**
* Called on every game's frame, allows for handling of object-specific runtime needs.
* <p>
* This method can be used for instance for handling pull of loot towards ships, flickering of lights, aiming
* crosses for ships and stuff alike.
*
* @param game Game this object belongs to.
*/
void update(SolGame game);
/**
* Denotes whether the object should be removed as of the time of calling.
* <p>
* Object should usually be removed when its health reaches zero, or, for instance, if the object is projectile, it
* reaches its target. This method should not handle removal of object for optimization purposes when it gets too
* far away, unless the object is specifically designed to exist only in close proximity of player, like some sort
* of kinetic defense. Removal for optimization purposes is handled in {@link #toFarObject()}.
*
* @param game Game this object belongs to.
* @return Boolean denoting whether the object should be removed.
*/
default boolean shouldBeRemoved(SolGame game) {
return false;
}
/**
* Called whenever an object is due to be removed from game.
* <p>
* This method should handle things like throwing out {@link Loot} when ships are destroyed, or creating smaller
* asteroids when a big {@link Asteroid} is destroyed. This method is also responsible for freeing its resources,
* when such is applicable. Note that this method is also called when an object is due to be removed for
* optimization purposes, and thus you need to explicitly check for {@link #shouldBeRemoved(SolGame)} if you have
* some code specific to destruction of object.
*
* @param game Game this object belongs to.
*/
void onRemove(SolGame game);
/**
* Called whenever this object should receive damage.
* <p>
* Whenever the object is hit by some projectile or other sort of damage dealing thing, this method is called on the
* object to allow it to perform its damage handling. This usually means just subtracting the damage from object's
* health and playing a hit sound, but if the object has no health pool or should be otherwise indestructible, or
* invincible against some types of damage, this method can be freely left blank.
*
* @param dmg Damage the object receives.
* @param game Game this object belongs to.
* @param position Position the object was hit at, if hit by point-based damage. Null if not applicable, such as fire.
* @param dmgType Type of the damage object receives.
*/
default void receiveDmg(float dmg, SolGame game, @Nullable Vector2 position, DmgType dmgType) {
}
/**
* Denotes whether this object is affected by gravity, this is usually constant.
*
* @return True if object is affected by gravity, false otherwise.
*/
default boolean receivesGravity() {
return true;
}
/**
* Applies external force to object.
* <p>
* This method usually just scales the {@code force} by objects mass if {@code acc} is set, and then passes the
* force to object's internal {@link Body}.
*
* @param force Force to apply to the object.
* @param game Game this object belongs to.
* @param acc Whether this objects is accelerating by the force, such as in gravity.
*/
void receiveForce(Vector2 force, SolGame game, boolean acc);
/**
* Returns object's position.
* <p>
* This method usually just returns the vector retrieved from object's internal {@link Body}.
*
* @return Position of the object.
*/
Vector2 getPosition();
/**
* Called when an object is too far from player/camera, and is thus to be converted to {@link FarObject}.
* <p>
* This method is used for optimization of game's objects, by converting to their more resource friendly versions
* when they get too far from player/camera. The {@code FarObject} returned by this method should be usable to get
* copy of this object back in reverse. If null is returned by this method, this object is designated to be removed
* when it gets too far from player/camera, and instead of recreating from {@code FarObject}, to be generated again.
*
* @return FarObject representation of this object, or null if object is to be removed.
*/
default FarObject toFarObject() {
return null;
}
/**
* Returns list of all {@link Drawable Drawables} this object has assigned.
*
* @return List of drawables this object has.
*/
List<Drawable> getDrawables();
/**
* Returns object's angle.
* <p>
* This method usually just returns the angle retrieved from object's internal {@link Body}.
*
* @return Angle of this object, in degrees.
*/
float getAngle();
/**
* Returns object's speed.
* <p>
* This method usually just returns the vector retrieved from object's internal {@link Body}.
*
* @return Speed of this object.
*/
Vector2 getSpeed();
/**
* Called whenever this object touches another object, and can be used for custom collisions.
* <p>
* This method is for instance used for collecting {@link Loot} by ships when these two touch. This method is not to
* be used for handling of applying force between the two objects nor playing any collision sounds, unless the
* object is specifically created to do so. This method should however apply collision damage. This method can be
* freely left blank if there is no custom contact handling.
*
* @param other Object this object touches.
* @param absImpulse Impulse the objects apply to each other.
* @param game Game this object belongs to.
* @param collPos Position where the two objects touch.
*/
default void handleContact(SolObject other, float absImpulse, SolGame game, Vector2 collPos) {
}
/**
* Used for retrieval of object's debug string.
* <p>
* Any kind of information can be used in the debug string, if you don't need/want to display any debug information,
* you can freely have this method return null. To display debug strings in-game, set the flag {@link DebugOptions#OBJ_INFO}.
* These strings should then be rendered in the proximity of their objects.
*
* @return Debug string with information about the object.
*/
String toDebugString();
/**
* Denotes whether this object is meant to behave as if made from metallic material.
* <p>
* This method is used mainly for choosing the sound to play after collision. Value true will play metallic sound,
* false will play rocky sound. Value of null means no sound will be played.
*
* @return Whether this object is made from metal.
*/
//TODO allow for more complex collision sounds. Or even better, completely rework the material system.
default Boolean isMetal() {
return null;
}
/**
* Denotes whether this object has a {@link Body} associated with it.
* <p>
* Generally, everything that can be touched has its {@code Body}.
*
* @return True if this object has {@code Body} associated, false otherwise.
*/
default boolean hasBody() {
return true;
}
}
| engine/src/main/java/org/destinationsol/game/SolObject.java | /*
* Copyright 2017 MovingBlocks
*
* 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.destinationsol.game;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import org.destinationsol.common.Nullable;
import org.destinationsol.game.asteroid.Asteroid;
import org.destinationsol.game.drawables.Drawable;
import org.destinationsol.game.item.Loot;
import java.util.List;
/**
* Generally speaking, SolObjects are all the game's foreground objects that are in the proximity of player/visible screen.
* <p>
* {@code SolObject} can be generally crashed into. Background objects aren't usually {@code SolObject}s, but they are
* rather just sprites rendered using some background manager. {@code SolObject} that gets too far from player/camera is
* usually transformed to {@link FarObject}, which has less runtime executable code and thus is faster and can be
* recreated back into {@code SolObject}. Some gameplay-wise unimportant {@code SolObjects}s are also just removed when
* they get too far from player/camera, and new ones are generated as needed.
*/
public interface SolObject {
/**
* Called on every game's frame, allows for handling of object-specific runtime needs.
* <p>
* This method can be used for instance for handling pull of loot towards ships, flickering of lights, aiming
* crosses for ships and stuff alike.
*
* @param game Game this object belongs to.
*/
void update(SolGame game);
/**
* Whether the object should be removed as of the time of calling.
* <p>
* Object should usually be removed when its health reaches zero, or, for instance, if the object is projectile, it
* reaches its target. This method should not handle removal of object for optimization purposes when it gets too
* far away, unless the object is specifically designed to exist only in close proximity of player, like some sort
* of kinetic defense. Removal for optimization purposes is handled in {@link #toFarObject()}.
*
* @param game Game this object belongs to.
* @return Boolean denoting whether the object should be removed.
*/
default boolean shouldBeRemoved(SolGame game) {
return false;
}
/**
* Called whenever an object is due to be removed from game.
* <p>
* This method should handle things like throwing out {@link Loot} when ships are destroyed, or creating smaller
* asteroids when a big {@link Asteroid} is destroyed. This method is also responsible for freeing its resources,
* when such is applicable. Note that this method is also called when an object is due to be removed for
* optimization purposes, and thus you need to explicitly check for {@link #shouldBeRemoved(SolGame)} if you have
* some code specific to destruction of object.
*
* @param game Game this object belongs to.
*/
void onRemove(SolGame game);
/**
* Called whenever this object should receive damage.
* <p>
* Whenever the object is hit by some projectile or other sort of damage dealing thing, this method is called on the
* object to allow it to perform its damage handling. This usually means just subtracting the damage from object's
* health and playing a hit sound, but if the object has no health pool or should be otherwise indestructible, or
* invincible against some types of damage, this method can be freely left blank.
*
* @param dmg Damage the object receives.
* @param game Game this object belongs to.
* @param position Position the object was hit at, if hit by point-based damage. Null if not applicable, such as fire.
* @param dmgType Type of the damage object receives.
*/
default void receiveDmg(float dmg, SolGame game, @Nullable Vector2 position, DmgType dmgType) {
}
/**
* Whether this object is affected by gravity, this is usually constant.
*
* @return True if object is affected by gravity, false otherwise.
*/
default boolean receivesGravity() {
return true;
}
/**
* Applies external force to object.
* <p>
* This method usually just scales the {@code force} by objects mass if {@code acc} is set, and then passes the
* force to object's internal {@link Body}.
*
* @param force Force to apply to the object.
* @param game Game this object belongs to.
* @param acc Whether this objects is accelerating by the force, such as in gravity.
*/
void receiveForce(Vector2 force, SolGame game, boolean acc);
/**
* Returns object's position.
* <p>
* This method usually just returns the vector retrieved from object's internal {@link Body}.
*
* @return Position of the object.
*/
Vector2 getPosition();
/**
* Called when an object is too far from player/camera, and is thus to be converted to {@link FarObject}.
* <p>
* This method is used for optimization of game's objects, by converting to their more resource friendly versions
* when they get too far from player/camera. The {@code FarObject} returned by this method should be usable to get
* copy of this object back in reverse. If null is returned by this method, this object is designated to be removed
* when it gets too far from player/camera, and instead of recreating from {@code FarObject}, to be generated again.
*
* @return FarObject representation of this object, or null if object is to be removed.
*/
default FarObject toFarObject() {
return null;
}
/**
* Returns list of all {@link Drawable Drawables} this object has assigned.
*
* @return List of drawables this object has.
*/
List<Drawable> getDrawables();
/**
* Returns object's angle.
* <p>
* This method usually just returns the angle retrieved from object's internal {@link Body}.
*
* @return Angle of this object, in degrees.
*/
float getAngle();
/**
* Returns object's speed.
* <p>
* This method usually just returns the vector retrieved from object's internal {@link Body}.
*
* @return Speed of this object.
*/
Vector2 getSpeed();
/**
* Called whenever this object touches another object, and can be used for custom collisions.
* <p>
* This method is for instance used for collecting {@link Loot} by ships when these two touch. This method is not to
* be used for handling of applying force between the two objects nor playing any collision sounds, unless the
* object is specifically created to do so. This method should however apply collision damage. This method can be
* freely left blank if there is no custom contact handling.
*
* @param other Object this object touches.
* @param absImpulse Impulse the objects apply to each other.
* @param game Game this object belongs to.
* @param collPos Position where the two objects touch.
*/
default void handleContact(SolObject other, float absImpulse, SolGame game, Vector2 collPos) {
}
/**
* Used for retrieval of object's debug string.
* <p>
* Any kind of information can be used in the debug string, if you don't need/want to display any debug information,
* you can freely have this method return null. To display debug strings in-game, set the flag {@link DebugOptions#OBJ_INFO}.
* These strings should then be rendered in the proximity of their objects.
*
* @return Debug string with information about the object.
*/
String toDebugString();
/**
* Whether this object is meant to behave as if made from metallic material.
* <p>
* This method is used mainly for choosing the sound to play after collision. Value true will play metallic sound,
* false will play rocky sound. Value of null means no sound will be played.
*
* @return Whether this object is made from metal.
*/
//TODO allow for more complex collision sounds. Or even better, completely rework the material system.
default Boolean isMetal() {
return null;
}
/**
* Whether this object has a {@link Body} associated with it.
* <p>
* Generally, everything that can be touched has its {@code Body}.
*
* @return True if this object has {@code Body} associated, false otherwise.
*/
default boolean hasBody() {
return true;
}
}
| Even tinier improvements
| engine/src/main/java/org/destinationsol/game/SolObject.java | Even tinier improvements |
|
Java | apache-2.0 | d12289f968bb970ea9aa4de93defaadba8ebfa55 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.test;
import com.google.common.collect.ImmutableList;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.ConfigModelRegistry;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.api.HostProvisioner;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.provision.Host;
import com.yahoo.config.model.provision.Hosts;
import com.yahoo.config.model.provision.InMemoryProvisioner;
import com.yahoo.config.model.provision.SingleNodeProvisioner;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Capacity;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.ProvisionLogger;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.yahoo.vespa.model.test.utils.ApplicationPackageUtils.generateSchemas;
/**
* Helper class which sets up a system with multiple hosts.
* Usage:
* <code>
* VespaModelTester tester = new VespaModelTester();
* tester.addHosts(count, flavor);
* ... add more nodes
* VespaModel model = tester.createModel(servicesString);
* ... assert on model
* </code>
*
* @author bratseth
*/
public class VespaModelTester {
private final ConfigModelRegistry configModelRegistry;
private boolean hosted = true;
private final Map<NodeResources, Collection<Host>> hostsByResources = new HashMap<>();
private ApplicationId applicationId = ApplicationId.defaultId();
private boolean useDedicatedNodeForLogserver = false;
private HostProvisioner provisioner;
public VespaModelTester() {
this(new NullConfigModelRegistry());
}
public VespaModelTester(ConfigModelRegistry configModelRegistry) {
this.configModelRegistry = configModelRegistry;
}
public HostProvisioner provisioner() {
if (provisioner instanceof ProvisionerAdapter)
return ((ProvisionerAdapter)provisioner).provisioner();
return provisioner;
}
/** Adds some nodes with resources 1, 3, 10 */
public Hosts addHosts(int count) { return addHosts(InMemoryProvisioner.defaultResources, count); }
public Hosts addHosts(NodeResources resources, int count) {
return addHosts(Optional.of(new Flavor(resources)), resources, count);
}
private Hosts addHosts(Optional<Flavor> flavor, NodeResources resources, int count) {
List<Host> hosts = new ArrayList<>();
for (int i = 0; i < count; ++i) {
// Let host names sort in the opposite order of the order the hosts are added
// This allows us to test index vs. name order selection when subsets of hosts are selected from a cluster
// (for e.g cluster controllers and slobrok nodes)
String hostname = String.format("%s-%02d",
"node" + "-" + Math.round(resources.vcpu()) +
"-" + Math.round(resources.memoryGb()) +
"-" + Math.round(resources.diskGb()),
count - i);
hosts.add(new Host(hostname, ImmutableList.of(), flavor));
}
this.hostsByResources.put(resources, hosts);
if (hosts.size() > 100)
throw new IllegalStateException("The host naming scheme is nameNN. To test more than 100 hosts, change to nameNNN");
return new Hosts(hosts);
}
/** Sets whether this sets up a model for a hosted system. Default: true */
public void setHosted(boolean hosted) { this.hosted = hosted; }
/** Sets the tenant, application name, and instance name of the model being built. */
public void setApplicationId(String tenant, String applicationName, String instanceName) {
applicationId = ApplicationId.from(tenant, applicationName, instanceName);
}
public void useDedicatedNodeForLogserver(boolean useDedicatedNodeForLogserver) {
this.useDedicatedNodeForLogserver = useDedicatedNodeForLogserver;
}
/** Creates a model which uses 0 as start index and fails on out of capacity */
public VespaModel createModel(String services, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, true, retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, DeployState.Builder builder) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0, Optional.empty(), builder);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, boolean alwaysReturnOneNode, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, alwaysReturnOneNode, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, int startIndexForClusters, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, startIndexForClusters,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, String ... retiredHostNames) {
return createModel(zone, services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity,
DeployState.Builder deployStateBuilder, String ... retiredHostNames) {
return createModel(zone, services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), deployStateBuilder, retiredHostNames);
}
/**
* Creates a model using the hosts already added to this
*
* @param services the services xml string
* @param useMaxResources false to use the minmal resources (when given a range), true to use max
* @param failOnOutOfCapacity whether we should get an exception when not enough hosts of the requested flavor
* is available or if we should just silently receive a smaller allocation
* @return the resulting model
*/
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, boolean useMaxResources,
boolean alwaysReturnOneNode,
int startIndexForClusters, Optional<VespaModel> previousModel,
DeployState.Builder deployStatebuilder, String ... retiredHostNames) {
VespaModelCreatorWithMockPkg modelCreatorWithMockPkg = new VespaModelCreatorWithMockPkg(null, services, generateSchemas("type1"));
ApplicationPackage appPkg = modelCreatorWithMockPkg.appPkg;
provisioner = hosted ? new ProvisionerAdapter(new InMemoryProvisioner(hostsByResources,
failOnOutOfCapacity,
useMaxResources,
alwaysReturnOneNode,
false,
startIndexForClusters,
retiredHostNames)) :
new SingleNodeProvisioner();
TestProperties properties = new TestProperties()
.setMultitenant(hosted) // Note: system tests are multitenant but not hosted
.setHostedVespa(hosted)
.setApplicationId(applicationId)
.setUseDedicatedNodeForLogserver(useDedicatedNodeForLogserver);
DeployState.Builder deployState = deployStatebuilder
.applicationPackage(appPkg)
.modelHostProvisioner(provisioner)
.properties(properties)
.zone(zone);
previousModel.ifPresent(deployState::previousModel);
return modelCreatorWithMockPkg.create(false, deployState.build(), configModelRegistry);
}
/** To verify that we don't call allocateHost(alias) in hosted environments */
private static class ProvisionerAdapter implements HostProvisioner {
private final InMemoryProvisioner provisioner;
public ProvisionerAdapter(InMemoryProvisioner provisioner) {
this.provisioner = provisioner;
}
public InMemoryProvisioner provisioner() { return provisioner; }
@Override
public HostSpec allocateHost(String alias) {
throw new UnsupportedOperationException("Allocating hosts using <node> tags is not supported in hosted environments, " +
"use <nodes count='N'> instead, see https://cloud.vespa.ai/en/reference/services");
}
@Override
public List<HostSpec> prepare(ClusterSpec cluster, Capacity capacity, ProvisionLogger logger) {
return provisioner.prepare(cluster, capacity, logger);
}
}
}
| config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTester.java | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.test;
import com.google.common.collect.ImmutableList;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.ConfigModelRegistry;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.api.HostProvisioner;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.provision.Host;
import com.yahoo.config.model.provision.Hosts;
import com.yahoo.config.model.provision.InMemoryProvisioner;
import com.yahoo.config.model.provision.SingleNodeProvisioner;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Capacity;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.ProvisionLogger;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.yahoo.vespa.model.test.utils.ApplicationPackageUtils.generateSchemas;
/**
* Helper class which sets up a system with multiple hosts.
* Usage:
* <code>
* VespaModelTester tester = new VespaModelTester();
* tester.addHosts(count, flavor);
* ... add more nodes
* VespaModel model = tester.createModel(servicesString);
* ... assert on model
* </code>
*
* @author bratseth
*/
public class VespaModelTester {
private final ConfigModelRegistry configModelRegistry;
private boolean hosted = true;
private final Map<NodeResources, Collection<Host>> hostsByResources = new HashMap<>();
private ApplicationId applicationId = ApplicationId.defaultId();
private boolean useDedicatedNodeForLogserver = false;
private HostProvisioner provisioner;
public VespaModelTester() {
this(new NullConfigModelRegistry());
}
public VespaModelTester(ConfigModelRegistry configModelRegistry) {
this.configModelRegistry = configModelRegistry;
}
public HostProvisioner provisioner() {
if (provisioner instanceof ProvisionerAdapter)
return ((ProvisionerAdapter)provisioner).provisioner();
return provisioner;
}
/** Adds some nodes with resources 1, 3, 10 */
public Hosts addHosts(int count) { return addHosts(InMemoryProvisioner.defaultResources, count); }
public Hosts addHosts(NodeResources resources, int count) {
return addHosts(Optional.of(new Flavor(resources)), resources, count);
}
private Hosts addHosts(Optional<Flavor> flavor, NodeResources resources, int count) {
List<Host> hosts = new ArrayList<>();
for (int i = 0; i < count; ++i) {
// Let host names sort in the opposite order of the order the hosts are added
// This allows us to test index vs. name order selection when subsets of hosts are selected from a cluster
// (for e.g cluster controllers and slobrok nodes)
String hostname = String.format("%s-%02d",
"node" + "-" + Math.round(resources.vcpu()) +
"-" + Math.round(resources.memoryGb()) +
"-" + Math.round(resources.diskGb()),
count - i);
hosts.add(new Host(hostname, ImmutableList.of(), flavor));
}
this.hostsByResources.put(resources, hosts);
if (hosts.size() > 100)
throw new IllegalStateException("The host naming scheme is nameNN. To test more than 100 hosts, change to nameNNN");
return new Hosts(hosts);
}
/** Sets whether this sets up a model for a hosted system. Default: true */
public void setHosted(boolean hosted) { this.hosted = hosted; }
/** Sets the tenant, application name, and instance name of the model being built. */
public void setApplicationId(String tenant, String applicationName, String instanceName) {
applicationId = ApplicationId.from(tenant, applicationName, instanceName);
}
public void useDedicatedNodeForLogserver(boolean useDedicatedNodeForLogserver) {
this.useDedicatedNodeForLogserver = useDedicatedNodeForLogserver;
}
/** Creates a model which uses 0 as start index and fails on node allocation */
public VespaModel createModel(String services, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, true, retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, DeployState.Builder builder) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0, Optional.empty(), builder);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, boolean alwaysReturnOneNode, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, alwaysReturnOneNode, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(String services, boolean failOnOutOfCapacity, int startIndexForClusters, String ... retiredHostNames) {
return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, startIndexForClusters,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, String ... retiredHostNames) {
return createModel(zone, services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), new DeployState.Builder(), retiredHostNames);
}
/** Creates a model which uses 0 as start index */
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity,
DeployState.Builder deployStateBuilder, String ... retiredHostNames) {
return createModel(zone, services, failOnOutOfCapacity, false, false, 0,
Optional.empty(), deployStateBuilder, retiredHostNames);
}
/**
* Creates a model using the hosts already added to this
*
* @param services the services xml string
* @param useMaxResources false to use the minmal resources (when given a range), true to use max
* @param failOnOutOfCapacity whether we should get an exception when not enough hosts of the requested flavor
* is available or if we should just silently receive a smaller allocation
* @return the resulting model
*/
public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, boolean useMaxResources,
boolean alwaysReturnOneNode,
int startIndexForClusters, Optional<VespaModel> previousModel,
DeployState.Builder deployStatebuilder, String ... retiredHostNames) {
VespaModelCreatorWithMockPkg modelCreatorWithMockPkg = new VespaModelCreatorWithMockPkg(null, services, generateSchemas("type1"));
ApplicationPackage appPkg = modelCreatorWithMockPkg.appPkg;
provisioner = hosted ? new ProvisionerAdapter(new InMemoryProvisioner(hostsByResources,
failOnOutOfCapacity,
useMaxResources,
alwaysReturnOneNode,
false,
startIndexForClusters,
retiredHostNames)) :
new SingleNodeProvisioner();
TestProperties properties = new TestProperties()
.setMultitenant(hosted) // Note: system tests are multitenant but not hosted
.setHostedVespa(hosted)
.setApplicationId(applicationId)
.setUseDedicatedNodeForLogserver(useDedicatedNodeForLogserver);
DeployState.Builder deployState = deployStatebuilder
.applicationPackage(appPkg)
.modelHostProvisioner(provisioner)
.properties(properties)
.zone(zone);
previousModel.ifPresent(deployState::previousModel);
return modelCreatorWithMockPkg.create(false, deployState.build(), configModelRegistry);
}
/** To verify that we don't call allocateHost(alias) in hosted environments */
private static class ProvisionerAdapter implements HostProvisioner {
private final InMemoryProvisioner provisioner;
public ProvisionerAdapter(InMemoryProvisioner provisioner) {
this.provisioner = provisioner;
}
public InMemoryProvisioner provisioner() { return provisioner; }
@Override
public HostSpec allocateHost(String alias) {
throw new UnsupportedOperationException("Allocating hosts using <node> tags is not supported in hosted environments, " +
"use <nodes count='N'> instead, see https://cloud.vespa.ai/en/reference/services");
}
@Override
public List<HostSpec> prepare(ClusterSpec cluster, Capacity capacity, ProvisionLogger logger) {
return provisioner.prepare(cluster, capacity, logger);
}
}
}
| Update comment
| config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTester.java | Update comment |
|
Java | apache-2.0 | 07b3d9824931323d66bf2f9b71922a64ba62a7cf | 0 | apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc | /*
* 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.shardingsphere.core.routing.router.sharding;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.constant.SQLType;
import org.apache.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData;
import org.apache.shardingsphere.core.optimizer.condition.ShardingConditions;
import org.apache.shardingsphere.core.parsing.antlr.sql.statement.dcl.DCLStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowTableStatusStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowTablesStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.UseStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.postgresql.statement.ResetParamStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.postgresql.statement.SetParamStatement;
import org.apache.shardingsphere.core.parsing.parser.sql.SQLStatement;
import org.apache.shardingsphere.core.routing.type.RoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.DatabaseBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.InstanceBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.TableBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.complex.ComplexRoutingEngine;
import org.apache.shardingsphere.core.routing.type.defaultdb.DefaultDatabaseRoutingEngine;
import org.apache.shardingsphere.core.routing.type.ignore.IgnoreRoutingEngine;
import org.apache.shardingsphere.core.routing.type.standard.StandardRoutingEngine;
import org.apache.shardingsphere.core.routing.type.unicast.UnicastRoutingEngine;
import org.apache.shardingsphere.core.rule.ShardingRule;
import java.util.Collection;
/**
* Routing engine factory.
*
* @author zhangliang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RoutingEngineFactory {
/**
* Create new instance of routing engine.
*
* @param shardingRule sharding rule
* @param shardingDataSourceMetaData sharding data source meta data
* @param sqlStatement sql statement
* @param shardingConditions sharding conditions
* @return new instance of routing engine
*/
public static RoutingEngine newInstance(final ShardingRule shardingRule,
final ShardingDataSourceMetaData shardingDataSourceMetaData, final SQLStatement sqlStatement, final ShardingConditions shardingConditions) {
Collection<String> tableNames = sqlStatement.getTables().getTableNames();
if (SQLType.TCL == sqlStatement.getType()) {
return new DatabaseBroadcastRoutingEngine(shardingRule);
}
if (SQLType.DDL == sqlStatement.getType()) {
return new TableBroadcastRoutingEngine(shardingRule, sqlStatement);
}
if (SQLType.DAL == sqlStatement.getType()) {
return getDALRoutingEngine(shardingRule, sqlStatement, tableNames);
}
if (SQLType.DCL == sqlStatement.getType()) {
return getDCLRoutingEngine(shardingRule, sqlStatement, shardingDataSourceMetaData);
}
if (shardingRule.isAllInDefaultDataSource(tableNames)) {
return new DefaultDatabaseRoutingEngine(shardingRule, tableNames);
}
if (shardingRule.isAllBroadcastTables(tableNames)) {
return SQLType.DQL == sqlStatement.getType() ? new UnicastRoutingEngine(shardingRule, tableNames) : new DatabaseBroadcastRoutingEngine(shardingRule);
}
if (shardingConditions.isAlwaysFalse() || tableNames.isEmpty()) {
return new UnicastRoutingEngine(shardingRule, tableNames);
}
Collection<String> shardingTableNames = shardingRule.getShardingLogicTableNames(tableNames);
if (1 == shardingTableNames.size() || shardingRule.isAllBindingTables(shardingTableNames)) {
return new StandardRoutingEngine(sqlStatement, shardingRule, shardingTableNames.iterator().next(), shardingConditions);
}
// TODO config for cartesian set
return new ComplexRoutingEngine(shardingRule, tableNames, shardingConditions);
}
private static RoutingEngine getDALRoutingEngine(final ShardingRule shardingRule, final SQLStatement sqlStatement, final Collection<String> tableNames) {
if (sqlStatement instanceof UseStatement) {
return new IgnoreRoutingEngine();
}
if (sqlStatement instanceof ShowDatabasesStatement || ((sqlStatement instanceof ShowTablesStatement || sqlStatement instanceof ShowTableStatusStatement) && tableNames.isEmpty())
|| sqlStatement instanceof SetParamStatement || sqlStatement instanceof ResetParamStatement) {
return new DatabaseBroadcastRoutingEngine(shardingRule);
}
return new UnicastRoutingEngine(shardingRule, tableNames);
}
private static RoutingEngine getDCLRoutingEngine(final ShardingRule shardingRule, final SQLStatement sqlStatement, final ShardingDataSourceMetaData shardingDataSourceMetaData) {
return ((DCLStatement) sqlStatement).isGrantForSingleTable()
? new TableBroadcastRoutingEngine(shardingRule, sqlStatement) : new InstanceBroadcastRoutingEngine(shardingRule, shardingDataSourceMetaData);
}
}
| sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/RoutingEngineFactory.java | /*
* 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.shardingsphere.core.routing.router.sharding;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.constant.SQLType;
import org.apache.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData;
import org.apache.shardingsphere.core.optimizer.condition.ShardingConditions;
import org.apache.shardingsphere.core.parsing.antlr.sql.statement.dcl.DCLStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowTableStatusStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowTablesStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.mysql.statement.UseStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.postgresql.statement.ResetParamStatement;
import org.apache.shardingsphere.core.parsing.parser.dialect.postgresql.statement.SetParamStatement;
import org.apache.shardingsphere.core.parsing.parser.sql.SQLStatement;
import org.apache.shardingsphere.core.routing.type.RoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.DatabaseBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.InstanceBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.broadcast.TableBroadcastRoutingEngine;
import org.apache.shardingsphere.core.routing.type.complex.ComplexRoutingEngine;
import org.apache.shardingsphere.core.routing.type.defaultdb.DefaultDatabaseRoutingEngine;
import org.apache.shardingsphere.core.routing.type.ignore.IgnoreRoutingEngine;
import org.apache.shardingsphere.core.routing.type.standard.StandardRoutingEngine;
import org.apache.shardingsphere.core.routing.type.unicast.UnicastRoutingEngine;
import org.apache.shardingsphere.core.rule.ShardingRule;
import java.util.Collection;
/**
* Routing engine factory.
*
* @author zhangliang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RoutingEngineFactory {
/**
* Create new instance of routing engine.
*
* @param shardingRule sharding rule
* @param shardingDataSourceMetaData sharding data source meta data
* @param sqlStatement sql statement
* @param shardingConditions sharding conditions
* @return new instance of routing engine
*/
public static RoutingEngine newInstance(final ShardingRule shardingRule,
final ShardingDataSourceMetaData shardingDataSourceMetaData, final SQLStatement sqlStatement, final ShardingConditions shardingConditions) {
Collection<String> tableNames = sqlStatement.getTables().getTableNames();
if (SQLType.TCL == sqlStatement.getType()) {
return new DatabaseBroadcastRoutingEngine(shardingRule);
}
if (SQLType.DDL == sqlStatement.getType()) {
return new TableBroadcastRoutingEngine(shardingRule, sqlStatement);
}
if (SQLType.DAL == sqlStatement.getType()) {
return getDALRoutingEngine(shardingRule, sqlStatement, tableNames);
}
if (SQLType.DCL == sqlStatement.getType()) {
return getDCLRoutingEngine(shardingRule, sqlStatement, shardingDataSourceMetaData);
}
if (shardingRule.isAllInDefaultDataSource(tableNames)) {
return new DefaultDatabaseRoutingEngine(shardingRule, tableNames);
}
if (shardingRule.isAllBroadcastTables(tableNames)) {
return SQLType.DQL == sqlStatement.getType() ? new UnicastRoutingEngine(shardingRule, tableNames) : new DatabaseBroadcastRoutingEngine(shardingRule);
}
if (shardingConditions.isAlwaysFalse() || tableNames.isEmpty()) {
return new UnicastRoutingEngine(shardingRule, tableNames);
}
Collection<String> shardingTableNames = shardingRule.getShardingLogicTableNames(tableNames);
if (1 == shardingTableNames.size() || shardingRule.isAllBindingTables(shardingTableNames)) {
return new StandardRoutingEngine(shardingRule, shardingTableNames.iterator().next(), shardingConditions);
}
// TODO config for cartesian set
return new ComplexRoutingEngine(shardingRule, tableNames, shardingConditions);
}
private static RoutingEngine getDALRoutingEngine(final ShardingRule shardingRule, final SQLStatement sqlStatement, final Collection<String> tableNames) {
if (sqlStatement instanceof UseStatement) {
return new IgnoreRoutingEngine();
}
if (sqlStatement instanceof ShowDatabasesStatement || ((sqlStatement instanceof ShowTablesStatement || sqlStatement instanceof ShowTableStatusStatement) && tableNames.isEmpty())
|| sqlStatement instanceof SetParamStatement || sqlStatement instanceof ResetParamStatement) {
return new DatabaseBroadcastRoutingEngine(shardingRule);
}
return new UnicastRoutingEngine(shardingRule, tableNames);
}
private static RoutingEngine getDCLRoutingEngine(final ShardingRule shardingRule, final SQLStatement sqlStatement, final ShardingDataSourceMetaData shardingDataSourceMetaData) {
return ((DCLStatement) sqlStatement).isGrantForSingleTable()
? new TableBroadcastRoutingEngine(shardingRule, sqlStatement) : new InstanceBroadcastRoutingEngine(shardingRule, shardingDataSourceMetaData);
}
}
| modify StandardRoutingEngine()
| sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/RoutingEngineFactory.java | modify StandardRoutingEngine() |
|
Java | apache-2.0 | 28ba2db21efef3d1e33644472739cc4bfef8a65e | 0 | jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,jmt4/Selenium2,jmt4/Selenium2,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2 | /*
Copyright 2007-2011 Selenium committers
Copyright 2011 Software Freedom Conservancy
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.openqa.selenium;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents the known and supported Platforms that WebDriver runs on. This is pretty close to the
* Operating System, but differs slightly, because this class is used to extract information such as
* program locations and line endings.
*/
// Useful URLs:
// http://hg.openjdk.java.net/jdk7/modules/jdk/file/a37326fa7f95/src/windows/native/java/lang/java_props_md.c
public enum Platform {
/**
* Never returned, but can be used to request a browser running on any version of Windows.
*/
WINDOWS("") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == XP
|| compareWith == VISTA || compareWith == WIN8;
}
},
/**
* For versions of Windows that "feel like" Windows XP. These are ones that store files in
* "\Program Files\" and documents under "\\documents and settings\\username"
*/
XP("Windows Server 2003", "xp", "windows", "winnt") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == XP;
}
},
/**
* For versions of Windows that "feel like" Windows Vista.
*/
VISTA("windows vista", "Windows Server 2008", "windows 7", "win7") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == VISTA;
}
},
/**
* For versions of Windows that "feel like" Windows 8.
*/
WIN8("Windows Server 2012", "windows 8", "win8") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == WIN8;
}
},
MAC("mac", "darwin") {},
/**
* Many platforms have UNIX traits, amongst them LINUX, Solaris and BSD.
*/
UNIX("solaris", "bsd") {},
LINUX("linux") {
@Override
public boolean is(Platform compareWith) {
return compareWith == UNIX || compareWith == LINUX;
}
},
ANDROID("android", "dalvik") {
public String getLineEnding() {
return "\n";
}
@Override
public boolean is(Platform compareWith) {
return compareWith == LINUX || compareWith == ANDROID;
}
},
/**
* Never returned, but can be used to request a browser running on any operating system.
*/
ANY("") {
@Override
public boolean is(Platform compareWith) {
return true;
}
};
private final String[] partOfOsName;
private final int minorVersion;
private final int majorVersion;
private Platform(String... partOfOsName) {
this.partOfOsName = partOfOsName;
String version = System.getProperty("os.version", "0.0.0");
int major = 0;
int min = 0;
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+).*");
Matcher matcher = pattern.matcher(version);
if (matcher.matches()) {
try {
major = Integer.parseInt(matcher.group(1));
min = Integer.parseInt(matcher.group(2));
} catch (NumberFormatException e) {
// These things happen
}
}
majorVersion = major;
minorVersion = min;
}
public String[] getPartOfOsName() {
return partOfOsName;
}
/**
* Get current platform (not necessarily the same as operating system).
*
* @return current platform
*/
public static Platform getCurrent() {
return extractFromSysProperty(System.getProperty("os.name"));
}
/**
* Extracts platforms based on system properties in Java and a heuristic to determine the most
* likely operating system. If not able to determine the operating system, it will default to
* UNIX.
*
* @param osName the operating system name to determine the platform of
* @return the most likely platform based on given operating system name
*/
public static Platform extractFromSysProperty(String osName) {
osName = osName.toLowerCase();
// os.name for android is linux
if ("dalvik".equalsIgnoreCase(System.getProperty("java.vm.name"))) {
return Platform.ANDROID;
}
Platform mostLikely = UNIX;
String previousMatch = null;
for (Platform os : Platform.values()) {
for (String matcher : os.partOfOsName) {
if ("".equals(matcher)) {
continue;
}
matcher = matcher.toLowerCase();
if (os.isExactMatch(osName, matcher)) {
return os;
}
if (os.isCurrentPlatform(osName, matcher) && isBetterMatch(previousMatch, matcher)) {
previousMatch = matcher;
mostLikely = os;
}
}
}
// Default to assuming we're on a UNIX variant (including LINUX)
return mostLikely;
}
/**
* Decides whether the previous match is better or not than the current match. If previous match
* is null, the newer match is always better.
*
* @param previous the previous match
* @param matcher the newer match
* @return true if newer match is better, false otherwise
*/
private static boolean isBetterMatch(String previous, String matcher) {
return previous == null || matcher.length() >= previous.length();
}
/**
* Heuristic for comparing two platforms. If platforms (which is not the same thing as operating
* systems) are found to be approximately similar in nature, this will return true. For instance
* the LINUX platform is similar to UNIX, and will give a positive result if compared.
*
* @param compareWith the platform to compare with
* @return true if platforms are approximately similar, false otherwise
*/
public boolean is(Platform compareWith) {
return this.equals(compareWith);
}
private boolean isCurrentPlatform(String osName, String matchAgainst) {
return osName.contains(matchAgainst);
}
private boolean isExactMatch(String osName, String matchAgainst) {
return matchAgainst.equals(osName);
}
/**
* Returns the major version of this platform.
*
* @return the major version of specified platform
*/
public int getMajorVersion() {
return majorVersion;
}
/**
* Returns the minor version of this platform.
*
* @return the minor version of specified platform
*/
public int getMinorVersion() {
return minorVersion;
}
}
| java/client/src/org/openqa/selenium/Platform.java | /*
Copyright 2007-2011 Selenium committers
Copyright 2011 Software Freedom Conservancy
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.openqa.selenium;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents the known and supported Platforms that WebDriver runs on. This is pretty close to the
* Operating System, but differs slightly, because this class is used to extract information such as
* program locations and line endings.
*/
// Useful URLs:
// http://hg.openjdk.java.net/jdk7/modules/jdk/file/a37326fa7f95/src/windows/native/java/lang/java_props_md.c
public enum Platform {
/**
* Never returned, but can be used to request a browser running on any version of Windows.
*/
WINDOWS("") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == XP || compareWith == VISTA;
}
},
/**
* For versions of Windows that "feel like" Windows XP. These are ones that store files in
* "\Program Files\" and documents under "\\documents and settings\\username"
*/
XP("xp", "windows", "winnt") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == XP;
}
},
/**
* For versions of Windows that "feel like" Windows Vista.
*/
VISTA("windows vista", "Windows Server 2008", "windows 7", "win7") {
@Override
public boolean is(Platform compareWith) {
return compareWith == WINDOWS || compareWith == VISTA;
}
},
MAC("mac", "darwin") {},
/**
* Many platforms have UNIX traits, amongst them LINUX, Solaris and BSD.
*/
UNIX("solaris", "bsd") {},
LINUX("linux") {
@Override
public boolean is(Platform compareWith) {
return compareWith == UNIX || compareWith == LINUX;
}
},
ANDROID("android", "dalvik") {
public String getLineEnding() {
return "\n";
}
@Override
public boolean is(Platform compareWith) {
return compareWith == LINUX || compareWith == ANDROID;
}
},
/**
* Never returned, but can be used to request a browser running on any operating system.
*/
ANY("") {
@Override
public boolean is(Platform compareWith) {
return true;
}
};
private final String[] partOfOsName;
private final int minorVersion;
private final int majorVersion;
private Platform(String... partOfOsName) {
this.partOfOsName = partOfOsName;
String version = System.getProperty("os.version", "0.0.0");
int major = 0;
int min = 0;
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+).*");
Matcher matcher = pattern.matcher(version);
if (matcher.matches()) {
try {
major = Integer.parseInt(matcher.group(1));
min = Integer.parseInt(matcher.group(2));
} catch (NumberFormatException e) {
// These things happen
}
}
majorVersion = major;
minorVersion = min;
}
public String[] getPartOfOsName() {
return partOfOsName;
}
/**
* Get current platform (not necessarily the same as operating system).
*
* @return current platform
*/
public static Platform getCurrent() {
return extractFromSysProperty(System.getProperty("os.name"));
}
/**
* Extracts platforms based on system properties in Java and a heuristic to determine the most
* likely operating system. If not able to determine the operating system, it will default to
* UNIX.
*
* @param osName the operating system name to determine the platform of
* @return the most likely platform based on given operating system name
*/
public static Platform extractFromSysProperty(String osName) {
osName = osName.toLowerCase();
// os.name for android is linux
if ("dalvik".equalsIgnoreCase(System.getProperty("java.vm.name"))) {
return Platform.ANDROID;
}
Platform mostLikely = UNIX;
String previousMatch = null;
for (Platform os : Platform.values()) {
for (String matcher : os.partOfOsName) {
if ("".equals(matcher)) {
continue;
}
matcher = matcher.toLowerCase();
if (os.isExactMatch(osName, matcher)) {
return os;
}
if (os.isCurrentPlatform(osName, matcher) && isBetterMatch(previousMatch, matcher)) {
previousMatch = matcher;
mostLikely = os;
}
}
}
// Default to assuming we're on a UNIX variant (including LINUX)
return mostLikely;
}
/**
* Decides whether the previous match is better or not than the current match. If previous match
* is null, the newer match is always better.
*
* @param previous the previous match
* @param matcher the newer match
* @return true if newer match is better, false otherwise
*/
private static boolean isBetterMatch(String previous, String matcher) {
return previous == null || matcher.length() >= previous.length();
}
/**
* Heuristic for comparing two platforms. If platforms (which is not the same thing as operating
* systems) are found to be approximately similar in nature, this will return true. For instance
* the LINUX platform is similar to UNIX, and will give a positive result if compared.
*
* @param compareWith the platform to compare with
* @return true if platforms are approximately similar, false otherwise
*/
public boolean is(Platform compareWith) {
return this.equals(compareWith);
}
private boolean isCurrentPlatform(String osName, String matchAgainst) {
return osName.contains(matchAgainst);
}
private boolean isExactMatch(String osName, String matchAgainst) {
return matchAgainst.equals(osName);
}
/**
* Returns the major version of this platform.
*
* @return the major version of specified platform
*/
public int getMajorVersion() {
return majorVersion;
}
/**
* Returns the minor version of this platform.
*
* @return the minor version of specified platform
*/
public int getMinorVersion() {
return minorVersion;
}
}
| AlexeiBarantsev: Adding Windows 8 to the list of platforms
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@18023 07704840-8298-11de-bf8c-fd130f914ac9
| java/client/src/org/openqa/selenium/Platform.java | AlexeiBarantsev: Adding Windows 8 to the list of platforms |
|
Java | apache-2.0 | 41d879b6aeb1ab183e557ee978148f517b6a7cc8 | 0 | NLeSC/vbrowser,NLeSC/vbrowser,NLeSC/vbrowser,NLeSC/vbrowser | /*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* 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 the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vbrowser.vb2.vlet.proxy.vrs;
import java.net.URISyntaxException;
import nl.esciencecenter.ptk.data.LongHolder;
import nl.esciencecenter.ptk.data.StringList;
import nl.esciencecenter.ptk.presentation.IPresentable;
import nl.esciencecenter.ptk.presentation.Presentation;
import nl.esciencecenter.vbrowser.vb2.ui.proxy.ProxyException;
import nl.esciencecenter.vbrowser.vb2.ui.proxy.ProxyNode;
import nl.esciencecenter.vbrowser.vrs.data.Attribute;
import nl.esciencecenter.vbrowser.vrs.data.AttributeType;
import nl.esciencecenter.vbrowser.vrs.exceptions.VRLSyntaxException;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
import nl.esciencecenter.vlet.vrs.VComposite;
import nl.esciencecenter.vlet.vrs.VNode;
import nl.esciencecenter.vlet.vrs.presentation.VRSPresentation;
import nl.esciencecenter.vlet.vrs.vrms.LogicalResourceNode;
import nl.esciencecenter.vlet.vrs.vrms.VResourceLink;
/**
* VRS ProxyNode
*/
public class VRSProxyNode extends ProxyNode
{
private VNode vnode;
public VRSProxyNode(VRSProxyFactory vrsProxyFactory, VNode vnode,VRL locator) throws ProxyException, URISyntaxException
{
super(vrsProxyFactory,locator);
this.vnode=vnode;
}
protected VRSProxyFactory factory()
{
return (VRSProxyFactory)this.getProxyFactory();
}
protected void doPrefetchAttributes() throws ProxyException
{
super.doPrefetchAttributes();
if (vnode instanceof VResourceLink)
{
// assume true for now:
this.cache.setIsComposite(true);
}
}
protected boolean isLogicalNode()
{
return (this.vnode instanceof LogicalResourceNode);
}
@Override
protected VRSProxyNode doGetParent() throws ProxyException
{
VNode parent;
try
{
parent = vnode.getParent();
if (parent==null)
return null;
return new VRSProxyNode(this.getProxyFactory(),parent,new VRL(parent.getVRL().toURI()));
}
catch (Exception e)
{
throw createProxyException("Couldn't get parent of:"+locator,e);
}
}
@Override
protected ProxyNode[] doGetChilds(int offset, int range,LongHolder numChildsLeft) throws ProxyException
{
debug("doGetChilds:"+this);
try
{
// check links first:
if (isResourceLink())
{
return resolve().doGetChilds(offset,range,numChildsLeft);
}
else
{
if ((vnode instanceof VComposite)==false)
return null;
VNode nodes[] = ((VComposite)vnode).getNodes();
return subrange(createNodes(nodes),offset,range);
}
}
catch (VrsException e)
{
throw createProxyException("Couldn't get childs of:"+locator,e);
}
}
protected VRSProxyNode resolve() throws ProxyException
{
debug("Resolving:"+this.vnode);
if ((vnode instanceof VResourceLink)==false)
return this;
nl.esciencecenter.vbrowser.vrs.vrl.VRL vrl;
try
{
vrl = ((VResourceLink)vnode).getTargetLocation();
VRSProxyNode node = factory()._openLocation(vrl);
debug("Resolved to:"+node);
return node;
}
catch (VrsException e)
{
throw createProxyException("Failed to resolve node:"+this.vnode,e);
}
}
protected VRSProxyNode[] createNodes(VNode[] nodes) throws ProxyException
{
if (nodes==null)
return null;
int len=nodes.length;
VRSProxyNode pnodes[]=new VRSProxyNode[len];
for (int i=0;i<len;i++)
{
pnodes[i]=createNode(nodes[i]);
}
return pnodes;
}
protected VRSProxyNode createNode(VNode node) throws ProxyException
{
try
{
return new VRSProxyNode(factory(),node,new VRL(node.getVRL().toURI()));
}
catch (Exception e)
{
throw createProxyException("Error creating proxy node from:"+node,e);
}
}
@Override
public String getIconURL(String status,int size) throws ProxyException
{
if (isLogicalNode())
{
return ((LogicalResourceNode)vnode).getTargetIconURL();
}
else
{
return vnode.getIconURL(size);
}
}
@Override
public VRSProxyFactory getProxyFactory()
{
return (VRSProxyFactory)super.getProxyFactory();
}
protected boolean isResourceLink()
{
if (vnode instanceof VResourceLink)
return true;
if (vnode.getVRL()==null)
return false;
// All .vlink AND .vrsx files are ResourceLinks !
if (vnode.getVRL().isVLink() == true)
return true;
return false;
}
protected void debug(String msg)
{
System.err.println("VRSProxyNode:"+msg);
}
public String toString()
{
return "<VRSProxyNode:"+getResourceType()+":"+getVRL();
}
@Override
protected String doGetMimeType() throws ProxyException
{
String mimeType=null;
try
{
mimeType=vnode.getMimeType();
}
catch (VrsException e)
{
throw new ProxyException("Couldn't determine mime type of:"+vnode,e);
}
if (vnode instanceof LogicalResourceNode)
{
LogicalResourceNode lnode=(LogicalResourceNode)vnode;
mimeType=lnode.getTargetMimeType();
}
return mimeType;
}
@Override
protected boolean doGetIsComposite() throws ProxyException
{
boolean isComposite=vnode.isComposite();
if (vnode instanceof LogicalResourceNode)
{
LogicalResourceNode lnode=(LogicalResourceNode)vnode;
try
{
isComposite=lnode.getTargetIsComposite(true);
}
catch (VrsException e)
{
throw createProxyException("Error checking LogicalResourceNode:"+lnode,e);
}
}
return isComposite;
}
@Override
protected String[] doGetChildTypes() throws ProxyException
{
if (vnode instanceof VComposite)
{
return ((VComposite)vnode).getResourceTypes();
}
return null;
}
// ========================================================================
// Misc
// ========================================================================
private ProxyException createProxyException(String msg, Exception e)
{
return new ProxyException(msg+"\n"+e.getMessage(),e);
}
@Override
protected String doGetName()
{
return vnode.getName();
}
@Override
protected String doGetResourceType()
{
return vnode.getResourceType();
}
@Override
protected String doGetResourceStatus() throws ProxyException
{
try
{
return this.vnode.getResourceStatus();
}
catch (VrsException e)
{
throw createProxyException("Couldn't get status of:"+vnode,e);
}
}
@Override
protected String[] doGetAttributeNames() throws ProxyException
{
return vnode.getAttributeNames();
}
@Override
protected Attribute[] doGetAttributes(String[] names) throws ProxyException
{
try
{
return vnode.getAttributes(names);
}
catch (VrsException e)
{
throw new ProxyException("Couldn't get attributes\n",e);
}
}
@Override
protected Presentation doGetPresentation()
{
if (vnode instanceof IPresentable)
{
return ((IPresentable) vnode).getPresentation();
}
String type=vnode.getResourceType();
return VRSPresentation.getPresentationFor(vnode.getVRL(),type, true);
}
} | source/nl.esciencecenter.vbrowser.vb2.vlet/src/nl/esciencecenter/vbrowser/vb2/vlet/proxy/vrs/VRSProxyNode.java | /*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* 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 the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vbrowser.vb2.vlet.proxy.vrs;
import java.net.URISyntaxException;
import nl.esciencecenter.ptk.data.LongHolder;
import nl.esciencecenter.ptk.presentation.IPresentable;
import nl.esciencecenter.ptk.presentation.Presentation;
import nl.esciencecenter.vbrowser.vb2.ui.proxy.ProxyException;
import nl.esciencecenter.vbrowser.vb2.ui.proxy.ProxyNode;
import nl.esciencecenter.vbrowser.vrs.data.Attribute;
import nl.esciencecenter.vbrowser.vrs.data.AttributeType;
import nl.esciencecenter.vbrowser.vrs.exceptions.VRLSyntaxException;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
import nl.esciencecenter.vlet.vrs.VComposite;
import nl.esciencecenter.vlet.vrs.VNode;
import nl.esciencecenter.vlet.vrs.presentation.VRSPresentation;
import nl.esciencecenter.vlet.vrs.vrms.LogicalResourceNode;
import nl.esciencecenter.vlet.vrs.vrms.VResourceLink;
/**
* VRS ProxyNode
*/
public class VRSProxyNode extends ProxyNode
{
private VNode vnode;
public VRSProxyNode(VRSProxyFactory vrsProxyFactory, VNode vnode,VRL locator) throws ProxyException, URISyntaxException
{
super(vrsProxyFactory,locator);
this.vnode=vnode;
}
protected VRSProxyFactory factory()
{
return (VRSProxyFactory)this.getProxyFactory();
}
protected void doPrefetchAttributes() throws ProxyException
{
super.doPrefetchAttributes();
if (vnode instanceof VResourceLink)
{
// assume true for now:
this.cache.setIsComposite(true);
}
}
protected boolean isLogicalNode()
{
return (this.vnode instanceof LogicalResourceNode);
}
@Override
protected VRSProxyNode doGetParent() throws ProxyException
{
VNode parent;
try
{
parent = vnode.getParent();
if (parent==null)
return null;
return new VRSProxyNode(this.getProxyFactory(),parent,new VRL(parent.getVRL().toURI()));
}
catch (Exception e)
{
throw createProxyException("Couldn't get parent of:"+locator,e);
}
}
@Override
protected ProxyNode[] doGetChilds(int offset, int range,LongHolder numChildsLeft) throws ProxyException
{
debug("doGetChilds:"+this);
try
{
// check links first:
if (isResourceLink())
{
return resolve().doGetChilds(offset,range,numChildsLeft);
}
else
{
if ((vnode instanceof VComposite)==false)
return null;
VNode nodes[] = ((VComposite)vnode).getNodes();
return subrange(createNodes(nodes),offset,range);
}
}
catch (VrsException e)
{
throw createProxyException("Couldn't get childs of:"+locator,e);
}
}
protected VRSProxyNode resolve() throws ProxyException
{
debug("Resolving:"+this.vnode);
if ((vnode instanceof VResourceLink)==false)
return this;
nl.esciencecenter.vbrowser.vrs.vrl.VRL vrl;
try
{
vrl = ((VResourceLink)vnode).getTargetLocation();
VRSProxyNode node = factory()._openLocation(vrl);
debug("Resolved to:"+node);
return node;
}
catch (VrsException e)
{
throw createProxyException("Failed to resolve node:"+this.vnode,e);
}
}
protected VRSProxyNode[] createNodes(VNode[] nodes) throws ProxyException
{
if (nodes==null)
return null;
int len=nodes.length;
VRSProxyNode pnodes[]=new VRSProxyNode[len];
for (int i=0;i<len;i++)
{
pnodes[i]=createNode(nodes[i]);
}
return pnodes;
}
protected VRSProxyNode createNode(VNode node) throws ProxyException
{
try
{
return new VRSProxyNode(factory(),node,new VRL(node.getVRL().toURI()));
}
catch (Exception e)
{
throw createProxyException("Error creating proxy node from:"+node,e);
}
}
@Override
public String getIconURL(String status,int size) throws ProxyException
{
if (isLogicalNode())
{
return ((LogicalResourceNode)vnode).getTargetIconURL();
}
else
{
return vnode.getIconURL(size);
}
}
@Override
public VRSProxyFactory getProxyFactory()
{
return (VRSProxyFactory)super.getProxyFactory();
}
protected boolean isResourceLink()
{
if (vnode instanceof VResourceLink)
return true;
if (vnode.getVRL()==null)
return false;
// All .vlink AND .vrsx files are ResourceLinks !
if (vnode.getVRL().isVLink() == true)
return true;
return false;
}
protected void debug(String msg)
{
System.err.println("VRSProxyNode:"+msg);
}
public String toString()
{
return "<ProxyNode>"+locator.toString();
}
@Override
protected String doGetMimeType() throws ProxyException
{
String mimeType=null;
try
{
mimeType=vnode.getMimeType();
}
catch (VrsException e)
{
throw new ProxyException("Couldn't determine mime type of:"+vnode,e);
}
if (vnode instanceof LogicalResourceNode)
{
LogicalResourceNode lnode=(LogicalResourceNode)vnode;
mimeType=lnode.getTargetMimeType();
}
return mimeType;
}
@Override
protected boolean doGetIsComposite() throws ProxyException
{
boolean isComposite=vnode.isComposite();
if (vnode instanceof LogicalResourceNode)
{
LogicalResourceNode lnode=(LogicalResourceNode)vnode;
try
{
isComposite=lnode.getTargetIsComposite(true);
}
catch (VrsException e)
{
throw createProxyException("Error checking LogicalResourceNode:"+lnode,e);
}
}
return isComposite;
}
@Override
protected String[] doGetChildTypes() throws ProxyException
{
if (vnode instanceof VComposite)
{
return ((VComposite)vnode).getResourceTypes();
}
return null;
}
// ========================================================================
// Misc
// ========================================================================
private ProxyException createProxyException(String msg, Exception e)
{
return new ProxyException(msg+"\n"+e.getMessage(),e);
}
@Override
protected String doGetName()
{
return vnode.getName();
}
@Override
protected String doGetResourceType()
{
return vnode.getResourceType();
}
@Override
protected String doGetResourceStatus() throws ProxyException
{
try
{
return this.vnode.getResourceStatus();
}
catch (VrsException e)
{
throw createProxyException("Couldn't get status of:"+vnode,e);
}
}
@Override
protected String[] doGetAttributeNames() throws ProxyException
{
return vnode.getAttributeNames();
}
@Override
protected Attribute[] doGetAttributes(String[] names) throws ProxyException
{
try
{
return vnode.getAttributes(names);
}
catch (VrsException e)
{
throw new ProxyException("Couldn't get attributes\n",e);
}
}
@Override
protected Presentation doGetPresentation()
{
if (vnode instanceof IPresentable)
{
return ((IPresentable) vnode).getPresentation();
}
String type=vnode.getResourceType();
return VRSPresentation.getPresentationFor(vnode.getVRL(),type, true);
}
} | Better toString() method.
| source/nl.esciencecenter.vbrowser.vb2.vlet/src/nl/esciencecenter/vbrowser/vb2/vlet/proxy/vrs/VRSProxyNode.java | Better toString() method. |
|
Java | apache-2.0 | d949647dfe786651b9f56985e8de5d02ee24538c | 0 | apache/jackrabbit,apache/jackrabbit,apache/jackrabbit | /*
* 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.jackrabbit.core.config;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemFactory;
import org.apache.jackrabbit.core.state.ISMLocking;
import org.apache.jackrabbit.core.state.ISMLockingFactory;
/**
* Workspace configuration. This configuration class is used to create
* configured workspace objects.
* <p/>
* The contained configuration information are: the home directory and name of
* the workspace, the file system, the persistence manager, the search index and
* the item state manager locking configuration. The search index and the item
* state manager locking and the security config are optional parts.
*/
public class WorkspaceConfig implements FileSystemFactory, ISMLockingFactory {
/**
* Workspace home directory.
*/
private final String home;
/**
* Workspace name.
*/
private final String name;
/**
* Flag indicating whether this workspace participates in a cluster.
*/
private final boolean clustered;
/**
* Workspace file system factory.
*/
private FileSystemFactory fsf;
/**
* Workspace persistence manager configuration.
*/
private PersistenceManagerConfig pmc;
/**
* Workspace search index configuration. Can be <code>null</code>.
*/
private SearchConfig sc;
/**
* The item state manager locking factory.
*/
private ISMLockingFactory ismLockingFactory;
/**
* Workspace security configuration. Can be <code>null</code>.
*/
private final WorkspaceSecurityConfig workspaceSecurityConfig;
/**
* Creates a workspace configuration object.
*
* @param home home directory
* @param name workspace name
* @param clustered
* @param fsf file system factory
* @param pmc persistence manager configuration
* @param sc search index configuration
* @param ismLockingFactory the item state manager locking factory
* @param workspaceSecurityConfig the workspace specific security configuration.
*/
public WorkspaceConfig(String home, String name, boolean clustered,
FileSystemFactory fsf, PersistenceManagerConfig pmc,
SearchConfig sc, ISMLockingFactory ismLockingFactory,
WorkspaceSecurityConfig workspaceSecurityConfig) {
this.home = home;
this.name = name;
this.clustered = clustered;
this.fsf = fsf;
this.pmc = pmc;
this.sc = sc;
this.ismLockingFactory = ismLockingFactory;
this.workspaceSecurityConfig = workspaceSecurityConfig;
}
/**
* Returns the workspace home directory.
*
* @return workspace home directory
*/
public String getHomeDir() {
return home;
}
/**
* Returns the workspace name.
*
* @return the workspace name
*/
public String getName() {
return name;
}
/**
* Returns a flag indicating whether this workspace participates in a cluster.
*
* @return <code>true</code> if this workspace participates in a cluster;
* <code>false</code> otherwise
*/
public boolean isClustered() {
return clustered;
}
/**
* Creates and returns the configured workspace locking strategy.
*
* @return the configured {@link ISMLocking}
* @throws RepositoryException if the locking strategy can not be created
*/
public ISMLocking getISMLocking() throws RepositoryException {
return ismLockingFactory.getISMLocking();
}
/**
* Creates and returns the configured workspace file system.
*
* @return the configured {@link FileSystem}
* @throws RepositoryException if the file system can not be created
*/
public FileSystem getFileSystem() throws RepositoryException {
return fsf.getFileSystem();
}
/**
* Returns the workspace persistence manager configuration.
*
* @return persistence manager configuration
*/
public PersistenceManagerConfig getPersistenceManagerConfig() {
return pmc;
}
/**
* Returns the workspace search index configuration. Returns
* <code>null</code> if a search index has not been configured.
*
* @return search index configuration, or <code>null</code>
*/
public SearchConfig getSearchConfig() {
return sc;
}
/**
* @return workspace-specific security settings.
* @see WorkspaceSecurityConfig
*/
public WorkspaceSecurityConfig getSecurityConfig() {
return workspaceSecurityConfig;
}
}
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/config/WorkspaceConfig.java | /*
* 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.jackrabbit.core.config;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemFactory;
import org.apache.jackrabbit.core.state.ISMLocking;
import org.apache.jackrabbit.core.state.ISMLockingFactory;
/**
* Workspace configuration. This configuration class is used to create
* configured workspace objects.
* <p/>
* The contained configuration information are: the home directory and name of
* the workspace, the file system, the persistence manager, the search index and
* the item state manager locking configuration. The search index and the item
* state manager locking and the security config are optional parts.
*/
public class WorkspaceConfig implements FileSystemFactory, ISMLockingFactory {
/**
* Workspace home directory.
*/
private final String home;
/**
* Workspace name.
*/
private final String name;
/**
* Flag indicating whether this workspace participates in a cluster.
*/
private final boolean clustered;
/**
* Workspace file system factory.
*/
private FileSystemFactory fsf;
/**
* Workspace persistence manager configuration.
*/
private PersistenceManagerConfig pmc;
/**
* Workspace search index configuration. Can be <code>null</code>.
*/
private SearchConfig sc;
/**
* The item state manager locking factory.
*/
private ISMLockingFactory ismLockingFactory;
/**
* Workspace security configuration. Can be <code>null</code>.
*/
private final WorkspaceSecurityConfig workspaceSecurityConfig;
/**
* Creates a workspace configuration object.
*
* @param home home directory
* @param name workspace name
* @param fsc file system factory
* @param pmc persistence manager configuration
* @param sc search index configuration
* @param ismLockingFactory the item state manager locking factory
* @param workspaceSecurityConfig the workspace specific security configuration.
*/
public WorkspaceConfig(String home, String name, boolean clustered,
FileSystemFactory fsf, PersistenceManagerConfig pmc,
SearchConfig sc, ISMLockingFactory ismLockingFactory,
WorkspaceSecurityConfig workspaceSecurityConfig) {
this.home = home;
this.name = name;
this.clustered = clustered;
this.fsf = fsf;
this.pmc = pmc;
this.sc = sc;
this.ismLockingFactory = ismLockingFactory;
this.workspaceSecurityConfig = workspaceSecurityConfig;
}
/**
* Returns the workspace home directory.
*
* @return workspace home directory
*/
public String getHomeDir() {
return home;
}
/**
* Returns the workspace name.
*
* @return the workspace name
*/
public String getName() {
return name;
}
/**
* Returns a flag indicating whether this workspace participates in a cluster.
*
* @return <code>true</code> if this workspace participates in a cluster;
* <code>false</code> otherwise
*/
public boolean isClustered() {
return clustered;
}
/**
* Creates and returns the configured workspace locking strategy.
*
* @return the configured {@link ISMLocking}
* @throws RepositoryException if the locking strategy can not be created
*/
public ISMLocking getISMLocking() throws RepositoryException {
return ismLockingFactory.getISMLocking();
}
/**
* Creates and returns the configured workspace file system.
*
* @return the configured {@link FileSystem}
* @throws RepositoryException if the file system can not be created
*/
public FileSystem getFileSystem() throws RepositoryException {
return fsf.getFileSystem();
}
/**
* Returns the workspace persistence manager configuration.
*
* @return persistence manager configuration
*/
public PersistenceManagerConfig getPersistenceManagerConfig() {
return pmc;
}
/**
* Returns the workspace search index configuration. Returns
* <code>null</code> if a search index has not been configured.
*
* @return search index configuration, or <code>null</code>
*/
public SearchConfig getSearchConfig() {
return sc;
}
/**
* @return workspace-specific security settings.
* @see WorkspaceSecurityConfig
*/
public WorkspaceSecurityConfig getSecurityConfig() {
return workspaceSecurityConfig;
}
}
| javadoc
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@748232 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/config/WorkspaceConfig.java | javadoc |
|
Java | mit | 525952f357e9b9e639c033b214e689440bd8ba40 | 0 | ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS | package de.tum.in.www1.artemis.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import de.tum.in.www1.artemis.domain.*;
import de.tum.in.www1.artemis.domain.enumeration.TutorParticipationStatus;
import de.tum.in.www1.artemis.domain.participation.TutorParticipation;
import de.tum.in.www1.artemis.repository.ExampleSubmissionRepository;
import de.tum.in.www1.artemis.repository.TutorParticipationRepository;
import de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;
import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;
/**
* Service Implementation for managing TutorParticipation.
*/
@Service
public class TutorParticipationService {
private final Logger log = LoggerFactory.getLogger(TutorParticipationService.class);
private final ExampleSubmissionRepository exampleSubmissionRepository;
private final static String ENTITY_NAME = "TutorParticipation";
private final TutorParticipationRepository tutorParticipationRepository;
private final ExampleSubmissionService exampleSubmissionService;
private static final float scoreRangePercentage = 10;
public TutorParticipationService(TutorParticipationRepository tutorParticipationRepository, ExampleSubmissionRepository exampleSubmissionRepository,
ExampleSubmissionService exampleSubmissionService) {
this.tutorParticipationRepository = tutorParticipationRepository;
this.exampleSubmissionRepository = exampleSubmissionRepository;
this.exampleSubmissionService = exampleSubmissionService;
}
/**
* Save a tutorParticipations.
*
* @param tutorParticipation the entity to save
* @return the persisted entity
*/
public TutorParticipation save(TutorParticipation tutorParticipation) {
log.debug("Request to save TutorParticipation : {}", tutorParticipation);
return tutorParticipationRepository.saveAndFlush(tutorParticipation);
}
/**
* Get one tutorParticipations by id.
*
* @param id the id of the entity
* @return the entity
*/
public TutorParticipation findOne(Long id) {
log.debug("Request to get TutorParticipation : {}", id);
Optional<TutorParticipation> tutorParticipation = tutorParticipationRepository.findById(id);
return tutorParticipation.orElse(null);
}
/**
* Given an exercise and a tutor, it retrieves the participation of the tutor for that exercise. If there isn't any participation in the database, it returns a participation
* with status NOT_PARTICIPATED
*
* @param exercise the exercise we want to retrieve the tutor participation
* @param tutor the tutor of who we want to retrieve the participation
* @return a tutor participation object for the pair (exercise, tutor) passed as argument
*/
public TutorParticipation findByExerciseAndTutor(Exercise exercise, User tutor) {
TutorParticipation participation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, tutor);
if (participation == null) {
participation = new TutorParticipation();
participation.setStatus(TutorParticipationStatus.NOT_PARTICIPATED);
}
return participation;
}
/**
* Checks if the tutor participation for the given values already exists to prevent duplicated values in the database
* @param assessedExerciseId the exercise we want to retrieve the tutor participation
* @param tutorId the tutor of who we want to retrieve the participation
* @return true if the tutor participation exists, false otherwise
*/
public Boolean existsByAssessedExerciseIdAndTutorId(Long assessedExerciseId, Long tutorId) {
return tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(assessedExerciseId, tutorId);
}
/**
* Given an exercise and a tutor it creates the participation of the tutor to that exercise The tutor starts a participation when she reads the grading instruction. If no
* grading instructions are available, then she starts her participation clicking on "Start participation". Usually, the first step is `REVIEWED_INSTRUCTIONS`: after that, she
* has to train reviewing some example submissions, and assessing others. If no example submissions are available, because the instructor hasn't created any, then she goes
* directly to the next step, that allows her to assess students' participations
*
* @param exercise the exercise the tutor is going to participate to
* @param tutor the tutor who is going to participate to the exercise
* @return a TutorParticipation for the exercise
*/
public TutorParticipation createNewParticipation(Exercise exercise, User tutor) {
TutorParticipation tutorParticipation = new TutorParticipation();
Long exampleSubmissionsCount = exampleSubmissionRepository.countAllByExerciseId(exercise.getId());
if (exampleSubmissionsCount == 0) {
tutorParticipation.setStatus(TutorParticipationStatus.TRAINED);
}
else {
tutorParticipation.setStatus(TutorParticipationStatus.REVIEWED_INSTRUCTIONS);
}
tutorParticipation.setTutor(tutor);
tutorParticipation.setAssessedExercise(exercise);
return save(tutorParticipation);
}
/**
* Given a course and a tutor, it finds all the participation of that tutor in the course, with related assessed exercise and trained example submissions
*
* @param course - the course we are interested in
* @param user - the tutor who is querying the service
* @return a list of tutor participation for the course
*/
public List<TutorParticipation> findAllByCourseAndTutor(Course course, User user) {
return tutorParticipationRepository.findAllByAssessedExercise_Course_IdAndTutor_Id(course.getId(), user.getId());
}
/**
* Given an exercise, it adds to the tutor participation of that exercise the example submission passed as argument, if it is valid (e.g: if it is an example submission used
* for tutorial, we check the result is close enough to the one of the instructor)
*
* @param exercise - the exercise we are referring to
* @param exampleSubmission - the example submission to add
* @param user - the user who invokes this request
* @return the updated tutor participation
* @throws EntityNotFoundException if example submission or tutor participation is not found
* @throws BadRequestAlertException if tutor didn't review the instructions before assessing example submissions
*/
public TutorParticipation addExampleSubmission(Exercise exercise, ExampleSubmission exampleSubmission, User user) throws EntityNotFoundException, BadRequestAlertException {
TutorParticipation existingTutorParticipation = this.findByExerciseAndTutor(exercise, user);
// Do not trust the user input
Optional<ExampleSubmission> exampleSubmissionFromDatabase = exampleSubmissionService.findByIdWithEagerTutorParticipations(exampleSubmission.getId());
if (existingTutorParticipation == null || exampleSubmissionFromDatabase.isEmpty()) {
throw new EntityNotFoundException("There isn't such example submission, or there isn't any tutor participation for this exercise");
}
ExampleSubmission originalExampleSubmission = exampleSubmissionFromDatabase.get();
// Cannot start an example submission if the tutor hasn't participated to the exercise yet
if (existingTutorParticipation.getStatus() == TutorParticipationStatus.NOT_PARTICIPATED) {
throw new BadRequestAlertException("The tutor needs review the instructions before assessing example submissions", ENTITY_NAME, "wrongStatus");
}
// Check if it is a tutorial or not
boolean isTutorial = Boolean.TRUE.equals(originalExampleSubmission.isUsedForTutorial());
// If it is a tutorial we check the assessment
if (isTutorial) {
// Retrieve the example feedback created by the instructor
List<Feedback> existingFeedback = this.exampleSubmissionService.getFeedbackForExampleSubmission(exampleSubmission.getId());
// Check if the result is the same
// TODO: at the moment we check only the score +/10%, maybe we want to do something smarter?
float instructorScore = calculateTotalScore(existingFeedback);
float lowerInstructorScore = instructorScore - instructorScore / scoreRangePercentage;
float higherInstructorScore = instructorScore + instructorScore / scoreRangePercentage;
float tutorScore = calculateTotalScore(exampleSubmission.getSubmission().getResult().getFeedbacks());
if (lowerInstructorScore > tutorScore) {
throw new BadRequestAlertException("tooLow", ENTITY_NAME, "tooLow");
}
if (tutorScore > higherInstructorScore) {
throw new BadRequestAlertException("tooHigh", ENTITY_NAME, "tooHigh");
}
}
List<ExampleSubmission> alreadyAssessedSubmissions = new ArrayList<>(existingTutorParticipation.getTrainedExampleSubmissions());
// If the example submission was already assessed, we do not assess it again, we just return the current participation
if (alreadyAssessedSubmissions.contains(exampleSubmission)) {
return existingTutorParticipation;
}
long numberOfExampleSubmissionsForTutor = this.exampleSubmissionRepository.findAllWithEagerResultByExerciseId(exercise.getId()).stream()
// We are only interested in example submissions with an assessment as these are the ones that can be reviewed/assessed by tutors.
// Otherwise, the tutor could not reach the total number of example submissions, if there are example submissions without assessment.
// In this case the tutor could not reach status "TRAINED" in the if statement below and would not be allowed
// to asses student submissions in the assessment dashboard.
.filter(exSub -> exSub.getSubmission() != null && exSub.getSubmission().getResult() != null && exSub.getSubmission().getResult().isExampleResult()).count();
int numberOfAlreadyAssessedSubmissions = alreadyAssessedSubmissions.size() + 1; // +1 because we haven't added yet the one we just did
/*
* When the tutor has read and assessed all the exercises, the tutor status goes to the next step.
*/
if (numberOfAlreadyAssessedSubmissions >= numberOfExampleSubmissionsForTutor) {
existingTutorParticipation.setStatus(TutorParticipationStatus.TRAINED);
}
// keep example submission set reference with loaded submission.results to reconnect after save response from DB
var exampleSubmissionSet = existingTutorParticipation.getTrainedExampleSubmissions();
existingTutorParticipation = existingTutorParticipation.addTrainedExampleSubmissions(originalExampleSubmission);
exampleSubmissionService.save(originalExampleSubmission);
existingTutorParticipation = save(existingTutorParticipation);
existingTutorParticipation.setTrainedExampleSubmissions(exampleSubmissionSet);
existingTutorParticipation.getTrainedExampleSubmissions().add(originalExampleSubmission);
return existingTutorParticipation;
}
/**
* This method removes the tutor participation for the example submission of an exercise
* @param exercise the exercise to which the example submission and tutor participation are linked to
* @param user the user for which the tutor participation should be removed
*/
public void removeTutorParticipations(Exercise exercise, User user) {
if (!tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(exercise.getId(), user.getId())) {
return;
}
Set<ExampleSubmission> exampleSubmissions = exampleSubmissionRepository.findAllByExerciseId(exercise.getId());
TutorParticipation tutorParticipation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, user);
for (ExampleSubmission exampleSubmission : exampleSubmissions) {
Optional<ExampleSubmission> exampleSubmissionWithTutorParticipation = exampleSubmissionRepository
.findByIdWithEagerResultsAndTutorParticipations(exampleSubmission.getId());
if (exampleSubmissionWithTutorParticipation.isPresent()) {
exampleSubmissionWithTutorParticipation.get().removeTutorParticipations(tutorParticipation);
tutorParticipationRepository.delete(tutorParticipation);
}
}
}
private float calculateTotalScore(List<Feedback> feedbacks) {
return (float) feedbacks.stream().mapToDouble(Feedback::getCredits).sum();
}
}
| src/main/java/de/tum/in/www1/artemis/service/TutorParticipationService.java | package de.tum.in.www1.artemis.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import de.tum.in.www1.artemis.domain.*;
import de.tum.in.www1.artemis.domain.enumeration.TutorParticipationStatus;
import de.tum.in.www1.artemis.domain.participation.TutorParticipation;
import de.tum.in.www1.artemis.repository.ExampleSubmissionRepository;
import de.tum.in.www1.artemis.repository.TutorParticipationRepository;
import de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;
import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;
/**
* Service Implementation for managing TutorParticipation.
*/
@Service
public class TutorParticipationService {
private final Logger log = LoggerFactory.getLogger(TutorParticipationService.class);
private final ExampleSubmissionRepository exampleSubmissionRepository;
private final static String ENTITY_NAME = "TutorParticipation";
private final TutorParticipationRepository tutorParticipationRepository;
private final ExampleSubmissionService exampleSubmissionService;
private static final float scoreRangePercentage = 10;
public TutorParticipationService(TutorParticipationRepository tutorParticipationRepository, ExampleSubmissionRepository exampleSubmissionRepository,
ExampleSubmissionService exampleSubmissionService) {
this.tutorParticipationRepository = tutorParticipationRepository;
this.exampleSubmissionRepository = exampleSubmissionRepository;
this.exampleSubmissionService = exampleSubmissionService;
}
/**
* Save a tutorParticipations.
*
* @param tutorParticipation the entity to save
* @return the persisted entity
*/
public TutorParticipation save(TutorParticipation tutorParticipation) {
log.debug("Request to save TutorParticipation : {}", tutorParticipation);
return tutorParticipationRepository.saveAndFlush(tutorParticipation);
}
/**
* Get one tutorParticipations by id.
*
* @param id the id of the entity
* @return the entity
*/
public TutorParticipation findOne(Long id) {
log.debug("Request to get TutorParticipation : {}", id);
Optional<TutorParticipation> tutorParticipation = tutorParticipationRepository.findById(id);
return tutorParticipation.orElse(null);
}
/**
* Given an exercise and a tutor, it retrieves the participation of the tutor for that exercise. If there isn't any participation in the database, it returns a participation
* with status NOT_PARTICIPATED
*
* @param exercise the exercise we want to retrieve the tutor participation
* @param tutor the tutor of who we want to retrieve the participation
* @return a tutor participation object for the pair (exercise, tutor) passed as argument
*/
public TutorParticipation findByExerciseAndTutor(Exercise exercise, User tutor) {
TutorParticipation participation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, tutor);
if (participation == null) {
participation = new TutorParticipation();
participation.setStatus(TutorParticipationStatus.NOT_PARTICIPATED);
}
return participation;
}
/**
* Checks if the tutor participation for the given values already exists to prevent duplicated values in the database
* @param assessedExerciseId the exercise we want to retrieve the tutor participation
* @param tutorId the tutor of who we want to retrieve the participation
* @return true if the tutor participation exists, false otherwise
*/
public Boolean existsByAssessedExerciseIdAndTutorId(Long assessedExerciseId, Long tutorId) {
return tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(assessedExerciseId, tutorId);
}
/**
* Given an exercise and a tutor it creates the participation of the tutor to that exercise The tutor starts a participation when she reads the grading instruction. If no
* grading instructions are available, then she starts her participation clicking on "Start participation". Usually, the first step is `REVIEWED_INSTRUCTIONS`: after that, she
* has to train reviewing some example submissions, and assessing others. If no example submissions are available, because the instructor hasn't created any, then she goes
* directly to the next step, that allows her to assess students' participations
*
* @param exercise the exercise the tutor is going to participate to
* @param tutor the tutor who is going to participate to the exercise
* @return a TutorParticipation for the exercise
*/
public TutorParticipation createNewParticipation(Exercise exercise, User tutor) {
TutorParticipation tutorParticipation = new TutorParticipation();
Long exampleSubmissionsCount = exampleSubmissionRepository.countAllByExerciseId(exercise.getId());
if (exampleSubmissionsCount == 0) {
tutorParticipation.setStatus(TutorParticipationStatus.TRAINED);
}
else {
tutorParticipation.setStatus(TutorParticipationStatus.REVIEWED_INSTRUCTIONS);
}
tutorParticipation.setTutor(tutor);
tutorParticipation.setAssessedExercise(exercise);
return save(tutorParticipation);
}
/**
* Given a course and a tutor, it finds all the participation of that tutor in the course, with related assessed exercise and trained example submissions
*
* @param course - the course we are interested in
* @param user - the tutor who is querying the service
* @return a list of tutor participation for the course
*/
public List<TutorParticipation> findAllByCourseAndTutor(Course course, User user) {
return tutorParticipationRepository.findAllByAssessedExercise_Course_IdAndTutor_Id(course.getId(), user.getId());
}
/**
* Given an exercise, it adds to the tutor participation of that exercise the example submission passed as argument, if it is valid (e.g: if it is an example submission used
* for tutorial, we check the result is close enough to the one of the instructor)
*
* @param exercise - the exercise we are referring to
* @param exampleSubmission - the example submission to add
* @param user - the user who invokes this request
* @return the updated tutor participation
* @throws EntityNotFoundException if example submission or tutor participation is not found
* @throws BadRequestAlertException if tutor didn't review the instructions before assessing example submissions
*/
public TutorParticipation addExampleSubmission(Exercise exercise, ExampleSubmission exampleSubmission, User user) throws EntityNotFoundException, BadRequestAlertException {
TutorParticipation existingTutorParticipation = this.findByExerciseAndTutor(exercise, user);
// Do not trust the user input
Optional<ExampleSubmission> exampleSubmissionFromDatabase = exampleSubmissionService.findByIdWithEagerTutorParticipations(exampleSubmission.getId());
if (existingTutorParticipation == null || exampleSubmissionFromDatabase.isEmpty()) {
throw new EntityNotFoundException("There isn't such example submission, or there isn't any tutor participation for this exercise");
}
ExampleSubmission originalExampleSubmission = exampleSubmissionFromDatabase.get();
// Cannot start an example submission if the tutor hasn't participated to the exercise yet
if (existingTutorParticipation.getStatus() == TutorParticipationStatus.NOT_PARTICIPATED) {
throw new BadRequestAlertException("The tutor needs review the instructions before assessing example submissions", ENTITY_NAME, "wrongStatus");
}
// Check if it is a tutorial or not
boolean isTutorial = Boolean.TRUE.equals(originalExampleSubmission.isUsedForTutorial());
// If it is a tutorial we check the assessment
if (isTutorial) {
// Retrieve the example feedback created by the instructor
List<Feedback> existingFeedback = this.exampleSubmissionService.getFeedbackForExampleSubmission(exampleSubmission.getId());
// Check if the result is the same
// TODO: at the moment we check only the score +/10%, maybe we want to do something smarter?
float instructorScore = calculateTotalScore(existingFeedback);
float lowerInstructorScore = instructorScore - instructorScore / scoreRangePercentage;
float higherInstructorScore = instructorScore + instructorScore / scoreRangePercentage;
float tutorScore = calculateTotalScore(exampleSubmission.getSubmission().getResult().getFeedbacks());
if (lowerInstructorScore > tutorScore) {
throw new BadRequestAlertException("tooLow", ENTITY_NAME, "tooLow");
}
if (tutorScore > higherInstructorScore) {
throw new BadRequestAlertException("tooHigh", ENTITY_NAME, "tooHigh");
}
}
List<ExampleSubmission> alreadyAssessedSubmissions = new ArrayList<>(existingTutorParticipation.getTrainedExampleSubmissions());
// If the example submission was already assessed, we do not assess it again, we just return the current participation
if (alreadyAssessedSubmissions.contains(exampleSubmission)) {
return existingTutorParticipation;
}
long numberOfExampleSubmissionsForTutor = this.exampleSubmissionRepository.findAllWithEagerResultByExerciseId(exercise.getId()).stream()
// We are only interested in example submissions with an assessment as these are the ones that can be reviewed/assessed by tutors.
// Otherwise, the tutor could not reach the total number of example submissions, if there are example submissions without assessment.
// In this case the tutor could not reach status "TRAINED" in the if statement below and would not be allowed
// to asses student submissions in the assessment dashboard.
.filter(exSub -> exSub.getSubmission() != null && exSub.getSubmission().getResult() != null && exSub.getSubmission().getResult().isExampleResult()).count();
int numberOfAlreadyAssessedSubmissions = alreadyAssessedSubmissions.size() + 1; // +1 because we haven't added yet the one we just did
/*
* When the tutor has read and assessed all the exercises, the tutor status goes to the next step.
*/
if (numberOfAlreadyAssessedSubmissions >= numberOfExampleSubmissionsForTutor) {
existingTutorParticipation.setStatus(TutorParticipationStatus.TRAINED);
}
existingTutorParticipation = existingTutorParticipation.addTrainedExampleSubmissions(originalExampleSubmission);
exampleSubmissionService.save(originalExampleSubmission);
existingTutorParticipation = save(existingTutorParticipation);
return existingTutorParticipation;
}
/**
* This method removes the tutor participation for the example submission of an exercise
* @param exercise the exercise to which the example submission and tutor participation are linked to
* @param user the user for which the tutor participation should be removed
*/
public void removeTutorParticipations(Exercise exercise, User user) {
if (!tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(exercise.getId(), user.getId())) {
return;
}
Set<ExampleSubmission> exampleSubmissions = exampleSubmissionRepository.findAllByExerciseId(exercise.getId());
TutorParticipation tutorParticipation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, user);
for (ExampleSubmission exampleSubmission : exampleSubmissions) {
Optional<ExampleSubmission> exampleSubmissionWithTutorParticipation = exampleSubmissionRepository
.findByIdWithEagerResultsAndTutorParticipations(exampleSubmission.getId());
if (exampleSubmissionWithTutorParticipation.isPresent()) {
exampleSubmissionWithTutorParticipation.get().removeTutorParticipations(tutorParticipation);
tutorParticipationRepository.delete(tutorParticipation);
}
}
}
private float calculateTotalScore(List<Feedback> feedbacks) {
return (float) feedbacks.stream().mapToDouble(Feedback::getCredits).sum();
}
}
| Fix lazy loading exception with example submissions (#2497)
| src/main/java/de/tum/in/www1/artemis/service/TutorParticipationService.java | Fix lazy loading exception with example submissions (#2497) |
|
Java | mit | 25fd3f36d323d382800c765268a49bad90f8f18d | 0 | mojohaus/buildnumber-maven-plugin,mojohaus/buildnumber-maven-plugin | package org.codehaus.mojo.build;
/**
* The MIT License
*
* Copyright (c) 2015 Learning Commons, University of Calgary
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmResult;
import org.apache.maven.scm.command.info.InfoItem;
import org.apache.maven.scm.command.info.InfoScmResult;
import org.apache.maven.scm.command.status.StatusScmResult;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.command.update.UpdateScmResultWithRevision;
import org.apache.maven.scm.log.ScmLogDispatcher;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.provider.ScmProvider;
import org.apache.maven.scm.provider.git.gitexe.command.branch.GitBranchCommand;
import org.apache.maven.scm.provider.git.repository.GitScmProviderRepository;
import org.apache.maven.scm.provider.hg.HgScmProvider;
import org.apache.maven.scm.provider.hg.HgUtils;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import static java.lang.Boolean.parseBoolean;
import static java.lang.Integer.parseInt;
/**
* This mojo is designed to give you a build number. So when you might make 100 builds of version 1.0-SNAPSHOT, you can
* differentiate between them all.
* <p>
* The build number is based on the revision number retrieved from SCM. It is known to work with Subversion, GIT, and
* Mercurial.
* <p>
* This mojo can also check to make sure that you have checked everything into SCM, before issuing the build number.
* That behaviour can be suppressed, and then the latest local build number is used.
* <p>
* Build numbers are not automatically reflected in your artifact's filename, but can be added to the metadata. You can
* access the build number in your pom with ${buildNumber}. You can also access ${timestamp} and the SCM branch of the
* build (if applicable) in ${scmBranch}
* <p>
* Note that there are several <code><strong>doFoo</strong></code> parameters. These parameters (doCheck, doUpdate, etc)
* are the first thing evaluated. If there is no matching expression, we get the default-value. If there is (ie
* <code>-Dmaven.buildNumber.doUpdate=false</code>), we get that value. So if the XML contains
* <tt><doCheck>true</doCheck></tt>, then normally that's the final value of the param in question. However,
* this mojo reverses that behaviour, such that the command line parameters get the last say.
*
* @author <a href="mailto:[email protected]">Julian Wood</a>
* @version $Id$
*/
@Mojo( name = "create", defaultPhase = LifecyclePhase.INITIALIZE, requiresProject = true, threadSafe = true )
public class CreateMojo
extends AbstractScmMojo
{
private static final String DEFAULT_BRANCH_NAME = "UNKNOWN_BRANCH";
/**
* You can rename the buildNumber property name to another property name if desired.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.buildNumberPropertyName", defaultValue = "buildNumber" )
private String buildNumberPropertyName;
/**
* You can rename the timestamp property name to another property name if desired.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.timestampPropertyName", defaultValue = "timestamp" )
private String timestampPropertyName;
/**
* If this is made true, we check for modified files, and if there are any, we fail the build. Note that this used
* to be inverted (skipCheck), but needed to be changed to allow releases to work. This corresponds to 'svn status'.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.doCheck", defaultValue = "false" )
private boolean doCheck;
/**
* If this is made true, then the revision will be updated to the latest in the repo, otherwise it will remain what
* it is locally. Note that this used to be inverted (skipUpdate), but needed to be changed to allow releases to
* work. This corresponds to 'svn update'.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.doUpdate", defaultValue = "false" )
private boolean doUpdate;
/**
* Specify a message as specified by java.text.MessageFormat. This triggers "items" configuration to be read
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.format" )
private String format;
/**
* Properties file to be created when "format" is not null and item has "buildNumber". See Usage for details
*
* @since 1.0-beta-2
*/
@Parameter( defaultValue = "${basedir}/buildNumber.properties" )
private File buildNumberPropertiesFileLocation;
/**
* Specify the corresponding items for the format message, as specified by java.text.MessageFormat. Special item
* values are "scmVersion", "timestamp" and "buildNumber[digits]", where [digits] are optional digits added to the
* end of the number to select a property.
*
* @since 1.0-beta-1
*/
@Parameter
private List<?> items;
/**
* The locale used for date and time formatting. The locale name should be in the format defined in
* {@link Locale#toString()}. The default locale is the platform default returned by {@link Locale#getDefault()}.
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.locale" )
private String locale;
/**
* whether to retrieve the revision for the last commit, or the last revision of the repository.
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.useLastCommittedRevision", defaultValue = "false" )
private boolean useLastCommittedRevision;
/**
* Apply this java.text.MessageFormat to the timestamp only (as opposed to the <code>format</code> parameter).
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.timestampFormat" )
private String timestampFormat;
/**
* Selects alternative SCM provider implementations. Each map key denotes the original provider type as given in the
* SCM URL like "cvs" or "svn", the map value specifies the provider type of the desired implementation to use
* instead. In other words, this map configures a substitution mapping for SCM providers.
*
* @since 1.0-beta-3
*/
@Parameter
private Map<String, String> providerImplementations;
/**
* If set to true, will get the scm revision once for all modules of a multi-module project instead of fetching once
* for each module.
*
* @since 1.0-beta-3
*/
@Parameter( property = "maven.buildNumber.getRevisionOnlyOnce", defaultValue = "false" )
private boolean getRevisionOnlyOnce;
/**
* You can rename the buildScmBranch property name to another property name if desired.
*
* @since 1.0-beta-4
*/
@Parameter( property = "maven.buildNumber.scmBranchPropertyName", defaultValue = "scmBranch" )
private String scmBranchPropertyName;
// ////////////////////////////////////// internal maven components ///////////////////////////////////
/**
* Contains the full list of projects in the reactor.
*
* @since 1.0-beta-3
*/
@Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true )
private List<MavenProject> reactorProjects;
@Parameter( defaultValue = "${session}", readonly = true, required = true )
private MavenSession session;
// ////////////////////////////////////// internal variables ///////////////////////////////////
private ScmLogDispatcher logger;
private String revision;
private boolean useScm;
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( skip )
{
getLog().info( "Skipping execution." );
return;
}
if ( providerImplementations != null )
{
for ( Entry<String, String> entry : providerImplementations.entrySet() )
{
String providerType = entry.getKey();
String providerImplementation = entry.getValue();
getLog().info( "Change the default '" + providerType + "' provider implementation to '"
+ providerImplementation + "'." );
scmManager.setScmProviderImplementation( providerType, providerImplementation );
}
}
Date now = Calendar.getInstance().getTime();
if ( format != null )
{
if ( items == null )
{
throw new MojoExecutionException(
" if you set a format, you must provide at least one item, please check documentation " );
}
// needs to be an array
// look for special values
Object[] itemAry = new Object[items.size()];
for ( int i = 0; i < items.size(); i++ )
{
Object item = items.get( i );
if ( item instanceof String )
{
String s = (String) item;
if ( s.equals( "timestamp" ) )
{
itemAry[i] = now;
}
else if ( s.startsWith( "scmVersion" ) )
{
useScm = true;
itemAry[i] = getRevision();
}
else if ( s.startsWith( "buildNumber" ) )
{
// check for properties file
File propertiesFile = this.buildNumberPropertiesFileLocation;
// create if not exists
if ( !propertiesFile.exists() )
{
try
{
if ( !propertiesFile.getParentFile().exists() )
{
propertiesFile.getParentFile().mkdirs();
}
propertiesFile.createNewFile();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't create properties file: " + propertiesFile,
e );
}
}
Properties properties = new Properties();
String buildNumberString = null;
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try
{
// get the number for the buildNumber specified
inputStream = new FileInputStream( propertiesFile );
properties.load( inputStream );
buildNumberString = properties.getProperty( s );
if ( buildNumberString == null )
{
buildNumberString = "0";
}
int buildNumber = parseInt( buildNumberString );
// store the increment
properties.setProperty( s, String.valueOf( ++buildNumber ) );
outputStream = new FileOutputStream( propertiesFile );
properties.store( outputStream, "maven.buildNumber.plugin properties file" );
// use in the message (format)
itemAry[i] = new Integer( buildNumber );
}
catch ( NumberFormatException e )
{
throw new MojoExecutionException(
"Couldn't parse buildNumber in properties file to an Integer: "
+ buildNumberString );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't load properties file: " + propertiesFile, e );
}
finally
{
IOUtil.close( inputStream );
IOUtil.close( outputStream );
}
}
else
{
itemAry[i] = item;
}
}
else
{
itemAry[i] = item;
}
}
revision = format( itemAry );
}
else
{
// Check if the plugin has already run.
revision = project.getProperties().getProperty( this.buildNumberPropertyName );
if ( this.getRevisionOnlyOnce && revision != null )
{
getLog().debug( "Revision available from previous execution" );
return;
}
if ( doCheck )
{
// we fail if there are local mods
checkForLocalModifications();
}
else
{
getLog().debug( "Checking for local modifications: skipped." );
}
if ( session.getSettings().isOffline() )
{
getLog().info( "maven is executed in offline mode, Updating project files from SCM: skipped." );
}
else
{
if ( doUpdate )
{
// we update your local repo
// even after you commit, your revision stays the same until you update, thus this
// action
List<ScmFile> changedFiles = update();
for ( ScmFile file : changedFiles )
{
getLog().debug( "Updated: " + file );
}
if ( changedFiles.size() == 0 )
{
getLog().debug( "No files needed updating." );
}
}
else
{
getLog().debug( "Updating project files from SCM: skipped." );
}
}
revision = getRevision();
}
if ( project != null )
{
String timestamp = String.valueOf( now.getTime() );
if ( timestampFormat != null )
{
timestamp = MessageFormat.format( timestampFormat, new Object[] { now } );
}
getLog().info( MessageFormat.format( "Storing buildNumber: {0} at timestamp: {1}", new Object[] { revision,
timestamp } ) );
if ( revision != null )
{
project.getProperties().put( buildNumberPropertyName, revision );
}
project.getProperties().put( timestampPropertyName, timestamp );
String scmBranch = getScmBranch();
getLog().info( "Storing buildScmBranch: " + scmBranch );
project.getProperties().put( scmBranchPropertyName, scmBranch );
// Add the revision and timestamp properties to each project in the reactor
if ( getRevisionOnlyOnce && reactorProjects != null )
{
Iterator<MavenProject> projIter = reactorProjects.iterator();
while ( projIter.hasNext() )
{
MavenProject nextProj = (MavenProject) projIter.next();
if ( revision != null )
{
nextProj.getProperties().put( this.buildNumberPropertyName, revision );
}
nextProj.getProperties().put( this.timestampPropertyName, timestamp );
nextProj.getProperties().put( this.scmBranchPropertyName, scmBranch );
}
}
}
}
/**
* Formats the given argument using the configured format template and locale.
*
* @param arguments arguments to be formatted @ @return formatted result
*/
private String format( Object[] arguments )
{
Locale l = Locale.getDefault();
if ( locale != null )
{
String[] parts = locale.split( "_", 3 );
if ( parts.length <= 1 )
{
l = new Locale( locale );
}
else if ( parts.length == 2 )
{
l = new Locale( parts[0], parts[1] );
}
else
{
l = new Locale( parts[0], parts[1], parts[2] );
}
}
return new MessageFormat( format, l ).format( arguments );
}
private void checkForLocalModifications()
throws MojoExecutionException
{
getLog().debug( "Verifying there are no local modifications ..." );
List<ScmFile> changedFiles;
try
{
changedFiles = getStatus();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "An error has occurred while checking scm status.", e );
}
if ( !changedFiles.isEmpty() )
{
StringBuilder message = new StringBuilder();
String ls = System.getProperty( "line.separator" );
for ( ScmFile file : changedFiles )
{
message.append( file.toString() );
message.append( ls );
}
throw new MojoExecutionException(
"Cannot create the build number because you have local modifications : \n"
+ message );
}
}
public List<ScmFile> update()
throws MojoExecutionException
{
try
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
UpdateScmResult result = scmProvider.update( repository, new ScmFileSet( scmDirectory ) );
if ( result == null )
{
return Collections.emptyList();
}
checkResult( result );
if ( result instanceof UpdateScmResultWithRevision )
{
String revision = ( (UpdateScmResultWithRevision) result ).getRevision();
getLog().info( "Got a revision during update: " + revision );
this.revision = revision;
}
return result.getUpdatedFiles();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Couldn't update project. " + e.getMessage(), e );
}
}
public List<ScmFile> getStatus()
throws ScmException
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
StatusScmResult result = scmProvider.status( repository, new ScmFileSet( scmDirectory ) );
if ( result == null )
{
return Collections.emptyList();
}
checkResult( result );
return result.getChangedFiles();
}
/**
* Get the branch info for this revision from the repository. For svn, it is in svn info.
*
* @return
* @throws MojoExecutionException
* @throws MojoExecutionException
*/
public String getScmBranch()
throws MojoExecutionException
{
try
{
ScmRepository repository = getScmRepository();
ScmProvider provider = scmManager.getProviderByRepository( repository );
/* git branch can be obtained directly by a command */
if ( GitScmProviderRepository.PROTOCOL_GIT.equals( provider.getScmType() ) )
{
ScmFileSet fileSet = new ScmFileSet( scmDirectory );
return GitBranchCommand.getCurrentBranch( getLogger(),
(GitScmProviderRepository) repository.getProviderRepository(),
fileSet );
} else if ( provider instanceof HgScmProvider ) {
/* hg branch can be obtained directly by a command */
HgOutputConsumer consumer = new HgOutputConsumer( getLogger() );
ScmResult result = HgUtils.execute( consumer, logger, scmDirectory, new String[] { "id", "-b" } );
checkResult( result );
if (StringUtils.isNotEmpty(consumer.getOutput())) {
return consumer.getOutput();
}
}
}
catch ( ScmException e )
{
getLog().warn( "Cannot get the branch information from the git repository: \n" + e.getLocalizedMessage() );
}
return getScmBranchFromUrl();
}
private String getScmBranchFromUrl()
throws MojoExecutionException
{
String scmUrl = null;
try
{
ScmRepository repository = getScmRepository();
InfoScmResult scmResult = info( repository, new ScmFileSet( scmDirectory ) );
if ( scmResult == null || !scmResult.isSuccess() )
{
getLog().debug( "Cannot get the branch information from the scm repository : "
+ ( scmResult == null ? "" : scmResult.getCommandOutput() ) );
return DEFAULT_BRANCH_NAME;
}
if ( scmResult.getInfoItems().isEmpty() )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
setDoCheck( false );
setDoUpdate( false );
return DEFAULT_BRANCH_NAME;
}
}
if ( !scmResult.getInfoItems().isEmpty() )
{
InfoItem info = scmResult.getInfoItems().get( 0 );
scmUrl = info.getURL();
}
}
catch ( ScmException e )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
getLog().warn( "Cannot get the branch information from the scm repository, proceeding with "
+ DEFAULT_BRANCH_NAME + " : \n" + e.getLocalizedMessage() );
setDoCheck( false );
setDoUpdate( false );
return DEFAULT_BRANCH_NAME;
}
throw new MojoExecutionException( "Cannot get the branch information from the scm repository : \n"
+ e.getLocalizedMessage(), e );
}
return filterBranchFromScmUrl( scmUrl );
}
protected String filterBranchFromScmUrl( String scmUrl )
{
String scmBranch = "UNKNOWN";
if ( StringUtils.contains( scmUrl, "/trunk" ) )
{
scmBranch = "trunk";
}
else if ( StringUtils.contains( scmUrl, "/branches" ) || StringUtils.contains( scmUrl, "/tags" ) )
{
scmBranch = scmUrl.replaceFirst( ".*((branches|tags)/[^/]*).*", "$1" );
}
return scmBranch;
}
/**
* Get the revision info from the repository. For svn, it is svn info
*
* @return
* @throws MojoExecutionException
*/
public String getRevision()
throws MojoExecutionException
{
if ( format != null && !useScm )
{
return revision;
}
useScm = false;
try
{
return this.getScmRevision();
}
catch ( ScmException e )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
getLog().warn( "Cannot get the revision information from the scm repository, proceeding with "
+ "revision of " + revisionOnScmFailure + " : \n" + e.getLocalizedMessage() );
setDoCheck( false );
setDoUpdate( false );
return revisionOnScmFailure;
}
throw new MojoExecutionException( "Cannot get the revision information from the scm repository : \n"
+ e.getLocalizedMessage(), e );
}
}
/**
* @return
* @todo normally this would be handled in AbstractScmProvider
*/
private ScmLogger getLogger()
{
if ( logger == null )
{
logger = new ScmLogDispatcher();
}
return logger;
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// setters to help with test
public void setScmManager( ScmManager scmManager )
{
this.scmManager = scmManager;
}
public void setUrlScm( String urlScm )
{
this.scmConnectionUrl = urlScm;
}
public void setUsername( String username )
{
this.username = username;
}
public void setPassword( String password )
{
this.password = password;
}
public void setDoCheck( boolean doCheck )
{
this.doCheck = getBooleanProperty( "maven.buildNumber.doCheck", doCheck );
}
public void setDoUpdate( boolean doUpdate )
{
this.doUpdate = getBooleanProperty( "maven.buildNumber.doUpdate", doUpdate );
}
private boolean getBooleanProperty( String key, boolean defaultValue ) {
String systemProperty = System.getProperty( key );
if (systemProperty == null)
{
return defaultValue;
}
else
{
return parseBoolean( systemProperty );
}
}
void setFormat( String format )
{
this.format = format;
}
void setLocale( String locale )
{
this.locale = locale;
}
void setItems( List<?> items )
{
this.items = items;
}
public void setBuildNumberPropertiesFileLocation( File buildNumberPropertiesFileLocation )
{
this.buildNumberPropertiesFileLocation = buildNumberPropertiesFileLocation;
}
public void setScmDirectory( File scmDirectory )
{
this.scmDirectory = scmDirectory;
}
public void setRevisionOnScmFailure( String revisionOnScmFailure )
{
this.revisionOnScmFailure = revisionOnScmFailure;
}
public void setShortRevisionLength( int shortRevision )
{
this.shortRevisionLength = shortRevision;
}
}
| src/main/java/org/codehaus/mojo/build/CreateMojo.java | package org.codehaus.mojo.build;
/**
* The MIT License
*
* Copyright (c) 2015 Learning Commons, University of Calgary
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmResult;
import org.apache.maven.scm.command.info.InfoItem;
import org.apache.maven.scm.command.info.InfoScmResult;
import org.apache.maven.scm.command.status.StatusScmResult;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.command.update.UpdateScmResultWithRevision;
import org.apache.maven.scm.log.ScmLogDispatcher;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.provider.ScmProvider;
import org.apache.maven.scm.provider.git.gitexe.command.branch.GitBranchCommand;
import org.apache.maven.scm.provider.git.repository.GitScmProviderRepository;
import org.apache.maven.scm.provider.hg.HgScmProvider;
import org.apache.maven.scm.provider.hg.HgUtils;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import static java.lang.Boolean.parseBoolean;
import static java.lang.Integer.parseInt;
/**
* This mojo is designed to give you a build number. So when you might make 100 builds of version 1.0-SNAPSHOT, you can
* differentiate between them all.
* <p>
* The build number is based on the revision number retrieved from SCM. It is known to work with Subversion, GIT, and
* Mercurial.
* <p>
* This mojo can also check to make sure that you have checked everything into SCM, before issuing the build number.
* That behaviour can be suppressed, and then the latest local build number is used.
* <p>
* Build numbers are not automatically reflected in your artifact's filename, but can be added to the metadata. You can
* access the build number in your pom with ${buildNumber}. You can also access ${timestamp} and the SCM branch of the
* build (if applicable) in ${SCMBranch}
* <p>
* Note that there are several <code><strong>doFoo</strong></code> parameters. These parameters (doCheck, doUpdate, etc)
* are the first thing evaluated. If there is no matching expression, we get the default-value. If there is (ie
* <code>-Dmaven.buildNumber.doUpdate=false</code>), we get that value. So if the XML contains
* <tt><doCheck>true</doCheck></tt>, then normally that's the final value of the param in question. However,
* this mojo reverses that behaviour, such that the command line parameters get the last say.
*
* @author <a href="mailto:[email protected]">Julian Wood</a>
* @version $Id$
*/
@Mojo( name = "create", defaultPhase = LifecyclePhase.INITIALIZE, requiresProject = true, threadSafe = true )
public class CreateMojo
extends AbstractScmMojo
{
private static final String DEFAULT_BRANCH_NAME = "UNKNOWN_BRANCH";
/**
* You can rename the buildNumber property name to another property name if desired.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.buildNumberPropertyName", defaultValue = "buildNumber" )
private String buildNumberPropertyName;
/**
* You can rename the timestamp property name to another property name if desired.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.timestampPropertyName", defaultValue = "timestamp" )
private String timestampPropertyName;
/**
* If this is made true, we check for modified files, and if there are any, we fail the build. Note that this used
* to be inverted (skipCheck), but needed to be changed to allow releases to work. This corresponds to 'svn status'.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.doCheck", defaultValue = "false" )
private boolean doCheck;
/**
* If this is made true, then the revision will be updated to the latest in the repo, otherwise it will remain what
* it is locally. Note that this used to be inverted (skipUpdate), but needed to be changed to allow releases to
* work. This corresponds to 'svn update'.
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.doUpdate", defaultValue = "false" )
private boolean doUpdate;
/**
* Specify a message as specified by java.text.MessageFormat. This triggers "items" configuration to be read
*
* @since 1.0-beta-1
*/
@Parameter( property = "maven.buildNumber.format" )
private String format;
/**
* Properties file to be created when "format" is not null and item has "buildNumber". See Usage for details
*
* @since 1.0-beta-2
*/
@Parameter( defaultValue = "${basedir}/buildNumber.properties" )
private File buildNumberPropertiesFileLocation;
/**
* Specify the corresponding items for the format message, as specified by java.text.MessageFormat. Special item
* values are "scmVersion", "timestamp" and "buildNumber[digits]", where [digits] are optional digits added to the
* end of the number to select a property.
*
* @since 1.0-beta-1
*/
@Parameter
private List<?> items;
/**
* The locale used for date and time formatting. The locale name should be in the format defined in
* {@link Locale#toString()}. The default locale is the platform default returned by {@link Locale#getDefault()}.
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.locale" )
private String locale;
/**
* whether to retrieve the revision for the last commit, or the last revision of the repository.
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.useLastCommittedRevision", defaultValue = "false" )
private boolean useLastCommittedRevision;
/**
* Apply this java.text.MessageFormat to the timestamp only (as opposed to the <code>format</code> parameter).
*
* @since 1.0-beta-2
*/
@Parameter( property = "maven.buildNumber.timestampFormat" )
private String timestampFormat;
/**
* Selects alternative SCM provider implementations. Each map key denotes the original provider type as given in the
* SCM URL like "cvs" or "svn", the map value specifies the provider type of the desired implementation to use
* instead. In other words, this map configures a substitution mapping for SCM providers.
*
* @since 1.0-beta-3
*/
@Parameter
private Map<String, String> providerImplementations;
/**
* If set to true, will get the scm revision once for all modules of a multi-module project instead of fetching once
* for each module.
*
* @since 1.0-beta-3
*/
@Parameter( property = "maven.buildNumber.getRevisionOnlyOnce", defaultValue = "false" )
private boolean getRevisionOnlyOnce;
/**
* You can rename the buildScmBranch property name to another property name if desired.
*
* @since 1.0-beta-4
*/
@Parameter( property = "maven.buildNumber.scmBranchPropertyName", defaultValue = "scmBranch" )
private String scmBranchPropertyName;
// ////////////////////////////////////// internal maven components ///////////////////////////////////
/**
* Contains the full list of projects in the reactor.
*
* @since 1.0-beta-3
*/
@Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true )
private List<MavenProject> reactorProjects;
@Parameter( defaultValue = "${session}", readonly = true, required = true )
private MavenSession session;
// ////////////////////////////////////// internal variables ///////////////////////////////////
private ScmLogDispatcher logger;
private String revision;
private boolean useScm;
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( skip )
{
getLog().info( "Skipping execution." );
return;
}
if ( providerImplementations != null )
{
for ( Entry<String, String> entry : providerImplementations.entrySet() )
{
String providerType = entry.getKey();
String providerImplementation = entry.getValue();
getLog().info( "Change the default '" + providerType + "' provider implementation to '"
+ providerImplementation + "'." );
scmManager.setScmProviderImplementation( providerType, providerImplementation );
}
}
Date now = Calendar.getInstance().getTime();
if ( format != null )
{
if ( items == null )
{
throw new MojoExecutionException(
" if you set a format, you must provide at least one item, please check documentation " );
}
// needs to be an array
// look for special values
Object[] itemAry = new Object[items.size()];
for ( int i = 0; i < items.size(); i++ )
{
Object item = items.get( i );
if ( item instanceof String )
{
String s = (String) item;
if ( s.equals( "timestamp" ) )
{
itemAry[i] = now;
}
else if ( s.startsWith( "scmVersion" ) )
{
useScm = true;
itemAry[i] = getRevision();
}
else if ( s.startsWith( "buildNumber" ) )
{
// check for properties file
File propertiesFile = this.buildNumberPropertiesFileLocation;
// create if not exists
if ( !propertiesFile.exists() )
{
try
{
if ( !propertiesFile.getParentFile().exists() )
{
propertiesFile.getParentFile().mkdirs();
}
propertiesFile.createNewFile();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't create properties file: " + propertiesFile,
e );
}
}
Properties properties = new Properties();
String buildNumberString = null;
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try
{
// get the number for the buildNumber specified
inputStream = new FileInputStream( propertiesFile );
properties.load( inputStream );
buildNumberString = properties.getProperty( s );
if ( buildNumberString == null )
{
buildNumberString = "0";
}
int buildNumber = parseInt( buildNumberString );
// store the increment
properties.setProperty( s, String.valueOf( ++buildNumber ) );
outputStream = new FileOutputStream( propertiesFile );
properties.store( outputStream, "maven.buildNumber.plugin properties file" );
// use in the message (format)
itemAry[i] = new Integer( buildNumber );
}
catch ( NumberFormatException e )
{
throw new MojoExecutionException(
"Couldn't parse buildNumber in properties file to an Integer: "
+ buildNumberString );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't load properties file: " + propertiesFile, e );
}
finally
{
IOUtil.close( inputStream );
IOUtil.close( outputStream );
}
}
else
{
itemAry[i] = item;
}
}
else
{
itemAry[i] = item;
}
}
revision = format( itemAry );
}
else
{
// Check if the plugin has already run.
revision = project.getProperties().getProperty( this.buildNumberPropertyName );
if ( this.getRevisionOnlyOnce && revision != null )
{
getLog().debug( "Revision available from previous execution" );
return;
}
if ( doCheck )
{
// we fail if there are local mods
checkForLocalModifications();
}
else
{
getLog().debug( "Checking for local modifications: skipped." );
}
if ( session.getSettings().isOffline() )
{
getLog().info( "maven is executed in offline mode, Updating project files from SCM: skipped." );
}
else
{
if ( doUpdate )
{
// we update your local repo
// even after you commit, your revision stays the same until you update, thus this
// action
List<ScmFile> changedFiles = update();
for ( ScmFile file : changedFiles )
{
getLog().debug( "Updated: " + file );
}
if ( changedFiles.size() == 0 )
{
getLog().debug( "No files needed updating." );
}
}
else
{
getLog().debug( "Updating project files from SCM: skipped." );
}
}
revision = getRevision();
}
if ( project != null )
{
String timestamp = String.valueOf( now.getTime() );
if ( timestampFormat != null )
{
timestamp = MessageFormat.format( timestampFormat, new Object[] { now } );
}
getLog().info( MessageFormat.format( "Storing buildNumber: {0} at timestamp: {1}", new Object[] { revision,
timestamp } ) );
if ( revision != null )
{
project.getProperties().put( buildNumberPropertyName, revision );
}
project.getProperties().put( timestampPropertyName, timestamp );
String scmBranch = getScmBranch();
getLog().info( "Storing buildScmBranch: " + scmBranch );
project.getProperties().put( scmBranchPropertyName, scmBranch );
// Add the revision and timestamp properties to each project in the reactor
if ( getRevisionOnlyOnce && reactorProjects != null )
{
Iterator<MavenProject> projIter = reactorProjects.iterator();
while ( projIter.hasNext() )
{
MavenProject nextProj = (MavenProject) projIter.next();
if ( revision != null )
{
nextProj.getProperties().put( this.buildNumberPropertyName, revision );
}
nextProj.getProperties().put( this.timestampPropertyName, timestamp );
nextProj.getProperties().put( this.scmBranchPropertyName, scmBranch );
}
}
}
}
/**
* Formats the given argument using the configured format template and locale.
*
* @param arguments arguments to be formatted @ @return formatted result
*/
private String format( Object[] arguments )
{
Locale l = Locale.getDefault();
if ( locale != null )
{
String[] parts = locale.split( "_", 3 );
if ( parts.length <= 1 )
{
l = new Locale( locale );
}
else if ( parts.length == 2 )
{
l = new Locale( parts[0], parts[1] );
}
else
{
l = new Locale( parts[0], parts[1], parts[2] );
}
}
return new MessageFormat( format, l ).format( arguments );
}
private void checkForLocalModifications()
throws MojoExecutionException
{
getLog().debug( "Verifying there are no local modifications ..." );
List<ScmFile> changedFiles;
try
{
changedFiles = getStatus();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "An error has occurred while checking scm status.", e );
}
if ( !changedFiles.isEmpty() )
{
StringBuilder message = new StringBuilder();
String ls = System.getProperty( "line.separator" );
for ( ScmFile file : changedFiles )
{
message.append( file.toString() );
message.append( ls );
}
throw new MojoExecutionException(
"Cannot create the build number because you have local modifications : \n"
+ message );
}
}
public List<ScmFile> update()
throws MojoExecutionException
{
try
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
UpdateScmResult result = scmProvider.update( repository, new ScmFileSet( scmDirectory ) );
if ( result == null )
{
return Collections.emptyList();
}
checkResult( result );
if ( result instanceof UpdateScmResultWithRevision )
{
String revision = ( (UpdateScmResultWithRevision) result ).getRevision();
getLog().info( "Got a revision during update: " + revision );
this.revision = revision;
}
return result.getUpdatedFiles();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Couldn't update project. " + e.getMessage(), e );
}
}
public List<ScmFile> getStatus()
throws ScmException
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
StatusScmResult result = scmProvider.status( repository, new ScmFileSet( scmDirectory ) );
if ( result == null )
{
return Collections.emptyList();
}
checkResult( result );
return result.getChangedFiles();
}
/**
* Get the branch info for this revision from the repository. For svn, it is in svn info.
*
* @return
* @throws MojoExecutionException
* @throws MojoExecutionException
*/
public String getScmBranch()
throws MojoExecutionException
{
try
{
ScmRepository repository = getScmRepository();
ScmProvider provider = scmManager.getProviderByRepository( repository );
/* git branch can be obtained directly by a command */
if ( GitScmProviderRepository.PROTOCOL_GIT.equals( provider.getScmType() ) )
{
ScmFileSet fileSet = new ScmFileSet( scmDirectory );
return GitBranchCommand.getCurrentBranch( getLogger(),
(GitScmProviderRepository) repository.getProviderRepository(),
fileSet );
} else if ( provider instanceof HgScmProvider ) {
/* hg branch can be obtained directly by a command */
HgOutputConsumer consumer = new HgOutputConsumer( getLogger() );
ScmResult result = HgUtils.execute( consumer, logger, scmDirectory, new String[] { "id", "-b" } );
checkResult( result );
if (StringUtils.isNotEmpty(consumer.getOutput())) {
return consumer.getOutput();
}
}
}
catch ( ScmException e )
{
getLog().warn( "Cannot get the branch information from the git repository: \n" + e.getLocalizedMessage() );
}
return getScmBranchFromUrl();
}
private String getScmBranchFromUrl()
throws MojoExecutionException
{
String scmUrl = null;
try
{
ScmRepository repository = getScmRepository();
InfoScmResult scmResult = info( repository, new ScmFileSet( scmDirectory ) );
if ( scmResult == null || !scmResult.isSuccess() )
{
getLog().debug( "Cannot get the branch information from the scm repository : "
+ ( scmResult == null ? "" : scmResult.getCommandOutput() ) );
return DEFAULT_BRANCH_NAME;
}
if ( scmResult.getInfoItems().isEmpty() )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
setDoCheck( false );
setDoUpdate( false );
return DEFAULT_BRANCH_NAME;
}
}
if ( !scmResult.getInfoItems().isEmpty() )
{
InfoItem info = scmResult.getInfoItems().get( 0 );
scmUrl = info.getURL();
}
}
catch ( ScmException e )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
getLog().warn( "Cannot get the branch information from the scm repository, proceeding with "
+ DEFAULT_BRANCH_NAME + " : \n" + e.getLocalizedMessage() );
setDoCheck( false );
setDoUpdate( false );
return DEFAULT_BRANCH_NAME;
}
throw new MojoExecutionException( "Cannot get the branch information from the scm repository : \n"
+ e.getLocalizedMessage(), e );
}
return filterBranchFromScmUrl( scmUrl );
}
protected String filterBranchFromScmUrl( String scmUrl )
{
String scmBranch = "UNKNOWN";
if ( StringUtils.contains( scmUrl, "/trunk" ) )
{
scmBranch = "trunk";
}
else if ( StringUtils.contains( scmUrl, "/branches" ) || StringUtils.contains( scmUrl, "/tags" ) )
{
scmBranch = scmUrl.replaceFirst( ".*((branches|tags)/[^/]*).*", "$1" );
}
return scmBranch;
}
/**
* Get the revision info from the repository. For svn, it is svn info
*
* @return
* @throws MojoExecutionException
*/
public String getRevision()
throws MojoExecutionException
{
if ( format != null && !useScm )
{
return revision;
}
useScm = false;
try
{
return this.getScmRevision();
}
catch ( ScmException e )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
getLog().warn( "Cannot get the revision information from the scm repository, proceeding with "
+ "revision of " + revisionOnScmFailure + " : \n" + e.getLocalizedMessage() );
setDoCheck( false );
setDoUpdate( false );
return revisionOnScmFailure;
}
throw new MojoExecutionException( "Cannot get the revision information from the scm repository : \n"
+ e.getLocalizedMessage(), e );
}
}
/**
* @return
* @todo normally this would be handled in AbstractScmProvider
*/
private ScmLogger getLogger()
{
if ( logger == null )
{
logger = new ScmLogDispatcher();
}
return logger;
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// setters to help with test
public void setScmManager( ScmManager scmManager )
{
this.scmManager = scmManager;
}
public void setUrlScm( String urlScm )
{
this.scmConnectionUrl = urlScm;
}
public void setUsername( String username )
{
this.username = username;
}
public void setPassword( String password )
{
this.password = password;
}
public void setDoCheck( boolean doCheck )
{
this.doCheck = getBooleanProperty( "maven.buildNumber.doCheck", doCheck );
}
public void setDoUpdate( boolean doUpdate )
{
this.doUpdate = getBooleanProperty( "maven.buildNumber.doUpdate", doUpdate );
}
private boolean getBooleanProperty( String key, boolean defaultValue ) {
String systemProperty = System.getProperty( key );
if (systemProperty == null)
{
return defaultValue;
}
else
{
return parseBoolean( systemProperty );
}
}
void setFormat( String format )
{
this.format = format;
}
void setLocale( String locale )
{
this.locale = locale;
}
void setItems( List<?> items )
{
this.items = items;
}
public void setBuildNumberPropertiesFileLocation( File buildNumberPropertiesFileLocation )
{
this.buildNumberPropertiesFileLocation = buildNumberPropertiesFileLocation;
}
public void setScmDirectory( File scmDirectory )
{
this.scmDirectory = scmDirectory;
}
public void setRevisionOnScmFailure( String revisionOnScmFailure )
{
this.revisionOnScmFailure = revisionOnScmFailure;
}
public void setShortRevisionLength( int shortRevision )
{
this.shortRevisionLength = shortRevision;
}
}
| Fixed #37 wrong mention property name in description.
| src/main/java/org/codehaus/mojo/build/CreateMojo.java | Fixed #37 wrong mention property name in description. |
|
Java | mit | 1e1c235502997373b31fdcf051f68f7e0792f1c0 | 0 | twentwo/ECharts,huhekai/ECharts,twentwo/ECharts,Pluto-Y/ECharts,Pluto-Y/ECharts,huhekai/ECharts,abel533/ECharts,abel533/ECharts,ntvis/ECharts,ntvis/ECharts | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.abel533.echarts.feature;
import com.github.abel533.echarts.style.LineStyle;
import com.github.abel533.echarts.style.TextStyle;
/**
* @author liuzh
*/
public class Feature {
public static final DataView dataView = new DataView();
public static final DataZoom dataZoom = new DataZoom();
public static final Mark mark = new Mark();
public static final SaveAsImage saveAsImage = new SaveAsImage();
public static final MagicType magicType = new MagicType();
public static final Restore restore = new Restore();
/**
* 是否显示
*/
private Boolean show;
/**
* 标题
*/
private Object title;
/**
* 类型
*
* @see com.github.abel533.echarts.code.Magic
* @see com.github.abel533.echarts.code.LineType
*/
private Object type;
/**
* 只读
*/
private Boolean readOnly;
/**
* lang 非IE浏览器支持点击下载,有保存话术,默认是“点击保存”,可修改
*/
private Object lang;
/**
* 线条颜色
*
* @see com.github.abel533.echarts.style.LineStyle
*/
private LineStyle lineStyle;
/**
* 文字颜色
*
* @see com.github.abel533.echarts.style.TextStyle
*/
private TextStyle textStyle;
/**
* 图标,image://开头
*/
private String icon;
public Boolean show() {
return this.show;
}
public Feature show(Boolean show) {
this.show = show;
return this;
}
public Object title() {
return this.title;
}
public Feature title(Object title) {
this.title = title;
return this;
}
public Object type() {
return this.type;
}
public Feature type(Object type) {
this.type = type;
return this;
}
public Boolean readOnly() {
return this.readOnly;
}
public Feature readOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
public Object lang() {
return this.lang;
}
public Feature lang(Object lang) {
this.lang = lang;
return this;
}
public LineStyle lineStyle() {
return this.lineStyle;
}
public Feature lineStyle(LineStyle lineStyle) {
this.lineStyle = lineStyle;
return this;
}
public TextStyle textStyle() {
return this.textStyle;
}
public Feature textStyle(TextStyle textStyle) {
this.textStyle = textStyle;
return this;
}
public String icon() {
return this.icon;
}
public Feature icon(String icon) {
this.icon = icon;
return this;
}
public Boolean getShow() {
return show;
}
public void setShow(Boolean show) {
this.show = show;
}
public Object getTitle() {
return title;
}
public void setTitle(Object title) {
this.title = title;
}
public Object getType() {
return type;
}
public void setType(Object type) {
this.type = type;
}
public Boolean getReadOnly() {
return readOnly;
}
public void setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
}
public Object getLang() {
return lang;
}
public void setLang(Object lang) {
this.lang = lang;
}
public LineStyle getLineStyle() {
return lineStyle;
}
public void setLineStyle(LineStyle lineStyle) {
this.lineStyle = lineStyle;
}
public TextStyle getTextStyle() {
return textStyle;
}
public void setTextStyle(TextStyle textStyle) {
this.textStyle = textStyle;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
| src/main/java/com/github/abel533/echarts/feature/Feature.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.abel533.echarts.feature;
import com.github.abel533.echarts.style.LineStyle;
import com.github.abel533.echarts.style.TextStyle;
/**
* @author liuzh
*/
public class Feature {
public static final DataView dataView = new DataView();
public static final DataZoom dataZoom = new DataZoom();
public static final Mark mark = new Mark();
public static final SaveAsImage saveAsImage = new SaveAsImage();
public static final MagicType magicType = new MagicType();
public static final Restore restore = new Restore();
/**
* 是否显示
*/
private Boolean show;
/**
* 标题
*/
private Object title;
/**
* 类型
*
* @see com.github.abel533.echarts.code.Magic
* @see com.github.abel533.echarts.code.LineType
*/
private Object type;
/**
* 只读
*/
private Boolean readOnly;
/**
* lang 非IE浏览器支持点击下载,有保存话术,默认是“点击保存”,可修改
*/
private Object lang;
/**
* 线条颜色
*
* @see com.github.abel533.echarts.style.LineStyle
*/
private LineStyle lineStyle;
/**
* 文字颜色
*
* @see com.github.abel533.echarts.style.TextStyle
*/
private TextStyle textStyle;
/**
* 图标,image://开头
*/
private String icon;
public Boolean show() {
return this.show;
}
public Feature show(Boolean show) {
this.show = show;
return this;
}
public Object title() {
return this.title;
}
public Feature title(Object title) {
this.title = title;
return this;
}
public Object type() {
return this.type;
}
public Feature type(Object type) {
this.type = type;
return this;
}
public Boolean readOnly() {
return this.readOnly;
}
public Feature readOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
public Object lang() {
return this.lang;
}
public Feature lang(Object lang) {
this.lang = lang;
return this;
}
public LineStyle lineStyle() {
return this.lineStyle;
}
public Feature lineStyle(LineStyle lineStyle) {
this.lineStyle = lineStyle;
return this;
}
public TextStyle textStyle() {
return this.textStyle;
}
public Feature textStyle(TextStyle textStyle) {
this.textStyle = textStyle;
return this;
}
public String icon() {
return this.icon;
}
public Feature icon(String icon) {
this.icon = icon;
return this;
}
}
| 增加缺少的setter,getter
| src/main/java/com/github/abel533/echarts/feature/Feature.java | 增加缺少的setter,getter |
|
Java | agpl-3.0 | 31b0ad1da429f5f81272346d156a0d394c2500c3 | 0 | Amine-H/PDFLego | package com.xhub.pdflego.formatter.pdf;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.xhub.pdflego.bloc.PLTextBlock;
import org.apache.log4j.Logger;
/**
* Created by amine
*/
public class TextRenderStrategy implements ComponenRenderStrategy<PLTextBlock>{
private Logger logger = Logger.getLogger(TextRenderStrategy.class);
@Override
public void render(Canvas componentCanvas, PLTextBlock component) {
String text = component.getText();
float leading = component.getFontSize() + component.getLineSpacing();
Paragraph paragraph = new Paragraph()
.setMargin(0)
.setFirstLineIndent(0)
.setFixedLeading(leading)
.setFont(component.getFont())
.setFontSize(component.getFontSize())
.add(text);
componentCanvas.add(paragraph);
}
}
| src/main/java/com/xhub/pdflego/formatter/pdf/TextRenderStrategy.java | package com.xhub.pdflego.formatter.pdf;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.xhub.pdflego.bloc.PLTextBlock;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Created by amine
*/
public class TextRenderStrategy implements ComponenRenderStrategy<PLTextBlock>{
private Logger logger = Logger.getLogger(TextRenderStrategy.class);
@Override
public void render(Canvas componentCanvas, PLTextBlock component) {
String text = new String(component.getText());
Integer blockWidth = component.getWidth();
Integer blockHeight = component.getHeight();
List<String> lines = new ArrayList<>();
String[] words = text.split(" ");
String myLine = "";
// get all words from the text
for(String word : words) {
if(!myLine.isEmpty()) {
myLine += " ";
}
// test the width of the current line + the current word
int textWidth = (int) (component.getFontSize() * component.getFont().getWidth(myLine + word) / 1000);
if(textWidth > blockWidth) {
// if the line would be too long with the current word, add the line without the current word
lines.add(myLine);
// and start a new line with the current word
myLine = word;
} else {
// if the current line + the current word would fit, add the current word to the line
myLine += word;
}
}
// add the rest to lines
lines.add(myLine);
//draw the list of lines
float textHeight = 0f;
float lineHeight = component.getFontSize() + component.getLineSpacing();
for(String line: lines){
if(textHeight + lineHeight > blockHeight){
this.logger.warn("text is bigger than the Component's Height, ignoring the rest of the text");
break;
}
Paragraph paragraph = new Paragraph(line)
.setFixedLeading(component.getLineSpacing())
.setFont(component.getFont())
.setFontSize(component.getFontSize());
componentCanvas.add(paragraph);
textHeight += lineHeight;
}
}
}
| refactored Textrendering strategy
| src/main/java/com/xhub/pdflego/formatter/pdf/TextRenderStrategy.java | refactored Textrendering strategy |
|
Java | agpl-3.0 | 39598adcc86df67bca87c802a89b4e21075aee7f | 0 | torakiki/sejda | /*
* Created on 21/set/2010
*
* Copyright 2010 by Andrea Vacondio ([email protected]).
*
* This file is part of the Sejda source code
*
* 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.sejda.core.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Ignore;
import org.junit.Test;
import org.sejda.model.input.PdfSource;
import org.sejda.model.output.ExistingOutputPolicy;
import org.sejda.model.parameter.ViewerPreferencesParameters;
import org.sejda.model.pdf.PdfVersion;
import org.sejda.model.pdf.viewerpreference.PdfBooleanPreference;
import org.sejda.model.pdf.viewerpreference.PdfDirection;
import org.sejda.model.pdf.viewerpreference.PdfDuplex;
import org.sejda.model.pdf.viewerpreference.PdfNonFullScreenPageMode;
import org.sejda.model.pdf.viewerpreference.PdfPageLayout;
import org.sejda.model.pdf.viewerpreference.PdfPageMode;
import org.sejda.model.pdf.viewerpreference.PdfPrintScaling;
import org.sejda.sambox.pdmodel.PDDocumentCatalog;
import org.sejda.sambox.pdmodel.PageLayout;
import org.sejda.sambox.pdmodel.PageMode;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.DUPLEX;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.NON_FULL_SCREEN_PAGE_MODE;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.PRINT_SCALING;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.READING_DIRECTION;
/**
* test unit for the viewer preferences task
*
* @author Andrea Vacondio
*
*/
@Ignore
public abstract class ViewerPreferencesTaskTest extends BaseTaskTest<ViewerPreferencesParameters> {
private ViewerPreferencesParameters parameters = new ViewerPreferencesParameters();
private void setUpParams(PdfSource<?> source) throws IOException {
parameters.setCompress(true);
parameters.setVersion(PdfVersion.VERSION_1_7);
parameters.setDirection(PdfDirection.LEFT_TO_RIGHT);
parameters.setDuplex(PdfDuplex.SIMPLEX);
parameters.setNfsMode(PdfNonFullScreenPageMode.USE_THUMNS);
parameters.setPageLayout(PdfPageLayout.ONE_COLUMN);
parameters.setPageMode(PdfPageMode.USE_THUMBS);
parameters.setPrintScaling(PdfPrintScaling.APP_DEFAULT);
parameters.addEnabledPreference(PdfBooleanPreference.CENTER_WINDOW);
parameters.addEnabledPreference(PdfBooleanPreference.HIDE_MENUBAR);
parameters.addSource(source);
parameters.setExistingOutputPolicy(ExistingOutputPolicy.OVERWRITE);
testContext.directoryOutputTo(parameters);
}
@Test
public void testExecute() throws IOException {
setUpParams(shortInput());
doExecute();
}
@Test
public void testExecuteEncrypted() throws IOException {
setUpParams(stronglyEncryptedInput());
doExecute();
}
@Test
public void specificResultFilenames() throws IOException {
setUpParams(shortInput());
parameters.addSource(regularInput());
parameters.addSource(mediumInput());
parameters.addSource(mediumInput());
parameters.addSpecificResultFilename("one");
parameters.addSpecificResultFilename("two");
execute(parameters);
testContext.assertTaskCompleted();
testContext.assertOutputSize(4).assertOutputContainsFilenames("one.pdf", "two.pdf", "medium-test-file.pdf",
"medium-test-file(1).pdf");
}
private void doExecute() throws IOException {
execute(parameters);
testContext.assertTaskCompleted();
testContext.assertCreator().assertVersion(PdfVersion.VERSION_1_7).forEachPdfOutput(d -> {
PDDocumentCatalog catalog = d.getDocumentCatalog();
PDViewerPreferences prefs = catalog.getViewerPreferences();
assertTrue(prefs.hideMenubar());
assertTrue(prefs.centerWindow());
assertFalse(prefs.hideToolbar());
assertEquals(DUPLEX.Simplex.toString(), prefs.getDuplex());
assertEquals(NON_FULL_SCREEN_PAGE_MODE.UseThumbs.toString(), prefs.getNonFullScreenPageMode());
assertEquals(PRINT_SCALING.AppDefault.toString(), prefs.getPrintScaling());
assertEquals(READING_DIRECTION.L2R.toString(), prefs.getReadingDirection());
assertEquals(PageLayout.ONE_COLUMN, catalog.getPageLayout());
assertEquals(PageMode.USE_THUMBS, catalog.getPageMode());
});
}
}
| sejda-core/src/test/java/org/sejda/core/service/ViewerPreferencesTaskTest.java | /*
* Created on 21/set/2010
*
* Copyright 2010 by Andrea Vacondio ([email protected]).
*
* This file is part of the Sejda source code
*
* 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.sejda.core.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Ignore;
import org.junit.Test;
import org.sejda.model.input.PdfSource;
import org.sejda.model.output.ExistingOutputPolicy;
import org.sejda.model.parameter.ViewerPreferencesParameters;
import org.sejda.model.pdf.PdfVersion;
import org.sejda.model.pdf.viewerpreference.PdfBooleanPreference;
import org.sejda.model.pdf.viewerpreference.PdfDirection;
import org.sejda.model.pdf.viewerpreference.PdfDuplex;
import org.sejda.model.pdf.viewerpreference.PdfNonFullScreenPageMode;
import org.sejda.model.pdf.viewerpreference.PdfPageLayout;
import org.sejda.model.pdf.viewerpreference.PdfPageMode;
import org.sejda.model.pdf.viewerpreference.PdfPrintScaling;
import org.sejda.sambox.pdmodel.PDDocumentCatalog;
import org.sejda.sambox.pdmodel.PageLayout;
import org.sejda.sambox.pdmodel.PageMode;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.DUPLEX;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.NON_FULL_SCREEN_PAGE_MODE;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.PRINT_SCALING;
import org.sejda.sambox.pdmodel.interactive.viewerpreferences.PDViewerPreferences.READING_DIRECTION;
/**
* test unit for the viewer preferences task
*
* @author Andrea Vacondio
*
*/
@Ignore
public abstract class ViewerPreferencesTaskTest extends BaseTaskTest<ViewerPreferencesParameters> {
private ViewerPreferencesParameters parameters = new ViewerPreferencesParameters();
private void setUpParams(PdfSource<?> source) throws IOException {
parameters.setCompress(true);
parameters.setVersion(PdfVersion.VERSION_1_7);
parameters.setDirection(PdfDirection.LEFT_TO_RIGHT);
parameters.setDuplex(PdfDuplex.SIMPLEX);
parameters.setNfsMode(PdfNonFullScreenPageMode.USE_THUMNS);
parameters.setPageLayout(PdfPageLayout.ONE_COLUMN);
parameters.setPageMode(PdfPageMode.USE_THUMBS);
parameters.setPrintScaling(PdfPrintScaling.APP_DEFAULT);
parameters.addEnabledPreference(PdfBooleanPreference.CENTER_WINDOW);
parameters.addEnabledPreference(PdfBooleanPreference.HIDE_MENUBAR);
parameters.addSource(source);
parameters.setExistingOutputPolicy(ExistingOutputPolicy.OVERWRITE);
testContext.directoryOutputTo(parameters);
}
@Test
public void testExecute() throws IOException {
setUpParams(shortInput());
doExecute();
}
@Test
public void testExecuteEncrypted() throws IOException {
setUpParams(stronglyEncryptedInput());
doExecute();
}
@Test
public void specificResultFilenames() throws IOException {
setUpParams(shortInput());
parameters.addSource(regularInput());
parameters.addSource(mediumInput());
parameters.addSource(mediumInput());
testContext.directoryOutputTo(parameters);
parameters.addSpecificResultFilename("one");
parameters.addSpecificResultFilename("two");
execute(parameters);
testContext.assertTaskCompleted();
testContext.assertOutputSize(4).assertOutputContainsFilenames("one.pdf", "two.pdf", "medium-test-file.pdf",
"medium-test-file(1).pdf");
}
private void doExecute() throws IOException {
execute(parameters);
testContext.assertTaskCompleted();
testContext.assertCreator().assertVersion(PdfVersion.VERSION_1_7).forEachPdfOutput(d -> {
PDDocumentCatalog catalog = d.getDocumentCatalog();
PDViewerPreferences prefs = catalog.getViewerPreferences();
assertTrue(prefs.hideMenubar());
assertTrue(prefs.centerWindow());
assertFalse(prefs.hideToolbar());
assertEquals(DUPLEX.Simplex.toString(), prefs.getDuplex());
assertEquals(NON_FULL_SCREEN_PAGE_MODE.UseThumbs.toString(), prefs.getNonFullScreenPageMode());
assertEquals(PRINT_SCALING.AppDefault.toString(), prefs.getPrintScaling());
assertEquals(READING_DIRECTION.L2R.toString(), prefs.getReadingDirection());
assertEquals(PageLayout.ONE_COLUMN, catalog.getPageLayout());
assertEquals(PageMode.USE_THUMBS, catalog.getPageMode());
});
}
}
| removed duplicated line
| sejda-core/src/test/java/org/sejda/core/service/ViewerPreferencesTaskTest.java | removed duplicated line |
|
Java | agpl-3.0 | 2ddc7a502ac2ab80467c9793d93ece8eb8492331 | 0 | tvesalainen/hoski-admin | /*
* Copyright (C) 2012 Helsingfors Segelklubb ry
*
* 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 fi.hoski.remote.ui;
import fi.hoski.util.Utils;
import fi.hoski.sailwave.Fleet;
import fi.hoski.sailwave.Competitor;
import fi.hoski.sailwave.Race;
import fi.hoski.sailwave.SailWaveFile;
import com.google.appengine.api.datastore.Blob;
import fi.hoski.remote.DataStoreService;
import fi.hoski.remote.DataStoreProxy;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.datastore.Text;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import fi.hoski.datastore.*;
import fi.hoski.datastore.repository.*;
import fi.hoski.datastore.repository.Attachment.Type;
import fi.hoski.datastore.repository.Event.EventType;
import fi.hoski.remote.DataStore;
import fi.hoski.datastore.repository.Event;
import fi.hoski.remote.*;
import fi.hoski.remote.sync.InspectionHandler;
import fi.hoski.remote.sync.IsNotInspectedFilter;
import fi.hoski.remote.sync.SqlConnection;
import fi.hoski.remote.ui.sms.SMSPlugin;
import fi.hoski.sms.SMSException;
import fi.hoski.util.BoatInfo;
import fi.hoski.util.CreditorReference;
import fi.hoski.util.Day;
import fi.hoski.util.Time;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.internet.AddressException;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.vesalainen.parsers.sql.dsql.ui.WorkBench;
/**
* @author Timo Vesalainen
*/
public class Admin extends WindowAdapter
{
public static final int MAXMEMBER = 90000;
public static URL SPREADSHEET_FEED_URL;
private static final String SAILWAVEDIR = "SailWaveDir";
private static final String BACKUPDIR = "BackupDir";
private static final String ATTACHDIR = "AttachDir";
private static final String RACEATTACHDIR = "RaceAttachDir";
public final static Cursor busyCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
public final static Cursor defaultCursor = Cursor.getDefaultCursor();
private JFrame frame;
private JPanel panel;
private JMenuBar menuBar;
private JScrollPane leftPane;
private JScrollPane rightPane;
private EventEditor[] creators;
private DataStoreService dss = DataStore.getDss();
private Messages messages;
private ServerProperties serverProperties;
private String server;
private String creator;
private JMenu menuReservation;
private Container safeContainer;
private JSplitPane splitPane;
private List<Reservation> reservationList;
private List<Reservation> selectedReservations;
private List<Reservation> unSelectedReservations;
private boolean privileged;
private boolean accessUser;
private String safeTitle;
static
{
try
{
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
}
catch (MalformedURLException ex)
{
throw new IllegalArgumentException(ex);
}
}
private WorkBench workBench;
public Admin(ServerProperties serverProperties) throws EntityNotFoundException, IOException, SMSException
{
this.serverProperties = serverProperties;
server = serverProperties.getServer();
creator = serverProperties.getUsername();
UIManager.getDefaults().addResourceBundle("fi.hoski.remote.ui.ui");
creators = new EventEditor[EventType.values().length];
int index = 0;
for (EventType eventType : EventType.values())
{
creators[index++] = new EventEditor(eventType, this.getFrame());
}
if (serverProperties.isZonerSMSSupported())
{
int credits = dss.messagesLeft();
if (credits < 100)
{
String smsLeftString = TextUtil.getString("SMS LEFT");
JOptionPane.showMessageDialog(frame, smsLeftString + " " + credits);
}
}
privileged = serverProperties.isSuperUser();
try
{
new SqlConnection(serverProperties.getProperties());
accessUser = true;
}
catch (ClassNotFoundException | SQLException ex)
{
}
initFrame();
}
/**
* Initializes frame
*/
private void initFrame() throws EntityNotFoundException, MalformedURLException
{
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new ExceptionHandler());
frame = new JFrame(TextUtil.getString("ADMIN") + " " + creator + " / " + server + " Version: " + Version.version());
frame.addWindowListener(this);
panel = new JPanel(new BorderLayout());
frame.add(panel);
menuBar = new JMenuBar();
menuFile();
menuRace();
if (serverProperties.isSuperUser())
{
menuEvent();
menuReservation();
menuSwapPatrolShift();
}
menuQuery();
frame.setJMenuBar(menuBar);
URL clubUrl = new URL("http", server, "club.ico");
ImageIcon clubIcon = new ImageIcon(clubUrl);
frame.setIconImage(clubIcon.getImage());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setSize(800, 580);
}
private void menuFile()
{
JMenu fileMenu = new JMenu(TextUtil.getString("FILE"));
menuBar.add(fileMenu);
if (accessUser)
{
fileMenu.add(menuItemSync());
}
fileMenu.add(menuItemTextMaintenence());
if (privileged)
{
fileMenu.add(menuItemTextUpload());
fileMenu.add(menuItemTextDownload());
fileMenu.add(menuItemAttach());
fileMenu.add(menuItemRemoveAttachment());
}
if (serverProperties.isZonerSMSSupported())
{
fileMenu.add(menuItemSMSCredits());
}
fileMenu.addSeparator();
if (privileged)
{
fileMenu.add(menuItemRemoveEntity());
fileMenu.add(menuItemRemoveYear());
fileMenu.addSeparator();
fileMenu.add(menuItemBackupEntity());
fileMenu.add(menuItemBackupYear());
fileMenu.addSeparator();
fileMenu.add(menuItemRestoreEntity());
fileMenu.add(menuItemRestore());
fileMenu.add(menuItemAddYear());
}
fileMenu.addSeparator();
if (accessUser)
{
fileMenu.add(menuItemInspectAllLightBoats());
fileMenu.add(menuItemInspectionFix1());
fileMenu.add(menuItemSql());
fileMenu.add(menuItemUninspectedBoats());
}
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem(TextUtil.getString("EXIT"));
ActionListener exitAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
confirmSaveReservations();
System.exit(0);
}
};
exitAction = createActionListener(frame, exitAction);
exitItem.addActionListener(exitAction);
fileMenu.add(exitItem);
}
private void menuRace()
{
JMenu raceMenu = new JMenu(TextUtil.getString("RACES"));
menuBar.add(raceMenu);
raceMenu.add(menuItemUploadRaceSeries());
raceMenu.add(menuItemEditRaceSeries());
raceMenu.add(menuItemRemoveRaceSeries());
raceMenu.add(menuItemDownloadCompetitorsForSailwave());
raceMenu.add(menuItemInsertCompetitorsToSailwave());
raceMenu.add(menuItemDownloadCompetitorsAsCVS());
raceMenu.add(menuItemCreatePLSGoogleDocs());
raceMenu.add(menuItemCreateToTGoogleDocs());
raceMenu.addSeparator();
raceMenu.add(menuItemUploadRanking());
raceMenu.addSeparator();
raceMenu.add(menuItemRaceEmail());
if (serverProperties.isZonerSMSSupported())
{
raceMenu.add(menuItemRaceSMS());
}
raceMenu.addSeparator();
raceMenu.add(menuItemAttachRaceSeries());
raceMenu.add(menuItemRemoveRaceSeriesAttachment());
raceMenu.addSeparator();
raceMenu.add(menuItemAddReferencePayments());
raceMenu.add(menuItemAddOtherPayments());
}
private void menuEvent()
{
JMenu eventMenu = new JMenu(TextUtil.getString("EVENTS"));
menuBar.add(eventMenu);
JMenu addEventMenu = new JMenu(TextUtil.getString("ADD EVENTS"));
eventMenu.add(addEventMenu);
JMenu editEventMenu = new JMenu(TextUtil.getString("EDIT EVENTS"));
eventMenu.add(editEventMenu);
JMenu deleteEventMenu = new JMenu(TextUtil.getString("DELETE EVENTS"));
eventMenu.add(deleteEventMenu);
int index = 0;
for (final EventType eventType : EventType.values())
{
// add
JMenuItem addItem = new JMenuItem(TextUtil.getString(eventType.name()));
addItem.addActionListener(creators[index++]);
addEventMenu.add(addItem);
// edit
ActionListener editAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Event selected = chooseEvent(eventType, "EDIT SELECTED");
if (selected != null)
{
EventEditor editor = new EventEditor(null);
editor.edit(selected);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
editAction = createActionListener(frame, editAction);
JMenuItem editItem = new JMenuItem(TextUtil.getString(eventType.name()));
editItem.addActionListener(editAction);
editEventMenu.add(editItem);
// delete
ActionListener deleteAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "DELETE SELECTED");
if (selected != null && selected.size() >= 1)
{
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM DELETE")) == JOptionPane.YES_OPTION)
{
dss.deleteEvents(selected);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
deleteAction = createActionListener(frame, deleteAction);
JMenuItem deleteItem = new JMenuItem(TextUtil.getString(eventType.name()));
deleteItem.addActionListener(deleteAction);
deleteEventMenu.add(deleteItem);
}
}
private void menuReservation()
{
menuReservation = new JMenu(TextUtil.getString("RESERVATIONS"));
menuBar.add(menuReservation);
JMenu menuMakeReservation = new JMenu(TextUtil.getString("MAKE RESERVATION"));
menuReservation.add(menuMakeReservation);
JMenu editReservation = new JMenu(TextUtil.getString("EDIT RESERVATION"));
menuReservation.add(editReservation);
JMenu mailMenu = new JMenu(TextUtil.getString("SEND EMAIL"));
menuReservation.add(mailMenu);
JMenu smsMenu = new JMenu(TextUtil.getString("SEND SMS"));
smsMenu.setEnabled(serverProperties.isZonerSMSSupported());
menuReservation.add(smsMenu);
for (final EventType eventType : EventType.values())
{
ActionListener action = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
reservate(eventType, null);
}
};
action = createActionListener(frame, action);
JMenuItem menuItem = new JMenuItem(TextUtil.getString(eventType.name()));
menuItem.addActionListener(action);
menuMakeReservation.add(menuItem);
JMenuItem editItem = new JMenuItem(TextUtil.getString(eventType.name()));
ActionListener editAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
editReservations(eventType);
}
};
editAction = createActionListener(frame, editAction);
editItem.addActionListener(editAction);
if (Event.isInspection(eventType))
{
editItem.setEnabled(accessUser);
}
editReservation.add(editItem);
JMenuItem mailItem = new JMenuItem(TextUtil.getString(eventType.name()));
ActionListener mailAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "CHOOSE", true);
if (selected != null && selected.size() == 1)
{
try
{
Event event = selected.get(0);
List<Reservation> reservationList = dss.getReservations(event);
Day date = (Day) event.get(Event.EventDate);
String subject = TextUtil.getString(eventType.name()) + " " + date;
String body = getMessage(eventType.name());
MailDialog md = new MailDialog(frame, subject, body, reservationList);
if (md.edit())
{
}
}
catch (AddressException ex)
{
throw new IllegalArgumentException(ex);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
mailAction = createActionListener(frame, mailAction);
mailItem.addActionListener(mailAction);
mailMenu.add(mailItem);
final String title = TextUtil.getString(eventType.name());
JMenuItem smsItem = new JMenuItem(title);
ActionListener smsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "CHOOSE", true);
if (selected != null && selected.size() == 1)
{
try
{
Event event = selected.get(0);
List<Reservation> reservationList = dss.getReservations(event);
List<String> phoneList = new ArrayList<String>();
for (Reservation r : reservationList)
{
String number = (String) r.get(Repository.JASENET_MOBILE);
if (number != null)
{
phoneList.add(number);
}
}
SMSDialog sd = new SMSDialog(
frame,
title,
"",
phoneList);
if (sd.edit())
{
}
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
catch (SMSException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
smsAction = createActionListener(frame, smsAction);
smsItem.addActionListener(smsAction);
smsMenu.add(smsItem);
}
}
private JMenuItem menuItemRemoveEntity()
{
final String title = TextUtil.getString("REMOVE ENTITY");
JMenuItem removeEntityItem = new JMenuItem(title);
ActionListener removeEntityAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
String confirm = TextUtil.getString("CONFIRM REMOVE") + " " + kind;
if (JOptionPane.showConfirmDialog(frame, confirm, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
List<String> kindList = new ArrayList<String>();
kindList.add(kind.toString());
int count = dss.remove(kindList);
JOptionPane.showMessageDialog(frame, TextUtil.getString("REMOVED") + " " + count);
}
}
}
};
removeEntityAction = createActionListener(frame, removeEntityAction);
removeEntityItem.addActionListener(removeEntityAction);
return removeEntityItem;
}
private JMenuItem menuItemRemoveYear()
{
final String title = TextUtil.getString("REMOVE YEAR");
JMenuItem removeEntityItem = new JMenuItem(title);
ActionListener removeEntityAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object yearString = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION);
if (yearString != null)
{
String confirm = TextUtil.getString("CONFIRM REMOVE") + " " + yearString;
if (JOptionPane.showConfirmDialog(frame, confirm, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
long year = Long.parseLong(yearString.toString());
Day now = new Day();
if (year < now.getYear())
{
int count = dss.remove(year);
JOptionPane.showMessageDialog(frame, TextUtil.getString("REMOVED") + " " + count);
}
else
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("CANNOT REMOVE") + " " + year);
}
}
}
}
};
removeEntityAction = createActionListener(frame, removeEntityAction);
removeEntityItem.addActionListener(removeEntityAction);
return removeEntityItem;
}
private static final String TSFORMAT = "yyyyMMddHHmmss";
private JMenuItem menuItemBackupEntity()
{
final String title = TextUtil.getString("BACKUP ENTITY");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
SimpleDateFormat format = new SimpleDateFormat(TSFORMAT);
String ts = format.format(new Date());
File file = saveFile(BACKUPDIR, kind + ts + ".ser", ".ser", "Backup");
if (file != null)
{
int count;
try (FileOutputStream fos = new FileOutputStream(file))
{
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
List<String> list = new ArrayList<String>();
list.add(kind.toString());
count = dss.backup(list, oos);
JOptionPane.showMessageDialog(frame, TextUtil.getString("STORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemBackupYear()
{
final String title = TextUtil.getString("BACKUP YEAR");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object yearString = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION);
if (yearString != null)
{
long year = Long.parseLong(yearString.toString());
File file = saveFile(BACKUPDIR, year + ".ser", ".ser", "Backup");
if (file != null)
{
int count;
try (FileOutputStream fos = new FileOutputStream(file))
{
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
count = dss.backup(year, oos);
JOptionPane.showMessageDialog(frame, TextUtil.getString("STORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemRestore()
{
final String title = TextUtil.getString("RESTORE");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(BACKUPDIR, ".ser", "Backup");
if (file != null)
{
int count;
try (FileInputStream fos = new FileInputStream(file))
{
BufferedInputStream bis = new BufferedInputStream(fos);
ObjectInputStream ois = new ObjectInputStream(bis);
count = dss.restore(ois);
JOptionPane.showMessageDialog(frame, TextUtil.getString("RESTORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemInspectionFix1()
{
final String title = "Inspection fix1";
JMenuItem insFix1Item = new JMenuItem(title);
ActionListener insFix1Action = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
dss.inspectionFix1();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
insFix1Action = createActionListener(frame, insFix1Action);
insFix1Item.addActionListener(insFix1Action);
return insFix1Item;
}
private JMenuItem menuItemSql()
{
final String title = TextUtil.getString("JDBC SQL");
JMenuItem sqlItem = new JMenuItem(title);
ActionListener sqlAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
SqlDialog dia = new SqlDialog(frame, "select ", serverProperties.getProperties());
dia.edit();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
sqlAction = createActionListener(frame, sqlAction);
sqlItem.addActionListener(sqlAction);
return sqlItem;
}
private JMenuItem menuItemUninspectedBoats()
{
final String title = TextUtil.getString("UNINSPECTED BOATS");
JMenuItem sqlItem = new JMenuItem(title);
ActionListener sqlAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
InspectionHandler ih = new InspectionHandler(serverProperties.getProperties());
String selectSql = "select Veneet.VeneID, Jasenet.Etunimi, Jasenet.Sukunimi, Veneet.Nimi, Veneet.Tyyppi from Veneet, Jasenet where Veneet.Omistaja = Jasenet.JasenNo and Veneet.Omistaja < "+MAXMEMBER;
SqlConnection connection = new SqlConnection(serverProperties.getProperties());
ResultSet rs = connection.query(selectSql);
ResultSetModel model = new ResultSetModel(rs);
List<DataObject> list = DataObject.convert(model, rs, new IsNotInspectedFilter(ih));
DataObjectListDialog<DataObject> dia = new DataObjectListDialog<>(frame, "", "OK", model, list);
dia.setAutoCreateRowSorter(true);
dia.select();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
sqlAction = createActionListener(frame, sqlAction);
sqlItem.addActionListener(sqlAction);
return sqlItem;
}
private JMenuItem menuItemAddYear()
{
final String title = TextUtil.getString("ADD YEAR");
JMenuItem addYearItem = new JMenuItem(title);
ActionListener addYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String year = JOptionPane.showInputDialog(frame, TextUtil.getString("ADD YEAR"));
int y = Integer.parseInt(year);
if (y >= 1800 && y <= 2100)
{
dss.addYear(y);
}
}
};
addYearAction = createActionListener(frame, addYearAction);
addYearItem.addActionListener(addYearAction);
return addYearItem;
}
private JMenuItem menuItemInspectAllLightBoats()
{
final String title = TextUtil.getString("INSPECT ALL LIGHT BOATS");
JMenuItem inspectAllLightBoatsItem = new JMenuItem(title);
ActionListener inspectAllLightBoatsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
dss.inspectAllLightBoats(MAXMEMBER);
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
inspectAllLightBoatsAction = createActionListener(frame, inspectAllLightBoatsAction);
inspectAllLightBoatsItem.addActionListener(inspectAllLightBoatsAction);
return inspectAllLightBoatsItem;
}
private JMenuItem menuItemRestoreEntity()
{
final String title = TextUtil.getString("RESTORE ENTITY");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
File file = openFile(BACKUPDIR, ".ser", "Backup");
if (file != null)
{
int count;
try (FileInputStream fos = new FileInputStream(file))
{
BufferedInputStream bis = new BufferedInputStream(fos);
ObjectInputStream ois = new ObjectInputStream(bis);
List<String> list = new ArrayList<String>();
list.add(kind.toString());
count = dss.restore(list, ois);
JOptionPane.showMessageDialog(frame, TextUtil.getString("RESTORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemSMSCredits()
{
JMenuItem creditItem = new JMenuItem(TextUtil.getString("CHECK CREDITS"));
ActionListener creditAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
int credits = dss.messagesLeft();
String smsLeftString = TextUtil.getString("SMS LEFT");
JOptionPane.showMessageDialog(frame, smsLeftString + " " + credits);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
catch (SMSException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
creditAction = createActionListener(frame, creditAction);
creditItem.addActionListener(creditAction);
return creditItem;
}
private JMenuItem menuItemDownloadCompetitorsForSailwave()
{
// download series
JMenuItem downloadRaceCompetitorsForSailwave = new JMenuItem(TextUtil.getString("DOWNLOAD COMPETITORS FOR SAILWAVE"));
ActionListener downloadCompetitorsForSailwaveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
downloadCompetitorsForSailwave();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
downloadCompetitorsForSailwaveAction = createActionListener(frame, downloadCompetitorsForSailwaveAction);
downloadRaceCompetitorsForSailwave.addActionListener(downloadCompetitorsForSailwaveAction);
return downloadRaceCompetitorsForSailwave;
}
private JMenuItem menuItemInsertCompetitorsToSailwave()
{
// download series
JMenuItem insertRaceCompetitorsToSailwave = new JMenuItem(TextUtil.getString("INSERT COMPETITORS TO SAILWAVE"));
ActionListener insertCompetitorsToSailwaveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
insertCompetitorsToSailwave();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
insertCompetitorsToSailwaveAction = createActionListener(frame, insertCompetitorsToSailwaveAction);
insertRaceCompetitorsToSailwave.addActionListener(insertCompetitorsToSailwaveAction);
return insertRaceCompetitorsToSailwave;
}
private JMenuItem menuItemDownloadCompetitorsAsCVS()
{
// download series
JMenuItem downloadRaceCompetitorsAsCVS = new JMenuItem(TextUtil.getString("DOWNLOAD COMPETITORS AS CVS"));
ActionListener downloadCompetitorsAsCVSAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
downloadCompetitorsAsCVS();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
downloadCompetitorsAsCVSAction = createActionListener(frame, downloadCompetitorsAsCVSAction);
downloadRaceCompetitorsAsCVS.addActionListener(downloadCompetitorsAsCVSAction);
return downloadRaceCompetitorsAsCVS;
}
private JMenuItem menuItemCreatePLSGoogleDocs()
{
// download series
JMenuItem createPLSGoogleDocs = new JMenuItem(TextUtil.getString("CREATE PLS GOOGLE DOCS"));
ActionListener createPLSGoogleDocsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
createPLSSpreadsheet();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
createPLSGoogleDocsAction = createActionListener(frame, createPLSGoogleDocsAction);
createPLSGoogleDocs.addActionListener(createPLSGoogleDocsAction);
return createPLSGoogleDocs;
}
private JMenuItem menuItemCreateToTGoogleDocs()
{
// download series
JMenuItem createToTGoogleDocs = new JMenuItem(TextUtil.getString("CREATE TOT GOOGLE DOCS"));
ActionListener createToTGoogleDocsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
createToTSpreadsheet();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
createToTGoogleDocsAction = createActionListener(frame, createToTGoogleDocsAction);
createToTGoogleDocs.addActionListener(createToTGoogleDocsAction);
return createToTGoogleDocs;
}
private JMenuItem menuItemRaceEmail()
{
// download series
JMenuItem raceEmail = new JMenuItem(TextUtil.getString("SEND EMAIL"));
ActionListener raceEmailAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
List<RaceEntry> competitors = chooseCompetitors();
MailDialog md = new MailDialog(frame, "", "", competitors);
md.edit();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
raceEmailAction = createActionListener(frame, raceEmailAction);
raceEmail.addActionListener(raceEmailAction);
return raceEmail;
}
private JMenuItem menuItemRaceSMS()
{
// download series
final String title = TextUtil.getString("SEND SMS");
JMenuItem raceSMS = new JMenuItem(title);
ActionListener raceSMSAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
List<RaceEntry> competitors = chooseCompetitors();
List<String> phoneList = new ArrayList<String>();
for (RaceEntry r : competitors)
{
String number = (String) r.get(RaceEntry.HELMPHONE);
if (number != null && !number.isEmpty())
{
phoneList.add(number);
}
}
SMSDialog sd = new SMSDialog(
frame,
title,
"",
phoneList);
if (sd.edit())
{
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
raceSMSAction = createActionListener(frame, raceSMSAction);
raceSMS.addActionListener(raceSMSAction);
return raceSMS;
}
private JMenu menuItemAttachRaceSeries()
{
// download series
JMenu attachRaceSeriesMenu = new JMenu(TextUtil.getString("ATTACH RACE"));
for (final Attachment.Type type : Attachment.Type.values())
{
JMenu attachmentType = new JMenu(TextUtil.getString(type.name()));
attachRaceSeriesMenu.add(attachmentType);
JMenuItem fileItem = new JMenuItem(TextUtil.getString("FILE"));
ActionListener fileAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachRaceSeriesFile(type);
}
catch (EntityNotFoundException | IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
fileAction = createActionListener(frame, fileAction);
fileItem.addActionListener(fileAction);
attachmentType.add(fileItem);
JMenuItem linkItem = new JMenuItem(TextUtil.getString("LINK"));
ActionListener linkAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachRaceSeriesLink(type);
}
catch (EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
linkAction = createActionListener(frame, linkAction);
linkItem.addActionListener(linkAction);
attachmentType.add(linkItem);
}
return attachRaceSeriesMenu;
}
private void attachRaceSeriesLink(Type type) throws EntityNotFoundException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
Attachment attachment = new Attachment(raceSeriesOrFleet);
attachment.set(Attachment.TYPE, type.ordinal());
DataObjectDialog<Attachment> dod = new DataObjectDialog<Attachment>(frame, attachment.getModel().hide(Attachment.TYPE), attachment);
if (dod.edit())
{
Link link = (Link) attachment.get(Attachment.URL);
try
{
URL url = new URL(link.getValue());
dss.put(attachment);
}
catch (MalformedURLException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
private void attachRaceSeriesFile(Type type) throws IOException, EntityNotFoundException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
File file = openFile(RACEATTACHDIR, null, null);
if (file != null)
{
String title = JOptionPane.showInputDialog(frame, TextUtil.getString("TITLE"), TextUtil.getString(type.name()));
if (title != null)
{
dss.upload(raceSeriesOrFleet, type, title, file);
}
}
}
}
private void removeRaceSeriesAttachment() throws EntityNotFoundException, IOException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
List<Attachment> attachments = chooseAttachments(raceSeriesOrFleet);
if (attachments != null)
{
dss.removeAttachments(attachments);
}
}
}
private JMenuItem menuItemRemoveRaceSeriesAttachment()
{
// download series
JMenuItem removeAttachmentItem = new JMenuItem(TextUtil.getString("REMOVE ATTACHMENT"));
ActionListener removeAttachmentAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeRaceSeriesAttachment();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeAttachmentAction = createActionListener(frame, removeAttachmentAction);
removeAttachmentItem.addActionListener(removeAttachmentAction);
return removeAttachmentItem;
}
private JMenuItem menuItemUploadRanking()
{
// upload ranking
JMenuItem uploadRankingItem = new JMenuItem(TextUtil.getString("UPLOAD RANKING"));
ActionListener uploadRankingAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (file != null)
{
try
{
uploadRanking(file);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
};
uploadRankingAction = createActionListener(frame, uploadRankingAction);
uploadRankingItem.addActionListener(uploadRankingAction);
return uploadRankingItem;
}
private JMenuItem menuItemAddReferencePayments()
{
JMenuItem addPaymentsItem = new JMenuItem(TextUtil.getString("ADD REFERENCE PAYMENTS"));
ActionListener addPaymentsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
addReferencePayments();
}
catch (EntityNotFoundException ex)
{
throw new IllegalArgumentException(ex);
}
}
};
addPaymentsAction = createActionListener(frame, addPaymentsAction);
addPaymentsItem.addActionListener(addPaymentsAction);
return addPaymentsItem;
}
private void addReferencePayments() throws EntityNotFoundException
{
while (true)
{
String reference = "";
CreditorReference cr = null;
while (true)
{
reference = JOptionPane.showInputDialog(frame, TextUtil.getString("REFERENCE"), reference);
if (reference == null)
{
return;
}
try
{
cr = new CreditorReference(reference, true);
break;
}
catch (IllegalArgumentException ex)
{
JOptionPane.showMessageDialog(frame, ex);
}
}
int rn = Integer.parseInt(reference.substring(0, reference.length() - 1));
RaceEntry raceEntry = dss.raceEntryForReference(rn);
Double fee = (Double) raceEntry.get(RaceEntry.FEE);
String paidStr = JOptionPane.showInputDialog(frame, "<html>" + raceEntry.getFieldsAsHtmlTable() + "</html>", fee);
if (paidStr != null)
{
try
{
fee = Double.parseDouble(paidStr);
}
catch (NumberFormatException ex)
{
continue;
}
raceEntry.set(RaceEntry.PAID, fee);
dss.put(raceEntry);
}
}
}
private JMenuItem menuItemAddOtherPayments()
{
JMenuItem addPaymentsItem = new JMenuItem(TextUtil.getString("ADD OTHER PAYMENTS"));
ActionListener addPaymentsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
addOtherPayments();
}
catch (EntityNotFoundException ex)
{
throw new IllegalArgumentException(ex);
}
}
};
addPaymentsAction = createActionListener(frame, addPaymentsAction);
addPaymentsItem.addActionListener(addPaymentsAction);
return addPaymentsItem;
}
private void addOtherPayments() throws EntityNotFoundException
{
DataObjectModel model = RaceEntry.MODEL.view(
RaceEntry.NAT,
RaceEntry.SAILNO,
RaceEntry.HELMNAME,
RaceEntry.CLUB,
RaceEntry.FLEET,
RaceEntry.FEE);
List<RaceEntry> unpaidRaceEntries = dss.getUnpaidRaceEntries();
while (true)
{
String totalStr = JOptionPane.showInputDialog(frame, TextUtil.getString("TOTAL"));
if (totalStr == null)
{
return;
}
double total = Double.parseDouble(totalStr);
Collections.sort(unpaidRaceEntries, new FeeComparator(total));
DataObjectChooser<RaceEntry> ec = new DataObjectChooser<RaceEntry>(
model,
unpaidRaceEntries,
"",
"CHOOSE");
ec.setSelectAlways(true);
List<RaceEntry> entries = ec.choose();
if (entries == null)
{
return;
}
for (RaceEntry re : entries)
{
re.set(RaceEntry.PAID, total);
dss.put(re);
unpaidRaceEntries.remove(re);
}
}
}
private class FeeComparator implements Comparator<RaceEntry>
{
private double target;
public FeeComparator(double target)
{
this.target = target;
}
@Override
public int compare(RaceEntry o1, RaceEntry o2)
{
Double fee1 = (Double) o1.get(RaceEntry.FEE);
if (fee1 == null)
{
return -1;
}
Double fee2 = (Double) o2.get(RaceEntry.FEE);
if (fee2 == null)
{
return 1;
}
Double d1 = new Double(Math.abs(target - fee1));
Double d2 = new Double(Math.abs(target - fee2));
return d1.compareTo(d2);
}
}
private File openFile(String lastDir, String suffix, String description)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
if (suffix != null && description != null)
{
FileFilter ff = new SuffixFileFilter(suffix, description);
fc.setFileFilter(ff);
}
File currentDirectory = LastInput.getDirectory(lastDir);
if (currentDirectory != null)
{
fc.setCurrentDirectory(currentDirectory);
}
if (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
LastInput.set(lastDir, file);
return file;
}
return null;
}
private File saveFile(String lastDir, String nameCandidate, String suffix, String description)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
FileFilter ff = new SuffixFileFilter(suffix, description);
fc.setFileFilter(ff);
fc.setSelectedFile(new File(nameCandidate));
File currentDirectory = LastInput.getDirectory(lastDir);
if (currentDirectory != null)
{
fc.setCurrentDirectory(currentDirectory);
}
if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if (file != null)
{
if (!file.getName().endsWith(suffix))
{
file = new File(file.getPath() + suffix);
}
LastInput.set(lastDir, file);
}
return file;
}
return null;
}
private JMenuItem menuItemUploadRaceSeries()
{
// upload series
JMenuItem uploadRaceSeriesItem = new JMenuItem(TextUtil.getString("UPLOAD RACE"));
ActionListener uploadRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (file != null)
{
try
{
uploadSeries(file);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
};
uploadRaceSeriesAction = createActionListener(frame, uploadRaceSeriesAction);
uploadRaceSeriesItem.addActionListener(uploadRaceSeriesAction);
return uploadRaceSeriesItem;
}
private JMenuItem menuItemEditRaceSeries()
{
// upload series
JMenuItem editRaceSeriesItem = new JMenuItem(TextUtil.getString("EDIT RACE"));
ActionListener editRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
editSeries();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
editRaceSeriesAction = createActionListener(frame, editRaceSeriesAction);
editRaceSeriesItem.addActionListener(editRaceSeriesAction);
return editRaceSeriesItem;
}
private JMenuItem menuItemRemoveRaceSeries()
{
// upload series
JMenuItem removeRaceSeriesItem = new JMenuItem(TextUtil.getString("REMOVE RACE"));
ActionListener removeRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeSeries();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeRaceSeriesAction = createActionListener(frame, removeRaceSeriesAction);
removeRaceSeriesItem.addActionListener(removeRaceSeriesAction);
return removeRaceSeriesItem;
}
private JMenuItem menuItemSync()
{
JMenuItem syncItem = new JMenuItem(TextUtil.getString("SYNCHRONIZE"));
ActionListener syncAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
SwingWorker task = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
Progress progress = new UIProgress(frame, TextUtil.getString("SYNCHRONIZE"));
progress.setNote("");
try
{
dss.synchronize(progress);
}
catch (Throwable ex)
{
progress.close();
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
return null;
}
};
task.execute();
}
};
syncAction = createActionListener(frame, syncAction);
syncItem.addActionListener(syncAction);
return syncItem;
}
private JMenuItem menuItemTextMaintenence()
{
JMenuItem textMaintenenceItem = new JMenuItem(TextUtil.getString("TEXT MAINTENANCE"));
ActionListener maintenanceAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Messages messages = dss.getMessages();
DataObjectDialog<Messages> dod = new DataObjectDialog<Messages>(frame, Messages.MODEL, messages);
dod.setPreferredSize(new Dimension(800, 600));
if (dod.edit())
{
dss.put(messages);
}
}
};
maintenanceAction = createActionListener(frame, maintenanceAction);
textMaintenenceItem.addActionListener(maintenanceAction);
return textMaintenenceItem;
}
private JMenuItem menuItemTextUpload()
{
JMenuItem textUploadItem = new JMenuItem(TextUtil.getString("TEXT UPLOAD"));
ActionListener textUploadAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
MessagesBackup mb = new MessagesBackup(frame);
mb.load();
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
textUploadAction = createActionListener(frame, textUploadAction);
textUploadItem.addActionListener(textUploadAction);
return textUploadItem;
}
private JMenuItem menuItemTextDownload()
{
JMenuItem textDownloadItem = new JMenuItem(TextUtil.getString("TEXT DOWNLOAD"));
ActionListener textDownloadAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
MessagesBackup mb = new MessagesBackup(frame);
mb.store();
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
textDownloadAction = createActionListener(frame, textDownloadAction);
textDownloadItem.addActionListener(textDownloadAction);
return textDownloadItem;
}
private JMenu menuItemAttach()
{
JMenu attachMenu = new JMenu(TextUtil.getString("ADD ATTACHMENT"));
JMenuItem fileItem = new JMenuItem(TextUtil.getString("FILE"));
ActionListener fileAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachFile();
}
catch (EntityNotFoundException | IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
fileAction = createActionListener(frame, fileAction);
fileItem.addActionListener(fileAction);
attachMenu.add(fileItem);
JMenuItem linkItem = new JMenuItem(TextUtil.getString("LINK"));
ActionListener linkAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachLink();
}
catch (EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
linkAction = createActionListener(frame, linkAction);
linkItem.addActionListener(linkAction);
attachMenu.add(linkItem);
return attachMenu;
}
private void attachLink() throws EntityNotFoundException
{
Title root = chooseTitle();
Attachment attachment = new Attachment(root);
attachment.set(Attachment.TYPE, Attachment.Type.OTHER);
DataObjectDialog<Attachment> dod = new DataObjectDialog<Attachment>(frame, attachment.getModel().hide(Attachment.TYPE), attachment);
if (dod.edit())
{
Link link = (Link) attachment.get(Attachment.URL);
try
{
URL url = new URL(link.getValue());
dss.put(attachment);
}
catch (MalformedURLException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
private void attachFile() throws IOException, EntityNotFoundException
{
Title root = chooseTitle();
File file = openFile(ATTACHDIR, null, null);
String title = JOptionPane.showInputDialog(frame, TextUtil.getString("TITLE"));
if (title != null)
{
dss.upload(root, Attachment.Type.OTHER, title, file);
}
}
private void removeAttachment() throws IOException, EntityNotFoundException
{
Title root = chooseTitle();
List<Attachment> attachments = chooseAttachments(root);
if (attachments != null)
{
dss.removeAttachments(attachments);
}
}
private JMenuItem menuItemRemoveAttachment()
{
// download series
JMenuItem removeAttachmentItem = new JMenuItem(TextUtil.getString("REMOVE ATTACHMENT"));
ActionListener removeAttachmentAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeAttachment();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeAttachmentAction = createActionListener(frame, removeAttachmentAction);
removeAttachmentItem.addActionListener(removeAttachmentAction);
return removeAttachmentItem;
}
private Title chooseTitle() throws EntityNotFoundException
{
List<Title> titles = null;
titles = dss.getTitles();
// choose one of the shifts
DataObjectChooser<Title> ec = new DataObjectChooser<Title>(
Title.MODEL,
titles,
TextUtil.getString("TITLE"),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<Title> selectedTitle = ec.choose();
if (selectedTitle != null && selectedTitle.size() == 1)
{
return selectedTitle.get(0);
}
else
{
return null;
}
}
/**
* Return a text from Messages kind
*
* @param name
* @return
*/
private String getMessage(String name)
{
if (messages == null)
{
messages = dss.getMessages();
}
Object obj = messages.get(name);
if (obj != null)
{
if (obj instanceof Text)
{
Text text = (Text) obj;
return text.getValue();
}
else
{
return obj.toString();
}
}
return null;
}
@Override
public void windowClosing(WindowEvent e)
{
confirmSaveReservations();
if (workBench != null)
{
workBench.close();
}
System.exit(0);
}
private void confirmSaveReservations()
{
if (reservationList != null)
{
String msg = TextUtil.getString("CONFIRM MODIFICATIONS");
if (JOptionPane.showConfirmDialog(frame, msg, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
saveReservations();
}
}
}
private void saveReservations()
{
long order = 1;
for (Reservation selectedReservation : selectedReservations)
{
selectedReservation.set(Reservation.ORDER, order++);
}
for (Reservation unSelectedReservation : unSelectedReservations)
{
unSelectedReservation.set(Reservation.ORDER, 0);
}
List<Reservation> updateList = new ArrayList<>();
updateList.addAll(unSelectedReservations);
reservationList.removeAll(unSelectedReservations);
updateList.addAll(selectedReservations);
dss.put(updateList);
reservationList.removeAll(selectedReservations);
dss.delete(reservationList);
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setTitle(safeTitle);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
private void setAsInspected() throws SQLException, ClassNotFoundException
{
for (Reservation selectedReservation : selectedReservations)
{
selectedReservation.set(Reservation.INSPECTED, true);
}
for (Reservation unSelectedReservation : unSelectedReservations)
{
unSelectedReservation.set(Reservation.INSPECTED, false);
}
InspectionHandler ih = new InspectionHandler(serverProperties.getProperties());
if (!unSelectedReservations.isEmpty())
{
ih.updateInspection(unSelectedReservations);
dss.put(unSelectedReservations);
}
reservationList.removeAll(unSelectedReservations);
if (!selectedReservations.isEmpty())
{
ih.updateInspection(selectedReservations);
dss.put(selectedReservations);
}
reservationList.removeAll(selectedReservations);
dss.delete(reservationList);
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
private void cancel()
{
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setTitle(safeTitle);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
public static ActionListener createActionListener(final Component component, final ActionListener actionListener)
{
ActionListener al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
component.setCursor(busyCursor);
component.repaint();
actionListener.actionPerformed(e);
}
finally
{
component.setCursor(defaultCursor);
}
}
};
return al;
}
public JFrame getFrame()
{
return frame;
}
public JMenuBar getMenuBar()
{
return menuBar;
}
public JPanel getPanel()
{
return panel;
}
private void editReservations(final EventType eventType)
{
final Event event = chooseEvent(eventType, "CHOOSE");
if (event != null)
{
final String eventTitle = TextUtil.getString(event.getEventType().name()) + " " + event.get(Event.EventDate);
safeTitle = frame.getTitle();
frame.setTitle(eventTitle);
reservationList = dss.getReservations(event);
selectedReservations = new ArrayList<Reservation>();
unSelectedReservations = new ArrayList<Reservation>();
if (Event.isInspection(eventType))
{
for (Reservation reservation : reservationList)
{
Boolean inspected = (Boolean) reservation.get(Reservation.INSPECTED);
if (inspected != null && inspected)
{
selectedReservations.add(reservation);
}
else
{
unSelectedReservations.add(reservation);
}
}
}
else
{
for (Reservation reservation : reservationList)
{
Long order = (Long) reservation.get(Reservation.ORDER);
if (order != null && order != 0)
{
selectedReservations.add(reservation);
}
else
{
unSelectedReservations.add(reservation);
}
}
}
DataObjectModel baseModel = Reservation.getModel(eventType);
DataObjectModel unorderedModel = null;
DataObjectModel orderedModel = null;
switch (eventType)
{
case LAUNCH:
case LIFT:
case HULL_INSPECTION:
unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
break;
case INSPECTION:
unorderedModel = baseModel.hide(
Reservation.BOAT,
Reservation.INSPECTED,
Reservation.CREATOR,
Reservation.EMAIL,
Reservation.MOBILEPHONE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.INSPECTION_GASS,
Reservation.INSPECTOR);
orderedModel = baseModel.hide(
Reservation.BOAT,
Reservation.INSPECTED,
Reservation.CREATOR,
Reservation.EMAIL,
Reservation.MOBILEPHONE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.NOTES);
break;
}
final DataObjectListTableModel<Reservation> unorderedTableModel =
new DataObjectListTableModel<Reservation>(unorderedModel, unSelectedReservations);
final JTable unorderedtable = new FitTable(unorderedTableModel);
TableSelectionHandler tsh1 = new TableSelectionHandler(unorderedtable);
unorderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
unorderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());
unorderedtable.addKeyListener(unorderedTableModel.getRemover(dss));
unorderedtable.setDragEnabled(true);
unorderedtable.setDropMode(DropMode.INSERT_ROWS);
TransferHandler unorderedTransferHandler = new DataObjectTransferHandler<Reservation>(unorderedTableModel);
unorderedtable.setTransferHandler(unorderedTransferHandler);
final DataObjectListTableModel<Reservation> orderedTableModel =
new DataObjectListTableModel<Reservation>(orderedModel, selectedReservations);
orderedTableModel.setEditable(Reservation.INSPECTION_CLASS, Reservation.INSPECTION_GASS, Reservation.BASICINSPECTION, Reservation.INSPECTOR);
final JTable orderedtable = new FitTable(orderedTableModel);
TableSelectionHandler tsh2 = new TableSelectionHandler(orderedtable);
orderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
orderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());
orderedtable.addKeyListener(orderedTableModel.getRemover(dss));
orderedtable.setDragEnabled(true);
orderedtable.setDropMode(DropMode.INSERT_ROWS);
TransferHandler orderedTransferHandler = new DataObjectTransferHandler<Reservation>(orderedTableModel);
orderedtable.setTransferHandler(orderedTransferHandler);
if (Event.isInspection(eventType))
{
unorderedtable.setAutoCreateRowSorter(true);
orderedtable.setAutoCreateRowSorter(true);
}
leftPane = new JScrollPane();
leftPane.setViewport(new InfoViewport(TextUtil.getString(eventType.name() + "-leftPane")));
leftPane.setViewportView(unorderedtable);
leftPane.setTransferHandler(unorderedTransferHandler);
rightPane = new JScrollPane();
rightPane.setViewport(new InfoViewport(TextUtil.getString(eventType.name() + "-rightPane")));
rightPane.setViewportView(orderedtable);
rightPane.setTransferHandler(orderedTransferHandler);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
splitPane.setDividerLocation(0.5);
menuReservation.setEnabled(false);
safeContainer = frame.getContentPane();
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(splitPane, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
contentPane.add(buttonPanel, BorderLayout.SOUTH);
JButton saveButton = new JButton(TextUtil.getString("SAVE"));
saveButton.setEnabled(!Event.isInspection(eventType));
ActionListener saveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
saveReservations();
}
};
saveButton.addActionListener(saveAction);
buttonPanel.add(saveButton);
switch (eventType)
{
case INSPECTION:
{
if (privileged)
{
JButton inspectButton = new JButton(TextUtil.getString("SET INSPECTED"));
inspectButton.setToolTipText(TextUtil.getString("SET INSPECTED TT"));
ActionListener inspectAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
TableCellEditor cellEditor = orderedtable.getCellEditor();
if (cellEditor != null)
{
cellEditor.stopCellEditing();
}
try
{
setAsInspected();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
inspectButton.addActionListener(inspectAction);
buttonPanel.add(inspectButton);
}
JButton addBoat = new JButton(TextUtil.getString("ADD BOAT"));
ActionListener addBoatAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Reservation reservation = reservate(eventType, event);
if (reservation != null)
{
reservationList.add(reservation);
unSelectedReservations.add(reservation);
unorderedTableModel.fireTableDataChanged();
}
}
};
addBoat.addActionListener(addBoatAction);
buttonPanel.add(addBoat);
JButton printTypeButton = new JButton(TextUtil.getString("PRINT"));
ActionListener printTypeAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printNameBoatTypeOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printTypeButton.addActionListener(printTypeAction);
buttonPanel.add(printTypeButton);
JButton printDockButton = new JButton(TextUtil.getString("PRINT DOCK ORDER"));
ActionListener printDockAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printDockOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printDockButton.addActionListener(printDockAction);
buttonPanel.add(printDockButton);
}
break;
case HULL_INSPECTION:
{
JButton print = new JButton(TextUtil.getString("PRINT"));
ActionListener printAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printAlphaOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
print.addActionListener(printAction);
buttonPanel.add(print);
}
break;
case LAUNCH:
case LIFT:
{
JButton addBoat = new JButton(TextUtil.getString("ADD BOAT"));
ActionListener addBoatAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Reservation reservation = reservate(eventType, event);
if (reservation != null)
{
reservationList.add(reservation);
unSelectedReservations.add(reservation);
unorderedTableModel.fireTableDataChanged();
}
}
};
addBoat.addActionListener(addBoatAction);
buttonPanel.add(addBoat);
JButton printBrief = new JButton(TextUtil.getString("BRIEF PRINT"));
ActionListener printBriefAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printOrderBrief(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printBrief.addActionListener(printBriefAction);
buttonPanel.add(printBrief);
JButton print = new JButton(TextUtil.getString("PRINT"));
ActionListener printAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (eventType == EventType.LAUNCH)
{
printLaunchOrder(eventTitle);
}
else
{
printLiftOrder(eventTitle);
}
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
print.addActionListener(printAction);
buttonPanel.add(print);
}
break;
}
JButton cancelButton = new JButton(TextUtil.getString("CANCEL"));
ActionListener cancelAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
cancel();
}
};
cancelButton.addActionListener(cancelAction);
buttonPanel.add(cancelButton);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
KeyListener keyListener = new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == 10)
{
int selectedRow = unorderedtable.getSelectedRow();
if (selectedRow != -1)
{
RowSorter<? extends TableModel> rowSorter = unorderedtable.getRowSorter();
if (rowSorter != null)
{
selectedRow = rowSorter.convertRowIndexToModel(selectedRow);
}
Reservation reservation = unorderedTableModel.getObject(selectedRow);
orderedTableModel.add(reservation);
unorderedTableModel.remove(reservation);
e.consume();
unorderedtable.changeSelection(selectedRow, 0, false, false);
}
}
}
};
unorderedtable.addKeyListener(keyListener);
unorderedtable.requestFocusInWindow();
}
}
private void printNameBoatTypeOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.BOATTYPE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.BASICINSPECTION);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.LASTNAME, Reservation.FIRSTNAME, Reservation.BOATNAME));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printDockOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.BASICINSPECTION);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.DOCK, Reservation.DOCKNUMBER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printAlphaOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.HULL_INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATTYPE,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.LASTNAME));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printOrderBrief(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LAUNCH);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printLaunchOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LAUNCH);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE,
Reservation.MOBILEPHONE,
Reservation.WEIGHT);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printLiftOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LIFT);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE,
Reservation.MOBILEPHONE,
Reservation.WEIGHT,
Reservation.LENGTH);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private Event chooseEvent(EventType eventType, String action)
{
List<Event> eventList = chooseEvents(eventType, action, true);
if (eventList != null)
{
return eventList.get(0);
}
else
{
return null;
}
}
private List<Event> chooseEvents(EventType eventType, String action)
{
return chooseEvents(eventType, action, false);
}
private List<Event> chooseEvents(EventType eventType, String action, boolean singleSelection)
{
List<Event> eventList = dss.getEvents(eventType);
DataObjectChooser<Event> ec = new DataObjectChooser<Event>(
Event.MODEL,
eventList,
TextUtil.getString(eventType.name()),
action);
ec.setSelectAlways(true);
if (singleSelection)
{
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
return ec.choose();
}
private Reservation reservate(EventType eventType, Event event)
{
// search a member
String[] columns = Member.MODEL.getProperties();
String lastName = JOptionPane.showInputDialog(panel, TextUtil.getString(Member.SUKUNIMI) + "?");
if (lastName == null)
{
return null;
}
lastName = Utils.convertName(lastName);
List<AnyDataObject> memberList = null;
memberList = dss.retrieve(Member.KIND, Member.SUKUNIMI, lastName, columns);
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Member.MODEL,
memberList,
TextUtil.getString(eventType.name()),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selected = ec.choose();
if (selected != null && selected.size() >= 1)
{
try
{
return reservate(eventType, selected.get(0), event);
}
catch (ParseException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
return null;
}
private Reservation reservate(EventType eventType, AnyDataObject user, Event event) throws ParseException
{
// search boats for member
String[] columns = Boat.MODEL.getProperties();
List<AnyDataObject> boatList = null;
boatList = dss.retrieve(Boat.KIND, Boat.OMISTAJA, user.createKey(), columns);
// choose one of the boats
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Boat.MODEL,
boatList,
TextUtil.getString(eventType.name()),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selectedBoats = ec.choose();
if (selectedBoats.size() == 1)
{
DataObject selectedBoat = selectedBoats.get(0);
// get available member data
Map<String, Object> userData = null;
userData = dss.getUserData(user.getEntity()); //, selectedBoat.createKeyString(), null);
if (event == null)
{
event = chooseEvent(eventType, "CHOOSE");
if (event == null)
{
return null;
}
}
Reservation reservation = new Reservation(event);
DataObjectModel model = reservation.getModel();
model = model.hide(Reservation.ORDER, Reservation.INSPECTED, Reservation.BOAT);
@SuppressWarnings("unchecked")
List<Map<String, Object>> boatLst = (List<Map<String, Object>>) userData.get(Repository.BOATS);
for (Map<String, Object> m : boatLst)
{
if (selectedBoat.createKeyString().equals(m.get(Repository.VENEET_KEY)))
{
reservation.setAll(m);
reservation.set(Reservation.BOAT, m.get(Repository.VENEET_KEY));
}
}
reservation.setAll(userData);
reservation.set(Reservation.CREATOR, creator);
String title = TextUtil.getString(eventType.name());
DataObjectDialog<Reservation> et = new DataObjectDialog<Reservation>(frame, title, model, reservation);
if (et.edit())
{
try
{
dss.createReservation(event, reservation, true);
return reservation;
}
catch (EntityNotFoundException | EventFullException | DoubleBookingException | BoatNotFoundException | MandatoryPropertyMissingException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage(), ex.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
return null;
}
private void menuSwapPatrolShift()
{
if (privileged)
{
JMenu patrolMenu = new JMenu(TextUtil.getString("PATROL SHIFT"));
menuBar.add(patrolMenu);
patrolMenu.add(menuItemSwapPatrolShift());
patrolMenu.add(menuItemChangePatrolShift());
patrolMenu.add(menuItemSwapLog());
}
}
private void menuQuery()
{
JMenu queryMenu = new JMenu(TextUtil.getString("QUERIES"));
menuBar.add(queryMenu);
queryMenu.add(menuItemQuery());
queryMenu.add(menuItemEditQuery());
}
private JMenuItem menuItemQuery()
{
ActionListener queryAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
startQuery(true, false);
}
};
queryAction = createActionListener(frame, queryAction);
JMenuItem queryItem = new JMenuItem(TextUtil.getString("START QUERY"));
queryItem.addActionListener(queryAction);
return queryItem;
}
private JMenuItem menuItemEditQuery()
{
ActionListener queryAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
startQuery(true, true);
}
};
queryAction = createActionListener(frame, queryAction);
JMenuItem queryItem = new JMenuItem(TextUtil.getString("EDIT QUERY"));
queryItem.addActionListener(queryAction);
return queryItem;
}
private void startQuery(boolean readonly, boolean edit)
{
try
{
if (workBench == null)
{
workBench = new WorkBench(serverProperties.getProperties(), true, readonly);
Messages texts = dss.getMessages();
workBench.addFetchResultPlugin(
new SMSPlugin(
texts.getString(Messages.SMSUSERNAME),
texts.getString(Messages.SMSPASSWORD)
));
}
if (edit)
{
workBench.setVisible(true);
}
else
{
workBench.open();
}
}
catch (IOException | InterruptedException ex)
{
throw new IllegalArgumentException(ex);
}
}
private AnyDataObject chooseMember(String title)
{
// search a member
String[] columns = Member.MODEL.getProperties();
String lastName = JOptionPane.showInputDialog(panel, TextUtil.getString(Member.SUKUNIMI) + "?", title, JOptionPane.QUESTION_MESSAGE);
if (lastName == null)
{
return null;
}
lastName = Utils.convertName(lastName);
List<AnyDataObject> memberList = dss.retrieve(Member.KIND, Member.SUKUNIMI, lastName, columns);
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Member.MODEL,
memberList,
title,
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selected = ec.choose();
if (selected != null && selected.size() == 1)
{
return selected.get(0);
}
else
{
return null;
}
}
private JMenuItem menuItemSwapPatrolShift()
{
ActionListener swapAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
AnyDataObject member = chooseMember(TextUtil.getString("CHOOSE MEMBER"));
if (member != null)
{
swapPatrolShift(member);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
swapAction = createActionListener(frame, swapAction);
JMenuItem swapItem = new JMenuItem(TextUtil.getString("SWAP PATROL SHIFT"));
swapItem.addActionListener(swapAction);
return swapItem;
}
private JMenuItem menuItemChangePatrolShift()
{
ActionListener swapAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
AnyDataObject member = chooseMember(TextUtil.getString("CHOOSE PATROL SHIFT LOOSER"));
if (member != null)
{
changePatrolShift(member);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
swapAction = createActionListener(frame, swapAction);
JMenuItem swapItem = new JMenuItem(TextUtil.getString("CHANGE PATROL SHIFT"));
swapItem.addActionListener(swapAction);
return swapItem;
}
private JMenuItem menuItemSwapLog()
{
ActionListener swapLogAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
TextDialog dia = new TextDialog(frame);
dss.swapLog(dia);
dia.edit();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
swapLogAction = createActionListener(frame, swapLogAction);
JMenuItem swapLogItem = new JMenuItem(TextUtil.getString("SWAP PATROL LOG"));
swapLogItem.addActionListener(swapLogAction);
return swapLogItem;
}
private PatrolShift choosePatrolShift(AnyDataObject user)
{
List<PatrolShift> shiftList = null;
shiftList = dss.getShifts(user.createKey());
// choose one of the shifts
DataObjectChooser<PatrolShift> ec = new DataObjectChooser<PatrolShift>(
PatrolShift.MODEL.view(Repository.PAIVA),
shiftList,
TextUtil.getString("PATROL SHIFT"),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<PatrolShift> selectedShifts = ec.choose();
if (selectedShifts != null && selectedShifts.size() == 1)
{
return selectedShifts.get(0);
}
else
{
return null;
}
}
private void swapPatrolShift(AnyDataObject user)
{
Long memberNumber = (Long) user.get(Member.JASENNO);
PatrolShift selectedShift = choosePatrolShift(user);
if (selectedShift != null)
{
SwapRequest req = new SwapRequest();
req.set(Repository.JASENNO, user.createKey());
req.set(Repository.VUOROID, selectedShift.createKey());
req.set(Repository.PAIVA, selectedShift.get(Repository.PAIVA));
List<Long> excluded = new ArrayList<Long>();
Day day = (Day) selectedShift.get(Repository.PAIVA);
excluded.add(day.getValue());
req.set(SwapRequest.EXCLUDE, excluded);
req.set(Repository.CREATOR, creator);
Object[] options =
{
TextUtil.getString("SWAP SHIFT"),
TextUtil.getString("EXCLUDE DATE"),
TextUtil.getString("DELETE PREVIOUS SWAP"),
TextUtil.getString("CANCEL")
};
String msg = TextUtil.getString("SWAP OPTIONS");
try
{
msg = dss.getShiftString(selectedShift.getEntity(), msg);
}
catch (EntityNotFoundException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
while (true)
{
int choise = JOptionPane.showOptionDialog(
frame,
msg + dateList(excluded),
"",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
switch (choise)
{
case 0:
try
{
msg = TextUtil.getString("SWAP CONFIRMATION");
msg = dss.getShiftString(selectedShift.getEntity(), msg) + dateList(excluded);
int confirm = JOptionPane.showConfirmDialog(frame, msg, TextUtil.getString("SWAP SHIFT"), JOptionPane.OK_CANCEL_OPTION);
if (JOptionPane.YES_OPTION == confirm)
{
boolean ok = dss.swapShift(req);
if (ok)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SwapOk"));
}
else
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SwapPending"));
}
}
}
catch (EntityNotFoundException | IOException | SMSException | AddressException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return;
case 1:
Day d = DateChooser.chooseDate(TextUtil.getString("EXCLUDE DATE"), new Day(excluded.get(excluded.size() - 1)));
excluded.add(d.getValue());
break;
case 2:
dss.deleteSwaps(memberNumber.intValue());
return;
case 3:
return;
}
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
private void changePatrolShift(AnyDataObject releasedUser)
{
Long releasedMemberNumber = (Long) releasedUser.get(Member.JASENNO);
PatrolShift selectedShift = choosePatrolShift(releasedUser);
if (selectedShift != null)
{
AnyDataObject executingUser = chooseMember(TextUtil.getString("CHOOSE PATROL SHIFT EXECUTER"));
if (executingUser != null)
{
dss.changeShiftExecutor(selectedShift, executingUser);
return;
}
}
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
private String dateList(List<Long> list)
{
StringBuilder sb = new StringBuilder();
Collections.sort(list);
for (Long l : list)
{
Day date = new Day(l);
sb.append('\n');
sb.append(date.toString());
}
return sb.toString();
}
private void uploadSeries(File file) throws IOException
{
SailWaveFile swf = new SailWaveFile(file);
Race firstRace = swf.getFirstRace();
RaceSeries rs = new RaceSeries();
rs.set(RaceSeries.ID, swf.getEventId());
rs.set(RaceSeries.EVENT, swf.getEvent());
rs.set(RaceSeries.RACE_AREA, swf.getVenue());
rs.set(RaceSeries.NOTES, swf.getNotes());
if (firstRace != null)
{
rs.set(RaceSeries.EventDate, firstRace.getDate());
rs.set(RaceSeries.STARTTIME, firstRace.getTime());
}
List<RaceFleet> fleetList = new ArrayList<>();
for (Fleet fleet : swf.getFleets())
{
RaceFleet rc = new RaceFleet(rs);
rc.set(RaceFleet.Fleet, fleet.getFleet());
rc.set(RaceFleet.Class, fleet.getClassname());
rc.set(RaceFleet.RatingSystem, fleet.getRatingSystem());
rc.set(RaceFleet.SailWaveId, fleet.getNumber());
if (firstRace != null)
{
rc.set(RaceFleet.EventDate, firstRace.getDate());
rc.set(RaceFleet.StartTime, firstRace.getTime());
}
fleetList.add(rc);
}
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.SAILWAVEFILE);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.RatingSystem, RaceFleet.ClosingDate, RaceFleet.ClosingDate2, RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rc = new RaceDialog(frame, swf.getEvent(), dss, model, rs, listModel, fleetList, swf);
rc.setEditable(listModel.getProperties());
if (rc.edit())
{
swf.setEvent((String) rs.get(RaceSeries.EVENT));
swf.setVenue((String) rs.get(RaceSeries.RACE_AREA));
Text notes = (Text) rs.get(RaceSeries.NOTES);
if (notes != null)
{
swf.setNotes(notes.getValue());
}
if (firstRace != null)
{
Day date = (Day) rs.get(RaceSeries.EventDate);
if (date != null)
{
firstRace.setDate(date.toString());
}
Time time = (Time) rs.get(RaceSeries.STARTTIME);
if (time != null)
{
firstRace.setTime(time.toString());
}
}
swf.updateFleets(fleetList);
swf.saveAs(file);
rs.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
while (true)
{
long id = 1;
RaceSeries existingRace = dss.getExistingRace(rs);
if (existingRace != null)
{
String eventName = (String) existingRace.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM REPLACE") + " " + eventName) == JOptionPane.YES_OPTION)
{
dss.putRace(rs, fleetList);
break;
}
else
{
swf.setId(id);
swf.saveAs(file);
rs.set(RaceSeries.ID, id);
}
}
else
{
dss.putRace(rs, fleetList);
break;
}
id++;
}
}
}
private void editSeries() throws IOException, EntityNotFoundException
{
RaceSeries raceSeries = chooseRace();
if (raceSeries != null)
{
Blob swb = (Blob) raceSeries.get(RaceSeries.SAILWAVEFILE);
SailWaveFile swf = new SailWaveFile(swb.getBytes());
List<RaceFleet> fleetList = dss.getFleets(raceSeries);
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.EventDate,
RaceSeries.SAILWAVEFILE);
String event = (String) raceSeries.get(RaceSeries.EVENT);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.RatingSystem, RaceFleet.ClosingDate, RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rd = new RaceDialog(frame, event, dss, model, raceSeries, listModel, fleetList, swf);
rd.setEditable(listModel.getProperties());
if (rd.edit())
{
swf.setEvent((String) raceSeries.get(RaceSeries.EVENT));
swf.setVenue((String) raceSeries.get(RaceSeries.RACE_AREA));
Text notes = (Text) raceSeries.get(RaceSeries.NOTES);
if (notes != null)
{
swf.setNotes(notes.getValue());
}
swf.updateFleets(fleetList);
raceSeries.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
dss.putRace(raceSeries, fleetList);
}
}
}
private void removeSeries() throws IOException, EntityNotFoundException
{
RaceSeries raceSeries = chooseRace();
if (raceSeries != null)
{
String event = (String) raceSeries.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM DELETE")) == JOptionPane.YES_OPTION)
{
int numberOfRaceEntriesFor = dss.getNumberOfRaceEntriesFor(raceSeries);
if (numberOfRaceEntriesFor > 0)
{
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM WHOLE RACE DELETE"),
TextUtil.getString("FLEET HAS ENTRIES"),
JOptionPane.WARNING_MESSAGE
) == JOptionPane.YES_OPTION)
{
dss.deleteWithChilds(raceSeries, "RaceFleet");
}
}
else
{
dss.deleteWithChilds(raceSeries, "RaceFleet");
}
}
}
}
private void uploadRanking(File file) throws IOException
{
SailWaveFile swf = new SailWaveFile(file);
RaceSeries rs = new RaceSeries();
rs.set(RaceSeries.ID, swf.getEventId());
rs.set(RaceSeries.EVENT, swf.getEvent());
rs.set(RaceSeries.RACE_AREA, swf.getVenue());
rs.set(RaceSeries.NOTES, swf.getNotes());
List<Fleet> fleets = swf.getFleets();
if (fleets.isEmpty())
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
if (fleets.size() > 1)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("FLEETS IN RANKING"));
return;
}
Fleet defFleet = swf.getDefaultFleet();
if (defFleet == null)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
String ratingSystem = fleets.get(0).getRatingSystem();
List<RaceFleet> startList = new ArrayList<>();
Map<RaceFleet, Race> startMap = new HashMap<>();
for (Race start : swf.getRaces())
{
RaceFleet st = new RaceFleet(rs);
st.set(RaceFleet.Ranking, true);
st.set(RaceFleet.Fleet, defFleet.getRatingSystem());
startMap.put(st, start);
String startDate = start.getDate();
String startTime = start.getTime();
if (startTime == null)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
if (startDate != null && !startDate.isEmpty())
{
Day sd = new Day(startDate);
st.set(RaceFleet.EventDate, sd);
st.set(RaceFleet.ClosingDate, sd);
}
if (startTime != null && !startTime.isEmpty())
{
st.set(RaceFleet.StartTime, new Time(startTime));
}
st.set(RaceFleet.RatingSystem, ratingSystem);
startList.add(st);
}
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.EventDate,
RaceSeries.TO,
RaceSeries.ClosingDate,
RaceSeries.STARTTIME,
RaceSeries.SAILWAVEFILE);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rc = new RaceDialog(frame, swf.getEvent(), dss, model, rs, listModel, startList, swf);
rc.setEditable(RaceFleet.EventDate, RaceFleet.StartTime, RaceFleet.ClosingDate);
if (rc.edit())
{
Day from = null;
Day to = null;
for (RaceFleet start : startList)
{
if (from == null)
{
from = (Day) start.get(RaceFleet.EventDate);
}
else
{
Day d = (Day) start.get(RaceFleet.EventDate);
if (from.after(d))
{
from = d;
}
}
if (to == null)
{
to = (Day) start.get(RaceFleet.EventDate);
}
else
{
Day d = (Day) start.get(RaceFleet.EventDate);
if (to.before(d))
{
to = d;
}
}
Race r = startMap.get(start);
r.setDate(start.get(RaceFleet.EventDate).toString());
r.setTime(start.get(RaceFleet.StartTime).toString());
}
rs.set(RaceSeries.EventDate, from);
rs.set(RaceSeries.TO, to);
swf.setEvent((String) rs.get(RaceSeries.EVENT));
swf.setVenue((String) rs.get(RaceSeries.RACE_AREA));
Text notes = (Text) rs.get(RaceSeries.NOTES);
swf.setNotes(notes.getValue());
swf.saveAs(file);
rs.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
while (true)
{
long id = 1;
RaceSeries existingRace = dss.getExistingRace(rs);
if (existingRace != null)
{
String eventName = (String) existingRace.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM REPLACE") + " " + eventName) == JOptionPane.YES_OPTION)
{
dss.putRace(rs, startList);
break;
}
else
{
swf.setId(id);
swf.saveAs(file);
rs.set(RaceSeries.ID, id);
}
}
else
{
dss.putRace(rs, startList);
break;
}
id++;
}
}
}
private RaceSeries chooseRace() throws EntityNotFoundException
{
List<RaceSeries> raceList = dss.getRaces();
DataObjectModel model = RaceSeries.MODEL.view(RaceSeries.EVENT);
// choose one of the shifts
DataObjectChooser<RaceSeries> ec = new DataObjectChooser<RaceSeries>(
model,
raceList,
TextUtil.getString("RACE SERIES"),
"CHOOSE");
ec.setSelectAlways(true);
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<RaceSeries> selectedRaceSeries = ec.choose();
if (selectedRaceSeries != null && selectedRaceSeries.size() == 1)
{
return selectedRaceSeries.get(0);
}
else
{
return null;
}
}
private List<RaceEntry> chooseCompetitors() throws EntityNotFoundException
{
KeyTreeChooser chooser = new KeyTreeChooser(frame, TextUtil.getString("CHOOSE COMPETITORS"), dss, dss.getYearKey(), "Year", "RaceSeries", "RaceFleet");
DataObject selected = chooser.select();
if (selected != null)
{
return dss.getRaceEntriesFor(selected);
}
return null;
}
private DataObject chooseRaceSeriesOrFleet() throws EntityNotFoundException
{
KeyTreeChooser chooser = new KeyTreeChooser(frame, TextUtil.getString("CHOOSE RACE"), dss, dss.getRootKey(), "Root", "Year", "RaceSeries", "RaceFleet");
return chooser.select();
}
private List<Attachment> chooseAttachments(DataObject parent)
{
List<Attachment> attachments = dss.getAttachmentsFor(parent);
// choose one of the shifts
DataObjectChooser<Attachment> ec = new DataObjectChooser<Attachment>(
Attachment.MODEL.view(Attachment.TITLE, Attachment.Filename),
attachments,
TextUtil.getString("ATTACHMENTS"),
"CHOOSE");
ec.setSelectAlways(true);
return ec.choose();
}
private void downloadCompetitorsForSailwave() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
RaceSeries raceSeries = (RaceSeries) entryList.get(0).getRaceSeries();
Blob swb = (Blob) raceSeries.get(RaceSeries.SAILWAVEFILE);
SailWaveFile swf = new SailWaveFile(swb.getBytes());
for (RaceEntry entry : entryList)
{
Competitor competitor = new Competitor();
competitor.setAll(entry.getAll());
swf.addCompetitor(competitor);
}
swf.deleteNotNeededFleets(entryList);
File selectedFile = saveFile(SAILWAVEDIR, swf.getEvent() + ".blw", ".blw", "SailWave");
if (selectedFile != null)
{
swf.saveAs(selectedFile);
}
}
private void insertCompetitorsToSailwave() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
File selectedFile = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (selectedFile == null)
{
return;
}
SailWaveFile swf = new SailWaveFile(selectedFile);
for (RaceEntry entry : entryList)
{
Competitor competitor = new Competitor();
competitor.setAll(checkRating(entry.getAll()));
swf.addCompetitor(competitor);
}
swf.saveAs(selectedFile);
}
private void downloadCompetitorsAsCVS() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
// TODO check ratings
RaceSeries raceSeries = (RaceSeries) entryList.get(0).getRaceSeries();
File selectedFile = saveFile(SAILWAVEDIR, raceSeries.getString(RaceSeries.EVENT) + ".cvs", ".cvs", "CVS");
if (selectedFile != null)
{
try (FileOutputStream fos = new FileOutputStream(selectedFile))
{
DataObjectModel model = RaceEntry.MODEL.view(entryList);
DataObject.writeCVS(model, entryList, fos);
}
}
}
private void createPLSSpreadsheet() throws IOException, EntityNotFoundException, JSONException, AuthenticationException, ServiceException
{
List<RaceEntry> competitors = chooseCompetitors();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setUserCredentials(serverProperties.getUsername(), serverProperties.getPassword());
SpreadsheetEntry spreadsheet = chooseSpreadsheet(service);
if (spreadsheet != null)
{
PLSSpreadsheet plsSheet = new PLSSpreadsheet(service, spreadsheet);
fillPLSRatings(competitors);
plsSheet.fill(competitors);
}
}
private void fillPLSRatings(List<RaceEntry> competitors) throws IOException, JSONException
{
for (RaceEntry entry : competitors)
{
JSONObject json = getRating("ORC", entry.getNationality(), entry.getNumber(), null);
if (json != null)
{
entry.set(RaceEntry.RATING, json.getString(BoatInfo.RATING));
entry.set(RaceEntry.PLDO, json.getString(RaceEntry.PLDO));
entry.set(RaceEntry.PLTO, json.getString(RaceEntry.PLTO));
}
}
}
private void updateRatings(List<RaceEntry> competitors) throws IOException, JSONException
{
for (RaceEntry entry : competitors)
{
String fleet = (String) entry.get(RaceEntry.FLEET);
String type = (String) entry.get(RaceEntry.CLASS);
JSONObject json = getRating(fleet, entry.getNationality(), entry.getNumber(), type);
if (json != null)
{
String rating = json.getString(BoatInfo.RATING);
if (rating != null && !rating.isEmpty())
{
entry.set(RaceEntry.RATING, rating);
}
}
}
}
private SpreadsheetEntry chooseSpreadsheet(SpreadsheetService service) throws IOException, ServiceException
{
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
String[] options = new String[spreadsheets.size()];
int index = 0;
for (SpreadsheetEntry spreadsheet : spreadsheets)
{
options[index++] = spreadsheet.getTitle().getPlainText();
}
SpreadsheetEntry spreadsheet = null;
String opt = (String) JOptionPane.showInputDialog(frame, TextUtil.getString("GOOGLE DOCS SPREADSHEET"), "", JOptionPane.OK_CANCEL_OPTION, null, options, null);
for (int ii = 0; ii < options.length; ii++)
{
if (options[ii].equals(opt))
{
spreadsheet = spreadsheets.get(ii);
break;
}
}
return spreadsheet;
}
private void createToTSpreadsheet() throws IOException, EntityNotFoundException, JSONException, AuthenticationException, ServiceException
{
List<RaceEntry> competitors = chooseCompetitors();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setUserCredentials(serverProperties.getUsername(), serverProperties.getPassword());
SpreadsheetEntry spreadsheet = chooseSpreadsheet(service);
if (spreadsheet != null)
{
ToTSpreadsheet totSheet = new ToTSpreadsheet(service, spreadsheet);
updateRatings(competitors);
totSheet.fill(competitors);
}
}
private Map<String, Object> checkRating(Map<String, Object> map) throws IOException, JSONException
{
String fleet = (String) map.get(RaceEntry.FLEET);
String nat = (String) map.get(RaceEntry.NAT);
nat = nat.toUpperCase();
Number sailNo = (Number) map.get(RaceEntry.SAILNO);
String clazz = (String) map.get(RaceEntry.CLASS);
String entryRatingStr = (String) map.get(RaceEntry.RATING);
if (entryRatingStr != null)
{
entryRatingStr = entryRatingStr.replace(',', '.');
}
else
{
entryRatingStr = "0.0";
}
int sn = 0;
if (sailNo != null)
{
sn = sailNo.intValue();
}
JSONObject json = getRating(fleet, nat, sn, clazz);
String ratingSystem = json.optString(BoatInfo.RATINGSYSTEM);
if ("UNKNOWN".equals(ratingSystem))
{
return map;
}
Map<String, Object> m2 = new HashMap<>();
m2.putAll(map);
String listedRatingStr = json.optString(RaceEntry.RATING);
if (listedRatingStr != null && !listedRatingStr.isEmpty())
{
try
{
BigDecimal listedRating = new BigDecimal(listedRatingStr.replace(',', '.'));
m2.put(RaceEntry.RATING, listedRating);
BigDecimal entryRating = new BigDecimal(entryRatingStr.replace(',', '.'));
if (!entryRating.equals(listedRating))
{
String privateNotes = TextUtil.getString("RATING DIFFERS");
privateNotes = String.format(privateNotes, entryRating, listedRating);
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
else
{
String privateNotes = TextUtil.getString("RATING OK");
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
}
catch (NumberFormatException ex)
{
String privateNotes = TextUtil.getString("RATING DIFFERS");
privateNotes = String.format(privateNotes, entryRatingStr, listedRatingStr);
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
}
else
{
String privateNotes = TextUtil.getString("NO RATING");
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
return m2;
}
private JSONObject getRating(String ratingSystem, String nat, int sailNo, String boatClass) throws IOException, JSONException
{
try
{
String path = "/race?RatingSystem=" + ratingSystem + "&Nat=" + nat + "&SailNo=" + sailNo + "&Class=" + boatClass;
URL url = new URL("http", server, path.replace(' ', '+'));
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "ASCII");
StringBuilder sb = new StringBuilder();
char[] cb = new char[256];
int rc = isr.read(cb);
while (rc != -1)
{
sb.append(cb, 0, rc);
rc = isr.read(cb);
}
return new JSONObject(sb.toString());
}
catch (MalformedURLException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
try
{
Properties properties = new Properties();
if (args.length == 0)
{
System.err.println("usage: ... <properties>");
System.exit(-1);
}
try (InputStream pFile = new FileInputStream(args[0]))
{
properties.load(pFile);
}
boolean savePassword = Boolean.valueOf(properties.getProperty(ServerProperties.SavePassword));
properties.remove(ServerProperties.SavePassword);
ServerProperties sp = new ServerProperties(properties);
sp.setSavePassword(savePassword);
DataObjectDialog<ServerProperties> dod = new DataObjectDialog<>(
null,
sp.getModel().hide(ServerProperties.Tables, ServerProperties.SupportsZonerSMS, ServerProperties.SuperUser),
sp);
if (dod.edit())
{
String[] server = sp.getServer().split(",");
RemoteAppEngine.init(server[0], sp.getUsername(), sp.getPassword());
DataStoreProxy dsp = new DataStoreProxy(properties);
dsp.start();
Admin r = new Admin(sp);
}
else
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
| src/fi/hoski/remote/ui/Admin.java | /*
* Copyright (C) 2012 Helsingfors Segelklubb ry
*
* 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 fi.hoski.remote.ui;
import fi.hoski.util.Utils;
import fi.hoski.sailwave.Fleet;
import fi.hoski.sailwave.Competitor;
import fi.hoski.sailwave.Race;
import fi.hoski.sailwave.SailWaveFile;
import com.google.appengine.api.datastore.Blob;
import fi.hoski.remote.DataStoreService;
import fi.hoski.remote.DataStoreProxy;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.datastore.Text;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import fi.hoski.datastore.*;
import fi.hoski.datastore.repository.*;
import fi.hoski.datastore.repository.Attachment.Type;
import fi.hoski.datastore.repository.Event.EventType;
import fi.hoski.remote.DataStore;
import fi.hoski.datastore.repository.Event;
import fi.hoski.remote.*;
import fi.hoski.remote.sync.InspectionHandler;
import fi.hoski.remote.sync.IsNotInspectedFilter;
import fi.hoski.remote.sync.SqlConnection;
import fi.hoski.remote.ui.sms.SMSPlugin;
import fi.hoski.sms.SMSException;
import fi.hoski.util.BoatInfo;
import fi.hoski.util.CreditorReference;
import fi.hoski.util.Day;
import fi.hoski.util.Time;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.internet.AddressException;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.vesalainen.parsers.sql.dsql.ui.WorkBench;
/**
* @author Timo Vesalainen
*/
public class Admin extends WindowAdapter
{
public static final int MAXMEMBER = 90000;
public static URL SPREADSHEET_FEED_URL;
private static final String SAILWAVEDIR = "SailWaveDir";
private static final String BACKUPDIR = "BackupDir";
private static final String ATTACHDIR = "AttachDir";
private static final String RACEATTACHDIR = "RaceAttachDir";
public final static Cursor busyCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
public final static Cursor defaultCursor = Cursor.getDefaultCursor();
private JFrame frame;
private JPanel panel;
private JMenuBar menuBar;
private JScrollPane leftPane;
private JScrollPane rightPane;
private EventEditor[] creators;
private DataStoreService dss = DataStore.getDss();
private Messages messages;
private ServerProperties serverProperties;
private String server;
private String creator;
private JMenu menuReservation;
private Container safeContainer;
private JSplitPane splitPane;
private List<Reservation> reservationList;
private List<Reservation> selectedReservations;
private List<Reservation> unSelectedReservations;
private boolean privileged;
private boolean accessUser;
private String safeTitle;
static
{
try
{
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
}
catch (MalformedURLException ex)
{
throw new IllegalArgumentException(ex);
}
}
private WorkBench workBench;
public Admin(ServerProperties serverProperties) throws EntityNotFoundException, IOException, SMSException
{
this.serverProperties = serverProperties;
server = serverProperties.getServer();
creator = serverProperties.getUsername();
UIManager.getDefaults().addResourceBundle("fi.hoski.remote.ui.ui");
creators = new EventEditor[EventType.values().length];
int index = 0;
for (EventType eventType : EventType.values())
{
creators[index++] = new EventEditor(eventType, this.getFrame());
}
if (serverProperties.isZonerSMSSupported())
{
int credits = dss.messagesLeft();
if (credits < 100)
{
String smsLeftString = TextUtil.getString("SMS LEFT");
JOptionPane.showMessageDialog(frame, smsLeftString + " " + credits);
}
}
privileged = serverProperties.isSuperUser();
try
{
new SqlConnection(serverProperties.getProperties());
accessUser = true;
}
catch (ClassNotFoundException | SQLException ex)
{
}
initFrame();
}
/**
* Initializes frame
*/
private void initFrame() throws EntityNotFoundException, MalformedURLException
{
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new ExceptionHandler());
frame = new JFrame(TextUtil.getString("ADMIN") + " " + creator + " / " + server + " Version: " + Version.version());
frame.addWindowListener(this);
panel = new JPanel(new BorderLayout());
frame.add(panel);
menuBar = new JMenuBar();
menuFile();
menuRace();
if (serverProperties.isSuperUser())
{
menuEvent();
menuReservation();
menuSwapPatrolShift();
}
menuQuery();
frame.setJMenuBar(menuBar);
URL clubUrl = new URL("http", server, "club.ico");
ImageIcon clubIcon = new ImageIcon(clubUrl);
frame.setIconImage(clubIcon.getImage());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setSize(800, 580);
}
private void menuFile()
{
JMenu fileMenu = new JMenu(TextUtil.getString("FILE"));
menuBar.add(fileMenu);
if (accessUser)
{
fileMenu.add(menuItemSync());
}
fileMenu.add(menuItemTextMaintenence());
if (privileged)
{
fileMenu.add(menuItemTextUpload());
fileMenu.add(menuItemTextDownload());
fileMenu.add(menuItemAttach());
fileMenu.add(menuItemRemoveAttachment());
}
if (serverProperties.isZonerSMSSupported())
{
fileMenu.add(menuItemSMSCredits());
}
fileMenu.addSeparator();
if (privileged)
{
fileMenu.add(menuItemRemoveEntity());
fileMenu.add(menuItemRemoveYear());
fileMenu.addSeparator();
fileMenu.add(menuItemBackupEntity());
fileMenu.add(menuItemBackupYear());
fileMenu.addSeparator();
fileMenu.add(menuItemRestoreEntity());
fileMenu.add(menuItemRestore());
fileMenu.add(menuItemAddYear());
}
fileMenu.addSeparator();
if (accessUser)
{
fileMenu.add(menuItemInspectAllLightBoats());
fileMenu.add(menuItemInspectionFix1());
fileMenu.add(menuItemSql());
fileMenu.add(menuItemUninspectedBoats());
}
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem(TextUtil.getString("EXIT"));
ActionListener exitAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
confirmSaveReservations();
System.exit(0);
}
};
exitAction = createActionListener(frame, exitAction);
exitItem.addActionListener(exitAction);
fileMenu.add(exitItem);
}
private void menuRace()
{
JMenu raceMenu = new JMenu(TextUtil.getString("RACES"));
menuBar.add(raceMenu);
raceMenu.add(menuItemUploadRaceSeries());
raceMenu.add(menuItemEditRaceSeries());
raceMenu.add(menuItemRemoveRaceSeries());
raceMenu.add(menuItemDownloadCompetitorsForSailwave());
raceMenu.add(menuItemInsertCompetitorsToSailwave());
raceMenu.add(menuItemDownloadCompetitorsAsCVS());
raceMenu.add(menuItemCreatePLSGoogleDocs());
raceMenu.add(menuItemCreateToTGoogleDocs());
raceMenu.addSeparator();
raceMenu.add(menuItemUploadRanking());
raceMenu.addSeparator();
raceMenu.add(menuItemRaceEmail());
if (serverProperties.isZonerSMSSupported())
{
raceMenu.add(menuItemRaceSMS());
}
raceMenu.addSeparator();
raceMenu.add(menuItemAttachRaceSeries());
raceMenu.add(menuItemRemoveRaceSeriesAttachment());
raceMenu.addSeparator();
raceMenu.add(menuItemAddReferencePayments());
raceMenu.add(menuItemAddOtherPayments());
}
private void menuEvent()
{
JMenu eventMenu = new JMenu(TextUtil.getString("EVENTS"));
menuBar.add(eventMenu);
JMenu addEventMenu = new JMenu(TextUtil.getString("ADD EVENTS"));
eventMenu.add(addEventMenu);
JMenu editEventMenu = new JMenu(TextUtil.getString("EDIT EVENTS"));
eventMenu.add(editEventMenu);
JMenu deleteEventMenu = new JMenu(TextUtil.getString("DELETE EVENTS"));
eventMenu.add(deleteEventMenu);
int index = 0;
for (final EventType eventType : EventType.values())
{
// add
JMenuItem addItem = new JMenuItem(TextUtil.getString(eventType.name()));
addItem.addActionListener(creators[index++]);
addEventMenu.add(addItem);
// edit
ActionListener editAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Event selected = chooseEvent(eventType, "EDIT SELECTED");
if (selected != null)
{
EventEditor editor = new EventEditor(null);
editor.edit(selected);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
editAction = createActionListener(frame, editAction);
JMenuItem editItem = new JMenuItem(TextUtil.getString(eventType.name()));
editItem.addActionListener(editAction);
editEventMenu.add(editItem);
// delete
ActionListener deleteAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "DELETE SELECTED");
if (selected != null && selected.size() >= 1)
{
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM DELETE")) == JOptionPane.YES_OPTION)
{
dss.deleteEvents(selected);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
deleteAction = createActionListener(frame, deleteAction);
JMenuItem deleteItem = new JMenuItem(TextUtil.getString(eventType.name()));
deleteItem.addActionListener(deleteAction);
deleteEventMenu.add(deleteItem);
}
}
private void menuReservation()
{
menuReservation = new JMenu(TextUtil.getString("RESERVATIONS"));
menuBar.add(menuReservation);
JMenu menuMakeReservation = new JMenu(TextUtil.getString("MAKE RESERVATION"));
menuReservation.add(menuMakeReservation);
JMenu editReservation = new JMenu(TextUtil.getString("EDIT RESERVATION"));
menuReservation.add(editReservation);
JMenu mailMenu = new JMenu(TextUtil.getString("SEND EMAIL"));
menuReservation.add(mailMenu);
JMenu smsMenu = new JMenu(TextUtil.getString("SEND SMS"));
smsMenu.setEnabled(serverProperties.isZonerSMSSupported());
menuReservation.add(smsMenu);
for (final EventType eventType : EventType.values())
{
ActionListener action = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
reservate(eventType, null);
}
};
action = createActionListener(frame, action);
JMenuItem menuItem = new JMenuItem(TextUtil.getString(eventType.name()));
menuItem.addActionListener(action);
menuMakeReservation.add(menuItem);
JMenuItem editItem = new JMenuItem(TextUtil.getString(eventType.name()));
ActionListener editAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
editReservations(eventType);
}
};
editAction = createActionListener(frame, editAction);
editItem.addActionListener(editAction);
if (Event.isInspection(eventType))
{
editItem.setEnabled(accessUser);
}
editReservation.add(editItem);
JMenuItem mailItem = new JMenuItem(TextUtil.getString(eventType.name()));
ActionListener mailAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "CHOOSE", true);
if (selected != null && selected.size() == 1)
{
try
{
Event event = selected.get(0);
List<Reservation> reservationList = dss.getReservations(event);
Day date = (Day) event.get(Event.EventDate);
String subject = TextUtil.getString(eventType.name()) + " " + date;
String body = getMessage(eventType.name());
MailDialog md = new MailDialog(frame, subject, body, reservationList);
if (md.edit())
{
}
}
catch (AddressException ex)
{
throw new IllegalArgumentException(ex);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
mailAction = createActionListener(frame, mailAction);
mailItem.addActionListener(mailAction);
mailMenu.add(mailItem);
final String title = TextUtil.getString(eventType.name());
JMenuItem smsItem = new JMenuItem(title);
ActionListener smsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List<Event> selected = chooseEvents(eventType, "CHOOSE", true);
if (selected != null && selected.size() == 1)
{
try
{
Event event = selected.get(0);
List<Reservation> reservationList = dss.getReservations(event);
List<String> phoneList = new ArrayList<String>();
for (Reservation r : reservationList)
{
String number = (String) r.get(Repository.JASENET_MOBILE);
if (number != null)
{
phoneList.add(number);
}
}
SMSDialog sd = new SMSDialog(
frame,
title,
"",
phoneList);
if (sd.edit())
{
}
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
catch (SMSException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
smsAction = createActionListener(frame, smsAction);
smsItem.addActionListener(smsAction);
smsMenu.add(smsItem);
}
}
private JMenuItem menuItemRemoveEntity()
{
final String title = TextUtil.getString("REMOVE ENTITY");
JMenuItem removeEntityItem = new JMenuItem(title);
ActionListener removeEntityAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
String confirm = TextUtil.getString("CONFIRM REMOVE") + " " + kind;
if (JOptionPane.showConfirmDialog(frame, confirm, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
List<String> kindList = new ArrayList<String>();
kindList.add(kind.toString());
int count = dss.remove(kindList);
JOptionPane.showMessageDialog(frame, TextUtil.getString("REMOVED") + " " + count);
}
}
}
};
removeEntityAction = createActionListener(frame, removeEntityAction);
removeEntityItem.addActionListener(removeEntityAction);
return removeEntityItem;
}
private JMenuItem menuItemRemoveYear()
{
final String title = TextUtil.getString("REMOVE YEAR");
JMenuItem removeEntityItem = new JMenuItem(title);
ActionListener removeEntityAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object yearString = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION);
if (yearString != null)
{
String confirm = TextUtil.getString("CONFIRM REMOVE") + " " + yearString;
if (JOptionPane.showConfirmDialog(frame, confirm, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
long year = Long.parseLong(yearString.toString());
Day now = new Day();
if (year < now.getYear())
{
int count = dss.remove(year);
JOptionPane.showMessageDialog(frame, TextUtil.getString("REMOVED") + " " + count);
}
else
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("CANNOT REMOVE") + " " + year);
}
}
}
}
};
removeEntityAction = createActionListener(frame, removeEntityAction);
removeEntityItem.addActionListener(removeEntityAction);
return removeEntityItem;
}
private static final String TSFORMAT = "yyyyMMddHHmmss";
private JMenuItem menuItemBackupEntity()
{
final String title = TextUtil.getString("BACKUP ENTITY");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
SimpleDateFormat format = new SimpleDateFormat(TSFORMAT);
String ts = format.format(new Date());
File file = saveFile(BACKUPDIR, kind + ts + ".ser", ".ser", "Backup");
if (file != null)
{
int count;
try (FileOutputStream fos = new FileOutputStream(file))
{
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
List<String> list = new ArrayList<String>();
list.add(kind.toString());
count = dss.backup(list, oos);
JOptionPane.showMessageDialog(frame, TextUtil.getString("STORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemBackupYear()
{
final String title = TextUtil.getString("BACKUP YEAR");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object yearString = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION);
if (yearString != null)
{
long year = Long.parseLong(yearString.toString());
File file = saveFile(BACKUPDIR, year + ".ser", ".ser", "Backup");
if (file != null)
{
int count;
try (FileOutputStream fos = new FileOutputStream(file))
{
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
count = dss.backup(year, oos);
JOptionPane.showMessageDialog(frame, TextUtil.getString("STORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemRestore()
{
final String title = TextUtil.getString("RESTORE");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(BACKUPDIR, ".ser", "Backup");
if (file != null)
{
int count;
try (FileInputStream fos = new FileInputStream(file))
{
BufferedInputStream bis = new BufferedInputStream(fos);
ObjectInputStream ois = new ObjectInputStream(bis);
count = dss.restore(ois);
JOptionPane.showMessageDialog(frame, TextUtil.getString("RESTORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemInspectionFix1()
{
final String title = "Inspection fix1";
JMenuItem insFix1Item = new JMenuItem(title);
ActionListener insFix1Action = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
dss.inspectionFix1();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
insFix1Action = createActionListener(frame, insFix1Action);
insFix1Item.addActionListener(insFix1Action);
return insFix1Item;
}
private JMenuItem menuItemSql()
{
final String title = TextUtil.getString("JDBC SQL");
JMenuItem sqlItem = new JMenuItem(title);
ActionListener sqlAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
SqlDialog dia = new SqlDialog(frame, "select ", serverProperties.getProperties());
dia.edit();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
sqlAction = createActionListener(frame, sqlAction);
sqlItem.addActionListener(sqlAction);
return sqlItem;
}
private JMenuItem menuItemUninspectedBoats()
{
final String title = TextUtil.getString("UNINSPECTED BOATS");
JMenuItem sqlItem = new JMenuItem(title);
ActionListener sqlAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
InspectionHandler ih = new InspectionHandler(serverProperties.getProperties());
String selectSql = "select Veneet.VeneID, Jasenet.Etunimi, Jasenet.Sukunimi, Veneet.Nimi, Veneet.Tyyppi from Veneet, Jasenet where Veneet.Omistaja = Jasenet.JasenNo and Veneet.Omistaja < "+MAXMEMBER;
SqlConnection connection = new SqlConnection(serverProperties.getProperties());
ResultSet rs = connection.query(selectSql);
ResultSetModel model = new ResultSetModel(rs);
List<DataObject> list = DataObject.convert(model, rs, new IsNotInspectedFilter(ih));
DataObjectListDialog<DataObject> dia = new DataObjectListDialog<>(frame, "", "OK", model, list);
dia.setAutoCreateRowSorter(true);
dia.select();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
sqlAction = createActionListener(frame, sqlAction);
sqlItem.addActionListener(sqlAction);
return sqlItem;
}
private JMenuItem menuItemAddYear()
{
final String title = TextUtil.getString("ADD YEAR");
JMenuItem addYearItem = new JMenuItem(title);
ActionListener addYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String year = JOptionPane.showInputDialog(frame, TextUtil.getString("ADD YEAR"));
int y = Integer.parseInt(year);
if (y >= 1800 && y <= 2100)
{
dss.addYear(y);
}
}
};
addYearAction = createActionListener(frame, addYearAction);
addYearItem.addActionListener(addYearAction);
return addYearItem;
}
private JMenuItem menuItemInspectAllLightBoats()
{
final String title = TextUtil.getString("INSPECT ALL LIGHT BOATS");
JMenuItem inspectAllLightBoatsItem = new JMenuItem(title);
ActionListener inspectAllLightBoatsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
dss.inspectAllLightBoats(MAXMEMBER);
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
inspectAllLightBoatsAction = createActionListener(frame, inspectAllLightBoatsAction);
inspectAllLightBoatsItem.addActionListener(inspectAllLightBoatsAction);
return inspectAllLightBoatsItem;
}
private JMenuItem menuItemRestoreEntity()
{
final String title = TextUtil.getString("RESTORE ENTITY");
JMenuItem backupYearItem = new JMenuItem(title);
ActionListener backupYearAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object kind = JOptionPane.showInputDialog(frame, title, "", JOptionPane.OK_CANCEL_OPTION, null, serverProperties.getTables(), null);
if (kind != null)
{
File file = openFile(BACKUPDIR, ".ser", "Backup");
if (file != null)
{
int count;
try (FileInputStream fos = new FileInputStream(file))
{
BufferedInputStream bis = new BufferedInputStream(fos);
ObjectInputStream ois = new ObjectInputStream(bis);
List<String> list = new ArrayList<String>();
list.add(kind.toString());
count = dss.restore(list, ois);
JOptionPane.showMessageDialog(frame, TextUtil.getString("RESTORED") + " " + count);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
};
backupYearAction = createActionListener(frame, backupYearAction);
backupYearItem.addActionListener(backupYearAction);
return backupYearItem;
}
private JMenuItem menuItemSMSCredits()
{
JMenuItem creditItem = new JMenuItem(TextUtil.getString("CHECK CREDITS"));
ActionListener creditAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
int credits = dss.messagesLeft();
String smsLeftString = TextUtil.getString("SMS LEFT");
JOptionPane.showMessageDialog(frame, smsLeftString + " " + credits);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
catch (SMSException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
creditAction = createActionListener(frame, creditAction);
creditItem.addActionListener(creditAction);
return creditItem;
}
private JMenuItem menuItemDownloadCompetitorsForSailwave()
{
// download series
JMenuItem downloadRaceCompetitorsForSailwave = new JMenuItem(TextUtil.getString("DOWNLOAD COMPETITORS FOR SAILWAVE"));
ActionListener downloadCompetitorsForSailwaveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
downloadCompetitorsForSailwave();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
downloadCompetitorsForSailwaveAction = createActionListener(frame, downloadCompetitorsForSailwaveAction);
downloadRaceCompetitorsForSailwave.addActionListener(downloadCompetitorsForSailwaveAction);
return downloadRaceCompetitorsForSailwave;
}
private JMenuItem menuItemInsertCompetitorsToSailwave()
{
// download series
JMenuItem insertRaceCompetitorsToSailwave = new JMenuItem(TextUtil.getString("INSERT COMPETITORS TO SAILWAVE"));
ActionListener insertCompetitorsToSailwaveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
insertCompetitorsToSailwave();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
insertCompetitorsToSailwaveAction = createActionListener(frame, insertCompetitorsToSailwaveAction);
insertRaceCompetitorsToSailwave.addActionListener(insertCompetitorsToSailwaveAction);
return insertRaceCompetitorsToSailwave;
}
private JMenuItem menuItemDownloadCompetitorsAsCVS()
{
// download series
JMenuItem downloadRaceCompetitorsAsCVS = new JMenuItem(TextUtil.getString("DOWNLOAD COMPETITORS AS CVS"));
ActionListener downloadCompetitorsAsCVSAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
downloadCompetitorsAsCVS();
}
catch (EntityNotFoundException | IOException | JSONException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
downloadCompetitorsAsCVSAction = createActionListener(frame, downloadCompetitorsAsCVSAction);
downloadRaceCompetitorsAsCVS.addActionListener(downloadCompetitorsAsCVSAction);
return downloadRaceCompetitorsAsCVS;
}
private JMenuItem menuItemCreatePLSGoogleDocs()
{
// download series
JMenuItem createPLSGoogleDocs = new JMenuItem(TextUtil.getString("CREATE PLS GOOGLE DOCS"));
ActionListener createPLSGoogleDocsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
createPLSSpreadsheet();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
createPLSGoogleDocsAction = createActionListener(frame, createPLSGoogleDocsAction);
createPLSGoogleDocs.addActionListener(createPLSGoogleDocsAction);
return createPLSGoogleDocs;
}
private JMenuItem menuItemCreateToTGoogleDocs()
{
// download series
JMenuItem createToTGoogleDocs = new JMenuItem(TextUtil.getString("CREATE TOT GOOGLE DOCS"));
ActionListener createToTGoogleDocsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
createToTSpreadsheet();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
createToTGoogleDocsAction = createActionListener(frame, createToTGoogleDocsAction);
createToTGoogleDocs.addActionListener(createToTGoogleDocsAction);
return createToTGoogleDocs;
}
private JMenuItem menuItemRaceEmail()
{
// download series
JMenuItem raceEmail = new JMenuItem(TextUtil.getString("SEND EMAIL"));
ActionListener raceEmailAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
List<RaceEntry> competitors = chooseCompetitors();
MailDialog md = new MailDialog(frame, "", "", competitors);
md.edit();
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
raceEmailAction = createActionListener(frame, raceEmailAction);
raceEmail.addActionListener(raceEmailAction);
return raceEmail;
}
private JMenuItem menuItemRaceSMS()
{
// download series
final String title = TextUtil.getString("SEND SMS");
JMenuItem raceSMS = new JMenuItem(title);
ActionListener raceSMSAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
List<RaceEntry> competitors = chooseCompetitors();
List<String> phoneList = new ArrayList<String>();
for (RaceEntry r : competitors)
{
String number = (String) r.get(RaceEntry.HELMPHONE);
if (number != null && !number.isEmpty())
{
phoneList.add(number);
}
}
SMSDialog sd = new SMSDialog(
frame,
title,
"",
phoneList);
if (sd.edit())
{
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
raceSMSAction = createActionListener(frame, raceSMSAction);
raceSMS.addActionListener(raceSMSAction);
return raceSMS;
}
private JMenu menuItemAttachRaceSeries()
{
// download series
JMenu attachRaceSeriesMenu = new JMenu(TextUtil.getString("ATTACH RACE"));
for (final Attachment.Type type : Attachment.Type.values())
{
JMenu attachmentType = new JMenu(TextUtil.getString(type.name()));
attachRaceSeriesMenu.add(attachmentType);
JMenuItem fileItem = new JMenuItem(TextUtil.getString("FILE"));
ActionListener fileAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachRaceSeriesFile(type);
}
catch (EntityNotFoundException | IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
fileAction = createActionListener(frame, fileAction);
fileItem.addActionListener(fileAction);
attachmentType.add(fileItem);
JMenuItem linkItem = new JMenuItem(TextUtil.getString("LINK"));
ActionListener linkAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachRaceSeriesLink(type);
}
catch (EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
linkAction = createActionListener(frame, linkAction);
linkItem.addActionListener(linkAction);
attachmentType.add(linkItem);
}
return attachRaceSeriesMenu;
}
private void attachRaceSeriesLink(Type type) throws EntityNotFoundException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
Attachment attachment = new Attachment(raceSeriesOrFleet);
attachment.set(Attachment.TYPE, type.ordinal());
DataObjectDialog<Attachment> dod = new DataObjectDialog<Attachment>(frame, attachment.getModel().hide(Attachment.TYPE), attachment);
if (dod.edit())
{
Link link = (Link) attachment.get(Attachment.URL);
try
{
URL url = new URL(link.getValue());
dss.put(attachment);
}
catch (MalformedURLException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
}
private void attachRaceSeriesFile(Type type) throws IOException, EntityNotFoundException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
File file = openFile(RACEATTACHDIR, null, null);
if (file != null)
{
String title = JOptionPane.showInputDialog(frame, TextUtil.getString("TITLE"), TextUtil.getString(type.name()));
if (title != null)
{
dss.upload(raceSeriesOrFleet, type, title, file);
}
}
}
}
private void removeRaceSeriesAttachment() throws EntityNotFoundException, IOException
{
DataObject raceSeriesOrFleet = chooseRaceSeriesOrFleet();
if (raceSeriesOrFleet != null)
{
List<Attachment> attachments = chooseAttachments(raceSeriesOrFleet);
if (attachments != null)
{
dss.removeAttachments(attachments);
}
}
}
private JMenuItem menuItemRemoveRaceSeriesAttachment()
{
// download series
JMenuItem removeAttachmentItem = new JMenuItem(TextUtil.getString("REMOVE ATTACHMENT"));
ActionListener removeAttachmentAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeRaceSeriesAttachment();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeAttachmentAction = createActionListener(frame, removeAttachmentAction);
removeAttachmentItem.addActionListener(removeAttachmentAction);
return removeAttachmentItem;
}
private JMenuItem menuItemUploadRanking()
{
// upload ranking
JMenuItem uploadRankingItem = new JMenuItem(TextUtil.getString("UPLOAD RANKING"));
ActionListener uploadRankingAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (file != null)
{
try
{
uploadRanking(file);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
};
uploadRankingAction = createActionListener(frame, uploadRankingAction);
uploadRankingItem.addActionListener(uploadRankingAction);
return uploadRankingItem;
}
private JMenuItem menuItemAddReferencePayments()
{
JMenuItem addPaymentsItem = new JMenuItem(TextUtil.getString("ADD REFERENCE PAYMENTS"));
ActionListener addPaymentsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
addReferencePayments();
}
catch (EntityNotFoundException ex)
{
throw new IllegalArgumentException(ex);
}
}
};
addPaymentsAction = createActionListener(frame, addPaymentsAction);
addPaymentsItem.addActionListener(addPaymentsAction);
return addPaymentsItem;
}
private void addReferencePayments() throws EntityNotFoundException
{
while (true)
{
String reference = "";
CreditorReference cr = null;
while (true)
{
reference = JOptionPane.showInputDialog(frame, TextUtil.getString("REFERENCE"), reference);
if (reference == null)
{
return;
}
try
{
cr = new CreditorReference(reference, true);
break;
}
catch (IllegalArgumentException ex)
{
JOptionPane.showMessageDialog(frame, ex);
}
}
int rn = Integer.parseInt(reference.substring(0, reference.length() - 1));
RaceEntry raceEntry = dss.raceEntryForReference(rn);
Double fee = (Double) raceEntry.get(RaceEntry.FEE);
String paidStr = JOptionPane.showInputDialog(frame, "<html>" + raceEntry.getFieldsAsHtmlTable() + "</html>", fee);
if (paidStr != null)
{
try
{
fee = Double.parseDouble(paidStr);
}
catch (NumberFormatException ex)
{
continue;
}
raceEntry.set(RaceEntry.PAID, fee);
dss.put(raceEntry);
}
}
}
private JMenuItem menuItemAddOtherPayments()
{
JMenuItem addPaymentsItem = new JMenuItem(TextUtil.getString("ADD OTHER PAYMENTS"));
ActionListener addPaymentsAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
addOtherPayments();
}
catch (EntityNotFoundException ex)
{
throw new IllegalArgumentException(ex);
}
}
};
addPaymentsAction = createActionListener(frame, addPaymentsAction);
addPaymentsItem.addActionListener(addPaymentsAction);
return addPaymentsItem;
}
private void addOtherPayments() throws EntityNotFoundException
{
DataObjectModel model = RaceEntry.MODEL.view(
RaceEntry.NAT,
RaceEntry.SAILNO,
RaceEntry.HELMNAME,
RaceEntry.CLUB,
RaceEntry.FLEET,
RaceEntry.FEE);
List<RaceEntry> unpaidRaceEntries = dss.getUnpaidRaceEntries();
while (true)
{
String totalStr = JOptionPane.showInputDialog(frame, TextUtil.getString("TOTAL"));
if (totalStr == null)
{
return;
}
double total = Double.parseDouble(totalStr);
Collections.sort(unpaidRaceEntries, new FeeComparator(total));
DataObjectChooser<RaceEntry> ec = new DataObjectChooser<RaceEntry>(
model,
unpaidRaceEntries,
"",
"CHOOSE");
ec.setSelectAlways(true);
List<RaceEntry> entries = ec.choose();
if (entries == null)
{
return;
}
for (RaceEntry re : entries)
{
re.set(RaceEntry.PAID, total);
dss.put(re);
unpaidRaceEntries.remove(re);
}
}
}
private class FeeComparator implements Comparator<RaceEntry>
{
private double target;
public FeeComparator(double target)
{
this.target = target;
}
@Override
public int compare(RaceEntry o1, RaceEntry o2)
{
Double fee1 = (Double) o1.get(RaceEntry.FEE);
if (fee1 == null)
{
return -1;
}
Double fee2 = (Double) o2.get(RaceEntry.FEE);
if (fee2 == null)
{
return 1;
}
Double d1 = new Double(Math.abs(target - fee1));
Double d2 = new Double(Math.abs(target - fee2));
return d1.compareTo(d2);
}
}
private File openFile(String lastDir, String suffix, String description)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
if (suffix != null && description != null)
{
FileFilter ff = new SuffixFileFilter(suffix, description);
fc.setFileFilter(ff);
}
File currentDirectory = LastInput.getDirectory(lastDir);
if (currentDirectory != null)
{
fc.setCurrentDirectory(currentDirectory);
}
if (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
LastInput.set(lastDir, file);
return file;
}
return null;
}
private File saveFile(String lastDir, String nameCandidate, String suffix, String description)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
FileFilter ff = new SuffixFileFilter(suffix, description);
fc.setFileFilter(ff);
fc.setSelectedFile(new File(nameCandidate));
File currentDirectory = LastInput.getDirectory(lastDir);
if (currentDirectory != null)
{
fc.setCurrentDirectory(currentDirectory);
}
if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if (file != null)
{
if (!file.getName().endsWith(suffix))
{
file = new File(file.getPath() + suffix);
}
LastInput.set(lastDir, file);
}
return file;
}
return null;
}
private JMenuItem menuItemUploadRaceSeries()
{
// upload series
JMenuItem uploadRaceSeriesItem = new JMenuItem(TextUtil.getString("UPLOAD RACE"));
ActionListener uploadRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
File file = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (file != null)
{
try
{
uploadSeries(file);
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
};
uploadRaceSeriesAction = createActionListener(frame, uploadRaceSeriesAction);
uploadRaceSeriesItem.addActionListener(uploadRaceSeriesAction);
return uploadRaceSeriesItem;
}
private JMenuItem menuItemEditRaceSeries()
{
// upload series
JMenuItem editRaceSeriesItem = new JMenuItem(TextUtil.getString("EDIT RACE"));
ActionListener editRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
editSeries();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
editRaceSeriesAction = createActionListener(frame, editRaceSeriesAction);
editRaceSeriesItem.addActionListener(editRaceSeriesAction);
return editRaceSeriesItem;
}
private JMenuItem menuItemRemoveRaceSeries()
{
// upload series
JMenuItem removeRaceSeriesItem = new JMenuItem(TextUtil.getString("REMOVE RACE"));
ActionListener removeRaceSeriesAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeSeries();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeRaceSeriesAction = createActionListener(frame, removeRaceSeriesAction);
removeRaceSeriesItem.addActionListener(removeRaceSeriesAction);
return removeRaceSeriesItem;
}
private JMenuItem menuItemSync()
{
JMenuItem syncItem = new JMenuItem(TextUtil.getString("SYNCHRONIZE"));
ActionListener syncAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
SwingWorker task = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
Progress progress = new UIProgress(frame, TextUtil.getString("SYNCHRONIZE"));
progress.setNote("");
try
{
dss.synchronize(progress);
}
catch (Throwable ex)
{
progress.close();
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
return null;
}
};
task.execute();
}
};
syncAction = createActionListener(frame, syncAction);
syncItem.addActionListener(syncAction);
return syncItem;
}
private JMenuItem menuItemTextMaintenence()
{
JMenuItem textMaintenenceItem = new JMenuItem(TextUtil.getString("TEXT MAINTENANCE"));
ActionListener maintenanceAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Messages messages = dss.getMessages();
DataObjectDialog<Messages> dod = new DataObjectDialog<Messages>(frame, Messages.MODEL, messages);
dod.setPreferredSize(new Dimension(800, 600));
if (dod.edit())
{
dss.put(messages);
}
}
};
maintenanceAction = createActionListener(frame, maintenanceAction);
textMaintenenceItem.addActionListener(maintenanceAction);
return textMaintenenceItem;
}
private JMenuItem menuItemTextUpload()
{
JMenuItem textUploadItem = new JMenuItem(TextUtil.getString("TEXT UPLOAD"));
ActionListener textUploadAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
MessagesBackup mb = new MessagesBackup(frame);
mb.load();
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
textUploadAction = createActionListener(frame, textUploadAction);
textUploadItem.addActionListener(textUploadAction);
return textUploadItem;
}
private JMenuItem menuItemTextDownload()
{
JMenuItem textDownloadItem = new JMenuItem(TextUtil.getString("TEXT DOWNLOAD"));
ActionListener textDownloadAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
MessagesBackup mb = new MessagesBackup(frame);
mb.store();
}
catch (IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
textDownloadAction = createActionListener(frame, textDownloadAction);
textDownloadItem.addActionListener(textDownloadAction);
return textDownloadItem;
}
private JMenu menuItemAttach()
{
JMenu attachMenu = new JMenu(TextUtil.getString("ADD ATTACHMENT"));
JMenuItem fileItem = new JMenuItem(TextUtil.getString("FILE"));
ActionListener fileAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachFile();
}
catch (EntityNotFoundException | IOException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
fileAction = createActionListener(frame, fileAction);
fileItem.addActionListener(fileAction);
attachMenu.add(fileItem);
JMenuItem linkItem = new JMenuItem(TextUtil.getString("LINK"));
ActionListener linkAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
attachLink();
}
catch (EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
linkAction = createActionListener(frame, linkAction);
linkItem.addActionListener(linkAction);
attachMenu.add(linkItem);
return attachMenu;
}
private void attachLink() throws EntityNotFoundException
{
Title root = chooseTitle();
Attachment attachment = new Attachment(root);
attachment.set(Attachment.TYPE, Attachment.Type.OTHER);
DataObjectDialog<Attachment> dod = new DataObjectDialog<Attachment>(frame, attachment.getModel().hide(Attachment.TYPE), attachment);
if (dod.edit())
{
Link link = (Link) attachment.get(Attachment.URL);
try
{
URL url = new URL(link.getValue());
dss.put(attachment);
}
catch (MalformedURLException ex)
{
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
private void attachFile() throws IOException, EntityNotFoundException
{
Title root = chooseTitle();
File file = openFile(ATTACHDIR, null, null);
String title = JOptionPane.showInputDialog(frame, TextUtil.getString("TITLE"));
if (title != null)
{
dss.upload(root, Attachment.Type.OTHER, title, file);
}
}
private void removeAttachment() throws IOException, EntityNotFoundException
{
Title root = chooseTitle();
List<Attachment> attachments = chooseAttachments(root);
if (attachments != null)
{
dss.removeAttachments(attachments);
}
}
private JMenuItem menuItemRemoveAttachment()
{
// download series
JMenuItem removeAttachmentItem = new JMenuItem(TextUtil.getString("REMOVE ATTACHMENT"));
ActionListener removeAttachmentAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
removeAttachment();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
};
removeAttachmentAction = createActionListener(frame, removeAttachmentAction);
removeAttachmentItem.addActionListener(removeAttachmentAction);
return removeAttachmentItem;
}
private Title chooseTitle() throws EntityNotFoundException
{
List<Title> titles = null;
titles = dss.getTitles();
// choose one of the shifts
DataObjectChooser<Title> ec = new DataObjectChooser<Title>(
Title.MODEL,
titles,
TextUtil.getString("TITLE"),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<Title> selectedTitle = ec.choose();
if (selectedTitle != null && selectedTitle.size() == 1)
{
return selectedTitle.get(0);
}
else
{
return null;
}
}
/**
* Return a text from Messages kind
*
* @param name
* @return
*/
private String getMessage(String name)
{
if (messages == null)
{
messages = dss.getMessages();
}
Object obj = messages.get(name);
if (obj != null)
{
if (obj instanceof Text)
{
Text text = (Text) obj;
return text.getValue();
}
else
{
return obj.toString();
}
}
return null;
}
@Override
public void windowClosing(WindowEvent e)
{
confirmSaveReservations();
if (workBench != null)
{
workBench.close();
}
System.exit(0);
}
private void confirmSaveReservations()
{
if (reservationList != null)
{
String msg = TextUtil.getString("CONFIRM MODIFICATIONS");
if (JOptionPane.showConfirmDialog(frame, msg, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
saveReservations();
}
}
}
private void saveReservations()
{
long order = 1;
for (Reservation selectedReservation : selectedReservations)
{
selectedReservation.set(Reservation.ORDER, order++);
}
for (Reservation unSelectedReservation : unSelectedReservations)
{
unSelectedReservation.set(Reservation.ORDER, 0);
}
List<Reservation> updateList = new ArrayList<>();
updateList.addAll(unSelectedReservations);
reservationList.removeAll(unSelectedReservations);
updateList.addAll(selectedReservations);
dss.put(updateList);
reservationList.removeAll(selectedReservations);
dss.delete(reservationList);
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setTitle(safeTitle);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
private void setAsInspected() throws SQLException, ClassNotFoundException
{
for (Reservation selectedReservation : selectedReservations)
{
selectedReservation.set(Reservation.INSPECTED, true);
}
for (Reservation unSelectedReservation : unSelectedReservations)
{
unSelectedReservation.set(Reservation.INSPECTED, false);
}
InspectionHandler ih = new InspectionHandler(serverProperties.getProperties());
if (!unSelectedReservations.isEmpty())
{
ih.updateInspection(unSelectedReservations);
dss.put(unSelectedReservations);
}
reservationList.removeAll(unSelectedReservations);
if (!selectedReservations.isEmpty())
{
ih.updateInspection(selectedReservations);
dss.put(selectedReservations);
}
reservationList.removeAll(selectedReservations);
dss.delete(reservationList);
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
private void cancel()
{
menuReservation.setEnabled(true);
frame.setContentPane(safeContainer);
frame.setTitle(safeTitle);
frame.setVisible(true);
reservationList = null;
selectedReservations = null;
unSelectedReservations = null;
}
public static ActionListener createActionListener(final Component component, final ActionListener actionListener)
{
ActionListener al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
component.setCursor(busyCursor);
component.repaint();
actionListener.actionPerformed(e);
}
finally
{
component.setCursor(defaultCursor);
}
}
};
return al;
}
public JFrame getFrame()
{
return frame;
}
public JMenuBar getMenuBar()
{
return menuBar;
}
public JPanel getPanel()
{
return panel;
}
private void editReservations(final EventType eventType)
{
final Event event = chooseEvent(eventType, "CHOOSE");
if (event != null)
{
final String eventTitle = TextUtil.getString(event.getEventType().name()) + " " + event.get(Event.EventDate);
safeTitle = frame.getTitle();
frame.setTitle(eventTitle);
reservationList = dss.getReservations(event);
selectedReservations = new ArrayList<Reservation>();
unSelectedReservations = new ArrayList<Reservation>();
if (Event.isInspection(eventType))
{
for (Reservation reservation : reservationList)
{
Boolean inspected = (Boolean) reservation.get(Reservation.INSPECTED);
if (inspected != null && inspected)
{
selectedReservations.add(reservation);
}
else
{
unSelectedReservations.add(reservation);
}
}
}
else
{
for (Reservation reservation : reservationList)
{
Long order = (Long) reservation.get(Reservation.ORDER);
if (order != null && order != 0)
{
selectedReservations.add(reservation);
}
else
{
unSelectedReservations.add(reservation);
}
}
}
DataObjectModel baseModel = Reservation.getModel(eventType);
DataObjectModel unorderedModel = null;
DataObjectModel orderedModel = null;
switch (eventType)
{
case LAUNCH:
case LIFT:
case HULL_INSPECTION:
unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
break;
case INSPECTION:
unorderedModel = baseModel.hide(
Reservation.BOAT,
Reservation.INSPECTED,
Reservation.CREATOR,
Reservation.EMAIL,
Reservation.MOBILEPHONE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.INSPECTION_GASS,
Reservation.INSPECTOR);
orderedModel = baseModel.hide(
Reservation.BOAT,
Reservation.INSPECTED,
Reservation.CREATOR,
Reservation.EMAIL,
Reservation.MOBILEPHONE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.NOTES);
break;
}
final DataObjectListTableModel<Reservation> unorderedTableModel =
new DataObjectListTableModel<Reservation>(unorderedModel, unSelectedReservations);
final JTable unorderedtable = new FitTable(unorderedTableModel);
TableSelectionHandler tsh1 = new TableSelectionHandler(unorderedtable);
unorderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
unorderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());
unorderedtable.addKeyListener(unorderedTableModel.getRemover(dss));
unorderedtable.setDragEnabled(true);
unorderedtable.setDropMode(DropMode.INSERT_ROWS);
TransferHandler unorderedTransferHandler = new DataObjectTransferHandler<Reservation>(unorderedTableModel);
unorderedtable.setTransferHandler(unorderedTransferHandler);
final DataObjectListTableModel<Reservation> orderedTableModel =
new DataObjectListTableModel<Reservation>(orderedModel, selectedReservations);
orderedTableModel.setEditable(Reservation.INSPECTION_CLASS, Reservation.INSPECTION_GASS, Reservation.BASICINSPECTION, Reservation.INSPECTOR);
final JTable orderedtable = new FitTable(orderedTableModel);
TableSelectionHandler tsh2 = new TableSelectionHandler(orderedtable);
orderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
orderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());
orderedtable.addKeyListener(orderedTableModel.getRemover(dss));
orderedtable.setDragEnabled(true);
orderedtable.setDropMode(DropMode.INSERT_ROWS);
TransferHandler orderedTransferHandler = new DataObjectTransferHandler<Reservation>(orderedTableModel);
orderedtable.setTransferHandler(orderedTransferHandler);
if (Event.isInspection(eventType))
{
unorderedtable.setAutoCreateRowSorter(true);
orderedtable.setAutoCreateRowSorter(true);
}
leftPane = new JScrollPane();
leftPane.setViewport(new InfoViewport(TextUtil.getString(eventType.name() + "-leftPane")));
leftPane.setViewportView(unorderedtable);
leftPane.setTransferHandler(unorderedTransferHandler);
rightPane = new JScrollPane();
rightPane.setViewport(new InfoViewport(TextUtil.getString(eventType.name() + "-rightPane")));
rightPane.setViewportView(orderedtable);
rightPane.setTransferHandler(orderedTransferHandler);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
splitPane.setDividerLocation(0.5);
menuReservation.setEnabled(false);
safeContainer = frame.getContentPane();
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(splitPane, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
contentPane.add(buttonPanel, BorderLayout.SOUTH);
JButton saveButton = new JButton(TextUtil.getString("SAVE"));
saveButton.setEnabled(!Event.isInspection(eventType));
ActionListener saveAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
saveReservations();
}
};
saveButton.addActionListener(saveAction);
buttonPanel.add(saveButton);
switch (eventType)
{
case INSPECTION:
{
if (privileged)
{
JButton inspectButton = new JButton(TextUtil.getString("SET INSPECTED"));
inspectButton.setToolTipText(TextUtil.getString("SET INSPECTED TT"));
ActionListener inspectAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
TableCellEditor cellEditor = orderedtable.getCellEditor();
if (cellEditor != null)
{
cellEditor.stopCellEditing();
}
try
{
setAsInspected();
}
catch (SQLException | ClassNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
inspectButton.addActionListener(inspectAction);
buttonPanel.add(inspectButton);
}
JButton addBoat = new JButton(TextUtil.getString("ADD BOAT"));
ActionListener addBoatAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Reservation reservation = reservate(eventType, event);
if (reservation != null)
{
reservationList.add(reservation);
unSelectedReservations.add(reservation);
unorderedTableModel.fireTableDataChanged();
}
}
};
addBoat.addActionListener(addBoatAction);
buttonPanel.add(addBoat);
JButton printTypeButton = new JButton(TextUtil.getString("PRINT"));
ActionListener printTypeAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printNameBoatTypeOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printTypeButton.addActionListener(printTypeAction);
buttonPanel.add(printTypeButton);
JButton printDockButton = new JButton(TextUtil.getString("PRINT DOCK ORDER"));
ActionListener printDockAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printDockOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printDockButton.addActionListener(printDockAction);
buttonPanel.add(printDockButton);
}
break;
case HULL_INSPECTION:
{
JButton print = new JButton(TextUtil.getString("PRINT"));
ActionListener printAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printAlphaOrder(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
print.addActionListener(printAction);
buttonPanel.add(print);
}
break;
case LAUNCH:
case LIFT:
{
JButton addBoat = new JButton(TextUtil.getString("ADD BOAT"));
ActionListener addBoatAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Reservation reservation = reservate(eventType, event);
if (reservation != null)
{
reservationList.add(reservation);
unSelectedReservations.add(reservation);
unorderedTableModel.fireTableDataChanged();
}
}
};
addBoat.addActionListener(addBoatAction);
buttonPanel.add(addBoat);
JButton printBrief = new JButton(TextUtil.getString("BRIEF PRINT"));
ActionListener printBriefAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
printOrderBrief(eventTitle);
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
printBrief.addActionListener(printBriefAction);
buttonPanel.add(printBrief);
JButton print = new JButton(TextUtil.getString("PRINT"));
ActionListener printAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (eventType == EventType.LAUNCH)
{
printLaunchOrder(eventTitle);
}
else
{
printLiftOrder(eventTitle);
}
}
catch (PrinterException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
print.addActionListener(printAction);
buttonPanel.add(print);
}
break;
}
JButton cancelButton = new JButton(TextUtil.getString("CANCEL"));
ActionListener cancelAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
cancel();
}
};
cancelButton.addActionListener(cancelAction);
buttonPanel.add(cancelButton);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
KeyListener keyListener = new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == 10)
{
int selectedRow = unorderedtable.getSelectedRow();
if (selectedRow != -1)
{
RowSorter<? extends TableModel> rowSorter = unorderedtable.getRowSorter();
if (rowSorter != null)
{
selectedRow = rowSorter.convertRowIndexToModel(selectedRow);
}
Reservation reservation = unorderedTableModel.getObject(selectedRow);
orderedTableModel.add(reservation);
unorderedTableModel.remove(reservation);
e.consume();
unorderedtable.changeSelection(selectedRow, 0, false, false);
}
}
}
};
unorderedtable.addKeyListener(keyListener);
unorderedtable.requestFocusInWindow();
}
}
private void printNameBoatTypeOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.BOATTYPE,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.BASICINSPECTION);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.LASTNAME, Reservation.FIRSTNAME, Reservation.BOATNAME));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printDockOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCK,
Reservation.DOCKNUMBER,
Reservation.BASICINSPECTION);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.DOCK, Reservation.DOCKNUMBER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printAlphaOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.HULL_INSPECTION);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATTYPE,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.LASTNAME));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printOrderBrief(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LAUNCH);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printLaunchOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LAUNCH);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE,
Reservation.MOBILEPHONE,
Reservation.WEIGHT);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private void printLiftOrder(String eventTitle) throws PrinterException
{
DataObjectModel model = Reservation.getModel(EventType.LIFT);
model = model.view(
Reservation.ORDER,
Reservation.LASTNAME,
Reservation.FIRSTNAME,
Reservation.BOATNAME,
Reservation.DOCKYARDPLACE,
Reservation.MOBILEPHONE,
Reservation.WEIGHT,
Reservation.LENGTH);
List<Reservation> list = new ArrayList<Reservation>();
for (Reservation r : reservationList)
{
list.add(r.clone());
}
Collections.sort(list, new DataObjectComparator(Reservation.ORDER));
int order = 1;
for (Reservation r : list)
{
r.set(Reservation.ORDER, order);
order++;
}
DataObjectListDialog<Reservation> dold = new DataObjectListDialog<Reservation>(frame, eventTitle, "OK", model, list);
dold.print();
}
private Event chooseEvent(EventType eventType, String action)
{
List<Event> eventList = chooseEvents(eventType, action, true);
if (eventList != null)
{
return eventList.get(0);
}
else
{
return null;
}
}
private List<Event> chooseEvents(EventType eventType, String action)
{
return chooseEvents(eventType, action, false);
}
private List<Event> chooseEvents(EventType eventType, String action, boolean singleSelection)
{
List<Event> eventList = dss.getEvents(eventType);
DataObjectChooser<Event> ec = new DataObjectChooser<Event>(
Event.MODEL,
eventList,
TextUtil.getString(eventType.name()),
action);
ec.setSelectAlways(true);
if (singleSelection)
{
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
return ec.choose();
}
private Reservation reservate(EventType eventType, Event event)
{
// search a member
String[] columns = Member.MODEL.getProperties();
String lastName = JOptionPane.showInputDialog(panel, TextUtil.getString(Member.SUKUNIMI) + "?");
if (lastName == null)
{
return null;
}
lastName = Utils.convertName(lastName);
List<AnyDataObject> memberList = null;
memberList = dss.retrieve(Member.KIND, Member.SUKUNIMI, lastName, columns);
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Member.MODEL,
memberList,
TextUtil.getString(eventType.name()),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selected = ec.choose();
if (selected != null && selected.size() >= 1)
{
try
{
return reservate(eventType, selected.get(0), event);
}
catch (ParseException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
return null;
}
private Reservation reservate(EventType eventType, AnyDataObject user, Event event) throws ParseException
{
// search boats for member
String[] columns = Boat.MODEL.getProperties();
List<AnyDataObject> boatList = null;
boatList = dss.retrieve(Boat.KIND, Boat.OMISTAJA, user.createKey(), columns);
// choose one of the boats
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Boat.MODEL,
boatList,
TextUtil.getString(eventType.name()),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selectedBoats = ec.choose();
if (selectedBoats.size() == 1)
{
DataObject selectedBoat = selectedBoats.get(0);
// get available member data
Map<String, Object> userData = null;
userData = dss.getUserData(user.getEntity()); //, selectedBoat.createKeyString(), null);
if (event == null)
{
event = chooseEvent(eventType, "CHOOSE");
if (event == null)
{
return null;
}
}
Reservation reservation = new Reservation(event);
DataObjectModel model = reservation.getModel();
model = model.hide(Reservation.ORDER, Reservation.INSPECTED, Reservation.BOAT);
@SuppressWarnings("unchecked")
List<Map<String, Object>> boatLst = (List<Map<String, Object>>) userData.get(Repository.BOATS);
for (Map<String, Object> m : boatLst)
{
if (selectedBoat.createKeyString().equals(m.get(Repository.VENEET_KEY)))
{
reservation.setAll(m);
reservation.set(Reservation.BOAT, m.get(Repository.VENEET_KEY));
}
}
reservation.setAll(userData);
reservation.set(Reservation.CREATOR, creator);
String title = TextUtil.getString(eventType.name());
DataObjectDialog<Reservation> et = new DataObjectDialog<Reservation>(frame, title, model, reservation);
if (et.edit())
{
try
{
dss.createReservation(event, reservation, true);
return reservation;
}
catch (EntityNotFoundException | EventFullException | DoubleBookingException | BoatNotFoundException | MandatoryPropertyMissingException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, ex.getMessage(), ex.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
return null;
}
private void menuSwapPatrolShift()
{
if (privileged)
{
JMenu patrolMenu = new JMenu(TextUtil.getString("PATROL SHIFT"));
menuBar.add(patrolMenu);
patrolMenu.add(menuItemSwapPatrolShift());
patrolMenu.add(menuItemChangePatrolShift());
patrolMenu.add(menuItemSwapLog());
}
}
private void menuQuery()
{
JMenu queryMenu = new JMenu(TextUtil.getString("QUERIES"));
menuBar.add(queryMenu);
queryMenu.add(menuItemQuery());
queryMenu.add(menuItemEditQuery());
}
private JMenuItem menuItemQuery()
{
ActionListener queryAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
startQuery(true, false);
}
};
queryAction = createActionListener(frame, queryAction);
JMenuItem queryItem = new JMenuItem(TextUtil.getString("START QUERY"));
queryItem.addActionListener(queryAction);
return queryItem;
}
private JMenuItem menuItemEditQuery()
{
ActionListener queryAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
startQuery(true, true);
}
};
queryAction = createActionListener(frame, queryAction);
JMenuItem queryItem = new JMenuItem(TextUtil.getString("EDIT QUERY"));
queryItem.addActionListener(queryAction);
return queryItem;
}
private void startQuery(boolean readonly, boolean edit)
{
try
{
if (workBench == null)
{
workBench = new WorkBench(serverProperties.getProperties(), true, readonly);
Messages texts = dss.getMessages();
workBench.addFetchResultPlugin(
new SMSPlugin(
texts.getString(Messages.SMSUSERNAME),
texts.getString(Messages.SMSPASSWORD)
));
}
if (edit)
{
workBench.setVisible(true);
}
else
{
workBench.open();
}
}
catch (IOException | InterruptedException ex)
{
throw new IllegalArgumentException(ex);
}
}
private AnyDataObject chooseMember(String title)
{
// search a member
String[] columns = Member.MODEL.getProperties();
String lastName = JOptionPane.showInputDialog(panel, TextUtil.getString(Member.SUKUNIMI) + "?", title, JOptionPane.QUESTION_MESSAGE);
if (lastName == null)
{
return null;
}
lastName = Utils.convertName(lastName);
List<AnyDataObject> memberList = dss.retrieve(Member.KIND, Member.SUKUNIMI, lastName, columns);
DataObjectChooser<AnyDataObject> ec = new DataObjectChooser<AnyDataObject>(
Member.MODEL,
memberList,
title,
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<AnyDataObject> selected = ec.choose();
if (selected != null && selected.size() == 1)
{
return selected.get(0);
}
else
{
return null;
}
}
private JMenuItem menuItemSwapPatrolShift()
{
ActionListener swapAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
AnyDataObject member = chooseMember(TextUtil.getString("CHOOSE MEMBER"));
if (member != null)
{
swapPatrolShift(member);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
swapAction = createActionListener(frame, swapAction);
JMenuItem swapItem = new JMenuItem(TextUtil.getString("SWAP PATROL SHIFT"));
swapItem.addActionListener(swapAction);
return swapItem;
}
private JMenuItem menuItemChangePatrolShift()
{
ActionListener swapAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
AnyDataObject member = chooseMember(TextUtil.getString("CHOOSE PATROL SHIFT LOOSER"));
if (member != null)
{
changePatrolShift(member);
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
};
swapAction = createActionListener(frame, swapAction);
JMenuItem swapItem = new JMenuItem(TextUtil.getString("CHANGE PATROL SHIFT"));
swapItem.addActionListener(swapAction);
return swapItem;
}
private JMenuItem menuItemSwapLog()
{
ActionListener swapLogAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
TextDialog dia = new TextDialog(frame);
dss.swapLog(dia);
dia.edit();
}
catch (IOException | EntityNotFoundException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
swapLogAction = createActionListener(frame, swapLogAction);
JMenuItem swapLogItem = new JMenuItem(TextUtil.getString("SWAP PATROL LOG"));
swapLogItem.addActionListener(swapLogAction);
return swapLogItem;
}
private PatrolShift choosePatrolShift(AnyDataObject user)
{
List<PatrolShift> shiftList = null;
shiftList = dss.getShifts(user.createKey());
// choose one of the shifts
DataObjectChooser<PatrolShift> ec = new DataObjectChooser<PatrolShift>(
PatrolShift.MODEL.view(Repository.PAIVA),
shiftList,
TextUtil.getString("PATROL SHIFT"),
"CHOOSE");
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<PatrolShift> selectedShifts = ec.choose();
if (selectedShifts != null && selectedShifts.size() == 1)
{
return selectedShifts.get(0);
}
else
{
return null;
}
}
private void swapPatrolShift(AnyDataObject user)
{
Long memberNumber = (Long) user.get(Member.JASENNO);
PatrolShift selectedShift = choosePatrolShift(user);
if (selectedShift != null)
{
SwapRequest req = new SwapRequest();
req.set(Repository.JASENNO, user.createKey());
req.set(Repository.VUOROID, selectedShift.createKey());
req.set(Repository.PAIVA, selectedShift.get(Repository.PAIVA));
List<Long> excluded = new ArrayList<Long>();
Day day = (Day) selectedShift.get(Repository.PAIVA);
excluded.add(day.getValue());
req.set(SwapRequest.EXCLUDE, excluded);
req.set(Repository.CREATOR, creator);
Object[] options =
{
TextUtil.getString("SWAP SHIFT"),
TextUtil.getString("EXCLUDE DATE"),
TextUtil.getString("DELETE PREVIOUS SWAP"),
TextUtil.getString("CANCEL")
};
String msg = TextUtil.getString("SWAP OPTIONS");
try
{
msg = dss.getShiftString(selectedShift.getEntity(), msg);
}
catch (EntityNotFoundException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
while (true)
{
int choise = JOptionPane.showOptionDialog(
frame,
msg + dateList(excluded),
"",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
switch (choise)
{
case 0:
try
{
msg = TextUtil.getString("SWAP CONFIRMATION");
msg = dss.getShiftString(selectedShift.getEntity(), msg) + dateList(excluded);
int confirm = JOptionPane.showConfirmDialog(frame, msg, TextUtil.getString("SWAP SHIFT"), JOptionPane.OK_CANCEL_OPTION);
if (JOptionPane.YES_OPTION == confirm)
{
boolean ok = dss.swapShift(req);
if (ok)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SwapOk"));
}
else
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SwapPending"));
}
}
}
catch (EntityNotFoundException | IOException | SMSException | AddressException ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return;
case 1:
Day d = DateChooser.chooseDate(TextUtil.getString("EXCLUDE DATE"), new Day(excluded.get(excluded.size() - 1)));
excluded.add(d.getValue());
break;
case 2:
dss.deleteSwaps(memberNumber.intValue());
return;
case 3:
return;
}
}
}
else
{
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
}
private void changePatrolShift(AnyDataObject releasedUser)
{
Long releasedMemberNumber = (Long) releasedUser.get(Member.JASENNO);
PatrolShift selectedShift = choosePatrolShift(releasedUser);
if (selectedShift != null)
{
AnyDataObject executingUser = chooseMember(TextUtil.getString("CHOOSE PATROL SHIFT EXECUTER"));
if (executingUser != null)
{
dss.changeShiftExecutor(selectedShift, executingUser);
return;
}
}
JOptionPane.showMessageDialog(
frame,
TextUtil.getString("NO SELECTION"),
TextUtil.getString("MESSAGE"),
JOptionPane.INFORMATION_MESSAGE);
}
private String dateList(List<Long> list)
{
StringBuilder sb = new StringBuilder();
Collections.sort(list);
for (Long l : list)
{
Day date = new Day(l);
sb.append('\n');
sb.append(date.toString());
}
return sb.toString();
}
private void uploadSeries(File file) throws IOException
{
SailWaveFile swf = new SailWaveFile(file);
Race firstRace = swf.getFirstRace();
RaceSeries rs = new RaceSeries();
rs.set(RaceSeries.ID, swf.getEventId());
rs.set(RaceSeries.EVENT, swf.getEvent());
rs.set(RaceSeries.RACE_AREA, swf.getVenue());
rs.set(RaceSeries.NOTES, swf.getNotes());
if (firstRace != null)
{
rs.set(RaceSeries.EventDate, firstRace.getDate());
rs.set(RaceSeries.STARTTIME, firstRace.getTime());
}
List<RaceFleet> fleetList = new ArrayList<>();
for (Fleet fleet : swf.getFleets())
{
RaceFleet rc = new RaceFleet(rs);
rc.set(RaceFleet.Fleet, fleet.getFleet());
rc.set(RaceFleet.Class, fleet.getClassname());
rc.set(RaceFleet.RatingSystem, fleet.getRatingSystem());
rc.set(RaceFleet.SailWaveId, fleet.getNumber());
if (firstRace != null)
{
rc.set(RaceFleet.EventDate, firstRace.getDate());
rc.set(RaceFleet.StartTime, firstRace.getTime());
}
fleetList.add(rc);
}
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.SAILWAVEFILE);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.RatingSystem, RaceFleet.ClosingDate, RaceFleet.ClosingDate2, RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rc = new RaceDialog(frame, swf.getEvent(), dss, model, rs, listModel, fleetList, swf);
rc.setEditable(listModel.getProperties());
if (rc.edit())
{
swf.setEvent((String) rs.get(RaceSeries.EVENT));
swf.setVenue((String) rs.get(RaceSeries.RACE_AREA));
Text notes = (Text) rs.get(RaceSeries.NOTES);
if (notes != null)
{
swf.setNotes(notes.getValue());
}
if (firstRace != null)
{
Day date = (Day) rs.get(RaceSeries.EventDate);
if (date != null)
{
firstRace.setDate(date.toString());
}
Time time = (Time) rs.get(RaceSeries.STARTTIME);
if (time != null)
{
firstRace.setTime(time.toString());
}
}
swf.updateFleets(fleetList);
swf.saveAs(file);
rs.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
while (true)
{
long id = 1;
RaceSeries existingRace = dss.getExistingRace(rs);
if (existingRace != null)
{
String eventName = (String) existingRace.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM REPLACE") + " " + eventName) == JOptionPane.YES_OPTION)
{
dss.putRace(rs, fleetList);
break;
}
else
{
swf.setId(id);
swf.saveAs(file);
rs.set(RaceSeries.ID, id);
}
}
else
{
dss.putRace(rs, fleetList);
break;
}
id++;
}
}
}
private void editSeries() throws IOException, EntityNotFoundException
{
RaceSeries raceSeries = chooseRace();
if (raceSeries != null)
{
Blob swb = (Blob) raceSeries.get(RaceSeries.SAILWAVEFILE);
SailWaveFile swf = new SailWaveFile(swb.getBytes());
List<RaceFleet> fleetList = dss.getFleets(raceSeries);
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.EventDate,
RaceSeries.SAILWAVEFILE);
String event = (String) raceSeries.get(RaceSeries.EVENT);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.RatingSystem, RaceFleet.ClosingDate, RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rd = new RaceDialog(frame, event, dss, model, raceSeries, listModel, fleetList, swf);
rd.setEditable(listModel.getProperties());
if (rd.edit())
{
swf.setEvent((String) raceSeries.get(RaceSeries.EVENT));
swf.setVenue((String) raceSeries.get(RaceSeries.RACE_AREA));
Text notes = (Text) raceSeries.get(RaceSeries.NOTES);
if (notes != null)
{
swf.setNotes(notes.getValue());
}
swf.updateFleets(fleetList);
raceSeries.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
dss.putRace(raceSeries, fleetList);
}
}
}
private void removeSeries() throws IOException, EntityNotFoundException
{
RaceSeries raceSeries = chooseRace();
if (raceSeries != null)
{
String event = (String) raceSeries.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM DELETE")) == JOptionPane.YES_OPTION)
{
int numberOfRaceEntriesFor = dss.getNumberOfRaceEntriesFor(raceSeries);
if (numberOfRaceEntriesFor > 0)
{
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM WHOLE RACE DELETE"),
TextUtil.getString("FLEET HAS ENTRIES"),
JOptionPane.WARNING_MESSAGE
) == JOptionPane.YES_OPTION)
{
dss.deleteWithChilds(raceSeries, "RaceFleet");
}
}
else
{
dss.deleteWithChilds(raceSeries, "RaceFleet");
}
}
}
}
private void uploadRanking(File file) throws IOException
{
SailWaveFile swf = new SailWaveFile(file);
RaceSeries rs = new RaceSeries();
rs.set(RaceSeries.ID, swf.getEventId());
rs.set(RaceSeries.EVENT, swf.getEvent());
rs.set(RaceSeries.RACE_AREA, swf.getVenue());
rs.set(RaceSeries.NOTES, swf.getNotes());
List<Fleet> fleets = swf.getFleets();
if (fleets.isEmpty())
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
if (fleets.size() > 1)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("FLEETS IN RANKING"));
return;
}
Fleet defFleet = swf.getDefaultFleet();
if (defFleet == null)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
String ratingSystem = fleets.get(0).getRatingSystem();
List<RaceFleet> startList = new ArrayList<>();
Map<RaceFleet, Race> startMap = new HashMap<>();
for (Race start : swf.getRaces())
{
RaceFleet st = new RaceFleet(rs);
st.set(RaceFleet.Ranking, true);
st.set(RaceFleet.Fleet, defFleet.getRatingSystem());
startMap.put(st, start);
String startDate = start.getDate();
String startTime = start.getTime();
if (startTime == null)
{
JOptionPane.showMessageDialog(frame, TextUtil.getString("SAILWAVEFILE PROBLEM"));
return;
}
if (startDate != null && !startDate.isEmpty())
{
Day sd = new Day(startDate);
st.set(RaceFleet.EventDate, sd);
st.set(RaceFleet.ClosingDate, sd);
}
if (startTime != null && !startTime.isEmpty())
{
st.set(RaceFleet.StartTime, new Time(startTime));
}
st.set(RaceFleet.RatingSystem, ratingSystem);
startList.add(st);
}
DataObjectModel model = RaceSeries.MODEL.hide(
RaceSeries.ID,
RaceSeries.EventDate,
RaceSeries.TO,
RaceSeries.ClosingDate,
RaceSeries.STARTTIME,
RaceSeries.SAILWAVEFILE);
DataObjectModel listModel = RaceFleet.Model.hide(RaceFleet.Ranking, RaceFleet.SailWaveId);
RaceDialog rc = new RaceDialog(frame, swf.getEvent(), dss, model, rs, listModel, startList, swf);
rc.setEditable(RaceFleet.EventDate, RaceFleet.StartTime, RaceFleet.ClosingDate);
if (rc.edit())
{
Day from = null;
Day to = null;
for (RaceFleet start : startList)
{
if (from == null)
{
from = (Day) start.get(RaceFleet.EventDate);
}
else
{
Day d = (Day) start.get(RaceFleet.EventDate);
if (from.after(d))
{
from = d;
}
}
if (to == null)
{
to = (Day) start.get(RaceFleet.EventDate);
}
else
{
Day d = (Day) start.get(RaceFleet.EventDate);
if (to.before(d))
{
to = d;
}
}
Race r = startMap.get(start);
r.setDate(start.get(RaceFleet.EventDate).toString());
r.setTime(start.get(RaceFleet.StartTime).toString());
}
rs.set(RaceSeries.EventDate, from);
rs.set(RaceSeries.TO, to);
swf.setEvent((String) rs.get(RaceSeries.EVENT));
swf.setVenue((String) rs.get(RaceSeries.RACE_AREA));
Text notes = (Text) rs.get(RaceSeries.NOTES);
swf.setNotes(notes.getValue());
swf.saveAs(file);
rs.set(RaceSeries.SAILWAVEFILE, swf.getBytes());
while (true)
{
long id = 1;
RaceSeries existingRace = dss.getExistingRace(rs);
if (existingRace != null)
{
String eventName = (String) existingRace.get(RaceSeries.EVENT);
if (JOptionPane.showConfirmDialog(
panel,
TextUtil.getString("CONFIRM REPLACE") + " " + eventName) == JOptionPane.YES_OPTION)
{
dss.putRace(rs, startList);
break;
}
else
{
swf.setId(id);
swf.saveAs(file);
rs.set(RaceSeries.ID, id);
}
}
else
{
dss.putRace(rs, startList);
break;
}
id++;
}
}
}
private RaceSeries chooseRace() throws EntityNotFoundException
{
List<RaceSeries> raceList = dss.getRaces();
DataObjectModel model = RaceSeries.MODEL.view(RaceSeries.EVENT);
// choose one of the shifts
DataObjectChooser<RaceSeries> ec = new DataObjectChooser<RaceSeries>(
model,
raceList,
TextUtil.getString("RACE SERIES"),
"CHOOSE");
ec.setSelectAlways(true);
ec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
List<RaceSeries> selectedRaceSeries = ec.choose();
if (selectedRaceSeries != null && selectedRaceSeries.size() == 1)
{
return selectedRaceSeries.get(0);
}
else
{
return null;
}
}
private List<RaceEntry> chooseCompetitors() throws EntityNotFoundException
{
KeyTreeChooser chooser = new KeyTreeChooser(frame, TextUtil.getString("CHOOSE COMPETITORS"), dss, dss.getYearKey(), "Year", "RaceSeries", "RaceFleet");
DataObject selected = chooser.select();
if (selected != null)
{
return dss.getRaceEntriesFor(selected);
}
return null;
}
private DataObject chooseRaceSeriesOrFleet() throws EntityNotFoundException
{
KeyTreeChooser chooser = new KeyTreeChooser(frame, TextUtil.getString("CHOOSE RACE"), dss, dss.getRootKey(), "Root", "Year", "RaceSeries", "RaceFleet");
return chooser.select();
}
private List<Attachment> chooseAttachments(DataObject parent)
{
List<Attachment> attachments = dss.getAttachmentsFor(parent);
// choose one of the shifts
DataObjectChooser<Attachment> ec = new DataObjectChooser<Attachment>(
Attachment.MODEL.view(Attachment.TITLE, Attachment.Filename),
attachments,
TextUtil.getString("ATTACHMENTS"),
"CHOOSE");
ec.setSelectAlways(true);
return ec.choose();
}
private void downloadCompetitorsForSailwave() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
RaceSeries raceSeries = (RaceSeries) entryList.get(0).getRaceSeries();
Blob swb = (Blob) raceSeries.get(RaceSeries.SAILWAVEFILE);
SailWaveFile swf = new SailWaveFile(swb.getBytes());
for (RaceEntry entry : entryList)
{
Competitor competitor = new Competitor();
competitor.setAll(checkRating(entry.getAll()));
swf.addCompetitor(competitor);
}
swf.deleteNotNeededFleets(entryList);
File selectedFile = saveFile(SAILWAVEDIR, swf.getEvent() + ".blw", ".blw", "SailWave");
if (selectedFile != null)
{
swf.saveAs(selectedFile);
}
}
private void insertCompetitorsToSailwave() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
File selectedFile = openFile(SAILWAVEDIR, ".blw", "SailWave");
if (selectedFile == null)
{
return;
}
SailWaveFile swf = new SailWaveFile(selectedFile);
for (RaceEntry entry : entryList)
{
Competitor competitor = new Competitor();
competitor.setAll(checkRating(entry.getAll()));
swf.addCompetitor(competitor);
}
swf.saveAs(selectedFile);
}
private void downloadCompetitorsAsCVS() throws IOException, EntityNotFoundException, JSONException
{
List<RaceEntry> entryList = chooseCompetitors();
if (entryList == null || entryList.isEmpty())
{
return;
}
// TODO check ratings
RaceSeries raceSeries = (RaceSeries) entryList.get(0).getRaceSeries();
File selectedFile = saveFile(SAILWAVEDIR, raceSeries.getString(RaceSeries.EVENT) + ".cvs", ".cvs", "CVS");
if (selectedFile != null)
{
try (FileOutputStream fos = new FileOutputStream(selectedFile))
{
DataObjectModel model = RaceEntry.MODEL.view(entryList);
DataObject.writeCVS(model, entryList, fos);
}
}
}
private void createPLSSpreadsheet() throws IOException, EntityNotFoundException, JSONException, AuthenticationException, ServiceException
{
List<RaceEntry> competitors = chooseCompetitors();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setUserCredentials(serverProperties.getUsername(), serverProperties.getPassword());
SpreadsheetEntry spreadsheet = chooseSpreadsheet(service);
if (spreadsheet != null)
{
PLSSpreadsheet plsSheet = new PLSSpreadsheet(service, spreadsheet);
fillPLSRatings(competitors);
plsSheet.fill(competitors);
}
}
private void fillPLSRatings(List<RaceEntry> competitors) throws IOException, JSONException
{
for (RaceEntry entry : competitors)
{
JSONObject json = getRating("ORC", entry.getNationality(), entry.getNumber(), null);
if (json != null)
{
entry.set(RaceEntry.RATING, json.getString(BoatInfo.RATING));
entry.set(RaceEntry.PLDO, json.getString(RaceEntry.PLDO));
entry.set(RaceEntry.PLTO, json.getString(RaceEntry.PLTO));
}
}
}
private void updateRatings(List<RaceEntry> competitors) throws IOException, JSONException
{
for (RaceEntry entry : competitors)
{
String fleet = (String) entry.get(RaceEntry.FLEET);
String type = (String) entry.get(RaceEntry.CLASS);
JSONObject json = getRating(fleet, entry.getNationality(), entry.getNumber(), type);
if (json != null)
{
String rating = json.getString(BoatInfo.RATING);
if (rating != null && !rating.isEmpty())
{
entry.set(RaceEntry.RATING, rating);
}
}
}
}
private SpreadsheetEntry chooseSpreadsheet(SpreadsheetService service) throws IOException, ServiceException
{
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
String[] options = new String[spreadsheets.size()];
int index = 0;
for (SpreadsheetEntry spreadsheet : spreadsheets)
{
options[index++] = spreadsheet.getTitle().getPlainText();
}
SpreadsheetEntry spreadsheet = null;
String opt = (String) JOptionPane.showInputDialog(frame, TextUtil.getString("GOOGLE DOCS SPREADSHEET"), "", JOptionPane.OK_CANCEL_OPTION, null, options, null);
for (int ii = 0; ii < options.length; ii++)
{
if (options[ii].equals(opt))
{
spreadsheet = spreadsheets.get(ii);
break;
}
}
return spreadsheet;
}
private void createToTSpreadsheet() throws IOException, EntityNotFoundException, JSONException, AuthenticationException, ServiceException
{
List<RaceEntry> competitors = chooseCompetitors();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setUserCredentials(serverProperties.getUsername(), serverProperties.getPassword());
SpreadsheetEntry spreadsheet = chooseSpreadsheet(service);
if (spreadsheet != null)
{
ToTSpreadsheet totSheet = new ToTSpreadsheet(service, spreadsheet);
updateRatings(competitors);
totSheet.fill(competitors);
}
}
private Map<String, Object> checkRating(Map<String, Object> map) throws IOException, JSONException
{
String fleet = (String) map.get(RaceEntry.FLEET);
String nat = (String) map.get(RaceEntry.NAT);
nat = nat.toUpperCase();
Number sailNo = (Number) map.get(RaceEntry.SAILNO);
String clazz = (String) map.get(RaceEntry.CLASS);
String entryRatingStr = (String) map.get(RaceEntry.RATING);
if (entryRatingStr != null)
{
entryRatingStr = entryRatingStr.replace(',', '.');
}
else
{
entryRatingStr = "0.0";
}
int sn = 0;
if (sailNo != null)
{
sn = sailNo.intValue();
}
JSONObject json = getRating(fleet, nat, sn, clazz);
String ratingSystem = json.optString(BoatInfo.RATINGSYSTEM);
if ("UNKNOWN".equals(ratingSystem))
{
return map;
}
Map<String, Object> m2 = new HashMap<>();
m2.putAll(map);
String listedRatingStr = json.optString(RaceEntry.RATING);
if (listedRatingStr != null && !listedRatingStr.isEmpty())
{
try
{
BigDecimal listedRating = new BigDecimal(listedRatingStr.replace(',', '.'));
m2.put(RaceEntry.RATING, listedRating);
BigDecimal entryRating = new BigDecimal(entryRatingStr.replace(',', '.'));
if (!entryRating.equals(listedRating))
{
String privateNotes = TextUtil.getString("RATING DIFFERS");
privateNotes = String.format(privateNotes, entryRating, listedRating);
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
else
{
String privateNotes = TextUtil.getString("RATING OK");
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
}
catch (NumberFormatException ex)
{
String privateNotes = TextUtil.getString("RATING DIFFERS");
privateNotes = String.format(privateNotes, entryRatingStr, listedRatingStr);
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
}
else
{
String privateNotes = TextUtil.getString("NO RATING");
m2.put(RaceEntry.PRIVATENOTES, privateNotes);
}
return m2;
}
private JSONObject getRating(String ratingSystem, String nat, int sailNo, String boatClass) throws IOException, JSONException
{
try
{
String path = "/race?RatingSystem=" + ratingSystem + "&Nat=" + nat + "&SailNo=" + sailNo + "&Class=" + boatClass;
URL url = new URL("http", server, path.replace(' ', '+'));
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "ASCII");
StringBuilder sb = new StringBuilder();
char[] cb = new char[256];
int rc = isr.read(cb);
while (rc != -1)
{
sb.append(cb, 0, rc);
rc = isr.read(cb);
}
return new JSONObject(sb.toString());
}
catch (MalformedURLException ex)
{
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
try
{
Properties properties = new Properties();
if (args.length == 0)
{
System.err.println("usage: ... <properties>");
System.exit(-1);
}
try (InputStream pFile = new FileInputStream(args[0]))
{
properties.load(pFile);
}
boolean savePassword = Boolean.valueOf(properties.getProperty(ServerProperties.SavePassword));
properties.remove(ServerProperties.SavePassword);
ServerProperties sp = new ServerProperties(properties);
sp.setSavePassword(savePassword);
DataObjectDialog<ServerProperties> dod = new DataObjectDialog<>(
null,
sp.getModel().hide(ServerProperties.Tables, ServerProperties.SupportsZonerSMS, ServerProperties.SuperUser),
sp);
if (dod.edit())
{
String[] server = sp.getServer().split(",");
RemoteAppEngine.init(server[0], sp.getUsername(), sp.getPassword());
DataStoreProxy dsp = new DataStoreProxy(properties);
dsp.start();
Admin r = new Admin(sp);
}
else
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
| Removed extra rating checking when downloading sailwave file | src/fi/hoski/remote/ui/Admin.java | Removed extra rating checking when downloading sailwave file |
|
Java | lgpl-2.1 | a180b7db2a511b760519f9f98a790d7c8ae9bf3e | 0 | adamretter/exist,lcahlander/exist,windauer/exist,wolfgangmm/exist,adamretter/exist,windauer/exist,eXist-db/exist,adamretter/exist,wolfgangmm/exist,lcahlander/exist,wolfgangmm/exist,dizzzz/exist,eXist-db/exist,eXist-db/exist,lcahlander/exist,adamretter/exist,adamretter/exist,windauer/exist,lcahlander/exist,dizzzz/exist,lcahlander/exist,windauer/exist,windauer/exist,wolfgangmm/exist,wolfgangmm/exist,eXist-db/exist,dizzzz/exist,eXist-db/exist,adamretter/exist,dizzzz/exist,dizzzz/exist,dizzzz/exist,lcahlander/exist,wolfgangmm/exist,windauer/exist,eXist-db/exist | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.storage.serializers;
import org.exist.Namespaces;
import org.exist.dom.persistent.AttrImpl;
import org.exist.dom.persistent.CDATASectionImpl;
import org.exist.dom.persistent.CommentImpl;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.DocumentTypeImpl;
import org.exist.dom.persistent.ElementImpl;
import org.exist.dom.persistent.IStoredNode;
import org.exist.dom.persistent.Match;
import org.exist.dom.persistent.NodeProxy;
import org.exist.dom.persistent.ProcessingInstructionImpl;
import org.exist.dom.QName;
import org.exist.dom.persistent.TextImpl;
import org.exist.numbering.NodeId;
import org.exist.storage.DBBroker;
import org.exist.util.Configuration;
import org.exist.util.serializer.AttrList;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.exist.storage.dom.INodeIterator;
import javax.xml.XMLConstants;
/**
* Serializer implementation for the native database backend.
*
* @author wolf
*/
public class NativeSerializer extends Serializer {
// private final static AttributesImpl EMPTY_ATTRIBUTES = new AttributesImpl();
private final static QName TEXT_ELEMENT = new QName("text", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName ATTRIB_ELEMENT = new QName("attribute", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName SOURCE_ATTRIB = new QName("source", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName ID_ATTRIB = new QName("id", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_ATTRIB = new QName("matches", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_OFFSET_ATTRIB = new QName("matches-offset", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_LENGTH_ATTRIB = new QName("matches-length", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static Pattern P_ZERO_VALUES = Pattern.compile("0(,0)?");
private final static Matcher M_ZERO_VALUES = P_ZERO_VALUES.matcher("");
public NativeSerializer(DBBroker broker, Configuration config) {
this(broker, config, null);
}
public NativeSerializer(DBBroker broker, Configuration config, List<String> chainOfReceivers) {
super(broker, config, chainOfReceivers);
}
protected void serializeToReceiver(NodeProxy p, boolean generateDocEvent, boolean checkAttributes)
throws SAXException {
if(Type.subTypeOf(p.getType(), Type.DOCUMENT) || p.getNodeId() == NodeId.DOCUMENT_NODE) {
serializeToReceiver(p.getOwnerDocument(), generateDocEvent);
return;
}
setDocument(p.getOwnerDocument());
if (generateDocEvent && !documentStarted) {
receiver.startDocument();
}
try(final INodeIterator domIter = broker.getNodeIterator(p)) {
serializeToReceiver(null, domIter, p.getOwnerDocument(), checkAttributes, p.getMatches(), new TreeSet<>());
} catch(final IOException e) {
LOG.warn("Unable to close node iterator", e);
}
if(generateDocEvent) {
receiver.endDocument();
}
}
protected void serializeToReceiver(DocumentImpl doc, boolean generateDocEvent) throws SAXException {
final long start = System.currentTimeMillis();
setDocument(doc);
final NodeList children = doc.getChildNodes();
if (generateDocEvent && !documentStarted) {
receiver.startDocument();
}
if (doc.getDoctype() != null){
if ("yes".equals(getProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "no"))) {
final DocumentTypeImpl docType = (DocumentTypeImpl)doc.getDoctype();
serializeToReceiver(docType, null, docType.getOwnerDocument(), true, null, new TreeSet<>());
}
}
// iterate through children
for (int i = 0; i < children.getLength(); i++) {
final IStoredNode<?> node = (IStoredNode<?>) children.item(i);
try(final INodeIterator domIter = broker.getNodeIterator(node)) {
domIter.next();
final NodeProxy p = new NodeProxy(node);
serializeToReceiver(node, domIter, (DocumentImpl) node.getOwnerDocument(),
true, p.getMatches(), new TreeSet<>());
} catch(final IOException ioe) {
LOG.warn("Unable to close node iterator", ioe);
}
}
if (generateDocEvent) {receiver.endDocument();}
if (LOG.isDebugEnabled())
{
LOG.debug("serializing document {} ({}) to SAX took {} msec", doc.getDocId(), doc.getURI(), System.currentTimeMillis() - start);}
}
protected void serializeToReceiver(IStoredNode node, INodeIterator iter,
DocumentImpl doc, boolean first, Match match, Set<String> namespaces) throws SAXException {
if (node == null && iter.hasNext()) {
node = iter.next();
}
if (node == null) {
return;
}
// char ch[];
String cdata;
switch (node.getNodeType()) {
case Node.ELEMENT_NODE:
receiver.setCurrentNode(node);
String defaultNS = null;
if (((ElementImpl) node).declaresNamespacePrefixes()) {
// declare namespaces used by this element
String prefix, uri;
for (final Iterator<String> i = ((ElementImpl) node).getPrefixes(); i.hasNext();) {
prefix = i.next();
if (prefix.isEmpty()) {
defaultNS = ((ElementImpl) node).getNamespaceForPrefix(prefix);
receiver.startPrefixMapping(XMLConstants.DEFAULT_NS_PREFIX, defaultNS);
namespaces.add(defaultNS);
} else {
uri = ((ElementImpl) node).getNamespaceForPrefix(prefix);
receiver.startPrefixMapping(prefix, uri);
namespaces.add(uri);
}
}
}
final String ns = defaultNS == null ? node.getNamespaceURI() : defaultNS;
if (ns != null && ns.length() > 0 && (!namespaces.contains(ns))) {
String prefix = node.getPrefix();
if(prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
receiver.startPrefixMapping(prefix, ns);
}
final AttrList attribs = new AttrList();
if ((first && showId == EXIST_ID_ELEMENT) || showId == EXIST_ID_ALL) {
attribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
/*
* This is a proposed fix-up that the serializer could do
* to make sure elements always have the namespace declarations
*
} else {
// This is fix-up for when the node has a namespace but there is no
// namespace declaration.
String elementNS = node.getNamespaceURI();
Node parent = node.getParentNode();
if (parent instanceof ElementImpl) {
ElementImpl parentElement = (ElementImpl)parent;
String declaredNS = parentElement.getNamespaceForPrefix(node.getPrefix());
if (elementNS!=null && declaredNS==null) {
// We need to declare the prefix as it was missed somehow
receiver.startPrefixMapping(node.getPrefix(), elementNS);
} else if (elementNS==null && declaredNS!=null) {
// We need to declare the default namespace to be the no namespace
receiver.startPrefixMapping(node.getPrefix(), elementNS);
} else if (!elementNS.equals(defaultNS)) {
// Same prefix but different namespace
receiver.startPrefixMapping(node.getPrefix(), elementNS);
}
} else if (elementNS!=null) {
// If the parent is the document, we must have a namespace
// declaration when there is a namespace URI.
receiver.startPrefixMapping(node.getPrefix(), elementNS);
}
*/
}
if (first && showId > 0) {
// String src = doc.getCollection().getName() + "/" + doc.getFileName();
attribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
final int children = node.getChildCount();
int count = 0;
IStoredNode child = null;
StringBuilder matchAttrCdata = null;
StringBuilder matchAttrOffsetsCdata = null;
StringBuilder matchAttrLengthsCdata = null;
while (count < children) {
child = iter.hasNext() ? iter.next() : null;
if (child != null && child.getNodeType() == Node.ATTRIBUTE_NODE) {
if ((getHighlightingMode() & TAG_ATTRIBUTE_MATCHES) == TAG_ATTRIBUTE_MATCHES && match != null && child.getNodeId().equals(match.getNodeId())) {
if(matchAttrCdata == null) {
matchAttrCdata = new StringBuilder();
matchAttrOffsetsCdata = new StringBuilder();
matchAttrLengthsCdata = new StringBuilder();
} else {
matchAttrCdata.append(",");
matchAttrOffsetsCdata.append(",");
matchAttrLengthsCdata.append(",");
}
matchAttrCdata.append(child.getQName().toString());
matchAttrOffsetsCdata.append(match.getOffset(0).getOffset());
matchAttrLengthsCdata.append(match.getOffset(0).getLength());
match = match.getNextMatch();
}
cdata = ((AttrImpl) child).getValue();
attribs.addAttribute(child.getQName(), cdata);
count++;
child.release();
} else {
break;
}
}
if(matchAttrCdata != null) {
attribs.addAttribute(MATCHES_ATTRIB, matchAttrCdata.toString());
//mask the full-text index which doesn't provide offset and length
M_ZERO_VALUES.reset(matchAttrOffsetsCdata);
final boolean offsetsIsZero = M_ZERO_VALUES.matches();
M_ZERO_VALUES.reset(matchAttrLengthsCdata);
final boolean lengthsIsZero = M_ZERO_VALUES.matches();
if(!offsetsIsZero && !lengthsIsZero) {
attribs.addAttribute(MATCHES_OFFSET_ATTRIB, matchAttrOffsetsCdata.toString());
attribs.addAttribute(MATCHES_LENGTH_ATTRIB, matchAttrLengthsCdata.toString());
}
}
receiver.setCurrentNode(node);
receiver.startElement(node.getQName(), attribs);
while (count < children) {
serializeToReceiver(child, iter, doc, false, match, namespaces);
if (++count < children) {
child = iter.hasNext() ? iter.next() : null;
} else
{break;}
}
receiver.setCurrentNode(node);
receiver.endElement(node.getQName());
if (((ElementImpl) node).declaresNamespacePrefixes()) {
for (final Iterator<String> i = ((ElementImpl) node).getPrefixes(); i.hasNext();) {
final String prefix = i.next();
receiver.endPrefixMapping(prefix);
}
}
if (ns != null && ns.length() > 0 && (!namespaces.contains(ns))) {
String prefix = node.getPrefix();
if(prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
receiver.endPrefixMapping(prefix);
}
node.release();
break;
case Node.TEXT_NODE:
if (first && createContainerElements) {
final AttrList tattribs = new AttrList();
if (showId > 0) {
tattribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
tattribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
receiver.startElement(TEXT_ELEMENT, tattribs);
}
receiver.setCurrentNode(node);
receiver.characters(((TextImpl) node).getXMLString());
if (first && createContainerElements)
{receiver.endElement(TEXT_ELEMENT);}
node.release();
break;
case Node.ATTRIBUTE_NODE:
if ((getHighlightingMode() & TAG_ATTRIBUTE_MATCHES) == TAG_ATTRIBUTE_MATCHES && match != null && node.getNodeId().equals(match.getNodeId())) {
//TODO(AR) do we need to expand attribute matches here also? see {@code matchAttrCdata} above
}
cdata = ((AttrImpl) node).getValue();
if(first) {
if (createContainerElements) {
final AttrList tattribs = new AttrList();
if (showId > 0) {
tattribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
tattribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
tattribs.addAttribute(node.getQName(), cdata);
receiver.startElement(ATTRIB_ELEMENT, tattribs);
receiver.endElement(ATTRIB_ELEMENT);
}
else {
if (this.outputProperties.getProperty("output-method") != null &&
"text".equals(this.outputProperties.getProperty("output-method"))) {
receiver.characters(node.getNodeValue());
} else {
LOG.warn("Error SENR0001: attribute '{}' has no parent element. While serializing document {}", node.getQName(), doc.getURI());
throw new SAXException("Error SENR0001: attribute '" + node.getQName() + "' has no parent element");
}
}
} else
{receiver.attribute(node.getQName(), cdata);}
node.release();
break;
case Node.DOCUMENT_TYPE_NODE:
final String systemId = ((DocumentTypeImpl) node).getSystemId();
final String publicId = ((DocumentTypeImpl) node).getPublicId();
final String name = ((DocumentTypeImpl) node).getName();
receiver.documentType(name, publicId, systemId);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
receiver.processingInstruction(
((ProcessingInstructionImpl) node).getTarget(),
((ProcessingInstructionImpl) node).getData());
node.release();
break;
case Node.COMMENT_NODE:
final String comment = ((CommentImpl) node).getData();
char data[] = new char[comment.length()];
comment.getChars(0, data.length, data, 0);
receiver.comment(data, 0, data.length);
node.release();
break;
case Node.CDATA_SECTION_NODE:
final String str = ((CDATASectionImpl)node).getData();
if (first)
{receiver.characters(str);}
else {
data = new char[str.length()];
str.getChars(0,str.length(), data, 0);
receiver.cdataSection(data, 0, data.length);
}
break;
//TODO : how to process other types ? -pb
}
}
}
| exist-core/src/main/java/org/exist/storage/serializers/NativeSerializer.java | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.storage.serializers;
import org.exist.Namespaces;
import org.exist.dom.persistent.AttrImpl;
import org.exist.dom.persistent.CDATASectionImpl;
import org.exist.dom.persistent.CommentImpl;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.DocumentTypeImpl;
import org.exist.dom.persistent.ElementImpl;
import org.exist.dom.persistent.IStoredNode;
import org.exist.dom.persistent.Match;
import org.exist.dom.persistent.NodeProxy;
import org.exist.dom.persistent.ProcessingInstructionImpl;
import org.exist.dom.QName;
import org.exist.dom.persistent.TextImpl;
import org.exist.numbering.NodeId;
import org.exist.storage.DBBroker;
import org.exist.util.Configuration;
import org.exist.util.serializer.AttrList;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.exist.storage.dom.INodeIterator;
import javax.xml.XMLConstants;
/**
* Serializer implementation for the native database backend.
*
* @author wolf
*/
public class NativeSerializer extends Serializer {
// private final static AttributesImpl EMPTY_ATTRIBUTES = new AttributesImpl();
private final static QName TEXT_ELEMENT = new QName("text", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName ATTRIB_ELEMENT = new QName("attribute", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName SOURCE_ATTRIB = new QName("source", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName ID_ATTRIB = new QName("id", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_ATTRIB = new QName("matches", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_OFFSET_ATTRIB = new QName("matches-offset", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static QName MATCHES_LENGTH_ATTRIB = new QName("matches-length", Namespaces.EXIST_NS, Namespaces.EXIST_NS_PREFIX);
private final static Pattern P_ZERO_VALUES = Pattern.compile("0(,0)?");
private final static Matcher M_ZERO_VALUES = P_ZERO_VALUES.matcher("");
public NativeSerializer(DBBroker broker, Configuration config) {
this(broker, config, null);
}
public NativeSerializer(DBBroker broker, Configuration config, List<String> chainOfReceivers) {
super(broker, config, chainOfReceivers);
}
protected void serializeToReceiver(NodeProxy p, boolean generateDocEvent, boolean checkAttributes)
throws SAXException {
if(Type.subTypeOf(p.getType(), Type.DOCUMENT) || p.getNodeId() == NodeId.DOCUMENT_NODE) {
serializeToReceiver(p.getOwnerDocument(), generateDocEvent);
return;
}
setDocument(p.getOwnerDocument());
if (generateDocEvent) {
receiver.startDocument();
}
try(final INodeIterator domIter = broker.getNodeIterator(p)) {
serializeToReceiver(null, domIter, p.getOwnerDocument(), checkAttributes, p.getMatches(), new TreeSet<>());
} catch(final IOException e) {
LOG.warn("Unable to close node iterator", e);
}
if(generateDocEvent) {
receiver.endDocument();
}
}
protected void serializeToReceiver(DocumentImpl doc, boolean generateDocEvent) throws SAXException {
final long start = System.currentTimeMillis();
setDocument(doc);
final NodeList children = doc.getChildNodes();
if (generateDocEvent && !documentStarted) {
receiver.startDocument();
}
if (doc.getDoctype() != null){
if ("yes".equals(getProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "no"))) {
final DocumentTypeImpl docType = (DocumentTypeImpl)doc.getDoctype();
serializeToReceiver(docType, null, docType.getOwnerDocument(), true, null, new TreeSet<>());
}
}
// iterate through children
for (int i = 0; i < children.getLength(); i++) {
final IStoredNode<?> node = (IStoredNode<?>) children.item(i);
try(final INodeIterator domIter = broker.getNodeIterator(node)) {
domIter.next();
final NodeProxy p = new NodeProxy(node);
serializeToReceiver(node, domIter, (DocumentImpl) node.getOwnerDocument(),
true, p.getMatches(), new TreeSet<>());
} catch(final IOException ioe) {
LOG.warn("Unable to close node iterator", ioe);
}
}
if (generateDocEvent) {receiver.endDocument();}
if (LOG.isDebugEnabled())
{
LOG.debug("serializing document {} ({}) to SAX took {} msec", doc.getDocId(), doc.getURI(), System.currentTimeMillis() - start);}
}
protected void serializeToReceiver(IStoredNode node, INodeIterator iter,
DocumentImpl doc, boolean first, Match match, Set<String> namespaces) throws SAXException {
if (node == null && iter.hasNext()) {
node = iter.next();
}
if (node == null) {
return;
}
// char ch[];
String cdata;
switch (node.getNodeType()) {
case Node.ELEMENT_NODE:
receiver.setCurrentNode(node);
String defaultNS = null;
if (((ElementImpl) node).declaresNamespacePrefixes()) {
// declare namespaces used by this element
String prefix, uri;
for (final Iterator<String> i = ((ElementImpl) node).getPrefixes(); i.hasNext();) {
prefix = i.next();
if (prefix.isEmpty()) {
defaultNS = ((ElementImpl) node).getNamespaceForPrefix(prefix);
receiver.startPrefixMapping(XMLConstants.DEFAULT_NS_PREFIX, defaultNS);
namespaces.add(defaultNS);
} else {
uri = ((ElementImpl) node).getNamespaceForPrefix(prefix);
receiver.startPrefixMapping(prefix, uri);
namespaces.add(uri);
}
}
}
final String ns = defaultNS == null ? node.getNamespaceURI() : defaultNS;
if (ns != null && ns.length() > 0 && (!namespaces.contains(ns))) {
String prefix = node.getPrefix();
if(prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
receiver.startPrefixMapping(prefix, ns);
}
final AttrList attribs = new AttrList();
if ((first && showId == EXIST_ID_ELEMENT) || showId == EXIST_ID_ALL) {
attribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
/*
* This is a proposed fix-up that the serializer could do
* to make sure elements always have the namespace declarations
*
} else {
// This is fix-up for when the node has a namespace but there is no
// namespace declaration.
String elementNS = node.getNamespaceURI();
Node parent = node.getParentNode();
if (parent instanceof ElementImpl) {
ElementImpl parentElement = (ElementImpl)parent;
String declaredNS = parentElement.getNamespaceForPrefix(node.getPrefix());
if (elementNS!=null && declaredNS==null) {
// We need to declare the prefix as it was missed somehow
receiver.startPrefixMapping(node.getPrefix(), elementNS);
} else if (elementNS==null && declaredNS!=null) {
// We need to declare the default namespace to be the no namespace
receiver.startPrefixMapping(node.getPrefix(), elementNS);
} else if (!elementNS.equals(defaultNS)) {
// Same prefix but different namespace
receiver.startPrefixMapping(node.getPrefix(), elementNS);
}
} else if (elementNS!=null) {
// If the parent is the document, we must have a namespace
// declaration when there is a namespace URI.
receiver.startPrefixMapping(node.getPrefix(), elementNS);
}
*/
}
if (first && showId > 0) {
// String src = doc.getCollection().getName() + "/" + doc.getFileName();
attribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
final int children = node.getChildCount();
int count = 0;
IStoredNode child = null;
StringBuilder matchAttrCdata = null;
StringBuilder matchAttrOffsetsCdata = null;
StringBuilder matchAttrLengthsCdata = null;
while (count < children) {
child = iter.hasNext() ? iter.next() : null;
if (child != null && child.getNodeType() == Node.ATTRIBUTE_NODE) {
if ((getHighlightingMode() & TAG_ATTRIBUTE_MATCHES) == TAG_ATTRIBUTE_MATCHES && match != null && child.getNodeId().equals(match.getNodeId())) {
if(matchAttrCdata == null) {
matchAttrCdata = new StringBuilder();
matchAttrOffsetsCdata = new StringBuilder();
matchAttrLengthsCdata = new StringBuilder();
} else {
matchAttrCdata.append(",");
matchAttrOffsetsCdata.append(",");
matchAttrLengthsCdata.append(",");
}
matchAttrCdata.append(child.getQName().toString());
matchAttrOffsetsCdata.append(match.getOffset(0).getOffset());
matchAttrLengthsCdata.append(match.getOffset(0).getLength());
match = match.getNextMatch();
}
cdata = ((AttrImpl) child).getValue();
attribs.addAttribute(child.getQName(), cdata);
count++;
child.release();
} else {
break;
}
}
if(matchAttrCdata != null) {
attribs.addAttribute(MATCHES_ATTRIB, matchAttrCdata.toString());
//mask the full-text index which doesn't provide offset and length
M_ZERO_VALUES.reset(matchAttrOffsetsCdata);
final boolean offsetsIsZero = M_ZERO_VALUES.matches();
M_ZERO_VALUES.reset(matchAttrLengthsCdata);
final boolean lengthsIsZero = M_ZERO_VALUES.matches();
if(!offsetsIsZero && !lengthsIsZero) {
attribs.addAttribute(MATCHES_OFFSET_ATTRIB, matchAttrOffsetsCdata.toString());
attribs.addAttribute(MATCHES_LENGTH_ATTRIB, matchAttrLengthsCdata.toString());
}
}
receiver.setCurrentNode(node);
receiver.startElement(node.getQName(), attribs);
while (count < children) {
serializeToReceiver(child, iter, doc, false, match, namespaces);
if (++count < children) {
child = iter.hasNext() ? iter.next() : null;
} else
{break;}
}
receiver.setCurrentNode(node);
receiver.endElement(node.getQName());
if (((ElementImpl) node).declaresNamespacePrefixes()) {
for (final Iterator<String> i = ((ElementImpl) node).getPrefixes(); i.hasNext();) {
final String prefix = i.next();
receiver.endPrefixMapping(prefix);
}
}
if (ns != null && ns.length() > 0 && (!namespaces.contains(ns))) {
String prefix = node.getPrefix();
if(prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
receiver.endPrefixMapping(prefix);
}
node.release();
break;
case Node.TEXT_NODE:
if (first && createContainerElements) {
final AttrList tattribs = new AttrList();
if (showId > 0) {
tattribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
tattribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
receiver.startElement(TEXT_ELEMENT, tattribs);
}
receiver.setCurrentNode(node);
receiver.characters(((TextImpl) node).getXMLString());
if (first && createContainerElements)
{receiver.endElement(TEXT_ELEMENT);}
node.release();
break;
case Node.ATTRIBUTE_NODE:
if ((getHighlightingMode() & TAG_ATTRIBUTE_MATCHES) == TAG_ATTRIBUTE_MATCHES && match != null && node.getNodeId().equals(match.getNodeId())) {
//TODO(AR) do we need to expand attribute matches here also? see {@code matchAttrCdata} above
}
cdata = ((AttrImpl) node).getValue();
if(first) {
if (createContainerElements) {
final AttrList tattribs = new AttrList();
if (showId > 0) {
tattribs.addAttribute(ID_ATTRIB, node.getNodeId().toString());
tattribs.addAttribute(SOURCE_ATTRIB, doc.getFileURI().toString());
}
tattribs.addAttribute(node.getQName(), cdata);
receiver.startElement(ATTRIB_ELEMENT, tattribs);
receiver.endElement(ATTRIB_ELEMENT);
}
else {
if (this.outputProperties.getProperty("output-method") != null &&
"text".equals(this.outputProperties.getProperty("output-method"))) {
receiver.characters(node.getNodeValue());
} else {
LOG.warn("Error SENR0001: attribute '{}' has no parent element. While serializing document {}", node.getQName(), doc.getURI());
throw new SAXException("Error SENR0001: attribute '" + node.getQName() + "' has no parent element");
}
}
} else
{receiver.attribute(node.getQName(), cdata);}
node.release();
break;
case Node.DOCUMENT_TYPE_NODE:
final String systemId = ((DocumentTypeImpl) node).getSystemId();
final String publicId = ((DocumentTypeImpl) node).getPublicId();
final String name = ((DocumentTypeImpl) node).getName();
receiver.documentType(name, publicId, systemId);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
receiver.processingInstruction(
((ProcessingInstructionImpl) node).getTarget(),
((ProcessingInstructionImpl) node).getData());
node.release();
break;
case Node.COMMENT_NODE:
final String comment = ((CommentImpl) node).getData();
char data[] = new char[comment.length()];
comment.getChars(0, data.length, data, 0);
receiver.comment(data, 0, data.length);
node.release();
break;
case Node.CDATA_SECTION_NODE:
final String str = ((CDATASectionImpl)node).getData();
if (first)
{receiver.characters(str);}
else {
data = new char[str.length()];
str.getChars(0,str.length(), data, 0);
receiver.cdataSection(data, 0, data.length);
}
break;
//TODO : how to process other types ? -pb
}
}
}
| [BugFix] RPC startDocument
| exist-core/src/main/java/org/exist/storage/serializers/NativeSerializer.java | [BugFix] RPC startDocument |
|
Java | lgpl-2.1 | 4e405e53a031c2ee8b701fd06b3a354f4473d4bb | 0 | julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine | package org.flymine.postprocess;
/*
* Copyright (C) 2002-2004 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.Collections;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.seq.DNATools;
import org.intermine.objectstore.query.*;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.DynamicUtil;
import org.intermine.objectstore.query.ResultsRow;
import org.flymine.model.genomic.*;
import org.apache.log4j.Logger;
/**
* Transfer sequences from the Contig objects to the other objects that are located on the Contigs
* and to the objects that the Contigs are located on (eg. Chromosomes).
*
* @author Kim Rutherford
*/
public class TransferSequences
{
private static final Logger LOG = Logger.getLogger(TransferSequences.class);
protected ObjectStoreWriter osw;
/**
* Create a new TransferSequences object from the given ObjectStoreWriter
* @param osw writer on genomic ObjectStore
*/
public TransferSequences (ObjectStoreWriter osw) {
this.osw = osw;
}
/**
* Copy the residues from the Contigs to the Chromosome in the ObjectStoreWriter that was
* passed to the constructor
* @throws Exception if there are problems with the transfer
*/
public void transferSequences()
throws Exception {
osw.beginTransaction();
transferToChromosome();
transferToLocatedSequenceFeatures();
transferToTranscripts();
osw.commitTransaction();
}
/**
* Copy the contig sequences to the appropriate place in the chromosome sequence and store a
* Sequence object for each Chromosome.
* Returns a Map from chromosome ID to a char array of the chromosome sequence.
*/
private void transferToChromosome()
throws IllegalSymbolException, IllegalAlphabetException, ObjectStoreException {
ObjectStore os = osw.getObjectStore();
Iterator resIter =
CalculateLocationsUtil.findLocations(os, Chromosome.class, Contig.class, true);
// keep the new Chromosome sequences in a char[] for speed - convert to String at the end
// this is a Map from Chromosome to char[]
Map seqArrayMap = new HashMap();
Integer currentChrId = null;
char[] currentChrBases = null;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
Chromosome chr = (Chromosome) os.getObjectById(chrId);
Contig contig = (Contig) rr.get(1);
Location contigOnChrLocation = (Location) rr.get(2);
if (currentChrId == null || !chrId.equals(currentChrId)) {
if (currentChrId != null) {
storeChromosome(chr, currentChrBases);
}
currentChrBases = new char[chr.getLength().intValue()];
// fill with '.' so we can see the parts of the Chromosome sequence that haven't
// been set
for (int i = 0; i < currentChrBases.length; i++) {
currentChrBases[i] = '.';
}
currentChrId = chrId;
}
copySeqArray(currentChrBases, contig.getSequence().getSequence(), contigOnChrLocation);
}
Chromosome chr = (Chromosome) os.getObjectById(currentChrId);
storeChromosome(chr, currentChrBases);
}
private void storeChromosome(Chromosome chr, char [] chrBases) throws ObjectStoreException {
Sequence sequence =
(Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
sequence.setSequence(new String(chrBases));
chr.setSequence(sequence);
osw.store(chr);
osw.store(sequence);
}
/**
* Use the Location relations to copy the sequence from the Chromosomes to every
* LocatedSequenceFeature that is located on a Chromosome and which doesn't already have a
* sequence (ie. don't copy to Contig).
*/
private void transferToLocatedSequenceFeatures()
throws IllegalSymbolException, IllegalAlphabetException, ObjectStoreException {
ObjectStore os = osw.getObjectStore();
Iterator resIter =
CalculateLocationsUtil.findLocations(os, Chromosome.class,
LocatedSequenceFeature.class, true);
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1);
Location locationOnChr = (Location) rr.get(2);
if (feature.getSequence() != null) {
// probably a contig
continue;
}
Chromosome chr = (Chromosome) os.getObjectById(chrId);
Sequence chromosomeSequence = chr.getSequence();
String featureSeq = getSubSequence(chromosomeSequence, locationOnChr);
Sequence sequence =
(Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
sequence.setSequence(featureSeq);
feature.setSequence(sequence);
osw.store(feature);
osw.store(sequence);
}
}
private String getSubSequence(Sequence chromosomeSequence, Location locationOnChr)
throws IllegalSymbolException, IllegalAlphabetException {
int charsToCopy =
locationOnChr.getEnd().intValue() - locationOnChr.getStart().intValue() + 1;
String chromosomeSequenceString = chromosomeSequence.getSequence();
int startPos = locationOnChr.getStart().intValue() - 1;
int endPos = startPos + charsToCopy;
String subSeqString = new String(chromosomeSequenceString.substring(startPos, endPos));
if (locationOnChr.getStrand().intValue() == -1) {
SymbolList symbolList = DNATools.createDNA(subSeqString);
symbolList = DNATools.reverseComplement(symbolList);
subSeqString = symbolList.seqString();
}
return subSeqString;
}
private void copySeqArray(char[] destArray, String sourceSequence, Location contigOnChrLocation)
throws IllegalSymbolException, IllegalAlphabetException {
char[] sourceArray;
if (contigOnChrLocation.getStrand().intValue() == -1) {
SymbolList symbolList = DNATools.createDNA(sourceSequence);
symbolList = DNATools.reverseComplement(symbolList);
sourceArray = symbolList.seqString().toCharArray();
} else {
sourceArray = sourceSequence.toCharArray();
}
int charsToCopy =
contigOnChrLocation.getEnd().intValue() - contigOnChrLocation.getStart().intValue() + 1;
System.arraycopy(sourceArray, 0,
destArray, contigOnChrLocation.getStart().intValue() - 1, charsToCopy);
}
/**
* For each Transcript, join and transfer the sequences to the parent Transcript.
*/
private void transferToTranscripts() {
ObjectStore os = osw.getObjectStore();
Query q = new Query();
q.setDistinct(false);
QueryClass qcTranscript = new QueryClass(Transcript.class);
q.addFrom(qcTranscript);
q.addToSelect(qcTranscript);
QueryClass qcExon = new QueryClass(Exon.class);
q.addFrom(qcExon);
q.addToSelect(qcExon);
// add to query so the Exon.getSequence() is (mostly) fast
QueryClass qcExonSequence = new QueryClass(Sequence.class);
q.addFrom(qcExonSequence);
q.addToSelect(qcExonSequence);
q.addToOrderBy(qcTranscript);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference exonRef = new QueryCollectionReference(qcTranscript, "exons");
ContainsConstraint cc1 = new ContainsConstraint(exonRef, ConstraintOp.CONTAINS, qcExon);
cs.addConstraint(cc1);
QueryObjectReference sequenceRef = new QueryObjectReference(qcExon, "sequence");
ContainsConstraint cc2 =
new ContainsConstraint(sequenceRef, ConstraintOp.CONTAINS, qcExonSequence);
cs.addConstraint(cc2);
q.setConstraint(cs);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(10000);
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
// org.intermine.web.LogMe.log("i", "next: " + resIter.next());
}
}
}
| flymine/model/genomic/src/java/org/flymine/postprocess/TransferSequences.java | package org.flymine.postprocess;
/*
* Copyright (C) 2002-2004 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.Collections;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.seq.DNATools;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.util.DynamicUtil;
import org.flymine.model.genomic.*;
import org.apache.log4j.Logger;
/**
* Transfer sequences from the Contig objects to the other objects that are located on the Contigs
* and to the objects that the Contigs are located on (eg. Chromosomes).
*
* @author Kim Rutherford
*/
public class TransferSequences
{
private static final Logger LOG = Logger.getLogger(TransferSequences.class);
protected ObjectStoreWriter osw;
/**
* Create a new TransferSequences object from the given ObjectStoreWriter
* @param osw writer on genomic ObjectStore
*/
public TransferSequences (ObjectStoreWriter osw) {
this.osw = osw;
}
/**
* Copy the residues from the Contigs to the Chromosome in the ObjectStoreWriter that was
* passed to the constructor
* @throws Exception if there are problems with the transfer
*/
public void transferSequences()
throws Exception {
osw.beginTransaction();
Map seqArrayMap = transferToChromosome();
transferToLocatedSequenceFeatures(seqArrayMap);
osw.commitTransaction();
}
private Map transferToChromosome()
throws IllegalSymbolException, IllegalAlphabetException, ObjectStoreException {
ObjectStore os = osw.getObjectStore();
Iterator resIter =
CalculateLocationsUtil.findLocations(os, Chromosome.class, Contig.class, true);
// keep the new Chromosome sequences in a char[] for speed - convert to String at the end
// this is a Map from Chromosome to char[]
Map seqArrayMap = new HashMap();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
Chromosome chr = (Chromosome) os.getObjectById(chrId);
Contig contig = (Contig) rr.get(1);
Location contigOnChrLocation = (Location) rr.get(2);
char[] chrSequence;
if (seqArrayMap.get(chrId) == null) {
chrSequence = new char[chr.getLength().intValue()];
// fill with '.' so we can see the parts of the Chromosome sequence that haven't
// been set
for (int i = 0; i < chrSequence.length; i++) {
chrSequence[i] = '.';
}
seqArrayMap.put(chrId, chrSequence);
} else {
chrSequence = (char[]) seqArrayMap.get(chrId);
}
copySeqArray(chrSequence, contig.getSequence().getSequence(),
contigOnChrLocation);
}
// XXX - Chromosome needs a residues field
//
// // set the Chromosome residue fields
// Iterator iter = seqArrayMap.keySet().iterator();
// while (iter.hasNext()) {
// Chromosome chr = (Chromosome) os.getObjectById((Integer) iter.next());
// chr.setResidues(new String((char[]) seqArrayMap(chr)));
// osw.store(chr);
// }
return seqArrayMap;
}
private void transferToLocatedSequenceFeatures(Map seqArrayMap)
throws IllegalSymbolException, IllegalAlphabetException, ObjectStoreException {
ObjectStore os = osw.getObjectStore();
Iterator resIter =
CalculateLocationsUtil.findLocations(os, Chromosome.class,
LocatedSequenceFeature.class, true);
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1);
Location locationOnChr = (Location) rr.get(2);
char[] chrSequence = (char[]) seqArrayMap.get(chrId);
String featureSeq = getSubSequence(chrSequence, locationOnChr);
Sequence seq =
(Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
seq.setSequence(featureSeq);
feature.setSequence(seq);
osw.store(seq);
osw.store(feature);
}
}
private String getSubSequence(char[] chrSequence, Location locationOnChr)
throws IllegalSymbolException, IllegalAlphabetException {
int charsToCopy =
locationOnChr.getEnd().intValue() - locationOnChr.getStart().intValue() + 1;
String subSeqString =
new String(chrSequence, locationOnChr.getStart().intValue() - 1, charsToCopy);
if (locationOnChr.getStrand().intValue() == -1) {
SymbolList symbolList = DNATools.createDNA(subSeqString);
symbolList = DNATools.reverseComplement(symbolList);
subSeqString = symbolList.seqString();
}
return subSeqString;
}
private void copySeqArray(char[] destArray, String sourceSequence, Location contigOnChrLocation)
throws IllegalSymbolException, IllegalAlphabetException {
char[] sourceArray;
if (contigOnChrLocation.getStrand().intValue() == -1) {
SymbolList symbolList = DNATools.createDNA(sourceSequence);
symbolList = DNATools.reverseComplement(symbolList);
sourceArray = symbolList.seqString().toCharArray();
} else {
sourceArray = sourceSequence.toCharArray();
}
int charsToCopy =
contigOnChrLocation.getEnd().intValue() - contigOnChrLocation.getStart().intValue() + 1;
System.arraycopy(sourceArray, 0,
destArray, contigOnChrLocation.getStart().intValue() - 1, charsToCopy);
}
}
| Model change: "residues" attribute is now a "sequence" reference.
transferToChromosome() now uses less memory by saving holding a reference to
one Chromosome sequence at a time.
Former-commit-id: 4327d8e672561dc658f87548decb88e1afe18061 | flymine/model/genomic/src/java/org/flymine/postprocess/TransferSequences.java | Model change: "residues" attribute is now a "sequence" reference. transferToChromosome() now uses less memory by saving holding a reference to one Chromosome sequence at a time. |
|
Java | lgpl-2.1 | 41b2785010d67c7cd6ef8231d351cc8cd4063b30 | 0 | jimregan/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.*;
import org.languagetool.rules.fr.*;
import org.languagetool.synthesis.FrenchSynthesizer;
import org.languagetool.synthesis.Synthesizer;
import org.languagetool.tagging.Tagger;
import org.languagetool.tagging.disambiguation.Disambiguator;
import org.languagetool.tagging.disambiguation.fr.FrenchHybridDisambiguator;
import org.languagetool.tagging.fr.FrenchTagger;
import org.languagetool.tokenizers.SRXSentenceTokenizer;
import org.languagetool.tokenizers.SentenceTokenizer;
import org.languagetool.tokenizers.Tokenizer;
import org.languagetool.tokenizers.fr.FrenchWordTokenizer;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class French extends Language implements AutoCloseable {
private LanguageModel languageModel;
@Override
public SentenceTokenizer createDefaultSentenceTokenizer() {
return new SRXSentenceTokenizer(this);
}
@Override
public String getName() {
return "French";
}
@Override
public String getShortCode() {
return "fr";
}
@Override
public String[] getCountries() {
return new String[]{"FR", "", "BE", "CH", "CA", "LU", "MC", "CM",
"CI", "HT", "ML", "SN", "CD", "MA", "RE"};
}
@NotNull
@Override
public Tagger createDefaultTagger() {
return new FrenchTagger();
}
@Nullable
@Override
public Synthesizer createDefaultSynthesizer() {
return new FrenchSynthesizer(this);
}
@Override
public Tokenizer createDefaultWordTokenizer() {
return new FrenchWordTokenizer();
}
@Override
public Disambiguator createDefaultDisambiguator() {
return new FrenchHybridDisambiguator();
}
@Override
public Contributor[] getMaintainers() {
return new Contributor[] {
Contributors.DOMINIQUE_PELLE
};
}
@Override
public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {
return Arrays.asList(
new CommaWhitespaceRule(messages, false),
new DoublePunctuationRule(messages),
new GenericUnpairedBracketsRule(messages,
Arrays.asList("[", "(", "{" /*"«", "‘"*/),
Arrays.asList("]", ")", "}"
/*"»", French dialog can contain multiple sentences. */
/*"’" used in "d’arm" and many other words */)),
new MorfologikFrenchSpellerRule(messages, this, userConfig, altLanguages),
new UppercaseSentenceStartRule(messages, this),
new MultipleWhitespaceRule(messages, this),
new SentenceWhitespaceRule(messages),
new LongSentenceRule(messages, userConfig, 40, true, true),
new LongParagraphRule(messages, this, userConfig),
// specific to French:
new CompoundRule(messages),
new QuestionWhitespaceStrictRule(messages, this),
new QuestionWhitespaceRule(messages, this),
new SimpleReplaceRule(messages),
new AnglicismReplaceRule(messages)
);
}
@Override
public List<Rule> getRelevantRulesGlobalConfig(ResourceBundle messages, GlobalConfig globalConfig, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {
List<Rule> rules = new ArrayList<>();
if (globalConfig != null && globalConfig.getGrammalecteServer() != null) {
rules.add(new GrammalecteRule(messages, globalConfig));
}
return rules;
}
/** @since 3.1 */
@Override
public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException {
return Arrays.asList(
new FrenchConfusionProbabilityRule(messages, languageModel, this)
);
}
/** @since 3.1 */
@Override
public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException {
languageModel = initLanguageModel(indexDir, languageModel);
return languageModel;
}
/** @since 5.1 */
@Override
public String getOpeningDoubleQuote() {
return "«";
}
/** @since 5.1 */
@Override
public String getClosingDoubleQuote() {
return "»";
}
/** @since 5.1 */
@Override
public String getOpeningSingleQuote() {
return "‘";
}
/** @since 5.1 */
@Override
public String getClosingSingleQuote() {
return "’";
}
/** @since 5.1 */
@Override
public boolean isAdvancedTypographyEnabled() {
return true;
}
@Override
public String toAdvancedTypography (String input) {
String output = super.toAdvancedTypography(input);
// special cases: apostrophe + quotation marks
String beforeApostrophe = "([cjnmtsldCJNMTSLD]|qu|jusqu|lorsqu|puisqu|quoiqu|Qu|Jusqu|Lorsqu|Puisqu|Quoiqu|QU|JUSQU|LORSQU|PUISQU|QUOIQU)";
output = output.replaceAll("(\\b"+beforeApostrophe+")'", "$1’");
output = output.replaceAll("(\\b"+beforeApostrophe+")’\"", "$1’" + getOpeningDoubleQuote());
output = output.replaceAll("(\\b"+beforeApostrophe+")’'", "$1’" + getOpeningSingleQuote());
// non-breaking (thin) space
// according to https://fr.wikipedia.org/wiki/Espace_ins%C3%A9cable#En_France
output = output.replaceAll("\u00a0;", "\u202f;");
output = output.replaceAll("\u00a0!", "\u202f!");
output = output.replaceAll("\u00a0\\?", "\u202f?");
output = output.replaceAll(";", "\u202f;");
output = output.replaceAll("!", "\u202f!");
output = output.replaceAll("\\?", "\u202f?");
output = output.replaceAll(":", "\u00a0:");
output = output.replaceAll("»", "\u00a0»");
output = output.replaceAll("«", "«\u00a0");
//remove duplicate spaces
output = output.replaceAll("\u00a0\u00a0", "\u00a0");
output = output.replaceAll("\u202f\u202f", "\u202f");
output = output.replaceAll(" ", " ");
output = output.replaceAll("\u00a0 ", "\u00a0");
output = output.replaceAll(" \u00a0", "\u00a0");
output = output.replaceAll(" \u202f", "\u202f");
output = output.replaceAll("\u202f ", "\u202f");
return output;
}
/**
* Closes the language model, if any.
* @since 3.1
*/
@Override
public void close() throws Exception {
if (languageModel != null) {
languageModel.close();
}
}
@Override
public LanguageMaintainedState getMaintainedState() {
return LanguageMaintainedState.ActivelyMaintained;
}
@Override
protected int getPriorityForId(String id) {
switch (id) {
case "FR_COMPOUNDS": return 500; // greater than agreement rules
case "AGREEMENT_EXCEPTIONS": return 100; // greater than D_N
case "EXPRESSIONS_VU": return 100; // greater than A_ACCENT_A
case "SA_CA": return 100; // greater than D_N
case "MA": return 100; // greater than D_J
case "SON_SONT": return 100; // greater than D_J
case "JE_TES": return 100; // greater than D_J
case "A_INFINITIF": return 100;
case "ON_ONT": return 100; // greater than PRONSUJ_NONVERBE
case "LEURS_LEUR": return 100; // greater than N_V
case "DU_DU": return 100; // greater than DU_LE
case "ACCORD_CHAQUE": return 100; // greater than ACCORD_NOMBRE
case "CEST_A_DIRE": return 100; // greater than A_A_ACCENT
case "A_VERBE_INFINITIF": return 20; // greater than PRONSUJ_NONVERBE
case "ESPACE_UNITES": return 10; // needs to have higher priority than spell checker
case "BYTES": return 10; // needs to be higher than spell checker for 10MB style matches
case "Y_A": return 10; // needs to be higher than spell checker for style suggestion
case "A_A_ACCENT": return 10; // triggers false alarms for IL_FAUT_INF if there is no a/à correction
case "A_ACCENT_A": return 10; // greater than PRONSUJ_NONVERBE
case "JE_M_APPEL": return 10; // override NON_V
case "ACCORD_R_PERS_VERBE": return 10; // match before POSER_UNE_QUESTION
case "JE_SUI": return 10; // needs higher priority than spell checker
//case "D_N": return 1; // needs to have higher priority than agreement postponed adj | Commented out because many other rules should be higher
//case "ACCORD_COULEUR": return 1; // needs to have higher priority than agreement postponed adj
case "CONFUSION_PAR_PART": return -1; // turn off completely when PART_OU_PAR is activated
case "FR_SIMPLE_REPLACE": return -10;
case "IMP_PRON": return -10; // less than D_N
case "PREP_V": return -20;
case "TOO_LONG_PARAGRAPH": return -15;
case "VERB_PRONOUN": return -50; // greater than FR_SPELLING_RULE; less than ACCORD_V_QUESTION
case "AGREEMENT_POSTPONED_ADJ": return -50;
case "FR_SPELLING_RULE": return -100;
case "ET_SENT_START": return -151; // lower than grammalecte rules
case "MAIS_SENT_START": return -151; // lower than grammalecte rules
case "ELISION": return -200; // should be lower in priority than spell checker
case "UPPERCASE_SENTENCE_START": return -300;
case "FRENCH_WHITESPACE_STRICT": return -350; // picky; if on, it should overwrite FRENCH_WHITESPACE
case "FRENCH_WHITESPACE": return -400; // lesser than UPPERCASE_SENTENCE_START and FR_SPELLING_RULE
}
if (id.startsWith("grammalecte_")) {
return -150;
}
return super.getPriorityForId(id);
}
}
| languagetool-language-modules/fr/src/main/java/org/languagetool/language/French.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.*;
import org.languagetool.rules.fr.*;
import org.languagetool.synthesis.FrenchSynthesizer;
import org.languagetool.synthesis.Synthesizer;
import org.languagetool.tagging.Tagger;
import org.languagetool.tagging.disambiguation.Disambiguator;
import org.languagetool.tagging.disambiguation.fr.FrenchHybridDisambiguator;
import org.languagetool.tagging.fr.FrenchTagger;
import org.languagetool.tokenizers.SRXSentenceTokenizer;
import org.languagetool.tokenizers.SentenceTokenizer;
import org.languagetool.tokenizers.Tokenizer;
import org.languagetool.tokenizers.fr.FrenchWordTokenizer;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class French extends Language implements AutoCloseable {
private LanguageModel languageModel;
@Override
public SentenceTokenizer createDefaultSentenceTokenizer() {
return new SRXSentenceTokenizer(this);
}
@Override
public String getName() {
return "French";
}
@Override
public String getShortCode() {
return "fr";
}
@Override
public String[] getCountries() {
return new String[]{"FR", "", "BE", "CH", "CA", "LU", "MC", "CM",
"CI", "HT", "ML", "SN", "CD", "MA", "RE"};
}
@NotNull
@Override
public Tagger createDefaultTagger() {
return new FrenchTagger();
}
@Nullable
@Override
public Synthesizer createDefaultSynthesizer() {
return new FrenchSynthesizer(this);
}
@Override
public Tokenizer createDefaultWordTokenizer() {
return new FrenchWordTokenizer();
}
@Override
public Disambiguator createDefaultDisambiguator() {
return new FrenchHybridDisambiguator();
}
@Override
public Contributor[] getMaintainers() {
return new Contributor[] {
Contributors.DOMINIQUE_PELLE
};
}
@Override
public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {
return Arrays.asList(
new CommaWhitespaceRule(messages, false),
new DoublePunctuationRule(messages),
new GenericUnpairedBracketsRule(messages,
Arrays.asList("[", "(", "{" /*"«", "‘"*/),
Arrays.asList("]", ")", "}"
/*"»", French dialog can contain multiple sentences. */
/*"’" used in "d’arm" and many other words */)),
new MorfologikFrenchSpellerRule(messages, this, userConfig, altLanguages),
new UppercaseSentenceStartRule(messages, this),
new MultipleWhitespaceRule(messages, this),
new SentenceWhitespaceRule(messages),
new LongSentenceRule(messages, userConfig, 40, true, true),
new LongParagraphRule(messages, this, userConfig),
// specific to French:
new CompoundRule(messages),
new QuestionWhitespaceStrictRule(messages, this),
new QuestionWhitespaceRule(messages, this),
new SimpleReplaceRule(messages),
new AnglicismReplaceRule(messages)
);
}
@Override
public List<Rule> getRelevantRulesGlobalConfig(ResourceBundle messages, GlobalConfig globalConfig, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {
List<Rule> rules = new ArrayList<>();
if (globalConfig != null && globalConfig.getGrammalecteServer() != null) {
rules.add(new GrammalecteRule(messages, globalConfig));
}
return rules;
}
/** @since 3.1 */
@Override
public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException {
return Arrays.asList(
new FrenchConfusionProbabilityRule(messages, languageModel, this)
);
}
/** @since 3.1 */
@Override
public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException {
languageModel = initLanguageModel(indexDir, languageModel);
return languageModel;
}
/** @since 5.1 */
@Override
public String getOpeningDoubleQuote() {
return "«";
}
/** @since 5.1 */
@Override
public String getClosingDoubleQuote() {
return "»";
}
/** @since 5.1 */
@Override
public String getOpeningSingleQuote() {
return "‘";
}
/** @since 5.1 */
@Override
public String getClosingSingleQuote() {
return "’";
}
/** @since 5.1 */
@Override
public boolean isAdvancedTypographyEnabled() {
return true;
}
@Override
public String toAdvancedTypography (String input) {
String output = super.toAdvancedTypography(input);
// special cases: apostrophe + quotation marks
String beforeApostrophe = "([cjnmtsldCJNMTSLD]|qu|jusqu|lorsqu|puisqu|quoiqu|Qu|Jusqu|Lorsqu|Puisqu|Quoiqu|QU|JUSQU|LORSQU|PUISQU|QUOIQU)";
output = output.replaceAll("(\\b"+beforeApostrophe+")'", "$1’");
output = output.replaceAll("(\\b"+beforeApostrophe+")’\"", "$1’" + getOpeningDoubleQuote());
output = output.replaceAll("(\\b"+beforeApostrophe+")’'", "$1’" + getOpeningSingleQuote());
// non-breaking (thin) space
// according to https://fr.wikipedia.org/wiki/Espace_ins%C3%A9cable#En_France
output = output.replaceAll("\u00a0;", "\u202f;");
output = output.replaceAll("\u00a0!", "\u202f!");
output = output.replaceAll("\u00a0\\?", "\u202f?");
output = output.replaceAll(";", "\u202f;");
output = output.replaceAll("!", "\u202f!");
output = output.replaceAll("\\?", "\u202f?");
output = output.replaceAll(":", "\u00a0:");
output = output.replaceAll("»", "\u00a0»");
output = output.replaceAll("«", "«\u00a0");
//remove duplicate spaces
output = output.replaceAll("\u00a0\u00a0", "\u00a0");
output = output.replaceAll("\u202f\u202f", "\u202f");
output = output.replaceAll(" ", " ");
output = output.replaceAll("\u00a0 ", "\u00a0");
output = output.replaceAll(" \u00a0", "\u00a0");
output = output.replaceAll(" \u202f", "\u202f");
output = output.replaceAll("\u202f ", "\u202f");
return output;
}
/**
* Closes the language model, if any.
* @since 3.1
*/
@Override
public void close() throws Exception {
if (languageModel != null) {
languageModel.close();
}
}
@Override
public LanguageMaintainedState getMaintainedState() {
return LanguageMaintainedState.ActivelyMaintained;
}
@Override
protected int getPriorityForId(String id) {
switch (id) {
case "FR_COMPOUNDS": return 500; // greater than agreement rules
case "AGREEMENT_EXCEPTIONS": return 100; // greater than D_N
case "EXPRESSIONS_VU": return 100; // greater than A_ACCENT_A
case "SA_CA": return 100; // greater than D_N
case "MA": return 100; // greater than D_J
case "SON_SONT": return 100; // greater than D_J
case "JE_TES": return 100; // greater than D_J
case "A_INFINITIF": return 100;
case "ON_ONT": return 100; // greater than PRONSUJ_NONVERBE
case "LEURS_LEUR": return 100; // greater than N_V
case "DU_DU": return 100; // greater than DU_LE
case "ACCORD_CHAQUE": return 100; // greater than ACCORD_NOMBRE
case "CEST_A_DIRE": return 100; // greater than A_A_ACCENT
case "A_VERBE_INFINITIF": return 20; // greater than PRONSUJ_NONVERBE
case "ESPACE_UNITES": return 10; // needs to have higher priority than spell checker
case "BYTES": return 10; // needs to be higher than spell checker for 10MB style matches
case "Y_A": return 10; // needs to be higher than spell checker for style suggestion
case "A_A_ACCENT": return 10; // triggers false alarms for IL_FAUT_INF if there is no a/à correction
case "A_ACCENT_A": return 10; // greater than PRONSUJ_NONVERBE
case "JE_M_APPEL": return 10; // override NON_V
case "ACCORD_R_PERS_VERBE": return 10; // match before POSER_UNE_QUESTION
case "JE_SUI": return 10; // needs higher priority than spell checker
//case "D_N": return 1; // needs to have higher priority than agreement postponed adj | Commented out because many other rules should be higher
//case "ACCORD_COULEUR": return 1; // needs to have higher priority than agreement postponed adj
case "CONFUSION_PAR_PART": return -1; // turn off completely when PART_OU_PAR is activated
case "FR_SIMPLE_REPLACE": return -10;
case "IMP_PRON": return -10; // less than D_N
case "PREP_V": return -20;
case "TOO_LONG_PARAGRAPH": return -15;
case "VERB_PRONOUN": return -50; // greater than FR_SPELLING_RULE; less than ACCORD_V_QUESTION
case "AGREEMENT_POSTPONED_ADJ": return -50;
case "FR_SPELLING_RULE": return -100;
case "ELISION": return -200; // should be lower in priority than spell checker
case "UPPERCASE_SENTENCE_START": return -300;
case "FRENCH_WHITESPACE_STRICT": return -350; // picky; if on, it should overwrite FRENCH_WHITESPACE
case "FRENCH_WHITESPACE": return -400; // lesser than UPPERCASE_SENTENCE_START and FR_SPELLING_RULE
}
if (id.startsWith("grammalecte_")) {
return -150;
}
return super.getPriorityForId(id);
}
}
| [fr] give ET/MAIS_SENT_START lower prio than grammalecte
| languagetool-language-modules/fr/src/main/java/org/languagetool/language/French.java | [fr] give ET/MAIS_SENT_START lower prio than grammalecte |
|
Java | lgpl-2.1 | 91b32052de03f183d2243dedb2ae7ab68c2b77aa | 0 | jstourac/wildfly,iweiss/wildfly,jstourac/wildfly,golovnin/wildfly,xasx/wildfly,golovnin/wildfly,rhusar/wildfly,jstourac/wildfly,wildfly/wildfly,xasx/wildfly,iweiss/wildfly,iweiss/wildfly,tadamski/wildfly,wildfly/wildfly,jstourac/wildfly,99sono/wildfly,iweiss/wildfly,99sono/wildfly,rhusar/wildfly,pferraro/wildfly,pferraro/wildfly,golovnin/wildfly,tadamski/wildfly,tomazzupan/wildfly,tadamski/wildfly,tomazzupan/wildfly,99sono/wildfly,rhusar/wildfly,tomazzupan/wildfly,wildfly/wildfly,rhusar/wildfly,wildfly/wildfly,pferraro/wildfly,xasx/wildfly,pferraro/wildfly | /*
* JBoss, a division of Red Hat
* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.as.test.integration.web.sso;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.test.integration.web.sso.interfaces.StatelessSession;
import org.jboss.as.test.shared.RetryTaskExecutor;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
/**
* Base class for tests of web app single sign-on
*
* @author Brian Stansberry
* @author [email protected]
*/
public abstract class SSOTestBase {
private static Logger log = Logger.getLogger(SSOTestBase.class);
/**
* Test single sign-on across two web apps using form based auth
*
* @throws Exception
*/
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
URL warA1 = new URL (serverA, "/war1/");
URL warB2 = new URL (serverB, "/war2/");
// Start by accessing the secured index.html of war1
DefaultHttpClient httpclient = new DefaultHttpClient();
checkAccessDenied(httpclient, warA1 + "index.html");
CookieStore store = httpclient.getCookieStore();
log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
// Submit the login form
executeFormLogin(httpclient, warA1);
String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
log.debug("Saw JSESSIONIDSSO=" + ssoID);
// Now try getting the war2 index using the JSESSIONIDSSO cookie
log.debug("Prepare /war2/index.html get");
checkAccessAllowed(httpclient, warB2 + "index.html");
// Access a secured servlet that calls a secured ejb in war2 to test
// propagation of the SSO identity to the ejb container.
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
// Now try logging out of war2
executeLogout(httpclient, warB2);
// Reset Http client
httpclient = new DefaultHttpClient();
// Try accessing war1 again
checkAccessDenied(httpclient, warA1 + "index.html");
// Try accessing war2 again
checkAccessDenied(httpclient, warB2 + "index.html");
}
public static void executeNoAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
URL warA1 = new URL(serverA, "/war1/");
URL warB2 = new URL(serverB + "/war2/");
URL warB6 = new URL(serverB + "/war6/");
// Start by accessing the secured index.html of war1
DefaultHttpClient httpclient = new DefaultHttpClient();
checkAccessDenied(httpclient, warA1 + "index.html");
CookieStore store = httpclient.getCookieStore();
log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
// Submit the login form
executeFormLogin(httpclient, warA1);
String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
log.debug("Saw JSESSIONIDSSO=" + ssoID);
// Now try getting the war2 index using the JSESSIONIDSSO cookie
log.debug("Prepare /war2/index.html get");
checkAccessAllowed(httpclient, warB2 + "index.html");
// Access a secured servlet that calls a secured ejb in war2 to test
// propagation of the SSO identity to the ejb container.
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
// Do the same test on war6 to test SSO auth replication with no auth
// configured war
checkAccessAllowed(httpclient, warB6 + "index.html");
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
}
public static void executeLogout(HttpClient httpConn, URL warURL) throws IOException {
HttpGet logout = new HttpGet(warURL + "Logout");
logout.setParams(new BasicHttpParams().setParameter("http.protocol.handle-redirects", false));
HttpResponse response = httpConn.execute(logout);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Logout: Didn't saw HTTP_MOVED_TEMP(" + statusCode + ")", statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
Header location = response.getFirstHeader("Location");
assertTrue("Get of " + warURL + "Logout not redirected to login page", location.getValue().indexOf("index.html") >= 0);
}
public static void checkAccessAllowed(HttpClient httpConn, String url) throws IOException {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = httpConn.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK);
String body = EntityUtils.toString(response.getEntity());
assertTrue("Get of " + url + " redirected to login page", body.indexOf("j_security_check") < 0);
}
public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException {
// Submit the login form
HttpPost formPost = new HttpPost(warURL + "j_security_check");
formPost.addHeader("Referer", warURL + "login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", "user1"));
formparams.add(new BasicNameValuePair("j_password", "password1"));
formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
HttpResponse postResponse = httpConn.execute(formPost);
int statusCode = postResponse.getStatusLine().getStatusCode();
Header[] errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(postResponse.getEntity());
// Follow the redirect to the index.html page
String indexURL = postResponse.getFirstHeader("Location").getValue();
HttpGet rediretGet = new HttpGet(indexURL.toString());
HttpResponse redirectResponse = httpConn.execute(rediretGet);
statusCode = redirectResponse.getStatusLine().getStatusCode();
errorHeaders = redirectResponse.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
String body = EntityUtils.toString(redirectResponse.getEntity());
assertTrue("Get of " + indexURL + " redirected to login page", body.indexOf("j_security_check") < 0);
}
public static void checkAccessDenied(HttpClient httpConn, String url) throws IOException {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = httpConn.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK);
String body = EntityUtils.toString(response.getEntity());
assertTrue("Redirected to login page for request=" + url + ", body[" + body + "]", body.indexOf("j_security_check") > 0);
}
public static String processSSOCookie(CookieStore cookieStore, String serverA, String serverB) {
String ssoID = null;
for (Cookie cookie : cookieStore.getCookies()) {
if ("JSESSIONIDSSO".equalsIgnoreCase(cookie.getName())) {
ssoID = cookie.getValue();
if (serverA.equals(serverB) == false) {
// Make an sso cookie to send to serverB
Cookie copy = copyCookie(cookie, serverB);
cookieStore.addCookie(copy);
}
}
}
assertTrue("Didn't saw JSESSIONIDSSO", ssoID != null);
return ssoID;
}
public static Cookie copyCookie(Cookie toCopy, String targetServer) {
// Parse the target server down to a domain name
int index = targetServer.indexOf("://");
if (index > -1) {
targetServer = targetServer.substring(index + 3);
}
// JBAS-8540
// need to be able to parse IPv6 URLs which have enclosing brackets
// HttpClient 3.1 creates cookies which oinclude the square brackets
// index = targetServer.indexOf(":");
index = targetServer.lastIndexOf(":");
if (index > -1) {
targetServer = targetServer.substring(0, index);
}
index = targetServer.indexOf("/");
if (index > -1) {
targetServer = targetServer.substring(0, index);
}
// Cookie copy = new Cookie(targetServer, toCopy.getName(), toCopy.getValue(), "/", null, false);
BasicClientCookie copy = new BasicClientCookie(toCopy.getName(), toCopy.getValue());
copy.setDomain(targetServer);
return copy;
}
public static String getSessionIdValueFromState(CookieStore cookieStore) {
String sessionID = null;
for (Cookie cookie : cookieStore.getCookies()) {
if ("JSESSIONID".equalsIgnoreCase(cookie.getName())) {
sessionID = cookie.getValue();
break;
}
}
return sessionID;
}
public static WebArchive createSsoWar(String warName) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, warName);
war.setWebXML(tccl.getResource(resourcesLocation + "web-form-auth.xml"));
war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");
war.addAsWebResource(tccl.getResource(resourcesLocation + "error.html"), "error.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.jsp"), "index.jsp");
war.addAsWebResource(tccl.getResource(resourcesLocation + "login.html"), "login.html");
war.addClass(EJBServlet.class);
war.addClass(LogoutServlet.class);
return war;
}
public static EnterpriseArchive createSsoEar() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/";
WebArchive war1 = createSsoWar("sso-form-auth1.war");
WebArchive war2 = createSsoWar("sso-form-auth2.war");
WebArchive war3 = createSsoWar("sso-with-no-auth.war");
// Remove jboss-web.xml so the war will not have an authenticator
war3.delete(war3.get("WEB-INF/jboss-web.xml").getPath());
JavaArchive webEjbs = ShrinkWrap.create(JavaArchive.class, "jbosstest-web-ejbs.jar");
webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "ejb-jar.xml"), "ejb-jar.xml");
webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "jboss.xml"), "jboss.xml");
webEjbs.addPackage(StatelessSession.class.getPackage());
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "web-sso.ear");
ear.setApplicationXML(tccl.getResource(resourcesLocation + "application.xml"));
ear.addAsModule(war1);
ear.addAsModule(war2);
ear.addAsModule(war3);
ear.addAsModule(webEjbs);
return ear;
}
public static void addSso(ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
// SSO element name must be 'configuration'
updates.add(createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", ADD));
applyUpdates(updates, client);
}
public static void addClusteredSso(ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
// SSO element name must be 'configuration'
ModelNode addOp = createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", ADD);
addOp.get("cache-container").set("web");
addOp.get("cache-name").set("sso");
updates.add(addOp);
applyUpdates(updates, client);
}
public static void removeSso(final ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
updates.add(createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", REMOVE));
applyUpdates(updates, client);
}
public static void applyUpdates(final List<ModelNode> updates, final ModelControllerClient client) throws Exception {
for (ModelNode update : updates) {
log.info("+++ Update on " + client + ":\n" + update.toString());
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if (result.hasDefined("result"))
log.info(result.get("result"));
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
}
// Reload operation is not handled well by Arquillian
// See ARQ-791: JMX: Arquillian is unable to reconnect to JMX server if the connection is lost
public static void restartServer(final ModelControllerClient client) {
try {
applyUpdates(Arrays.asList(createOpNode(null, "reload")), client);
} catch (Exception e) {
throw new RuntimeException("Restart operation not successful. " + e.getMessage());
}
try {
RetryTaskExecutor<Boolean> rte = new RetryTaskExecutor<Boolean>();
rte.retryTask(new Callable<Boolean>() {
public Boolean call() throws Exception {
ModelNode readOp = createOpNode(null, READ_ATTRIBUTE_OPERATION);
readOp.get("name").set("server-state");
ModelNode result = client.execute(new OperationBuilder(readOp).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if ((result.hasDefined("result")) && (result.get("result").asString().equals("running")))
return true;
}
log.info("Server is down.");
throw new Exception("Connector not available.");
}
});
} catch (TimeoutException e) {
throw new RuntimeException("Timeout on restart operation. " + e.getMessage());
}
log.info("Server is up.");
}
}
| testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/SSOTestBase.java | /*
* JBoss, a division of Red Hat
* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.as.test.integration.web.sso;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.test.integration.web.sso.interfaces.StatelessSession;
import org.jboss.as.test.shared.RetryTaskExecutor;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
/**
* Base class for tests of web app single sign-on
*
* @author Brian Stansberry
* @author [email protected]
*/
public abstract class SSOTestBase {
private static Logger log = Logger.getLogger(SSOTestBase.class);
/**
* Test single sign-on across two web apps using form based auth
*
* @throws Exception
*/
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
URL warA1 = new URL (serverA, "/war1/");
URL warB2 = new URL (serverB, "/war2/");
// Start by accessing the secured index.html of war1
DefaultHttpClient httpclient = new DefaultHttpClient();
checkAccessDenied(httpclient, warA1 + "index.html");
CookieStore store = httpclient.getCookieStore();
log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
// Submit the login form
executeFormLogin(httpclient, warA1);
String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
log.debug("Saw JSESSIONIDSSO=" + ssoID);
// Now try getting the war2 index using the JSESSIONIDSSO cookie
log.debug("Prepare /war2/index.html get");
checkAccessAllowed(httpclient, warB2 + "index.html");
// Access a secured servlet that calls a secured ejb in war2 to test
// propagation of the SSO identity to the ejb container.
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
// Now try logging out of war2
executeLogout(httpclient, warB2);
// Reset Http client
httpclient = new DefaultHttpClient();
// Try accessing war1 again
checkAccessDenied(httpclient, warA1 + "index.html");
// Try accessing war2 again
checkAccessDenied(httpclient, warB2 + "index.html");
}
public static void executeNoAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
URL warA1 = new URL(serverA, "/war1/");
URL warB2 = new URL(serverB + "/war2/");
URL warB6 = new URL(serverB + "/war6/");
// Start by accessing the secured index.html of war1
DefaultHttpClient httpclient = new DefaultHttpClient();
checkAccessDenied(httpclient, warA1 + "index.html");
CookieStore store = httpclient.getCookieStore();
log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
// Submit the login form
executeFormLogin(httpclient, warA1);
String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
log.debug("Saw JSESSIONIDSSO=" + ssoID);
// Now try getting the war2 index using the JSESSIONIDSSO cookie
log.debug("Prepare /war2/index.html get");
checkAccessAllowed(httpclient, warB2 + "index.html");
// Access a secured servlet that calls a secured ejb in war2 to test
// propagation of the SSO identity to the ejb container.
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
// Do the same test on war6 to test SSO auth replication with no auth
// configured war
checkAccessAllowed(httpclient, warB6 + "index.html");
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
}
public static void executeLogout(HttpClient httpConn, URL warURL) throws IOException {
HttpGet logout = new HttpGet(warURL + "Logout");
logout.setParams(new BasicHttpParams().setParameter("http.protocol.handle-redirects", false));
HttpResponse response = httpConn.execute(logout);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Logout: Didn't saw HTTP_MOVED_TEMP(" + statusCode + ")", statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
Header location = response.getFirstHeader("Location");
assertTrue("Get of " + warURL + "Logout not redirected to login page", location.getValue().indexOf("index.html") >= 0);
}
public static void checkAccessAllowed(HttpClient httpConn, String url) throws IOException {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = httpConn.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK);
String body = EntityUtils.toString(response.getEntity());
assertTrue("Get of " + url + " redirected to login page", body.indexOf("j_security_check") < 0);
}
public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException {
// Submit the login form
HttpPost formPost = new HttpPost(warURL + "j_security_check");
formPost.addHeader("Referer", warURL + "login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", "user1"));
formparams.add(new BasicNameValuePair("j_password", "password1"));
formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
HttpResponse postResponse = httpConn.execute(formPost);
int statusCode = postResponse.getStatusLine().getStatusCode();
Header[] errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(postResponse.getEntity());
// Follow the redirect to the index.html page
String indexURL = postResponse.getFirstHeader("Location").getValue();
HttpGet rediretGet = new HttpGet(indexURL.toString());
HttpResponse redirectResponse = httpConn.execute(rediretGet);
statusCode = redirectResponse.getStatusLine().getStatusCode();
errorHeaders = redirectResponse.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
String body = EntityUtils.toString(redirectResponse.getEntity());
assertTrue("Get of " + indexURL + " redirected to login page", body.indexOf("j_security_check") < 0);
}
public static void checkAccessDenied(HttpClient httpConn, String url) throws IOException {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = httpConn.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK);
String body = EntityUtils.toString(response.getEntity());
assertTrue("Redirected to login page for request=" + url + ", body[" + body + "]", body.indexOf("j_security_check") > 0);
}
public static String processSSOCookie(CookieStore cookieStore, String serverA, String serverB) {
String ssoID = null;
for (Cookie cookie : cookieStore.getCookies()) {
if ("JSESSIONIDSSO".equalsIgnoreCase(cookie.getName())) {
ssoID = cookie.getValue();
if (serverA.equals(serverB) == false) {
// Make an sso cookie to send to serverB
Cookie copy = copyCookie(cookie, serverB);
cookieStore.addCookie(copy);
}
}
}
assertTrue("Didn't saw JSESSIONIDSSO", ssoID != null);
return ssoID;
}
public static Cookie copyCookie(Cookie toCopy, String targetServer) {
// Parse the target server down to a domain name
int index = targetServer.indexOf("://");
if (index > -1) {
targetServer = targetServer.substring(index + 3);
}
// JBAS-8540
// need to be able to parse IPv6 URLs which have enclosing brackets
// HttpClient 3.1 creates cookies which oinclude the square brackets
// index = targetServer.indexOf(":");
index = targetServer.lastIndexOf(":");
if (index > -1) {
targetServer = targetServer.substring(0, index);
}
index = targetServer.indexOf("/");
if (index > -1) {
targetServer = targetServer.substring(0, index);
}
// Cookie copy = new Cookie(targetServer, toCopy.getName(), toCopy.getValue(), "/", null, false);
return new BasicClientCookie(toCopy.getName(), toCopy.getValue());
}
public static String getSessionIdValueFromState(CookieStore cookieStore) {
String sessionID = null;
for (Cookie cookie : cookieStore.getCookies()) {
if ("JSESSIONID".equalsIgnoreCase(cookie.getName())) {
sessionID = cookie.getValue();
break;
}
}
return sessionID;
}
public static WebArchive createSsoWar(String warName) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, warName);
war.setWebXML(tccl.getResource(resourcesLocation + "web-form-auth.xml"));
war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");
war.addAsWebResource(tccl.getResource(resourcesLocation + "error.html"), "error.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.jsp"), "index.jsp");
war.addAsWebResource(tccl.getResource(resourcesLocation + "login.html"), "login.html");
war.addClass(EJBServlet.class);
war.addClass(LogoutServlet.class);
return war;
}
public static EnterpriseArchive createSsoEar() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/";
WebArchive war1 = createSsoWar("sso-form-auth1.war");
WebArchive war2 = createSsoWar("sso-form-auth2.war");
WebArchive war3 = createSsoWar("sso-with-no-auth.war");
// Remove jboss-web.xml so the war will not have an authenticator
war3.delete(war3.get("WEB-INF/jboss-web.xml").getPath());
JavaArchive webEjbs = ShrinkWrap.create(JavaArchive.class, "jbosstest-web-ejbs.jar");
webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "ejb-jar.xml"), "ejb-jar.xml");
webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "jboss.xml"), "jboss.xml");
webEjbs.addPackage(StatelessSession.class.getPackage());
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "web-sso.ear");
ear.setApplicationXML(tccl.getResource(resourcesLocation + "application.xml"));
ear.addAsModule(war1);
ear.addAsModule(war2);
ear.addAsModule(war3);
ear.addAsModule(webEjbs);
return ear;
}
public static void addSso(ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
// SSO element name must be 'configuration'
updates.add(createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", ADD));
applyUpdates(updates, client);
}
public static void addClusteredSso(ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
// SSO element name must be 'configuration'
ModelNode addOp = createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", ADD);
addOp.get("cache-container").set("web");
addOp.get("cache-name").set("sso");
updates.add(addOp);
applyUpdates(updates, client);
}
public static void removeSso(final ModelControllerClient client) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
updates.add(createOpNode("subsystem=web/virtual-server=default-host/sso=configuration", REMOVE));
applyUpdates(updates, client);
}
public static void applyUpdates(final List<ModelNode> updates, final ModelControllerClient client) throws Exception {
for (ModelNode update : updates) {
log.info("+++ Update on " + client + ":\n" + update.toString());
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if (result.hasDefined("result"))
log.info(result.get("result"));
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
}
// Reload operation is not handled well by Arquillian
// See ARQ-791: JMX: Arquillian is unable to reconnect to JMX server if the connection is lost
public static void restartServer(final ModelControllerClient client) {
try {
applyUpdates(Arrays.asList(createOpNode(null, "reload")), client);
} catch (Exception e) {
throw new RuntimeException("Restart operation not successful. " + e.getMessage());
}
try {
RetryTaskExecutor<Boolean> rte = new RetryTaskExecutor<Boolean>();
rte.retryTask(new Callable<Boolean>() {
public Boolean call() throws Exception {
ModelNode readOp = createOpNode(null, READ_ATTRIBUTE_OPERATION);
readOp.get("name").set("server-state");
ModelNode result = client.execute(new OperationBuilder(readOp).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if ((result.hasDefined("result")) && (result.get("result").asString().equals("running")))
return true;
}
log.info("Server is down.");
throw new Exception("Connector not available.");
}
});
} catch (TimeoutException e) {
throw new RuntimeException("Timeout on restart operation. " + e.getMessage());
}
log.info("Server is up.");
}
}
| Fixed cookie copy.
| testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/SSOTestBase.java | Fixed cookie copy. |
|
Java | lgpl-2.1 | 7879bd269a046da2fb6e401d0bb545a21d510482 | 0 | adamretter/exist,adamretter/exist,joewiz/exist,wshager/exist,jensopetersen/exist,ambs/exist,adamretter/exist,hungerburg/exist,adamretter/exist,kohsah/exist,shabanovd/exist,windauer/exist,ljo/exist,jessealama/exist,jessealama/exist,ambs/exist,shabanovd/exist,wshager/exist,lcahlander/exist,opax/exist,ambs/exist,kohsah/exist,dizzzz/exist,lcahlander/exist,windauer/exist,zwobit/exist,shabanovd/exist,olvidalo/exist,ambs/exist,hungerburg/exist,ambs/exist,ljo/exist,joewiz/exist,zwobit/exist,adamretter/exist,dizzzz/exist,hungerburg/exist,dizzzz/exist,windauer/exist,patczar/exist,MjAbuz/exist,lcahlander/exist,wshager/exist,ljo/exist,windauer/exist,joewiz/exist,wolfgangmm/exist,wshager/exist,zwobit/exist,RemiKoutcherawy/exist,MjAbuz/exist,zwobit/exist,lcahlander/exist,jessealama/exist,joewiz/exist,jensopetersen/exist,shabanovd/exist,dizzzz/exist,zwobit/exist,zwobit/exist,wolfgangmm/exist,windauer/exist,dizzzz/exist,RemiKoutcherawy/exist,jensopetersen/exist,wshager/exist,wshager/exist,jensopetersen/exist,kohsah/exist,eXist-db/exist,eXist-db/exist,jessealama/exist,olvidalo/exist,RemiKoutcherawy/exist,lcahlander/exist,dizzzz/exist,wolfgangmm/exist,hungerburg/exist,RemiKoutcherawy/exist,eXist-db/exist,ambs/exist,jensopetersen/exist,MjAbuz/exist,jessealama/exist,kohsah/exist,joewiz/exist,shabanovd/exist,opax/exist,eXist-db/exist,kohsah/exist,MjAbuz/exist,opax/exist,wolfgangmm/exist,opax/exist,ljo/exist,kohsah/exist,adamretter/exist,ljo/exist,olvidalo/exist,RemiKoutcherawy/exist,eXist-db/exist,wolfgangmm/exist,MjAbuz/exist,shabanovd/exist,jessealama/exist,patczar/exist,opax/exist,MjAbuz/exist,joewiz/exist,patczar/exist,hungerburg/exist,windauer/exist,eXist-db/exist,patczar/exist,patczar/exist,patczar/exist,wolfgangmm/exist,lcahlander/exist,olvidalo/exist,jensopetersen/exist,ljo/exist,olvidalo/exist,RemiKoutcherawy/exist | package org.exist.xquery;
import org.exist.dom.NodeProxy;
import org.exist.dom.QName;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
/**
* Tests if a node is of a given node type.
*
* @author Wolfgang Meier ([email protected])
*/
public class TypeTest implements NodeTest {
protected int nodeType = 0;
public TypeTest(int nodeType) {
setType(nodeType);
}
public void setType(int nodeType) {
this.nodeType = nodeType;
}
public int getType() {
return nodeType;
}
public QName getName() {
return null;
}
protected boolean isOfType(short type) {
int domType;
switch (nodeType) {
case Type.ELEMENT :
domType = Node.ELEMENT_NODE;
break;
case Type.TEXT :
domType = Node.TEXT_NODE;
break;
case Type.ATTRIBUTE :
domType = Node.ATTRIBUTE_NODE;
break;
case Type.COMMENT :
domType = Node.COMMENT_NODE;
break;
case Type.PROCESSING_INSTRUCTION :
domType = Node.PROCESSING_INSTRUCTION_NODE;
break;
case Type.NODE :
default :
return true;
}
return (type == domType);
}
public String toString() {
return nodeType == Type.NODE ? "node()" : Type.NODETYPES[nodeType] + "()";
}
/* (non-Javadoc)
* @see org.exist.xquery.NodeTest#matches(org.exist.dom.NodeProxy)
*/
public boolean matches(NodeProxy proxy) {
short otherNodeType = proxy.getNodeType();
if(otherNodeType == Type.ITEM || otherNodeType == Type.NODE) {
//TODO : what are the semantics of Type.NODE ?
if (this.nodeType == Type.NODE)
return true;
return isOfType(proxy.getNode().getNodeType());
} else
return isOfType(otherNodeType);
}
public boolean matches(Node other) {
if(other == null)
return false;
return isOfType(other.getNodeType());
}
/* (non-Javadoc)
* @see org.exist.xquery.NodeTest#isWildcardTest()
*/
public boolean isWildcardTest() {
return true;
}
}
| src/org/exist/xquery/TypeTest.java | package org.exist.xquery;
import org.exist.dom.NodeProxy;
import org.exist.dom.QName;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
/**
* Tests if a node is of a given node type.
*
* @author Wolfgang Meier ([email protected])
*/
public class TypeTest implements NodeTest {
protected int nodeType = 0;
public TypeTest(int nodeType) {
setType(nodeType);
}
public void setType(int nodeType) {
this.nodeType = nodeType;
}
public int getType() {
return nodeType;
}
public QName getName() {
return null;
}
protected boolean isOfType(short type) {
int domType;
switch (nodeType) {
case Type.ELEMENT :
domType = Node.ELEMENT_NODE;
break;
case Type.TEXT :
domType = Node.TEXT_NODE;
break;
case Type.ATTRIBUTE :
domType = Node.ATTRIBUTE_NODE;
break;
case Type.COMMENT :
domType = Node.COMMENT_NODE;
break;
case Type.PROCESSING_INSTRUCTION :
domType = Node.PROCESSING_INSTRUCTION_NODE;
break;
case Type.NODE :
default :
return true;
}
return (type == domType);
}
public String toString() {
return nodeType == Type.NODE ? "node()" : Type.NODETYPES[nodeType] + "()";
}
/* (non-Javadoc)
* @see org.exist.xquery.NodeTest#matches(org.exist.dom.NodeProxy)
*/
public boolean matches(NodeProxy proxy) {
short otherNodeType = proxy.getNodeType();
if(otherNodeType == Type.ITEM || otherNodeType == Type.NODE) {
//TODO : what are the semantics of Type.NODE ?
if (this.nodeType == Type.NODE)
return true;
return matches(proxy);
} else
return isOfType(otherNodeType);
}
public boolean matches(Node other) {
if(other == null)
return false;
return isOfType(other.getNodeType());
}
/* (non-Javadoc)
* @see org.exist.xquery.NodeTest#isWildcardTest()
*/
public boolean isWildcardTest() {
return true;
}
}
| Endless loop in TypeTest.matches. Was already fixed in the DLN branch but not ported back to trunk.
svn path=/trunk/eXist-1.0/; revision=3653
| src/org/exist/xquery/TypeTest.java | Endless loop in TypeTest.matches. Was already fixed in the DLN branch but not ported back to trunk. |
|
Java | unlicense | 975e670b48ccbc74c1228d7cdd74633ada502d0b | 0 | Samourai-Wallet/samourai-wallet-android | package com.samourai.wallet.bip47;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
//import android.util.Log;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu;
import net.i2p.android.ext.floatingactionbutton.FloatingActionButton;
import net.sourceforge.zbar.Symbol;
import org.apache.commons.lang3.StringEscapeUtils;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.script.Script;
import org.bouncycastle.util.encoders.Hex;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.DecoderException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import com.google.common.base.Splitter;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.SendActivity;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.bip47.paynym.ClaimPayNymActivity;
import com.samourai.wallet.bip47.rpc.NotSecp256k1Exception;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip47.rpc.SecretPoint;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionInput;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.UTXOFactory;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MessageSignUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.R;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.samourai.wallet.send.PushTx;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.WebUtil;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
public class BIP47Activity extends Activity {
private static final int EDIT_PCODE = 2000;
private static final int RECOMMENDED_PCODE = 2001;
private static final int SCAN_PCODE = 2077;
private SwipeMenuListView listView = null;
BIP47EntryAdapter adapter = null;
private String[] pcodes = null;
private static HashMap<String,String> meta = null;
private static HashMap<String,Bitmap> bitmaps = null;
private FloatingActionsMenu ibBIP47Menu = null;
private FloatingActionButton actionAdd = null;
private FloatingActionButton actionSign = null;
private Menu _menu = null;
private Timer timer = null;
private Handler handler = null;
private ProgressDialog progress = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bip47_list);
setTitle(R.string.paynyms);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ibBIP47Menu = (FloatingActionsMenu)findViewById(R.id.bip47_menu);
actionAdd = (FloatingActionButton)findViewById(R.id.bip47_add);
actionAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
doAdd();
}
});
actionSign = (FloatingActionButton)findViewById(R.id.bip47_sign);
actionSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
doSign();
}
});
if(meta == null) {
meta = new HashMap<String,String>();
}
if(bitmaps == null) {
bitmaps = new HashMap<String,Bitmap>();
}
listView = (SwipeMenuListView) findViewById(R.id.list);
handler = new Handler();
refreshList();
adapter = new BIP47EntryAdapter();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String itemValue = (String) listView.getItemAtPosition(position);
String msg = "";
if (BIP47Meta.getInstance().getLabel(itemValue) != null && BIP47Meta.getInstance().getLabel(itemValue).length() > 0) {
msg = BIP47Meta.getInstance().getLabel(itemValue) + ":";
}
// Toast.makeText(getApplicationContext(), msg + "Outgoing status:" + BIP47Meta.getInstance().getOutgoingStatus(itemValue), Toast.LENGTH_LONG).show();
if (BIP47Meta.getInstance().getOutgoingStatus(itemValue) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(itemValue);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(itemValue) == BIP47Meta.STATUS_SENT_NO_CFM) {
// Toast.makeText(BIP47Activity.this, R.string.bip47_wait_for_confirmation, Toast.LENGTH_SHORT).show();
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip47_wait_for_confirmation_or_retry)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doNotifTx(itemValue);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
if(!isFinishing()) {
dlg.show();
}
}
else {
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip47_spend_to_pcode)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(BIP47Activity.this).restartApp("pcode", itemValue);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
dlg.show();
}
}
});
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
{
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("label", BIP47Meta.getInstance().getLabel(pcodes[position]));
intent.putExtra("pcode", pcodes[position]);
startActivityForResult(intent, EDIT_PCODE);
}
break;
case 1:
doSync(pcodes[position]);
break;
case 2:
{
Intent intent = new Intent(BIP47Activity.this, BIP47ShowQR.class);
intent.putExtra("label", BIP47Meta.getInstance().getLabel(pcodes[position]));
intent.putExtra("pcode", pcodes[position]);
startActivity(intent);
}
break;
case 3:
// archive
BIP47Meta.getInstance().setArchived(pcodes[position], true);
refreshList();
adapter.notifyDataSetChanged();
break;
}
return false;
}
});
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
int outgoing = BIP47Meta.getInstance().getOutgoingIdx(pcodes[position]);
int incoming = BIP47Meta.getInstance().getIncomingIdx(pcodes[position]);
// Toast.makeText(BIP47Activity.this, pcodes[position], Toast.LENGTH_SHORT).show();
Toast.makeText(BIP47Activity.this, "Incoming index:" + incoming + ", Outgoing index:" + outgoing, Toast.LENGTH_SHORT).show();
return true;
}
});
SwipeMenuCreator creator = new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
// create "edit" item
SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
openItem.setWidth(180);
// set a icon
openItem.setIcon(R.drawable.ic_edit_white_24dp);
// add to menu
menu.addMenuItem(openItem);
// create "sync" item
SwipeMenuItem syncItem = new SwipeMenuItem(getApplicationContext());
// set item background
syncItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
syncItem.setWidth(180);
// set a icon
syncItem.setIcon(android.R.drawable.ic_popup_sync);
// add to menu
menu.addMenuItem(syncItem);
// create "qr" item
SwipeMenuItem qrItem = new SwipeMenuItem(getApplicationContext());
// set item background
qrItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
qrItem.setWidth(180);
// set a icon
qrItem.setIcon(R.drawable.ic_receive_qr);
// add to menu
menu.addMenuItem(qrItem);
// create "qr" item
SwipeMenuItem archiveItem = new SwipeMenuItem(getApplicationContext());
// set item background
archiveItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
archiveItem.setWidth(180);
// set a icon
archiveItem.setIcon(android.R.drawable.ic_media_pause);
// add to menu
menu.addMenuItem(archiveItem);
}
};
listView.setMenuCreator(creator);
listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
doTimer();
Bundle extras = getIntent().getExtras();
if(extras != null && extras.containsKey("pcode")) {
String pcode = extras.getString("pcode");
String meta = null;
if(extras.containsKey("meta")) {
meta = extras.getString("meta");
}
String _meta = null;
try {
Map<String, String> map = new HashMap<String,String>();
if(meta != null && meta.length() > 0) {
_meta = URLDecoder.decode(meta, "UTF-8");
map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta);
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", pcode);
intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : "");
startActivityForResult(intent, EDIT_PCODE);
}
catch(UnsupportedEncodingException uee) {
;
}
catch(Exception e) {
;
}
}
}
@Override
protected void onResume() {
super.onResume();
AppUtil.getInstance(BIP47Activity.this).checkTimeOut();
if(_menu != null && PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
_menu.findItem(R.id.action_claim_paynym).setVisible(false);
}
refreshList();
}
@Override
protected void onDestroy() {
killTimer();
try {
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
}
catch(Exception e) {
;
}
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SCAN_PCODE) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
processScan(strResult);
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_PCODE) {
;
}
else if (resultCode == Activity.RESULT_OK && requestCode == EDIT_PCODE) {
if(data.hasExtra("pcode")) {
String pcode = data.getStringExtra("pcode");
if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(pcode);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == EDIT_PCODE) {
;
}
else if (resultCode == Activity.RESULT_OK && requestCode == RECOMMENDED_PCODE) {
if(data.hasExtra("pcode") && data.hasExtra("label")) {
String pcode = data.getStringExtra("pcode");
String label = data.getStringExtra("label");
BIP47Meta.getInstance().setLabel(pcode, label);
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance().getPIN()));
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(DecoderException de) {
de.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(JSONException je) {
je.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(java.lang.NullPointerException npe) {
npe.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(DecryptionException de) {
de.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
finally {
;
}
Looper.loop();
}
}).start();
if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(pcode);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == RECOMMENDED_PCODE) {
;
}
else {
;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bip47_menu, menu);
_menu = menu;
if(PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
menu.findItem(R.id.action_claim_paynym).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home) {
finish();
}
else if(id == R.id.action_show_qr) {
Intent intent = new Intent(BIP47Activity.this, BIP47ShowQR.class);
startActivity(intent);
}
else if(id == R.id.action_unarchive) {
doUnArchive();
}
else if(id == R.id.action_sync_all) {
doSyncAll();
}
else if(id == R.id.action_claim_paynym) {
doClaimPayNym();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
private void doClaimPayNym() {
Intent intent = new Intent(BIP47Activity.this, ClaimPayNymActivity.class);
startActivity(intent);
}
private void doScan() {
Intent intent = new Intent(BIP47Activity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_PCODE);
}
private void processScan(String data) {
if(data.startsWith("bitcoin://") && data.length() > 10) {
data = data.substring(10);
}
if(data.startsWith("bitcoin:") && data.length() > 8) {
data = data.substring(8);
}
if(FormatsUtil.getInstance().isValidPaymentCode(data)) {
try {
if(data.equals(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_scan_own_pcode, Toast.LENGTH_SHORT).show();
return;
}
} catch (AddressFormatException afe) {
;
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", data);
startActivityForResult(intent, EDIT_PCODE);
}
else if(data.contains("?") && (data.length() >= data.indexOf("?"))) {
String meta = data.substring(data.indexOf("?") + 1);
String _meta = null;
try {
Map<String, String> map = new HashMap<String,String>();
if(meta != null && meta.length() > 0) {
_meta = URLDecoder.decode(meta, "UTF-8");
map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta);
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", data.substring(0, data.indexOf("?")));
intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : "");
startActivityForResult(intent, EDIT_PCODE);
}
catch(UnsupportedEncodingException uee) {
;
}
catch(Exception e) {
;
}
}
else {
Toast.makeText(BIP47Activity.this, R.string.scan_error, Toast.LENGTH_SHORT).show();
}
}
private void doAdd() {
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.bip47_add1_title)
.setMessage(R.string.bip47_add1_text)
.setPositiveButton(R.string.paste, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
startActivityForResult(intent, EDIT_PCODE);
}
}).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doScan();
}
});
dlg.show();
}
private void doSign() {
MessageSignUtil.getInstance(BIP47Activity.this).doSign(BIP47Activity.this.getString(R.string.bip47_sign),
BIP47Activity.this.getString(R.string.bip47_sign_text1),
BIP47Activity.this.getString(R.string.bip47_sign_text2),
BIP47Util.getInstance(BIP47Activity.this).getNotificationAddress().getECKey());
}
private void doUnArchive() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(true);
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
for (String pcode : _pcodes) {
BIP47Meta.getInstance().setArchived(pcode, false);
}
pcodes = new String[_pcodes.size()];
int i = 0;
for (String pcode : _pcodes) {
pcodes[i] = pcode;
++i;
}
adapter.notifyDataSetChanged();
}
private void doSyncAll() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(false);
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
for (String pcode : _pcodes) {
doSync(pcode);
}
adapter.notifyDataSetChanged();
}
private void refreshList() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(false);
if(_pcodes.size() < 1) {
BIP47Meta.getInstance().setLabel(BIP47Meta.strSamouraiDonationPCode, "Samourai Wallet Donations");
}
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
pcodes = new String[_pcodes.size()];
int i = 0;
for (String pcode : _pcodes) {
pcodes[i] = pcode;
++i;
}
doPayNymTask();
adapter = new BIP47EntryAdapter();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void doNotifTx(final String pcode) {
//
// get wallet balance
//
long balance = 0L;
try {
balance = APIFactory.getInstance(BIP47Activity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BIP47Activity.this).get().getAccount(0).xpubstr());
}
catch(IOException ioe) {
balance = 0L;
}
catch(MnemonicException.MnemonicLengthException mle) {
balance = 0L;
}
catch(java.lang.NullPointerException npe) {
balance = 0L;
}
final List<UTXO> selectedUTXO = new ArrayList<UTXO>();
long totalValueSelected = 0L;
// long change = 0L;
BigInteger fee = null;
//
// spend dust threshold amount to notification address
//
long amount = SendNotifTxFactory._bNotifTxValue.longValue();
//
// calc btc fee from USD Samourai fee
//
double btc_fx = ExchangeRateFactory.getInstance(BIP47Activity.this).getBitfinexPrice("USD");
BigInteger currentSWFee = BigInteger.valueOf((long)((btc_fx / SendNotifTxFactory._dSWFeeUSD) * 1e8));
if(currentSWFee.longValue() < SendNotifTxFactory._bSWFee.longValue() || currentSWFee.longValue() > SendNotifTxFactory._bSWCeilingFee.longValue()) {
currentSWFee = SendNotifTxFactory._bSWFee;
}
//
// add Samourai Wallet fee to total amount
//
amount += currentSWFee.longValue();
//
// get unspents
//
List<UTXO> utxos = null;
if(UTXOFactory.getInstance().getTotalP2SH_P2WPKH() > amount + FeeUtil.getInstance().estimatedFeeSegwit(0,1, 4).longValue()) {
utxos = new ArrayList<UTXO>();
utxos.addAll(UTXOFactory.getInstance().getP2SH_P2WPKH().values());
}
else {
utxos = APIFactory.getInstance(BIP47Activity.this).getUtxos(true);
}
// sort in ascending order by value
final List<UTXO> _utxos = utxos;
Collections.sort(_utxos, new UTXO.UTXOComparator());
Collections.reverse(_utxos);
//
// get smallest 1 UTXO > than spend + fee + sw fee + dust
//
for(UTXO u : _utxos) {
if(u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(1, 4).longValue())) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
Log.d("BIP47Activity", "single output");
Log.d("BIP47Activity", "value selected:" + u.getValue());
Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
//
// use low fee settings
//
SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
if(selectedUTXO.size() == 0) {
// sort in descending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
int selected = 0;
// get largest UTXOs > than spend + fee + dust
for(UTXO u : _utxos) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
selected += u.getOutpoints().size();
if(totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 4).longValue())) {
Log.d("BIP47Activity", "multiple outputs");
Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
fee = FeeUtil.getInstance().estimatedFee(selected, 4);
}
else {
fee = FeeUtil.getInstance().estimatedFee(1, 4);
}
//
// reset fee to previous setting
//
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
//
// total amount to spend including fee
//
if((amount + fee.longValue()) >= balance) {
String message = getText(R.string.bip47_notif_tx_insufficient_funds_1) + " ";
BigInteger biAmount = SendNotifTxFactory._bSWFee.add(SendNotifTxFactory._bNotifTxValue.add(FeeUtil.getInstance().estimatedFee(1, 4, FeeUtil.getInstance().getLowFee().getDefaultPerKB())));
String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) biAmount.longValue()) / 1e8) + " BTC ";
message += strAmount;
message += " " + getText(R.string.bip47_notif_tx_insufficient_funds_2);
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.help, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/article/58-connecting-to-a-paynym-contact"));
startActivity(browserIntent);
}
})
.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
return;
}
//
// payment code to be notified
//
PaymentCode payment_code;
try {
payment_code = new PaymentCode(pcode);
}
catch (AddressFormatException afe) {
payment_code = null;
}
if(payment_code == null) {
return;
}
//
// create outpoints for spend later
//
final List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>();
for(UTXO u : selectedUTXO) {
outpoints.addAll(u.getOutpoints());
}
//
// create inputs from outpoints
//
List<MyTransactionInput> inputs = new ArrayList<MyTransactionInput>();
for(MyTransactionOutPoint o : outpoints) {
Script script = new Script(o.getScriptBytes());
if(script.getScriptType() == Script.ScriptType.NO_TYPE) {
continue;
}
MyTransactionInput input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], o, o.getTxHash().toString(), o.getTxOutputN());
inputs.add(input);
}
//
// sort inputs
//
Collections.sort(inputs, new SendFactory.BIP69InputComparator());
//
// find outpoint that corresponds to 0th input
//
MyTransactionOutPoint outPoint = null;
for(MyTransactionOutPoint o : outpoints) {
if(o.getTxHash().toString().equals(inputs.get(0).getTxHash()) && o.getTxOutputN() == inputs.get(0).getTxPos()) {
outPoint = o;
break;
}
}
if(outPoint == null) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_identify_outpoint, Toast.LENGTH_SHORT).show();
return;
}
byte[] op_return = null;
//
// get private key corresponding to outpoint
//
try {
Script inputScript = new Script(outPoint.getConnectedPubKeyScript());
String address = inputScript.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
ECKey ecKey = SendFactory.getPrivKey(address);
if(ecKey == null || !ecKey.hasPrivKey()) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
//
// use outpoint for payload masking
//
byte[] privkey = ecKey.getPrivKeyBytes();
byte[] pubkey = payment_code.notificationAddress().getPubKey();
byte[] outpoint = outPoint.bitcoinSerialize();
// Log.i("BIP47Activity", "outpoint:" + Hex.toHexString(outpoint));
// Log.i("BIP47Activity", "payer shared secret:" + Hex.toHexString(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes()));
byte[] mask = PaymentCode.getMask(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes(), outpoint);
// Log.i("BIP47Activity", "mask:" + Hex.toHexString(mask));
// Log.i("BIP47Activity", "mask length:" + mask.length);
// Log.i("BIP47Activity", "payload0:" + Hex.toHexString(BIP47Util.getInstance(context).getPaymentCode().getPayload()));
op_return = PaymentCode.blind(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().getPayload(), mask);
// Log.i("BIP47Activity", "payload1:" + Hex.toHexString(op_return));
}
catch(InvalidKeyException ike) {
Toast.makeText(BIP47Activity.this, ike.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(InvalidKeySpecException ikse) {
Toast.makeText(BIP47Activity.this, ikse.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(NoSuchAlgorithmException nsae) {
Toast.makeText(BIP47Activity.this, nsae.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(NoSuchProviderException nspe) {
Toast.makeText(BIP47Activity.this, nspe.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(Hex.toHexString(op_return), BigInteger.ZERO);
receivers.put(payment_code.notificationAddress().getAddressString(), SendNotifTxFactory._bNotifTxValue);
receivers.put(SamouraiWallet.getInstance().isTestNet() ? SendNotifTxFactory.TESTNET_SAMOURAI_NOTIF_TX_FEE_ADDRESS : SendNotifTxFactory.SAMOURAI_NOTIF_TX_FEE_ADDRESS, currentSWFee);
final long change = totalValueSelected - (amount + fee.longValue());
if(change > 0L) {
String change_address = BIP49Util.getInstance(BIP47Activity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString();
receivers.put(change_address, BigInteger.valueOf(change));
}
Log.d("BIP47Activity", "outpoints:" + outpoints.size());
Log.d("BIP47Activity", "totalValueSelected:" + BigInteger.valueOf(totalValueSelected).toString());
Log.d("BIP47Activity", "amount:" + BigInteger.valueOf(amount).toString());
Log.d("BIP47Activity", "change:" + BigInteger.valueOf(change).toString());
Log.d("BIP47Activity", "fee:" + fee.toString());
if(change < 0L) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
final MyTransactionOutPoint _outPoint = outPoint;
String strNotifTxMsg = getText(R.string.bip47_setup4_text1) + " ";
long notifAmount = amount;
String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) notifAmount + fee.longValue()) / 1e8) + " BTC ";
strNotifTxMsg += strAmount + getText(R.string.bip47_setup4_text2);
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.bip47_setup4_title)
.setMessage(strNotifTxMsg)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Transaction tx = SendFactory.getInstance(BIP47Activity.this).makeTransaction(0, outpoints, receivers);
if(tx != null) {
String input0hash = tx.getInput(0L).getOutpoint().getHash().toString();
Log.d("BIP47Activity", "input0 hash:" + input0hash);
Log.d("BIP47Activity", "_outPoint hash:" + _outPoint.getTxHash().toString());
int input0index = (int)tx.getInput(0L).getOutpoint().getIndex();
Log.d("BIP47Activity", "input0 index:" + input0index);
Log.d("BIP47Activity", "_outPoint index:" + _outPoint.getTxOutputN());
if(!input0hash.equals(_outPoint.getTxHash().toString()) || input0index != _outPoint.getTxOutputN()) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
tx = SendFactory.getInstance(BIP47Activity.this).signTransaction(tx);
final String hexTx = new String(org.bouncycastle.util.encoders.Hex.encode(tx.bitcoinSerialize()));
Log.d("SendActivity", tx.getHashAsString());
Log.d("SendActivity", hexTx);
boolean isOK = false;
String response = null;
try {
response = PushTx.getInstance(BIP47Activity.this).samourai(hexTx);
Log.d("SendActivity", "pushTx:" + response);
if(response != null) {
org.json.JSONObject jsonObject = new org.json.JSONObject(response);
if(jsonObject.has("status")) {
if(jsonObject.getString("status").equals("ok")) {
isOK = true;
}
}
}
else {
Toast.makeText(BIP47Activity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show();
return;
}
if(isOK) {
Toast.makeText(BIP47Activity.this, R.string.payment_channel_init, Toast.LENGTH_SHORT).show();
//
// set outgoing index for payment code to 0
//
BIP47Meta.getInstance().setOutgoingIdx(pcode, 0);
// Log.i("SendNotifTxFactory", "tx hash:" + tx.getHashAsString());
//
// status to NO_CFM
//
BIP47Meta.getInstance().setOutgoingStatus(pcode, tx.getHashAsString(), BIP47Meta.STATUS_SENT_NO_CFM);
//
// increment change index
//
if(change > 0L) {
BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().incAddrIdx();
}
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
}
else {
Toast.makeText(BIP47Activity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
}
catch(JSONException je) {
Toast.makeText(BIP47Activity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(MnemonicException.MnemonicLengthException mle) {
Toast.makeText(BIP47Activity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(DecoderException de) {
Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(IOException ioe) {
Toast.makeText(BIP47Activity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(DecryptionException de) {
Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
Looper.loop();
}
}).start();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
dlg.show();
}
private class BIP47EntryAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public BIP47EntryAdapter() {
inflater = (LayoutInflater)BIP47Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return pcodes.length;
}
@Override
public Object getItem(int position) {
return pcodes[position];
}
@Override
public long getItemId(int position) {
return 0L;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)BIP47Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.bip47_entry, null);
}
else {
view = convertView;
}
String strLabel = BIP47Meta.getInstance().getDisplayLabel(pcodes[position]);
final TextView tvInitial = (TextView)view.findViewById(R.id.Initial);
tvInitial.setText(strLabel.substring(0, 1).toUpperCase());
if(position % 3 == 0) {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_red);
}
else if(position % 2 == 1) {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_green);
}
else {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_blue);
}
final TextView tvLabel = (TextView)view.findViewById(R.id.Label);
tvLabel.setText(strLabel);
final ImageView ivAvatar = (ImageView)view.findViewById(R.id.Avatar);
ivAvatar.setVisibility(View.GONE);
if(meta.containsKey(pcodes[position])) {
try {
JSONObject obj = new JSONObject(meta.get(pcodes[position]));
if(obj.has("user-avatar")) {
String avatarUrl = obj.getString("user-avatar");
if(bitmaps.containsKey(pcodes[position])) {
ivAvatar.setImageBitmap(bitmaps.get(pcodes[position]));
}
else {
Picasso.with(BIP47Activity.this)
.load(avatarUrl)
.into(new Target() {
@Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
ivAvatar.setImageBitmap(bitmap);
bitmaps.put(pcodes[position], bitmap);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
@Override
public void onBitmapFailed(Drawable errorDrawable) {}
});
}
tvInitial.setVisibility(View.GONE);
ivAvatar.setVisibility(View.VISIBLE);
}
if(obj.has("title")) {
String label = StringEscapeUtils.unescapeHtml4(obj.getString("title"));
if((BIP47Meta.getInstance().getLabel(pcodes[position]) == null ||
BIP47Meta.getInstance().getLabel(pcodes[position]).length() == 0 ||
FormatsUtil.getInstance().isValidPaymentCode(BIP47Meta.getInstance().getLabel(pcodes[position]))
&&
(label != null && label.length() > 0))) {
strLabel = label;
BIP47Meta.getInstance().setLabel(pcodes[position], strLabel);
tvLabel.setText(strLabel);
}
}
}
catch(JSONException je) {
;
}
}
TextView tvLatest = (TextView)view.findViewById(R.id.Latest);
String strLatest = "";
if(BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_NOT_SENT) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_tbe);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_SENT_NO_CFM) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_pending);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_SENT_CFM) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_active);
}
else {
;
}
if(BIP47Meta.getInstance().getLatestEvent(pcodes[position]) != null && BIP47Meta.getInstance().getLatestEvent(pcodes[position]).length() > 0) {
strLatest += "\n" + BIP47Meta.getInstance().getLatestEvent(pcodes[position]);
}
tvLatest.setText(strLatest);
return view;
}
}
private void killTimer() {
if(timer != null) {
timer.cancel();
timer = null;
}
}
private void doTimer() {
if(timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
if(refreshDisplay()) {
handler.post(new Runnable() {
@Override
public void run() {
refreshList();
adapter.notifyDataSetChanged();
}
});
}
}
}).start();
}
});
}
}, 5000, 30000);
}
}
public boolean refreshDisplay() {
boolean changed = false;
//
// check for incoming payment code notification tx
//
int before = BIP47Meta.getInstance().getLabels().size();
try {
PaymentCode pcode = BIP47Util.getInstance(BIP47Activity.this).getPaymentCode();
APIFactory.getInstance(BIP47Activity.this).getNotifAddress(pcode.notificationAddress().getAddressString());
}
catch (AddressFormatException afe) {
afe.printStackTrace();
Toast.makeText(BIP47Activity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
int after = BIP47Meta.getInstance().getLabels().size();
if(before != after) {
changed = true;
}
//
// check on outgoing payment code notification tx
//
List<org.apache.commons.lang3.tuple.Pair<String, String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed();
for(org.apache.commons.lang3.tuple.Pair<String,String> pair : outgoingUnconfirmed) {
//Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft());
//Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight());
int confirmations = APIFactory.getInstance(BIP47Activity.this).getNotifTxConfirmations(pair.getRight());
if(confirmations > 0) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM);
changed = true;
}
if(confirmations == -1) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT);
}
}
return changed;
}
private void doSync(final String pcode) {
progress = new ProgressDialog(BIP47Activity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
PaymentCode payment_code = new PaymentCode(pcode);
int idx = 0;
boolean loop = true;
ArrayList<String> addrs = new ArrayList<String>();
while(loop) {
addrs.clear();
for(int i = idx; i < (idx + 20); i++) {
PaymentAddress receiveAddress = BIP47Util.getInstance(BIP47Activity.this).getReceiveAddress(payment_code, i);
// Log.i("BIP47Activity", "sync receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().setIncomingIdx(payment_code.toString(), i, receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), payment_code.toString());
addrs.add(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
String[] s = addrs.toArray(new String[addrs.size()]);
int nb = APIFactory.getInstance(BIP47Activity.this).syncBIP47Incoming(s);
// Log.i("BIP47Activity", "sync receive idx:" + idx + ", nb == " + nb);
if(nb == 0) {
loop = false;
}
idx += 20;
}
idx = 0;
loop = true;
BIP47Meta.getInstance().setOutgoingIdx(pcode, 0);
while(loop) {
addrs.clear();
for(int i = idx; i < (idx + 20); i++) {
PaymentAddress sendAddress = BIP47Util.getInstance(BIP47Activity.this).getSendAddress(payment_code, i);
// Log.i("BIP47Activity", "sync send to " + i + ":" + sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
// BIP47Meta.getInstance().setOutgoingIdx(payment_code.toString(), i);
BIP47Meta.getInstance().getIdx4AddrLookup().put(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), payment_code.toString());
addrs.add(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
String[] s = addrs.toArray(new String[addrs.size()]);
int nb = APIFactory.getInstance(BIP47Activity.this).syncBIP47Outgoing(s);
// Log.i("BIP47Activity", "sync send idx:" + idx + ", nb == " + nb);
if(nb == 0) {
loop = false;
}
idx += 20;
}
BIP47Meta.getInstance().pruneIncoming();
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
LocalBroadcastManager.getInstance(BIP47Activity.this).sendBroadcast(intent);
}
catch(IOException ioe) {
;
}
catch(JSONException je) {
;
}
catch(DecryptionException de) {
;
}
catch(NotSecp256k1Exception nse) {
;
}
catch(InvalidKeySpecException ikse) {
;
}
catch(InvalidKeyException ike) {
;
}
catch(NoSuchAlgorithmException nsae) {
;
}
catch(NoSuchProviderException nspe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
if (refreshDisplay()) {
handler.post(new Runnable() {
@Override
public void run() {
refreshList();
adapter.notifyDataSetChanged();
}
});
}
}
}).start();
}
});
}
}).start();
}
private void doPayNymTask() {
if(PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
new Thread(new Runnable() {
private Handler handler = new Handler();
@Override
public void run() {
Looper.prepare();
final String strPaymentCode = BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString();
try {
JSONObject obj = new JSONObject();
obj.put("nym", strPaymentCode);
String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BIP47Activity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym", obj.toString());
Log.d("BIP47Activity", res);
JSONObject responseObj = new JSONObject(res);
if(responseObj.has("codes")) {
JSONArray array = responseObj.getJSONArray("codes");
if(array.getJSONObject(0).has("claimed") && array.getJSONObject(0).getBoolean("claimed") == true) {
final String strNymName = responseObj.getString("nymName");
handler.post(new Runnable() {
public void run() {
((RelativeLayout) findViewById(R.id.paynym)).setVisibility(View.VISIBLE);
Log.d("BIP47Activity", strNymName);
final ImageView ivAvatar = (ImageView) findViewById(R.id.avatar);
// get screen width
Display display = BIP47Activity.this.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
if (size.x > 240) {
// load avatar
Picasso.with(BIP47Activity.this).load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + strPaymentCode + "/avatar").into(ivAvatar);
}
else {
// screen too small, hide avatar
ivAvatar.setVisibility(View.INVISIBLE);
}
((TextView)findViewById(R.id.nymName)).setText(strNymName);
((TextView)findViewById(R.id.pcode)).setText(BIP47Meta.getInstance().getDisplayLabel(strPaymentCode));
}
});
}
else {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
}
}
else {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
}
}
catch(Exception e) {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
e.printStackTrace();
}
Looper.loop();
}
}).start();
}
}
| app/src/main/java/com/samourai/wallet/bip47/BIP47Activity.java | package com.samourai.wallet.bip47;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
//import android.util.Log;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu;
import net.i2p.android.ext.floatingactionbutton.FloatingActionButton;
import net.sourceforge.zbar.Symbol;
import org.apache.commons.lang3.StringEscapeUtils;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.script.Script;
import org.bouncycastle.util.encoders.Hex;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.DecoderException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import com.google.common.base.Splitter;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.bip47.paynym.ClaimPayNymActivity;
import com.samourai.wallet.bip47.rpc.NotSecp256k1Exception;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip47.rpc.SecretPoint;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionInput;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.UTXOFactory;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MessageSignUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.R;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.samourai.wallet.send.PushTx;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.WebUtil;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
public class BIP47Activity extends Activity {
private static final int EDIT_PCODE = 2000;
private static final int RECOMMENDED_PCODE = 2001;
private static final int SCAN_PCODE = 2077;
private SwipeMenuListView listView = null;
BIP47EntryAdapter adapter = null;
private String[] pcodes = null;
private static HashMap<String,String> meta = null;
private static HashMap<String,Bitmap> bitmaps = null;
private FloatingActionsMenu ibBIP47Menu = null;
private FloatingActionButton actionAdd = null;
private FloatingActionButton actionSign = null;
private Menu _menu = null;
private Timer timer = null;
private Handler handler = null;
private ProgressDialog progress = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bip47_list);
setTitle(R.string.paynyms);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ibBIP47Menu = (FloatingActionsMenu)findViewById(R.id.bip47_menu);
actionAdd = (FloatingActionButton)findViewById(R.id.bip47_add);
actionAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
doAdd();
}
});
actionSign = (FloatingActionButton)findViewById(R.id.bip47_sign);
actionSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
doSign();
}
});
if(meta == null) {
meta = new HashMap<String,String>();
}
if(bitmaps == null) {
bitmaps = new HashMap<String,Bitmap>();
}
listView = (SwipeMenuListView) findViewById(R.id.list);
handler = new Handler();
refreshList();
adapter = new BIP47EntryAdapter();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String itemValue = (String) listView.getItemAtPosition(position);
String msg = "";
if (BIP47Meta.getInstance().getLabel(itemValue) != null && BIP47Meta.getInstance().getLabel(itemValue).length() > 0) {
msg = BIP47Meta.getInstance().getLabel(itemValue) + ":";
}
// Toast.makeText(getApplicationContext(), msg + "Outgoing status:" + BIP47Meta.getInstance().getOutgoingStatus(itemValue), Toast.LENGTH_LONG).show();
if (BIP47Meta.getInstance().getOutgoingStatus(itemValue) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(itemValue);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(itemValue) == BIP47Meta.STATUS_SENT_NO_CFM) {
// Toast.makeText(BIP47Activity.this, R.string.bip47_wait_for_confirmation, Toast.LENGTH_SHORT).show();
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip47_wait_for_confirmation_or_retry)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doNotifTx(itemValue);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
if(!isFinishing()) {
dlg.show();
}
}
else {
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip47_spend_to_pcode)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(BIP47Activity.this).restartApp("pcode", itemValue);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
dlg.show();
}
}
});
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
{
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("label", BIP47Meta.getInstance().getLabel(pcodes[position]));
intent.putExtra("pcode", pcodes[position]);
startActivityForResult(intent, EDIT_PCODE);
}
break;
case 1:
doSync(pcodes[position]);
break;
case 2:
{
Intent intent = new Intent(BIP47Activity.this, BIP47ShowQR.class);
intent.putExtra("label", BIP47Meta.getInstance().getLabel(pcodes[position]));
intent.putExtra("pcode", pcodes[position]);
startActivity(intent);
}
break;
case 3:
// archive
BIP47Meta.getInstance().setArchived(pcodes[position], true);
refreshList();
adapter.notifyDataSetChanged();
break;
}
return false;
}
});
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
int outgoing = BIP47Meta.getInstance().getOutgoingIdx(pcodes[position]);
int incoming = BIP47Meta.getInstance().getIncomingIdx(pcodes[position]);
// Toast.makeText(BIP47Activity.this, pcodes[position], Toast.LENGTH_SHORT).show();
Toast.makeText(BIP47Activity.this, "Incoming index:" + incoming + ", Outgoing index:" + outgoing, Toast.LENGTH_SHORT).show();
return true;
}
});
SwipeMenuCreator creator = new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
// create "edit" item
SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
openItem.setWidth(180);
// set a icon
openItem.setIcon(R.drawable.ic_edit_white_24dp);
// add to menu
menu.addMenuItem(openItem);
// create "sync" item
SwipeMenuItem syncItem = new SwipeMenuItem(getApplicationContext());
// set item background
syncItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
syncItem.setWidth(180);
// set a icon
syncItem.setIcon(android.R.drawable.ic_popup_sync);
// add to menu
menu.addMenuItem(syncItem);
// create "qr" item
SwipeMenuItem qrItem = new SwipeMenuItem(getApplicationContext());
// set item background
qrItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
qrItem.setWidth(180);
// set a icon
qrItem.setIcon(R.drawable.ic_receive_qr);
// add to menu
menu.addMenuItem(qrItem);
// create "qr" item
SwipeMenuItem archiveItem = new SwipeMenuItem(getApplicationContext());
// set item background
archiveItem.setBackground(new ColorDrawable(Color.rgb(0x17, 0x1B, 0x24)));
// set item width
archiveItem.setWidth(180);
// set a icon
archiveItem.setIcon(android.R.drawable.ic_media_pause);
// add to menu
menu.addMenuItem(archiveItem);
}
};
listView.setMenuCreator(creator);
listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
doTimer();
Bundle extras = getIntent().getExtras();
if(extras != null && extras.containsKey("pcode")) {
String pcode = extras.getString("pcode");
String meta = null;
if(extras.containsKey("meta")) {
meta = extras.getString("meta");
}
String _meta = null;
try {
Map<String, String> map = new HashMap<String,String>();
if(meta != null && meta.length() > 0) {
_meta = URLDecoder.decode(meta, "UTF-8");
map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta);
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", pcode);
intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : "");
startActivityForResult(intent, EDIT_PCODE);
}
catch(UnsupportedEncodingException uee) {
;
}
catch(Exception e) {
;
}
}
}
@Override
protected void onResume() {
super.onResume();
AppUtil.getInstance(BIP47Activity.this).checkTimeOut();
if(_menu != null && PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
_menu.findItem(R.id.action_claim_paynym).setVisible(false);
}
refreshList();
}
@Override
protected void onDestroy() {
killTimer();
try {
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
}
catch(Exception e) {
;
}
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SCAN_PCODE) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
processScan(strResult);
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_PCODE) {
;
}
else if (resultCode == Activity.RESULT_OK && requestCode == EDIT_PCODE) {
if(data.hasExtra("pcode")) {
String pcode = data.getStringExtra("pcode");
if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(pcode);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == EDIT_PCODE) {
;
}
else if (resultCode == Activity.RESULT_OK && requestCode == RECOMMENDED_PCODE) {
if(data.hasExtra("pcode") && data.hasExtra("label")) {
String pcode = data.getStringExtra("pcode");
String label = data.getStringExtra("label");
BIP47Meta.getInstance().setLabel(pcode, label);
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance().getPIN()));
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(DecoderException de) {
de.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(JSONException je) {
je.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(java.lang.NullPointerException npe) {
npe.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(DecryptionException de) {
de.printStackTrace();
Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
finally {
;
}
Looper.loop();
}
}).start();
if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
doNotifTx(pcode);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED && requestCode == RECOMMENDED_PCODE) {
;
}
else {
;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bip47_menu, menu);
_menu = menu;
if(PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
menu.findItem(R.id.action_claim_paynym).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home) {
finish();
}
else if(id == R.id.action_show_qr) {
Intent intent = new Intent(BIP47Activity.this, BIP47ShowQR.class);
startActivity(intent);
}
else if(id == R.id.action_unarchive) {
doUnArchive();
}
else if(id == R.id.action_sync_all) {
doSyncAll();
}
else if(id == R.id.action_claim_paynym) {
doClaimPayNym();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
private void doClaimPayNym() {
Intent intent = new Intent(BIP47Activity.this, ClaimPayNymActivity.class);
startActivity(intent);
}
private void doScan() {
Intent intent = new Intent(BIP47Activity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_PCODE);
}
private void processScan(String data) {
if(data.startsWith("bitcoin://") && data.length() > 10) {
data = data.substring(10);
}
if(data.startsWith("bitcoin:") && data.length() > 8) {
data = data.substring(8);
}
if(FormatsUtil.getInstance().isValidPaymentCode(data)) {
try {
if(data.equals(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_scan_own_pcode, Toast.LENGTH_SHORT).show();
return;
}
} catch (AddressFormatException afe) {
;
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", data);
startActivityForResult(intent, EDIT_PCODE);
}
else if(data.contains("?") && (data.length() >= data.indexOf("?"))) {
String meta = data.substring(data.indexOf("?") + 1);
String _meta = null;
try {
Map<String, String> map = new HashMap<String,String>();
if(meta != null && meta.length() > 0) {
_meta = URLDecoder.decode(meta, "UTF-8");
map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta);
}
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
intent.putExtra("pcode", data.substring(0, data.indexOf("?")));
intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : "");
startActivityForResult(intent, EDIT_PCODE);
}
catch(UnsupportedEncodingException uee) {
;
}
catch(Exception e) {
;
}
}
else {
Toast.makeText(BIP47Activity.this, R.string.scan_error, Toast.LENGTH_SHORT).show();
}
}
private void doAdd() {
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.bip47_add1_title)
.setMessage(R.string.bip47_add1_text)
.setPositiveButton(R.string.paste, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Intent intent = new Intent(BIP47Activity.this, BIP47Add.class);
startActivityForResult(intent, EDIT_PCODE);
}
}).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doScan();
}
});
dlg.show();
}
private void doSign() {
MessageSignUtil.getInstance(BIP47Activity.this).doSign(BIP47Activity.this.getString(R.string.bip47_sign),
BIP47Activity.this.getString(R.string.bip47_sign_text1),
BIP47Activity.this.getString(R.string.bip47_sign_text2),
BIP47Util.getInstance(BIP47Activity.this).getNotificationAddress().getECKey());
}
private void doUnArchive() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(true);
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
for (String pcode : _pcodes) {
BIP47Meta.getInstance().setArchived(pcode, false);
}
pcodes = new String[_pcodes.size()];
int i = 0;
for (String pcode : _pcodes) {
pcodes[i] = pcode;
++i;
}
adapter.notifyDataSetChanged();
}
private void doSyncAll() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(false);
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
for (String pcode : _pcodes) {
doSync(pcode);
}
adapter.notifyDataSetChanged();
}
private void refreshList() {
Set<String> _pcodes = BIP47Meta.getInstance().getSortedByLabels(false);
if(_pcodes.size() < 1) {
BIP47Meta.getInstance().setLabel(BIP47Meta.strSamouraiDonationPCode, "Samourai Wallet Donations");
}
//
// check for own payment code
//
try {
if (_pcodes.contains(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString())) {
_pcodes.remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
BIP47Meta.getInstance().remove(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString());
}
} catch (AddressFormatException afe) {
;
}
pcodes = new String[_pcodes.size()];
int i = 0;
for (String pcode : _pcodes) {
pcodes[i] = pcode;
++i;
}
doPayNymTask();
adapter = new BIP47EntryAdapter();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void doNotifTx(final String pcode) {
//
// get wallet balance
//
long balance = 0L;
try {
balance = APIFactory.getInstance(BIP47Activity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BIP47Activity.this).get().getAccount(0).xpubstr());
}
catch(IOException ioe) {
balance = 0L;
}
catch(MnemonicException.MnemonicLengthException mle) {
balance = 0L;
}
catch(java.lang.NullPointerException npe) {
balance = 0L;
}
final List<UTXO> selectedUTXO = new ArrayList<UTXO>();
long totalValueSelected = 0L;
// long change = 0L;
BigInteger fee = null;
//
// spend dust threshold amount to notification address
//
long amount = SendNotifTxFactory._bNotifTxValue.longValue();
//
// calc btc fee from USD Samourai fee
//
double btc_fx = ExchangeRateFactory.getInstance(BIP47Activity.this).getBitfinexPrice("USD");
BigInteger currentSWFee = BigInteger.valueOf((long)((btc_fx / SendNotifTxFactory._dSWFeeUSD) * 1e8));
if(currentSWFee.longValue() < SendNotifTxFactory._bSWFee.longValue() || currentSWFee.longValue() > SendNotifTxFactory._bSWCeilingFee.longValue()) {
currentSWFee = SendNotifTxFactory._bSWFee;
}
//
// add Samourai Wallet fee to total amount
//
amount += currentSWFee.longValue();
//
// get unspents
//
List<UTXO> utxos = null;
if(UTXOFactory.getInstance().getTotalP2SH_P2WPKH() > amount + FeeUtil.getInstance().estimatedFeeSegwit(0,1, 4).longValue()) {
utxos = new ArrayList<UTXO>();
utxos.addAll(UTXOFactory.getInstance().getP2SH_P2WPKH().values());
}
else {
utxos = APIFactory.getInstance(BIP47Activity.this).getUtxos(true);
}
// sort in ascending order by value
final List<UTXO> _utxos = utxos;
Collections.sort(_utxos, new UTXO.UTXOComparator());
Collections.reverse(_utxos);
//
// get smallest 1 UTXO > than spend + fee + sw fee + dust
//
for(UTXO u : _utxos) {
if(u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(1, 4).longValue())) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
Log.d("BIP47Activity", "single output");
Log.d("BIP47Activity", "value selected:" + u.getValue());
Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
//
// use low fee settings
//
SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
if(selectedUTXO.size() == 0) {
// sort in descending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
int selected = 0;
// get largest UTXOs > than spend + fee + dust
for(UTXO u : _utxos) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
selected += u.getOutpoints().size();
if(totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 4).longValue())) {
Log.d("BIP47Activity", "multiple outputs");
Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
fee = FeeUtil.getInstance().estimatedFee(selected, 4);
}
else {
fee = FeeUtil.getInstance().estimatedFee(1, 4);
}
//
// reset fee to previous setting
//
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
//
// total amount to spend including fee
//
if((amount + fee.longValue()) >= balance) {
String message = getText(R.string.bip47_notif_tx_insufficient_funds_1) + " ";
BigInteger biAmount = SendNotifTxFactory._bSWFee.add(SendNotifTxFactory._bNotifTxValue.add(FeeUtil.getInstance().estimatedFee(1, 4, FeeUtil.getInstance().getLowFee().getDefaultPerKB())));
String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) biAmount.longValue()) / 1e8) + " BTC ";
message += strAmount;
message += " " + getText(R.string.bip47_notif_tx_insufficient_funds_2);
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.help, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/article/58-connecting-to-a-paynym-contact"));
startActivity(browserIntent);
}
})
.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
return;
}
//
// payment code to be notified
//
PaymentCode payment_code;
try {
payment_code = new PaymentCode(pcode);
}
catch (AddressFormatException afe) {
payment_code = null;
}
if(payment_code == null) {
return;
}
//
// create outpoints for spend later
//
final List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>();
for(UTXO u : selectedUTXO) {
outpoints.addAll(u.getOutpoints());
}
//
// create inputs from outpoints
//
List<MyTransactionInput> inputs = new ArrayList<MyTransactionInput>();
for(MyTransactionOutPoint o : outpoints) {
Script script = new Script(o.getScriptBytes());
if(script.getScriptType() == Script.ScriptType.NO_TYPE) {
continue;
}
MyTransactionInput input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], o, o.getTxHash().toString(), o.getTxOutputN());
inputs.add(input);
}
//
// sort inputs
//
Collections.sort(inputs, new SendFactory.BIP69InputComparator());
//
// find outpoint that corresponds to 0th input
//
MyTransactionOutPoint outPoint = null;
for(MyTransactionOutPoint o : outpoints) {
if(o.getTxHash().toString().equals(inputs.get(0).getTxHash()) && o.getTxOutputN() == inputs.get(0).getTxPos()) {
outPoint = o;
break;
}
}
if(outPoint == null) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_identify_outpoint, Toast.LENGTH_SHORT).show();
return;
}
byte[] op_return = null;
//
// get private key corresponding to outpoint
//
try {
Script inputScript = new Script(outPoint.getConnectedPubKeyScript());
String address = inputScript.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
ECKey ecKey = SendFactory.getPrivKey(address);
if(ecKey == null || !ecKey.hasPrivKey()) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
//
// use outpoint for payload masking
//
byte[] privkey = ecKey.getPrivKeyBytes();
byte[] pubkey = payment_code.notificationAddress().getPubKey();
byte[] outpoint = outPoint.bitcoinSerialize();
// Log.i("BIP47Activity", "outpoint:" + Hex.toHexString(outpoint));
// Log.i("BIP47Activity", "payer shared secret:" + Hex.toHexString(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes()));
byte[] mask = PaymentCode.getMask(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes(), outpoint);
// Log.i("BIP47Activity", "mask:" + Hex.toHexString(mask));
// Log.i("BIP47Activity", "mask length:" + mask.length);
// Log.i("BIP47Activity", "payload0:" + Hex.toHexString(BIP47Util.getInstance(context).getPaymentCode().getPayload()));
op_return = PaymentCode.blind(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().getPayload(), mask);
// Log.i("BIP47Activity", "payload1:" + Hex.toHexString(op_return));
}
catch(InvalidKeyException ike) {
Toast.makeText(BIP47Activity.this, ike.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(InvalidKeySpecException ikse) {
Toast.makeText(BIP47Activity.this, ikse.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(NoSuchAlgorithmException nsae) {
Toast.makeText(BIP47Activity.this, nsae.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(NoSuchProviderException nspe) {
Toast.makeText(BIP47Activity.this, nspe.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(Hex.toHexString(op_return), BigInteger.ZERO);
receivers.put(payment_code.notificationAddress().getAddressString(), SendNotifTxFactory._bNotifTxValue);
receivers.put(SamouraiWallet.getInstance().isTestNet() ? SendNotifTxFactory.TESTNET_SAMOURAI_NOTIF_TX_FEE_ADDRESS : SendNotifTxFactory.SAMOURAI_NOTIF_TX_FEE_ADDRESS, currentSWFee);
final long change = totalValueSelected - (amount + fee.longValue());
if(change > 0L) {
String change_address = BIP49Util.getInstance(BIP47Activity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString();
receivers.put(change_address, BigInteger.valueOf(change));
}
Log.d("BIP47Activity", "outpoints:" + outpoints.size());
Log.d("BIP47Activity", "totalValueSelected:" + BigInteger.valueOf(totalValueSelected).toString());
Log.d("BIP47Activity", "amount:" + BigInteger.valueOf(amount).toString());
Log.d("BIP47Activity", "change:" + BigInteger.valueOf(change).toString());
Log.d("BIP47Activity", "fee:" + fee.toString());
if(change < 0L) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
final MyTransactionOutPoint _outPoint = outPoint;
String strNotifTxMsg = getText(R.string.bip47_setup4_text1) + " ";
long notifAmount = amount;
String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) notifAmount + fee.longValue()) / 1e8) + " BTC ";
strNotifTxMsg += strAmount + getText(R.string.bip47_setup4_text2);
AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this)
.setTitle(R.string.bip47_setup4_title)
.setMessage(strNotifTxMsg)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Transaction tx = SendFactory.getInstance(BIP47Activity.this).makeTransaction(0, outpoints, receivers);
if(tx != null) {
String input0hash = tx.getInput(0L).getOutpoint().getHash().toString();
Log.d("BIP47Activity", "input0 hash:" + input0hash);
Log.d("BIP47Activity", "_outPoint hash:" + _outPoint.getTxHash().toString());
int input0index = (int)tx.getInput(0L).getOutpoint().getIndex();
Log.d("BIP47Activity", "input0 index:" + input0index);
Log.d("BIP47Activity", "_outPoint index:" + _outPoint.getTxOutputN());
if(!input0hash.equals(_outPoint.getTxHash().toString()) || input0index != _outPoint.getTxOutputN()) {
Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
return;
}
tx = SendFactory.getInstance(BIP47Activity.this).signTransaction(tx);
final String hexTx = new String(org.bouncycastle.util.encoders.Hex.encode(tx.bitcoinSerialize()));
Log.d("SendActivity", tx.getHashAsString());
Log.d("SendActivity", hexTx);
boolean isOK = false;
String response = null;
try {
response = PushTx.getInstance(BIP47Activity.this).samourai(hexTx);
Log.d("SendActivity", "pushTx:" + response);
if(response != null) {
org.json.JSONObject jsonObject = new org.json.JSONObject(response);
if(jsonObject.has("status")) {
if(jsonObject.getString("status").equals("ok")) {
isOK = true;
}
}
}
else {
Toast.makeText(BIP47Activity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show();
return;
}
if(isOK) {
Toast.makeText(BIP47Activity.this, R.string.payment_channel_init, Toast.LENGTH_SHORT).show();
//
// set outgoing index for payment code to 0
//
BIP47Meta.getInstance().setOutgoingIdx(pcode, 0);
// Log.i("SendNotifTxFactory", "tx hash:" + tx.getHashAsString());
//
// status to NO_CFM
//
BIP47Meta.getInstance().setOutgoingStatus(pcode, tx.getHashAsString(), BIP47Meta.STATUS_SENT_NO_CFM);
//
// increment change index
//
if(change > 0L) {
BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().incAddrIdx();
}
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
}
else {
Toast.makeText(BIP47Activity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
}
catch(JSONException je) {
Toast.makeText(BIP47Activity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(MnemonicException.MnemonicLengthException mle) {
Toast.makeText(BIP47Activity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(DecoderException de) {
Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(IOException ioe) {
Toast.makeText(BIP47Activity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
catch(DecryptionException de) {
Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
Looper.loop();
}
}).start();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
dlg.show();
}
private class BIP47EntryAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public BIP47EntryAdapter() {
inflater = (LayoutInflater)BIP47Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return pcodes.length;
}
@Override
public Object getItem(int position) {
return pcodes[position];
}
@Override
public long getItemId(int position) {
return 0L;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)BIP47Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.bip47_entry, null);
}
else {
view = convertView;
}
String strLabel = BIP47Meta.getInstance().getDisplayLabel(pcodes[position]);
final TextView tvInitial = (TextView)view.findViewById(R.id.Initial);
tvInitial.setText(strLabel.substring(0, 1).toUpperCase());
if(position % 3 == 0) {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_red);
}
else if(position % 2 == 1) {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_green);
}
else {
tvInitial.setBackgroundResource(R.drawable.ripple_initial_blue);
}
final TextView tvLabel = (TextView)view.findViewById(R.id.Label);
tvLabel.setText(strLabel);
final ImageView ivAvatar = (ImageView)view.findViewById(R.id.Avatar);
ivAvatar.setVisibility(View.GONE);
if(meta.containsKey(pcodes[position])) {
try {
JSONObject obj = new JSONObject(meta.get(pcodes[position]));
if(obj.has("user-avatar")) {
String avatarUrl = obj.getString("user-avatar");
if(bitmaps.containsKey(pcodes[position])) {
ivAvatar.setImageBitmap(bitmaps.get(pcodes[position]));
}
else {
Picasso.with(BIP47Activity.this)
.load(avatarUrl)
.into(new Target() {
@Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
ivAvatar.setImageBitmap(bitmap);
bitmaps.put(pcodes[position], bitmap);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
@Override
public void onBitmapFailed(Drawable errorDrawable) {}
});
}
tvInitial.setVisibility(View.GONE);
ivAvatar.setVisibility(View.VISIBLE);
}
if(obj.has("title")) {
String label = StringEscapeUtils.unescapeHtml4(obj.getString("title"));
if((BIP47Meta.getInstance().getLabel(pcodes[position]) == null ||
BIP47Meta.getInstance().getLabel(pcodes[position]).length() == 0 ||
FormatsUtil.getInstance().isValidPaymentCode(BIP47Meta.getInstance().getLabel(pcodes[position]))
&&
(label != null && label.length() > 0))) {
strLabel = label;
BIP47Meta.getInstance().setLabel(pcodes[position], strLabel);
tvLabel.setText(strLabel);
}
}
}
catch(JSONException je) {
;
}
}
TextView tvLatest = (TextView)view.findViewById(R.id.Latest);
String strLatest = "";
if(BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_NOT_SENT) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_tbe);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_SENT_NO_CFM) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_pending);
}
else if (BIP47Meta.getInstance().getOutgoingStatus(pcodes[position]) == BIP47Meta.STATUS_SENT_CFM) {
if(BIP47Meta.getInstance().incomingExists(pcodes[position])) {
strLatest = BIP47Activity.this.getText(R.string.bip47_status_incoming) + "\n";
}
strLatest += BIP47Activity.this.getText(R.string.bip47_status_active);
}
else {
;
}
if(BIP47Meta.getInstance().getLatestEvent(pcodes[position]) != null && BIP47Meta.getInstance().getLatestEvent(pcodes[position]).length() > 0) {
strLatest += "\n" + BIP47Meta.getInstance().getLatestEvent(pcodes[position]);
}
tvLatest.setText(strLatest);
return view;
}
}
private void killTimer() {
if(timer != null) {
timer.cancel();
timer = null;
}
}
private void doTimer() {
if(timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
if(refreshDisplay()) {
handler.post(new Runnable() {
@Override
public void run() {
refreshList();
adapter.notifyDataSetChanged();
}
});
}
}
}).start();
}
});
}
}, 5000, 30000);
}
}
public boolean refreshDisplay() {
boolean changed = false;
//
// check for incoming payment code notification tx
//
int before = BIP47Meta.getInstance().getLabels().size();
try {
PaymentCode pcode = BIP47Util.getInstance(BIP47Activity.this).getPaymentCode();
APIFactory.getInstance(BIP47Activity.this).getNotifAddress(pcode.notificationAddress().getAddressString());
}
catch (AddressFormatException afe) {
afe.printStackTrace();
Toast.makeText(BIP47Activity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
int after = BIP47Meta.getInstance().getLabels().size();
if(before != after) {
changed = true;
}
//
// check on outgoing payment code notification tx
//
List<org.apache.commons.lang3.tuple.Pair<String, String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed();
for(org.apache.commons.lang3.tuple.Pair<String,String> pair : outgoingUnconfirmed) {
//Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft());
//Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight());
int confirmations = APIFactory.getInstance(BIP47Activity.this).getNotifTxConfirmations(pair.getRight());
if(confirmations > 0) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM);
changed = true;
}
if(confirmations == -1) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT);
}
}
return changed;
}
private void doSync(final String pcode) {
progress = new ProgressDialog(BIP47Activity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
PaymentCode payment_code = new PaymentCode(pcode);
int idx = 0;
boolean loop = true;
ArrayList<String> addrs = new ArrayList<String>();
while(loop) {
addrs.clear();
for(int i = idx; i < (idx + 20); i++) {
PaymentAddress receiveAddress = BIP47Util.getInstance(BIP47Activity.this).getReceiveAddress(payment_code, i);
// Log.i("BIP47Activity", "sync receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().setIncomingIdx(payment_code.toString(), i, receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), payment_code.toString());
addrs.add(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
String[] s = addrs.toArray(new String[addrs.size()]);
int nb = APIFactory.getInstance(BIP47Activity.this).syncBIP47Incoming(s);
// Log.i("BIP47Activity", "sync receive idx:" + idx + ", nb == " + nb);
if(nb == 0) {
loop = false;
}
idx += 20;
}
idx = 0;
loop = true;
BIP47Meta.getInstance().setOutgoingIdx(pcode, 0);
while(loop) {
addrs.clear();
for(int i = idx; i < (idx + 20); i++) {
PaymentAddress sendAddress = BIP47Util.getInstance(BIP47Activity.this).getSendAddress(payment_code, i);
// Log.i("BIP47Activity", "sync send to " + i + ":" + sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
// BIP47Meta.getInstance().setOutgoingIdx(payment_code.toString(), i);
BIP47Meta.getInstance().getIdx4AddrLookup().put(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), payment_code.toString());
addrs.add(sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
String[] s = addrs.toArray(new String[addrs.size()]);
int nb = APIFactory.getInstance(BIP47Activity.this).syncBIP47Outgoing(s);
// Log.i("BIP47Activity", "sync send idx:" + idx + ", nb == " + nb);
if(nb == 0) {
loop = false;
}
idx += 20;
}
BIP47Meta.getInstance().pruneIncoming();
PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
LocalBroadcastManager.getInstance(BIP47Activity.this).sendBroadcast(intent);
}
catch(IOException ioe) {
;
}
catch(JSONException je) {
;
}
catch(DecryptionException de) {
;
}
catch(NotSecp256k1Exception nse) {
;
}
catch(InvalidKeySpecException ikse) {
;
}
catch(InvalidKeyException ike) {
;
}
catch(NoSuchAlgorithmException nsae) {
;
}
catch(NoSuchProviderException nspe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
if (refreshDisplay()) {
handler.post(new Runnable() {
@Override
public void run() {
refreshList();
adapter.notifyDataSetChanged();
}
});
}
}
}).start();
}
});
}
}).start();
}
private void doPayNymTask() {
if(PrefsUtil.getInstance(BIP47Activity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true) {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
new Thread(new Runnable() {
private Handler handler = new Handler();
@Override
public void run() {
Looper.prepare();
final String strPaymentCode = BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().toString();
try {
JSONObject obj = new JSONObject();
obj.put("nym", strPaymentCode);
String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BIP47Activity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym", obj.toString());
Log.d("BIP47Activity", res);
JSONObject responseObj = new JSONObject(res);
if(responseObj.has("codes")) {
JSONArray array = responseObj.getJSONArray("codes");
if(array.getJSONObject(0).has("claimed") && array.getJSONObject(0).getBoolean("claimed") == true) {
final String strNymName = responseObj.getString("nymName");
handler.post(new Runnable() {
public void run() {
((RelativeLayout) findViewById(R.id.paynym)).setVisibility(View.VISIBLE);
Log.d("BIP47Activity", strNymName);
final ImageView ivAvatar = (ImageView) findViewById(R.id.avatar);
Picasso.with(BIP47Activity.this).load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + strPaymentCode + "/avatar").into(ivAvatar);
((TextView)findViewById(R.id.nymName)).setText(strNymName);
((TextView)findViewById(R.id.pcode)).setText(BIP47Meta.getInstance().getDisplayLabel(strPaymentCode));
}
});
}
else {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
}
}
else {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
}
}
catch(Exception e) {
handler.post(new Runnable() {
public void run() {
((RelativeLayout)findViewById(R.id.paynym)).setVisibility(View.GONE);
}
});
e.printStackTrace();
}
Looper.loop();
}
}).start();
}
}
| Fix #105: BIP47Activity: layout messed up on low-res
Hide avatar for low-res devices
| app/src/main/java/com/samourai/wallet/bip47/BIP47Activity.java | Fix #105: BIP47Activity: layout messed up on low-res |
|
Java | apache-2.0 | cdadb834b0a7b9c609334dbfd22b4fb43549306b | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2020 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
*
* https://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.springframework.core.io;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
/**
* Default implementation of the {@link ResourceLoader} interface.
* Used by {@link ResourceEditor}, and serves as base class for
* {@link org.springframework.context.support.AbstractApplicationContext}.
* Can also be used standalone.
*
* <p>Will return a {@link UrlResource} if the location value is a URL,
* and a {@link ClassPathResource} if it is a non-URL path or a
* "classpath:" pseudo-URL.
*
* @author Juergen Hoeller
* @since 10.03.2004
* @see FileSystemResourceLoader
* @see org.springframework.context.support.ClassPathXmlApplicationContext
*/
public class DefaultResourceLoader implements ResourceLoader {
@Nullable
private ClassLoader classLoader;
private final Set<ProtocolResolver> protocolResolvers = new LinkedHashSet<>(4);
private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);
/**
* Create a new DefaultResourceLoader.
* <p>ClassLoader access will happen using the thread context class loader
* at the time of actual resource access (since 5.3). For more control, pass
* a specific ClassLoader to {@link #DefaultResourceLoader(ClassLoader)}.
* @see java.lang.Thread#getContextClassLoader()
*/
public DefaultResourceLoader() {
}
/**
* Create a new DefaultResourceLoader.
* @param classLoader the ClassLoader to load class path resources with, or {@code null}
* for using the thread context class loader at the time of actual resource access
*/
public DefaultResourceLoader(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Specify the ClassLoader to load class path resources with, or {@code null}
* for using the thread context class loader at the time of actual resource access.
* <p>The default is that ClassLoader access will happen using the thread context
* class loader at the time of this ResourceLoader's initialization.
*/
public void setClassLoader(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the ClassLoader to load class path resources with.
* <p>Will get passed to ClassPathResource's constructor for all
* ClassPathResource objects created by this resource loader.
* @see ClassPathResource
*/
@Override
@Nullable
public ClassLoader getClassLoader() {
return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
}
/**
* Register the given resolver with this resource loader, allowing for
* additional protocols to be handled.
* <p>Any such resolver will be invoked ahead of this loader's standard
* resolution rules. It may therefore also override any default rules.
* @since 4.3
* @see #getProtocolResolvers()
*/
public void addProtocolResolver(ProtocolResolver resolver) {
Assert.notNull(resolver, "ProtocolResolver must not be null");
this.protocolResolvers.add(resolver);
}
/**
* Return the collection of currently registered protocol resolvers,
* allowing for introspection as well as modification.
* @since 4.3
*/
public Collection<ProtocolResolver> getProtocolResolvers() {
return this.protocolResolvers;
}
/**
* Obtain a cache for the given value type, keyed by {@link Resource}.
* @param valueType the value type, e.g. an ASM {@code MetadataReader}
* @return the cache {@link Map}, shared at the {@code ResourceLoader} level
* @since 5.0
*/
@SuppressWarnings("unchecked")
public <T> Map<Resource, T> getResourceCache(Class<T> valueType) {
return (Map<Resource, T>) this.resourceCaches.computeIfAbsent(valueType, key -> new ConcurrentHashMap<>());
}
/**
* Clear all resource caches in this resource loader.
* @since 5.0
* @see #getResourceCache
*/
public void clearResourceCaches() {
this.resourceCaches.clear();
}
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : getProtocolResolvers()) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
/**
* Return a Resource handle for the resource at the given path.
* <p>The default implementation supports class path locations. This should
* be appropriate for standalone implementations but can be overridden,
* e.g. for implementations targeted at a Servlet container.
* @param path the path to the resource
* @return the corresponding Resource handle
* @see ClassPathResource
* @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {
public ClassPathContextResource(String path, @Nullable ClassLoader classLoader) {
super(path, classLoader);
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassPathContextResource(pathToUse, getClassLoader());
}
}
}
| spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java | /*
* Copyright 2002-2019 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
*
* https://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.springframework.core.io;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
/**
* Default implementation of the {@link ResourceLoader} interface.
* Used by {@link ResourceEditor}, and serves as base class for
* {@link org.springframework.context.support.AbstractApplicationContext}.
* Can also be used standalone.
*
* <p>Will return a {@link UrlResource} if the location value is a URL,
* and a {@link ClassPathResource} if it is a non-URL path or a
* "classpath:" pseudo-URL.
*
* @author Juergen Hoeller
* @since 10.03.2004
* @see FileSystemResourceLoader
* @see org.springframework.context.support.ClassPathXmlApplicationContext
*/
public class DefaultResourceLoader implements ResourceLoader {
@Nullable
private ClassLoader classLoader;
private final Set<ProtocolResolver> protocolResolvers = new LinkedHashSet<>(4);
private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);
/**
* Create a new DefaultResourceLoader.
* <p>ClassLoader access will happen using the thread context class loader
* at the time of this ResourceLoader's initialization.
* @see java.lang.Thread#getContextClassLoader()
*/
public DefaultResourceLoader() {
this.classLoader = ClassUtils.getDefaultClassLoader();
}
/**
* Create a new DefaultResourceLoader.
* @param classLoader the ClassLoader to load class path resources with, or {@code null}
* for using the thread context class loader at the time of actual resource access
*/
public DefaultResourceLoader(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Specify the ClassLoader to load class path resources with, or {@code null}
* for using the thread context class loader at the time of actual resource access.
* <p>The default is that ClassLoader access will happen using the thread context
* class loader at the time of this ResourceLoader's initialization.
*/
public void setClassLoader(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the ClassLoader to load class path resources with.
* <p>Will get passed to ClassPathResource's constructor for all
* ClassPathResource objects created by this resource loader.
* @see ClassPathResource
*/
@Override
@Nullable
public ClassLoader getClassLoader() {
return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
}
/**
* Register the given resolver with this resource loader, allowing for
* additional protocols to be handled.
* <p>Any such resolver will be invoked ahead of this loader's standard
* resolution rules. It may therefore also override any default rules.
* @since 4.3
* @see #getProtocolResolvers()
*/
public void addProtocolResolver(ProtocolResolver resolver) {
Assert.notNull(resolver, "ProtocolResolver must not be null");
this.protocolResolvers.add(resolver);
}
/**
* Return the collection of currently registered protocol resolvers,
* allowing for introspection as well as modification.
* @since 4.3
*/
public Collection<ProtocolResolver> getProtocolResolvers() {
return this.protocolResolvers;
}
/**
* Obtain a cache for the given value type, keyed by {@link Resource}.
* @param valueType the value type, e.g. an ASM {@code MetadataReader}
* @return the cache {@link Map}, shared at the {@code ResourceLoader} level
* @since 5.0
*/
@SuppressWarnings("unchecked")
public <T> Map<Resource, T> getResourceCache(Class<T> valueType) {
return (Map<Resource, T>) this.resourceCaches.computeIfAbsent(valueType, key -> new ConcurrentHashMap<>());
}
/**
* Clear all resource caches in this resource loader.
* @since 5.0
* @see #getResourceCache
*/
public void clearResourceCaches() {
this.resourceCaches.clear();
}
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : getProtocolResolvers()) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
/**
* Return a Resource handle for the resource at the given path.
* <p>The default implementation supports class path locations. This should
* be appropriate for standalone implementations but can be overridden,
* e.g. for implementations targeted at a Servlet container.
* @param path the path to the resource
* @return the corresponding Resource handle
* @see ClassPathResource
* @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {
public ClassPathContextResource(String path, @Nullable ClassLoader classLoader) {
super(path, classLoader);
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassPathContextResource(pathToUse, getClassLoader());
}
}
}
| Redefine DefaultResourceLoader default constructor for late TCCL access
Closes gh-24957
| spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java | Redefine DefaultResourceLoader default constructor for late TCCL access |
|
Java | apache-2.0 | 5b14f0793588a314ac134be46e639921587e9b78 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | /**
*
*/
package org.commcare.views;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.support.v4.util.Pair;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.Space;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import org.commcare.dalvik.R;
import org.commcare.models.AsyncEntity;
import org.commcare.models.Entity;
import org.commcare.suite.model.Detail;
import org.commcare.util.GridCoordinate;
import org.commcare.util.GridStyle;
import org.commcare.utils.CachingAsyncImageLoader;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.MediaUtil;
import org.commcare.views.media.AudioButton;
import org.commcare.views.media.ViewId;
import org.javarosa.core.services.Logger;
import org.javarosa.xpath.XPathUnhandledException;
import java.util.Arrays;
/**
* @author wspride
* This class defines an individual panel within an advanced case list.
* Each panel is defined by a Detail and an Entity
* Significant axis of configuration are NUMBER_ROWS, NUMBER_COLUMNS, AND CELL_HEIGHT_DIVISOR defined below
*/
public class EntityViewTile extends GridLayout {
private String[] searchTerms;
// All of the views that are being shown in this tile, one for each field of the entity's detail
private View[] mFieldViews;
private boolean mFuzzySearchEnabled = false;
private boolean mIsAsynchronous = false;
// load the screen-size-dependent font sizes
private final float SMALL_FONT = getResources().getDimension(R.dimen.font_size_small);
private final float MEDIUM_FONT = getResources().getDimension(R.dimen.font_size_medium);
private final float LARGE_FONT = getResources().getDimension(R.dimen.font_size_large);
private final float XLARGE_FONT = getResources().getDimension(R.dimen.font_size_xlarge);
private final float DENSITY = getResources().getDisplayMetrics().density;
private final int DEFAULT_TILE_PADDING_HORIZONTAL =
(int)getResources().getDimension(R.dimen.row_padding_horizontal);
private final int DEFAULT_TILE_PADDING_VERTICAL =
(int)getResources().getDimension(R.dimen.row_padding_vertical);
// Constants used to calibrate how many tiles should be shown on a screen at once -- This is
// saying that we expect a device with a density of 160 dpi and a height of 4 inches to look
// good in portrait mode with 4 tiles of 6 rows each being displayed at once.
private static final double DEFAULT_SCREEN_HEIGHT_IN_INCHES = 4.0;
private static final int DEFAULT_SCREEN_DENSITY = DisplayMetrics.DENSITY_MEDIUM;
private static final double DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT = 4;
private static final int DEFAULT_NUMBER_ROWS_PER_GRID = 6;
private static final double LANDSCAPE_TO_PORTRAIT_RATIO = .75;
// this is fixed for all tiles
private static final int NUMBER_COLUMNS_PER_GRID = 12;
private final int numRowsPerTile;
private final int numTilesPerRow;
private double cellWidth;
private double cellHeight;
private final CachingAsyncImageLoader mImageLoader;
private final boolean beingDisplayedInAwesomeMode;
public static EntityViewTile createTileForIndividualDisplay(Context context, Detail detail,
Entity entity) {
return new EntityViewTile(context, detail, entity, new String[0],
new CachingAsyncImageLoader(context), false, false);
}
public static EntityViewTile createTileForEntitySelectDisplay(Context context, Detail detail,
Entity entity,
String[] searchTerms,
CachingAsyncImageLoader loader,
boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
return new EntityViewTile(context, detail, entity, searchTerms, loader,
fuzzySearchEnabled, inAwesomeMode);
}
private EntityViewTile(Context context, Detail detail, Entity entity, String[] searchTerms,
CachingAsyncImageLoader loader, boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
super(context);
this.searchTerms = searchTerms;
this.mIsAsynchronous = entity instanceof AsyncEntity;
this.mImageLoader = loader;
this.mFuzzySearchEnabled = fuzzySearchEnabled;
this.numRowsPerTile = getMaxRows(detail);
this.numTilesPerRow = detail.getNumEntitiesToDisplayPerRow();
this.beingDisplayedInAwesomeMode = inAwesomeMode;
setEssentialGridLayoutValues();
setCellWidthAndHeight(context, detail);
addFieldViews(context, detail, entity);
}
/**
* @return the maximum height of the grid view for the given detail
*/
private static int getMaxRows(Detail detail) {
GridCoordinate[] coordinates = detail.getGridCoordinates();
int currentMaxHeight = 0;
for (GridCoordinate coordinate : coordinates) {
int yCoordinate = coordinate.getY();
int height = coordinate.getHeight();
int maxHeight = yCoordinate + height;
if (maxHeight > currentMaxHeight) {
currentMaxHeight = maxHeight;
}
}
return currentMaxHeight;
}
private void setEssentialGridLayoutValues() {
setColumnCount(NUMBER_COLUMNS_PER_GRID);
setRowCount(numRowsPerTile);
setPaddingIfNotInGridView();
}
private void setCellWidthAndHeight(Context context, Detail detail) {
Pair<Integer, Integer> tileWidthAndHeight = computeTileWidthAndHeight(context);
cellWidth = tileWidthAndHeight.first / (double)NUMBER_COLUMNS_PER_GRID;
if (detail.useUniformUnitsInCaseTile()) {
cellHeight = cellWidth;
} else {
cellHeight = tileWidthAndHeight.second / (double)numRowsPerTile;
}
}
/**
* Compute what the width and height of a single tile should be, based upon the available
* screen space, how many columns there should be, and how many rows we want to show at a time.
* Round up to the nearest integer since the GridView's width and height will ultimately be
* computed indirectly from these values, and those values need to be integers, and we don't
* want to end up cutting things off
*/
private Pair<Integer, Integer> computeTileWidthAndHeight(Context context) {
double screenWidth, screenHeight;
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
} else {
screenWidth = display.getWidth();
screenHeight = display.getHeight();
}
if (!tileBeingShownInGridView()) {
// If we added padding, subtract that space since we can't use it
screenWidth = screenWidth - DEFAULT_TILE_PADDING_HORIZONTAL * 2;
}
int tileHeight;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (beingDisplayedInAwesomeMode) {
// if in awesome mode, split available width in half
screenWidth = screenWidth / 2;
}
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(false, screenHeight));
} else {
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(true, screenHeight));
}
int tileWidth = (int)Math.ceil(screenWidth / numTilesPerRow);
return new Pair<>(tileWidth, tileHeight);
}
/**
* @return - The number of tiles that should be displayed on a single screen on this device,
* calibrated against our default values based upon both the screen density and the screen
* height in inches
*/
private double computeNumTilesPerScreen(boolean inPortrait, double screenHeightInPixels) {
double numTilesPerScreenPortrait = DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT *
(DEFAULT_NUMBER_ROWS_PER_GRID / (float) numRowsPerTile);
double baseNumberOfTiles;
if (inPortrait) {
baseNumberOfTiles = numTilesPerScreenPortrait;
} else {
baseNumberOfTiles = numTilesPerScreenPortrait * LANDSCAPE_TO_PORTRAIT_RATIO;
}
int screenDensity = getResources().getDisplayMetrics().densityDpi;
return (baseNumberOfTiles + getAdditionalTilesBasedOnScreenDensity(screenDensity))
* getScreenHeightMultiplier(screenDensity, screenHeightInPixels);
}
private static double getAdditionalTilesBasedOnScreenDensity(int screenDensity) {
// For every additional 160dpi from the default density, show one more tile on the screen
int defaultDensityDpi = DEFAULT_SCREEN_DENSITY;
return (screenDensity - defaultDensityDpi) / 160;
}
private static double getScreenHeightMultiplier(int screenDensity, double screenHeightInPixels) {
double screenHeightInInches = screenHeightInPixels / screenDensity;
return screenHeightInInches / DEFAULT_SCREEN_HEIGHT_IN_INCHES;
}
/**
* Add Spaces to this GridLayout to strictly enforce that Grid columns and rows stay the width/height we want
* Android GridLayout tries to be very "smart" about moving entries placed arbitrarily within the grid so that
* they look "ordered" even though this often ends up looking not how we want it. It will only make these adjustments
* to rows/columns that end up empty or near empty, so we solve this by adding spaces to every row and column.
* We just add a space of width cellWidth and height 1 to every column of the first row, and likewise a sapce of height
* cellHeight and width 1 to every row of the first column. These are then written on top of if need be.
*/
private void addBuffers(Context context) {
for (int i = 0; i < numRowsPerTile; i++) {
Spec rowSpec = GridLayout.spec(i);
Spec colSpec = GridLayout.spec(0);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = 1;
mGridParams.height = (int) cellHeight;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
for (int i = 0; i < NUMBER_COLUMNS_PER_GRID; i++) {
Spec rowSpec = GridLayout.spec(0);
Spec colSpec = GridLayout.spec(i);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = (int) cellWidth;
mGridParams.height = 1;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
}
/**
* Add the view for each field in the detail
*
* @param detail - the Detail describing how to display each entry
* @param entity - the Entity describing the actual data of each entry
*/
public void addFieldViews(Context context, Detail detail, Entity entity) {
this.removeAllViews();
addBuffers(context); // add spacers to enforce regularized column and row size
GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates();
String[] typesOfEachField = detail.getTemplateForms();
GridStyle[] stylesOfEachField = detail.getGridStyles();
Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) +
" | Coords: " + Arrays.toString(coordinatesOfEachField) +
" | Styles: " + Arrays.toString(stylesOfEachField));
setPaddingIfNotInGridView();
if (tileBeingShownInGridView()) {
// Fake dividers between each square in the grid view by using contrasting
// background colors for the grid view as a whole and each element in the grid view
setBackgroundColor(Color.parseColor("#ffffff"));
}
mFieldViews = new View[coordinatesOfEachField.length];
for (int i = 0; i < mFieldViews.length; i++) {
addFieldView(context, typesOfEachField[i], stylesOfEachField[i],
coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i);
}
}
private void addFieldView(Context context, String form,
GridStyle style, GridCoordinate coordinateData, String fieldString,
String sortField, int index) {
if (coordinatesInvalid(coordinateData)) {
return;
}
ViewId uniqueId = new ViewId(coordinateData.getX(), coordinateData.getY(), false);
GridLayout.LayoutParams gridParams = getLayoutParamsForField(coordinateData);
View view = getView(context, style, form, fieldString, uniqueId, sortField,
gridParams.width, gridParams.height);
if (!(view instanceof ImageView)) {
gridParams.height = LayoutParams.WRAP_CONTENT;
}
view.setLayoutParams(gridParams);
mFieldViews[index] = view;
this.addView(view, gridParams);
}
private GridLayout.LayoutParams getLayoutParamsForField(GridCoordinate coordinateData) {
Spec columnSpec = GridLayout.spec(coordinateData.getX(), coordinateData.getWidth());
Spec rowSpec = GridLayout.spec(coordinateData.getY(), coordinateData.getHeight());
GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridParams.width = (int)Math.ceil(cellWidth * coordinateData.getWidth());
gridParams.height = (int)Math.ceil(cellHeight * coordinateData.getHeight());
return gridParams;
}
private boolean coordinatesInvalid(GridCoordinate coordinate) {
if (coordinate.getX() + coordinate.getWidth() > NUMBER_COLUMNS_PER_GRID ||
coordinate.getY() + coordinate.getHeight() > numRowsPerTile) {
Logger.log("e", "Grid entry dimensions exceed allotted sizes");
throw new XPathUnhandledException("grid coordinates out of bounds: " +
coordinate.getX() + " " + coordinate.getWidth() + ", " +
coordinate.getY() + " " + coordinate.getHeight());
}
return (coordinate.getX() < 0 || coordinate.getY() < 0);
}
/**
* Get the correct View for this particular activity.
*
* @param fieldForm either "image", "audio", or default text. Describes how this XPath result should be displayed.
* @param rowData The actual data to display, either an XPath to media or a String to display.
*/
private View getView(Context context, GridStyle style, String fieldForm, String rowData,
ViewId uniqueId, String searchField, int maxWidth, int maxHeight) {
// How the text should be aligned horizontally - left, center, or right
String horzAlign = style.getHorzAlign();
// How the text should be aligned vertically - top, center, or bottom
String vertAlign = style.getVertAlign();
View retVal;
switch (fieldForm) {
case EntityView.FORM_IMAGE:
retVal = new ImageView(context);
setScaleType((ImageView)retVal, horzAlign);
// make the image's padding proportional to its size
retVal.setPadding(maxWidth/6, maxHeight/6, maxWidth/6, maxHeight/6);
if (rowData != null && !rowData.equals("")) {
if (mImageLoader != null) {
mImageLoader.display(rowData, ((ImageView) retVal), R.drawable.info_bubble,
maxWidth, maxHeight);
} else {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), rowData,
maxWidth, maxHeight);
((ImageView) retVal).setImageBitmap(b);
}
}
break;
case EntityView.FORM_AUDIO:
if (rowData != null & rowData.length() > 0) {
retVal = new AudioButton(context, rowData, uniqueId, true);
} else {
retVal = new AudioButton(context, rowData, uniqueId, false);
}
break;
default:
retVal = new TextView(context);
//the html spanner currently does weird stuff like converts "a a" into "a a"
//so we've gotta mirror that for the search text. Booooo. I dunno if there's any
//other other side effects (newlines? nbsp?)
String htmlIfiedSearchField = searchField == null ? searchField : MarkupUtil.getSpannable(searchField).toString();
String cssid = style.getCssID();
if (cssid != null && !cssid.equals("none")) {
// user defined a style we want to use
Spannable mSpannable = MarkupUtil.getCustomSpannable(cssid, rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView) retVal).setText(mSpannable);
} else {
// just process inline markup
Spannable mSpannable = MarkupUtil.returnCSS(rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView) retVal).setText(mSpannable);
}
int gravity = 0;
// handle horizontal alignments
switch (horzAlign) {
case "center":
gravity |= Gravity.CENTER_HORIZONTAL;
break;
case "left":
gravity |= Gravity.LEFT;
break;
case "right":
gravity |= Gravity.RIGHT;
break;
}
// handle vertical alignment
switch (vertAlign) {
case "center":
gravity |= Gravity.CENTER_VERTICAL;
break;
case "top":
gravity |= Gravity.TOP;
break;
case "bottom":
gravity |= Gravity.BOTTOM;
break;
}
if(gravity != 0) {
((TextView) retVal).setGravity(gravity);
}
// handle text resizing
switch (style.getFontSize()) {
case "large":
((TextView) retVal).setTextSize(LARGE_FONT / DENSITY);
break;
case "small":
((TextView) retVal).setTextSize(SMALL_FONT / DENSITY);
break;
case "medium":
((TextView) retVal).setTextSize(MEDIUM_FONT / DENSITY);
break;
case "xlarge":
((TextView) retVal).setTextSize(XLARGE_FONT / DENSITY);
break;
}
}
return retVal;
}
private static void setScaleType(ImageView imageView, String horizontalAlignment) {
switch (horizontalAlignment) {
case "center":
imageView.setScaleType(ScaleType.CENTER_INSIDE);
break;
case "left":
imageView.setScaleType(ScaleType.FIT_START);
break;
case "right":
imageView.setScaleType(ScaleType.FIT_END);
break;
}
}
public void setSearchTerms(String[] currentSearchTerms) {
this.searchTerms = currentSearchTerms;
}
public void setTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
}
}
}
public void setTitleTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
return;
}
}
}
private boolean tileBeingShownInGridView() {
return numTilesPerRow > 1;
}
private void setPaddingIfNotInGridView() {
if (!tileBeingShownInGridView()) {
setPadding(DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL,
DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL);
}
}
}
| app/src/org/commcare/views/EntityViewTile.java | /**
*
*/
package org.commcare.views;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.support.v4.util.Pair;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.Space;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import org.commcare.dalvik.R;
import org.commcare.models.AsyncEntity;
import org.commcare.models.Entity;
import org.commcare.suite.model.Detail;
import org.commcare.util.GridCoordinate;
import org.commcare.util.GridStyle;
import org.commcare.utils.CachingAsyncImageLoader;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.MediaUtil;
import org.commcare.views.media.AudioButton;
import org.commcare.views.media.ViewId;
import org.javarosa.core.services.Logger;
import org.javarosa.xpath.XPathUnhandledException;
import java.util.Arrays;
/**
* @author wspride
* This class defines an individual panel within an advanced case list.
* Each panel is defined by a Detail and an Entity
* Significant axis of configuration are NUMBER_ROWS, NUMBER_COLUMNS, AND CELL_HEIGHT_DIVISOR defined below
*/
public class EntityViewTile extends GridLayout {
private String[] searchTerms;
// All of the views that are being shown in this tile, one for each field of the entity's detail
private View[] mFieldViews;
private boolean mFuzzySearchEnabled = false;
private boolean mIsAsynchronous = false;
// load the screen-size-dependent font sizes
private final float SMALL_FONT = getResources().getDimension(R.dimen.font_size_small);
private final float MEDIUM_FONT = getResources().getDimension(R.dimen.font_size_medium);
private final float LARGE_FONT = getResources().getDimension(R.dimen.font_size_large);
private final float XLARGE_FONT = getResources().getDimension(R.dimen.font_size_xlarge);
private final float DENSITY = getResources().getDisplayMetrics().density;
private final int DEFAULT_TILE_PADDING_HORIZONTAL =
(int)getResources().getDimension(R.dimen.row_padding_horizontal);
private final int DEFAULT_TILE_PADDING_VERTICAL =
(int)getResources().getDimension(R.dimen.row_padding_vertical);
// constants used to calibrate how many tiles should be shown on a screen
private static final int DEFAULT_NUMBER_ROWS_PER_GRID = 6;
private static final double DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT = 4;
private static final double DEFAULT_SCREEN_HEIGHT_IN_INCHES = 4.0;
private static final double LANDSCAPE_TO_PORTRAIT_RATIO = .75;
// this is fixed for all tiles
private static final int NUMBER_COLUMNS_PER_GRID = 12;
private final int numRowsPerTile;
private final int numTilesPerRow;
private double cellWidth;
private double cellHeight;
private final CachingAsyncImageLoader mImageLoader;
private final boolean beingDisplayedInAwesomeMode;
public static EntityViewTile createTileForIndividualDisplay(Context context, Detail detail,
Entity entity) {
return new EntityViewTile(context, detail, entity, new String[0],
new CachingAsyncImageLoader(context), false, false);
}
public static EntityViewTile createTileForEntitySelectDisplay(Context context, Detail detail,
Entity entity,
String[] searchTerms,
CachingAsyncImageLoader loader,
boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
return new EntityViewTile(context, detail, entity, searchTerms, loader,
fuzzySearchEnabled, inAwesomeMode);
}
private EntityViewTile(Context context, Detail detail, Entity entity, String[] searchTerms,
CachingAsyncImageLoader loader, boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
super(context);
this.searchTerms = searchTerms;
this.mIsAsynchronous = entity instanceof AsyncEntity;
this.mImageLoader = loader;
this.mFuzzySearchEnabled = fuzzySearchEnabled;
this.numRowsPerTile = getMaxRows(detail);
this.numTilesPerRow = detail.getNumEntitiesToDisplayPerRow();
this.beingDisplayedInAwesomeMode = inAwesomeMode;
setEssentialGridLayoutValues();
setCellWidthAndHeight(context, detail);
addFieldViews(context, detail, entity);
}
/**
* @return the maximum height of the grid view for the given detail
*/
private static int getMaxRows(Detail detail) {
GridCoordinate[] coordinates = detail.getGridCoordinates();
int currentMaxHeight = 0;
for (GridCoordinate coordinate : coordinates) {
int yCoordinate = coordinate.getY();
int height = coordinate.getHeight();
int maxHeight = yCoordinate + height;
if (maxHeight > currentMaxHeight) {
currentMaxHeight = maxHeight;
}
}
return currentMaxHeight;
}
private void setEssentialGridLayoutValues() {
setColumnCount(NUMBER_COLUMNS_PER_GRID);
setRowCount(numRowsPerTile);
setPaddingIfNotInGridView();
}
private void setCellWidthAndHeight(Context context, Detail detail) {
Pair<Integer, Integer> tileWidthAndHeight = computeTileWidthAndHeight(context);
cellWidth = tileWidthAndHeight.first / (double)NUMBER_COLUMNS_PER_GRID;
if (detail.useUniformUnitsInCaseTile()) {
cellHeight = cellWidth;
} else {
cellHeight = tileWidthAndHeight.second / (double)numRowsPerTile;
}
}
/**
* Compute what the width and height of a single tile should be, based upon the available
* screen space, how many columns there should be, and how many rows we want to show at a time.
* Round up to the nearest integer since the GridView's width and height will ultimately be
* computed indirectly from these values, and those values need to be integers, and we don't
* want to end up cutting things off
*/
private Pair<Integer, Integer> computeTileWidthAndHeight(Context context) {
double screenWidth, screenHeight;
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
} else {
screenWidth = display.getWidth();
screenHeight = display.getHeight();
}
if (!tileBeingShownInGridView()) {
// If we added padding, subtract that space since we can't use it
screenWidth = screenWidth - DEFAULT_TILE_PADDING_HORIZONTAL * 2;
}
int tileHeight;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (beingDisplayedInAwesomeMode) {
// if in awesome mode, split available width in half
screenWidth = screenWidth / 2;
}
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(false, screenHeight));
} else {
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(true, screenHeight));
}
int tileWidth = (int)Math.ceil(screenWidth / numTilesPerRow);
return new Pair<>(tileWidth, tileHeight);
}
/**
* @return - the number of tiles that should be displayed on a single screen on this device,
* calibrated based upon both the screen density and the screen height in inches
*/
private double computeNumTilesPerScreen(boolean inPortrait, double screenHeightInPixels) {
double numTilesPerScreenPortrait = DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT *
(DEFAULT_NUMBER_ROWS_PER_GRID / (float) numRowsPerTile);
double baseNumberOfTiles;
if (inPortrait) {
baseNumberOfTiles = numTilesPerScreenPortrait;
} else {
baseNumberOfTiles = numTilesPerScreenPortrait * LANDSCAPE_TO_PORTRAIT_RATIO;
}
int screenDensity = getResources().getDisplayMetrics().densityDpi;
return (baseNumberOfTiles + getAdditionalTilesBasedOnScreenDensity(screenDensity))
* getScreenHeightMultiplier(screenDensity, screenHeightInPixels);
}
private static double getAdditionalTilesBasedOnScreenDensity(int screenDensity) {
// For every additional 160dpi from the default density, show one more tile on the screen
int defaultDensityDpi = DisplayMetrics.DENSITY_MEDIUM;
return (screenDensity - defaultDensityDpi) / 160;
}
private static double getScreenHeightMultiplier(int screenDensity, double screenHeightInPixels) {
double screenHeightInInches = screenHeightInPixels / screenDensity;
return screenHeightInInches / DEFAULT_SCREEN_HEIGHT_IN_INCHES;
}
/**
* Add Spaces to this GridLayout to strictly enforce that Grid columns and rows stay the width/height we want
* Android GridLayout tries to be very "smart" about moving entries placed arbitrarily within the grid so that
* they look "ordered" even though this often ends up looking not how we want it. It will only make these adjustments
* to rows/columns that end up empty or near empty, so we solve this by adding spaces to every row and column.
* We just add a space of width cellWidth and height 1 to every column of the first row, and likewise a sapce of height
* cellHeight and width 1 to every row of the first column. These are then written on top of if need be.
*/
private void addBuffers(Context context) {
for (int i = 0; i < numRowsPerTile; i++) {
Spec rowSpec = GridLayout.spec(i);
Spec colSpec = GridLayout.spec(0);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = 1;
mGridParams.height = (int) cellHeight;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
for (int i = 0; i < NUMBER_COLUMNS_PER_GRID; i++) {
Spec rowSpec = GridLayout.spec(0);
Spec colSpec = GridLayout.spec(i);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = (int) cellWidth;
mGridParams.height = 1;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
}
/**
* Add the view for each field in the detail
*
* @param detail - the Detail describing how to display each entry
* @param entity - the Entity describing the actual data of each entry
*/
public void addFieldViews(Context context, Detail detail, Entity entity) {
this.removeAllViews();
addBuffers(context); // add spacers to enforce regularized column and row size
GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates();
String[] typesOfEachField = detail.getTemplateForms();
GridStyle[] stylesOfEachField = detail.getGridStyles();
Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) +
" | Coords: " + Arrays.toString(coordinatesOfEachField) +
" | Styles: " + Arrays.toString(stylesOfEachField));
setPaddingIfNotInGridView();
if (tileBeingShownInGridView()) {
// Fake dividers between each square in the grid view by using contrasting
// background colors for the grid view as a whole and each element in the grid view
setBackgroundColor(Color.parseColor("#ffffff"));
}
mFieldViews = new View[coordinatesOfEachField.length];
for (int i = 0; i < mFieldViews.length; i++) {
addFieldView(context, typesOfEachField[i], stylesOfEachField[i],
coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i);
}
}
private void addFieldView(Context context, String form,
GridStyle style, GridCoordinate coordinateData, String fieldString,
String sortField, int index) {
if (coordinatesInvalid(coordinateData)) {
return;
}
ViewId uniqueId = new ViewId(coordinateData.getX(), coordinateData.getY(), false);
GridLayout.LayoutParams gridParams = getLayoutParamsForField(coordinateData);
View view = getView(context, style, form, fieldString, uniqueId, sortField,
gridParams.width, gridParams.height);
if (!(view instanceof ImageView)) {
gridParams.height = LayoutParams.WRAP_CONTENT;
}
view.setLayoutParams(gridParams);
mFieldViews[index] = view;
this.addView(view, gridParams);
}
private GridLayout.LayoutParams getLayoutParamsForField(GridCoordinate coordinateData) {
Spec columnSpec = GridLayout.spec(coordinateData.getX(), coordinateData.getWidth());
Spec rowSpec = GridLayout.spec(coordinateData.getY(), coordinateData.getHeight());
GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridParams.width = (int)Math.ceil(cellWidth * coordinateData.getWidth());
gridParams.height = (int)Math.ceil(cellHeight * coordinateData.getHeight());
return gridParams;
}
private boolean coordinatesInvalid(GridCoordinate coordinate) {
if (coordinate.getX() + coordinate.getWidth() > NUMBER_COLUMNS_PER_GRID ||
coordinate.getY() + coordinate.getHeight() > numRowsPerTile) {
Logger.log("e", "Grid entry dimensions exceed allotted sizes");
throw new XPathUnhandledException("grid coordinates out of bounds: " +
coordinate.getX() + " " + coordinate.getWidth() + ", " +
coordinate.getY() + " " + coordinate.getHeight());
}
return (coordinate.getX() < 0 || coordinate.getY() < 0);
}
/**
* Get the correct View for this particular activity.
*
* @param fieldForm either "image", "audio", or default text. Describes how this XPath result should be displayed.
* @param rowData The actual data to display, either an XPath to media or a String to display.
*/
private View getView(Context context, GridStyle style, String fieldForm, String rowData,
ViewId uniqueId, String searchField, int maxWidth, int maxHeight) {
// How the text should be aligned horizontally - left, center, or right
String horzAlign = style.getHorzAlign();
// How the text should be aligned vertically - top, center, or bottom
String vertAlign = style.getVertAlign();
View retVal;
switch (fieldForm) {
case EntityView.FORM_IMAGE:
retVal = new ImageView(context);
setScaleType((ImageView)retVal, horzAlign);
// make the image's padding proportional to its size
retVal.setPadding(maxWidth/6, maxHeight/6, maxWidth/6, maxHeight/6);
if (rowData != null && !rowData.equals("")) {
if (mImageLoader != null) {
mImageLoader.display(rowData, ((ImageView) retVal), R.drawable.info_bubble,
maxWidth, maxHeight);
} else {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), rowData,
maxWidth, maxHeight);
((ImageView) retVal).setImageBitmap(b);
}
}
break;
case EntityView.FORM_AUDIO:
if (rowData != null & rowData.length() > 0) {
retVal = new AudioButton(context, rowData, uniqueId, true);
} else {
retVal = new AudioButton(context, rowData, uniqueId, false);
}
break;
default:
retVal = new TextView(context);
//the html spanner currently does weird stuff like converts "a a" into "a a"
//so we've gotta mirror that for the search text. Booooo. I dunno if there's any
//other other side effects (newlines? nbsp?)
String htmlIfiedSearchField = searchField == null ? searchField : MarkupUtil.getSpannable(searchField).toString();
String cssid = style.getCssID();
if (cssid != null && !cssid.equals("none")) {
// user defined a style we want to use
Spannable mSpannable = MarkupUtil.getCustomSpannable(cssid, rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView) retVal).setText(mSpannable);
} else {
// just process inline markup
Spannable mSpannable = MarkupUtil.returnCSS(rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView) retVal).setText(mSpannable);
}
int gravity = 0;
// handle horizontal alignments
switch (horzAlign) {
case "center":
gravity |= Gravity.CENTER_HORIZONTAL;
break;
case "left":
gravity |= Gravity.LEFT;
break;
case "right":
gravity |= Gravity.RIGHT;
break;
}
// handle vertical alignment
switch (vertAlign) {
case "center":
gravity |= Gravity.CENTER_VERTICAL;
break;
case "top":
gravity |= Gravity.TOP;
break;
case "bottom":
gravity |= Gravity.BOTTOM;
break;
}
if(gravity != 0) {
((TextView) retVal).setGravity(gravity);
}
// handle text resizing
switch (style.getFontSize()) {
case "large":
((TextView) retVal).setTextSize(LARGE_FONT / DENSITY);
break;
case "small":
((TextView) retVal).setTextSize(SMALL_FONT / DENSITY);
break;
case "medium":
((TextView) retVal).setTextSize(MEDIUM_FONT / DENSITY);
break;
case "xlarge":
((TextView) retVal).setTextSize(XLARGE_FONT / DENSITY);
break;
}
}
return retVal;
}
private static void setScaleType(ImageView imageView, String horizontalAlignment) {
switch (horizontalAlignment) {
case "center":
imageView.setScaleType(ScaleType.CENTER_INSIDE);
break;
case "left":
imageView.setScaleType(ScaleType.FIT_START);
break;
case "right":
imageView.setScaleType(ScaleType.FIT_END);
break;
}
}
public void setSearchTerms(String[] currentSearchTerms) {
this.searchTerms = currentSearchTerms;
}
public void setTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
}
}
}
public void setTitleTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
return;
}
}
}
private boolean tileBeingShownInGridView() {
return numTilesPerRow > 1;
}
private void setPaddingIfNotInGridView() {
if (!tileBeingShownInGridView()) {
setPadding(DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL,
DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL);
}
}
}
| better comments
| app/src/org/commcare/views/EntityViewTile.java | better comments |
|
Java | apache-2.0 | 3610e6592994d64163300eef4f2198c8188e8eca | 0 | bonhamdaniel/benchwarmer-timemachine,bonhamdaniel/benchwarmer-timemachine | /**
* BenchwarmerController is the main controller for the NHL Time Machine web application.
* It handles all request mapping, as well as flow control and access to utility classes.
*
* @author Dan Bonham
* @version 1.0.0
* @since 2017-08-26
*/
package com.benchwarmer.spring;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.benchwarmer.spring.service.GoalieSeasonsService;
import com.benchwarmer.spring.service.PlayerService;
import com.benchwarmer.spring.model.Goalieseasons;
import com.benchwarmer.spring.model.Player;
import com.benchwarmer.spring.service.SeasonService;
import com.benchwarmer.spring.model.Season;
import com.benchwarmer.spring.service.SkaterSeasonsService;
import com.benchwarmer.spring.model.Skaterseasons;
@Controller
@SessionAttributes({"playerbios", "searchableplayers", "seasons", "skater", "baseS", "targetS", "min", "sort", "pageNum", "players", "goalies"})
public class BenchwarmerController {
@Autowired private SeasonService seasonService;
@Autowired private SkaterSeasonsService skaterService;
@Autowired private GoalieSeasonsService goalieService;
@Autowired private PlayerService playerService;
@ModelAttribute("playerbios") public List<Player> playerbios() { return playerService.playerList(); } // used to populate player select inputs
@ModelAttribute("seasons") public List<Season> seasons() { return seasonService.seasonList(); } // used to populate season select inputs
@ModelAttribute("baseS") public int baseS() { return 20162017; } // holds base season for stat transformation - the season to transform
@ModelAttribute("targetS") public int targetS() { return 20162017; } // holds target season for stat transformation - the production levels to transform to
@ModelAttribute("min") public int min() { return 20; } // used to filter results by a minimum number of player games played
@ModelAttribute("sort") public String sort() { return "pts"; } // used to hold the column currently used to sort the data
@ModelAttribute("pageNum") public int pageNum() { return 1; } // used to hold the current table data page - pagination
@ModelAttribute("players") public List<ConvertedSkater> players() { return transformStats(skaterService.skaterList(20162017, 20), 20162017, 20162017); } // holds the skater transformation result sets
@ModelAttribute("goalies") public List<ConvertedGoalie> goalies() { return transformGoalies(goalieService.goalieList(20162017, 20), 20162017, 20162017); } // holds the goalie transformation result sets
@ModelAttribute("searchableplayers") // ensures player bio data is only accessed once and can then be searched by playerid
public Map<Integer, Player> searchableplayers(@ModelAttribute("playerbios") List<Player> playerbios) { // retrieves all player bios from db
Map<Integer, Player> players = new HashMap<Integer, Player>(); // creates new hashmap with playerid as key and player bio as value
for(Player p : playerbios) players.put(p.getPlayerid(), p); // adds each player bio to map with key added
return players; // returns new player bio hashmap
} // searchableplayers()
@RequestMapping({"/welcome"}) // handles initial loading of the application
public String welcome(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "welcome";
} // welcome()
@RequestMapping({"/intro"}) // handles initial loading of the application
public String intro(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "intro";
} // intro()
@RequestMapping({"/timemachine"}) // handles initial loading of the application
public String timemachine(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "timemachine";
} // timemachine()
@RequestMapping(value = "/skaters") // handles view for skater transformation menu with default values
public String skaters(Model model) {
model.addAttribute("baseS", "20162017");
model.addAttribute("targetS", "20162017");
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
model.addAttribute("min", 20);
return "skaters";
} // skaters()
@RequestMapping(value = "/goalies") // handles view for goalie transformation menu with default values
public String goalies(Model model) {
model.addAttribute("baseS", "20162017");
model.addAttribute("targetS", "20162017");
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
model.addAttribute("min", 20);
return "goalies";
} // goalies()
@RequestMapping(value = "/comparator") // handles view for player comparator menu with default values
public String comparator(Model model, @ModelAttribute("playerbios") List<Player> playerbios, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
model.addAttribute("baseS", "20162017");
model.addAttribute("p1", searchableplayers.get(8478550));
model.addAttribute("p2", searchableplayers.get(8476453));
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
return "comparator";
}// comparator()
@RequestMapping(value = "/skatertable", method = RequestMethod.GET) // handles view for the presentation of skater transformation data
public String skatertable(@RequestParam Map<String, String> params, Model model, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("seasons") List<Season> seasons) {
int targetSeason = Integer.parseInt(params.get("targetSeason")); // retrieves target season for transformation from get request
int min = Integer.parseInt(params.get("min")); // retrieves minimum games played for filtering the transformation from get request
int baseSeason; // will hold user-specified base season
if (params.get("baseSeason").equals("0")) { // retrieves base season for transformation from get request
baseSeason = 0; // value used when the user wishes to transform skater data from all available seasons
players = new ArrayList<ConvertedSkater>(); // prepares for new result set
for (Season s : seasons) // gets skater data for each season
players.addAll(transformStats(skaterService.skaterList(s.getSeasonid(), min), s.getSeasonid(), targetSeason)); // transforms skater data
} // if (season==0)
else { // handles individual season transformation requests
baseSeason = Integer.parseInt(params.get("baseSeason")); // retrieves requested base season from get
players = transformStats(skaterService.skaterList(baseSeason, min), baseSeason, targetSeason); // transforms base season skater data
if (params.containsKey("include")) { // determines whether the user has requested to include skater data from target season for comparison
players.addAll(transformStats(skaterService.skaterList(targetSeason, min), targetSeason, targetSeason)); // transforms target season skater data
} // if (include)
} // else
sortSkaters(players, params.get("sort")); // retrieves user-specified sort column and sorts skater data
model.addAttribute("players", players); // adds newly created skater transformation data to model
model.addAttribute("skaters", players.subList(0, 25)); // limits data to first 25 results - used for pagination
model.addAttribute("baseS", baseSeason); // sets user-specified base season to model
model.addAttribute("targetS", targetSeason); // sets user-specified target season to model
model.addAttribute("min", min); // sets user-specified minimum games played for filtering to model
return "skatertable"; // directs to skater table view
}// skatertable()
@RequestMapping(value = "/goalietable", method = RequestMethod.GET) // handles view for the presentation of goalie transformation data
public String goalietable(@RequestParam Map<String, String> params, Model model, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("seasons") List<Season> seasons) {
int targetSeason = Integer.parseInt(params.get("targetSeason")); // retrieves target season for transformation from get request
int min = Integer.parseInt(params.get("min")); // retrieves minimum games played for filtering the transformation from get request
int baseSeason; // will hold user-specified base season
if (params.get("baseSeason").equals("0")) { // retrieves base season for transformation from get request
baseSeason = 0; // values used when the user wishes to transform goalie data from all available seasons
goalies = new ArrayList<ConvertedGoalie>(); // prepares for new result set
for (Season s : seasons) // gets skater data for each season
goalies.addAll(transformGoalies(goalieService.goalieList(s.getSeasonid(), min), s.getSeasonid(), targetSeason)); // transforms goalie data
} // if (season==0)
else { // handles individual season transformation requests
baseSeason= Integer.parseInt(params.get("baseSeason")); // retrieves requested base season from get
goalies = transformGoalies(goalieService.goalieList(baseSeason, min), baseSeason, targetSeason); // transforms base season goalie data
if (params.containsKey("include")) { // determines whether the user has requested to include goalie data from target season for comparison
goalies.addAll(transformGoalies(goalieService.goalieList(targetSeason, min), targetSeason, targetSeason)); // transforms target season goalie data
} // if (include)
} // else
sortGoalies(goalies, params.get("sort")); // retrieves user-specified sort column and sorts goalie data
model.addAttribute("goalies", goalies); // adds newly created goalie transformation data to model
model.addAttribute("current", goalies.subList(0, 25)); // limits data to first 25 results - used for pagination
model.addAttribute("baseS", baseSeason); // sets user-specified base season to model
model.addAttribute("targetS", targetSeason); // sets user-specified target season to model
model.addAttribute("min", min); // sets user-specified minimum games played for filtering to model
return "goalietable"; // directs to goalie table view
} // goalietable()
@RequestMapping(value = "/validatecomparator", method = RequestMethod.GET)
public @ResponseBody String validatecomparator(@RequestParam("player1") String player1, @RequestParam("player2") String player2, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
String result;
Player p1 = searchableplayers.get(Integer.parseInt(player1)); // retrieves user-specified player to be used for comparison
Player p2 = searchableplayers.get(Integer.parseInt(player2)); // retrieves user-specified player to be used for comparison
if ((p1.getPosition().equals("G") && !p2.getPosition().equals("G")) || (p2.getPosition().equals("G") && !p1.getPosition().equals("G"))) { // handles incomparable data
result = "false";
} // if (incomparable data)
else result = "true";
return result;
} // validatecomparator()
@RequestMapping(value = "/comptable", method = RequestMethod.GET) // handles view for the presentation of player comparison data
public String comptable(HttpServletRequest request, @RequestParam Map<String, String> params, Model model, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
int baseSeason = Integer.parseInt(params.get("baseSeason")); // retrieves user-specified base season to be used for player comparison
Player p1 = searchableplayers.get(Integer.parseInt(params.get("player1"))); // retrieves user-specified player to be used for comparison
Player p2 = searchableplayers.get(Integer.parseInt(params.get("player2"))); // retrieves user-specified player to be used for comparison
if ((p1.getPosition().equals("G") && !p2.getPosition().equals("G")) || (p2.getPosition().equals("G") && !p1.getPosition().equals("G"))) { // handles incomparable data
String referer = request.getHeader("Referer");
return "redirect:" + referer;
} // if (incomparable data)
if (!p1.getPosition().equals("G")) { // handles skater comparisons
List<Skaterseasons> p1Seasons = skaterService.playerSeasons(p1.getPlayerid()); // gets data for all applicable seasons for first skater
List<Skaterseasons> p2Seasons = skaterService.playerSeasons(p2.getPlayerid()); // gets data for all applicable seasons for second skater
if (params.containsKey("include")) { // determines whether the user has specified to display individual season data
players = transformStats(p1Seasons, baseSeason); // transforms skater one seasons to base year
players.addAll(transformStats(p2Seasons, baseSeason)); // transforms skater two seasons to base year
} // if (include)
else { // handles skater data transformed and presented by complete career
players = transformStats(p1Seasons, p2Seasons, baseSeason); // transforms both skater's data
} // else
sortSkaters(players, params.get("sort")); // sorts skater data based on user-specified column
model.addAttribute("baseS", "20992100"); // included for table caption formatting - dummy value
model.addAttribute("targetS", String.valueOf(baseSeason)); // sets user-specified base season to model (uses targetS variable bc comparison data is calculated differently)
model.addAttribute("p1", p1); // adds user-specified first comparable skater to model
model.addAttribute("p2", p2); // adds user-specified second comparable skater to model
model.addAttribute("players", players); // adds newly created skater transformation data to model
if (players.size() > 25) model.addAttribute("skaters", players.subList(0, 25)); // limits result set to first 25 skaters - pagination
else model.addAttribute("skaters", players); // adds all skaters if less than 25 results
return "skatertable"; // directs to skater table view
} // if (skater)
else { // handles goalie comparisons
List<Goalieseasons> p1Seasons = goalieService.goalieSeasons(p1.getPlayerid()); // gets data for all applicable seasons for first goalie
List<Goalieseasons> p2Seasons = goalieService.goalieSeasons(p2.getPlayerid()); // gets data for all applicable seasons for second goalie
if (params.containsKey("include")) { // determines whether the user has specified to display individual season data
goalies = transformGoalies(p1Seasons, baseSeason); // transforms goalie one seasons to base year
goalies.addAll(transformGoalies(p2Seasons, baseSeason)); // transforms goalie two seasons to base year
} // if (include)
else { // handles goalie data transformed and presented by complete career
goalies = transformGoalies(p1Seasons, p2Seasons, baseSeason); // transforms both goalie's data
} // else
sortGoalies(goalies, params.get("sort")); // sorts goalie data based on user-specified column
model.addAttribute("targetS", String.valueOf(baseSeason)); // sets user-specified base season to model (uses targetS variable bc comparison data is calculated differently)
model.addAttribute("p1", p1); // adds user-specified first comparable goalie to model
model.addAttribute("p2", p2); // adds user-specified second comparable goalie to model
model.addAttribute("goalies", goalies); // adds newly created goalie transformation data to model
if (goalies.size() > 25) model.addAttribute("current", goalies.subList(0, 25)); // limits result set to first 25 goalies - pagination
else model.addAttribute("current", goalies); // adds all goalies if less than 25 results
return "goalietable"; // directs to goalie table view
} // else
} // comptable()
@RequestMapping(value = "/sortskater", method = RequestMethod.GET) // handles the user-requested sorting of skater data
public String sortskater(Model model, @RequestParam Map<String, String> params, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("sort") String sort, @ModelAttribute("pageNum") int pageNum) {
sort = params.get("sort"); // retrieves user-specified sort column from get
pageNum = Integer.parseInt(params.get("pageNum")); // retrieves current table page number - current location in data set
sortSkaters(players, sort); // sorts skater data based on specified column
if (players.size() > 25*pageNum) model.addAttribute("skaters", players.subList(25*pageNum-25, 25*pageNum)); // limits data set to 25 results - pagination
else model.addAttribute("skaters", players.subList(25*pageNum-25, players.size())); // adds all skaters if less than 25 results
model.addAttribute("sort", sort); // sets user-specified sort column to model
model.addAttribute("pageNum", pageNum); // sets current data location (in table) to model
return "skatertable"; // directs to skater table view
} // sortskater()
@RequestMapping(value = "/sortgoalie", method = RequestMethod.GET) // handles the user-requested sorting of goalie data
public String sortgoalie(Model model, @RequestParam Map<String, String> params, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("sort") String sort, @ModelAttribute("pageNum") int pageNum) {
sort = params.get("sort"); // retrieves user-specified sort column from get
pageNum = Integer.parseInt(params.get("pageNum")); // retrieves current table page number - current location in data set
sortGoalies(goalies, params.get("sort")); // sorts goalie data based on specified column
if (goalies.size() > 25*pageNum) model.addAttribute("current", goalies.subList(25*pageNum-25, 25*pageNum)); // limits data set to 25 results - pagination
else model.addAttribute("current", goalies.subList(25*pageNum-25, goalies.size())); // adds all goalies if less than 25 results
model.addAttribute("sort", sort); // sets user-specified sort column to model
model.addAttribute("pageNum", pageNum); // sets current data location (in table) to model
return "goalietable"; // directs to goalie table view
} // sortgoalie()
// sorts skater data set based on specified column
public void sortSkaters(List<ConvertedSkater> skaters, String column) {
skaters.sort(ConvertedSkater.getSort(column)); // sorts skaters based on specified column
for(int i = 0; i < skaters.size(); i++) skaters.get(i).setRank(i+1); // adds skater rank based on new sort
} // sortSkaters()
// sorts goalie data set based on specified column
public void sortGoalies(List<ConvertedGoalie> goalies, String column) {
goalies.sort(ConvertedGoalie.getSort(column)); // sorts goalies based on specified column
for(int i = 0; i < goalies.size(); i++) goalies.get(i).setRank(i+1); // adds goalie rank based on new sort
} // sortGoalies()
// transforms individual season skater data to specified era and returns result
public List<ConvertedSkater> transformStats(List<Skaterseasons> players, int baseS, int targetS) {
Season baseSeason = seasonService.getSeason(baseS).get(0); // retrieves data for base season
Season targetSeason = seasonService.getSeason(targetS).get(0); // retrieves data for target season
float evAdj = targetSeason.getEvgGp() / baseSeason.getEvgGp(); // calculates even strength goals adjustment
float ppAdj = targetSeason.getPpgGp() / baseSeason.getPpgGp(); // calculates power play goals adjustment
float shAdj = targetSeason.getShgGp() / baseSeason.getShgGp(); // calculates short handed goals adjustment
float sAdj = targetSeason.getSGp() / baseSeason.getSGp(); // calculates shots adjustment
float pimAdj = targetSeason.getPimGp() / baseSeason.getPimGp(); // calculates penalty minutes adjustment
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
for(Skaterseasons p : players) { // loops through and transforms each skater season applicable
int evg = (int)((p.getGoals()-p.getPpg()-p.getShg())*evAdj); // calculates skater's transformed even strength goals
int eva = (int)((p.getAssists()-p.getPpa()-p.getSha())*evAdj); // calculates skater's transformed even strength assists
int ppg = (int)(p.getPpg()*ppAdj); // calculates skater's transformed power play goals
int ppa = (int)(p.getPpa()*ppAdj); // calculates skater's transformed power play assists
int shg = (int)(p.getShg()*shAdj); // calculates skater's transformed short handed goals
int sha = (int)(p.getSha()*shAdj); // calculates skater's transformed short handed assists
int pim = (int)(p.getPim()*pimAdj); // calculates skater's transformed penalty minutes
int s = (int)(p.getShots()*sAdj); // calculates skater's transformed shots
int g = evg + ppg + shg; // sums skater's transformed total goals
int a = eva + ppa + sha; // sums skater's transformed total assists
int pts = evg + ppg + shg + eva + ppa + sha; // sums skater's total points
int evp = evg + eva; // sums skater's transformed total even strength points
int ppp = ppg + ppa; // sums skater's transformed total power play points
int shp = shg + sha; // sums skater's transformed total short handed points
float gpg = g / p.getGp(); // calculates skater's transformed goals per game
float apg = a / p.getGp(); // calculates skater's transformed assists per game
float pperg = pts / p.getGp(); // calculates skater's transformed points per game
skaters.add(new ConvertedSkater(p.getPlayername(), p.getSeasonid(), p.getGp(), evg, eva, ppg, ppa, shg, sha, pim, s, g, a, pts, evp, ppp, shp, gpg, apg, pperg)); // adds transformed skater season to result set
} // for (skater season)
return skaters; // returns transformed skater data
} // transformStats(individual season)
// transforms individual season goalie data to specified era and returns result
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> players, int baseS, int targetS) {
Season baseSeason = seasonService.getSeason(baseS).get(0); // retrieves data for base season
Season targetSeason = seasonService.getSeason(targetS).get(0); // retrieves data for target season
float sAdj = (1.0f*targetSeason.getSGp()) / (1.0f*baseSeason.getSGp()); // calculates shots adjustment
float svAdj = ((targetSeason.getS()*1.0f - 1.0f*targetSeason.getG()) / (1.0f*targetSeason.getS())) / ((baseSeason.getS()*1.0f - 1.0f*baseSeason.getG()) / (1.0f*baseSeason.getS())); // calculates save percentage adjustment
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
for(Goalieseasons p : players) { // loops through and transforms each goalie season applicable
if (p.getSa() > 0 && p.getSv() > 0) { // removes seasons where the goalie did not make a save
int w = (int)(p.getW() - p.getSow()); // calculates goalie's transformed wins
int l = (int)(p.getL() - p.getSol()); // calculates goalie's transformed losses
int sa = (int)(p.getSa() * sAdj); // calculates goalie's transformed shots against
float svpct = (1.0f*p.getSv())/(1.0f*p.getSa()); // calculates goalie's transformed save percentage
int sv = (int)(1.0f*sa * svpct); // calculates goalie's transformed saves
sv = (int)(1.0f*sv * svAdj);
goalies.add(new ConvertedGoalie(p.getPlayername(), p.getSeasonid(), p.getGp(), p.getToi(), w, l, sa, sv/*, sa60, gaa, svpct*/)); // adds transformed goalie season to result set
} // if (no data)
} // for (goalie season)
return goalies; // returns transformed goalie data
} // transformGoalies(individual season)
// transforms each season of career skater data to specified era and returns result
public List<ConvertedSkater> transformStats(List<Skaterseasons> players, int baseS) {
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
for (Skaterseasons p : players) { // loops through each season of skater data
List<Skaterseasons> temp = new ArrayList<Skaterseasons>(); // temporarily holds individual season skater data
temp.add(p); // adds current season of data
skaters.addAll(transformStats(temp, (p.getSeasonid()), baseS)); // adds current transformed season to skater's transformed career stats
} // for (season)
return skaters; // returns transformed skater career
}// transformStats(career seasons)
// transforms each season of career goalie data to specified era and returns result
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> players, int baseS) {
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
for (Goalieseasons p : players) { // loops through each season of goalie data
List<Goalieseasons> temp = new ArrayList<Goalieseasons>(); // temporarily holds individual season goalie data
temp.add(p); // adds current season of data
goalies.addAll(transformGoalies(temp, (p.getSeasonid()), baseS)); // adds current transformed season to goalie's transformed career stats
} // for (season)
return goalies; // returns transformed goalie career
}// transformGoalies(career seasons)
// helper function compiles sum of career skater data for comparison
public List<ConvertedSkater> transformStats(List<Skaterseasons> player1, List<Skaterseasons> player2, int baseS) {
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
skaters.add(convertSkater(player1, baseS)); // adds career data for skater one
skaters.add(convertSkater(player2, baseS)); // adds career data for skater two
return skaters; // returns compiled and transformed skater career data
} // transformStats(career sum)
// transforms, sums and returns a skater's career stats
public ConvertedSkater convertSkater(List<Skaterseasons> skater, int baseS) {
ConvertedSkater s = new ConvertedSkater(); // will hold transformed skater stats
s.setName(skater.get(0).getPlayername()); // sets the skater name
int minY = skater.get(0).getSeasonid(); // used to set skater's career span
int maxY = skater.get(0).getSeasonid(); // used to set skater's career span
for (Skaterseasons p : skater) { // loops through all a skater's active seasons
List<Skaterseasons> temp = new ArrayList<Skaterseasons>(); // will hold individual season data
temp.add(p); // adds current season
s.addAll(transformStats(temp, (p.getSeasonid()), baseS)); // adds current transformed season to transformed career total
if (p.getSeasonid() < minY) minY = p.getSeasonid(); // sets oldest year skater was active
if (p.getSeasonid() > maxY) maxY = p.getSeasonid(); // sets most recent year skater was active
} // for (seasons)
s.setCareerSpan(minY, maxY); // sets the span of seasons the skater was active
return s; // return transformed and compiled skater career data
} // convertSkater(career)
// helper function compiles sum of career goalie data for comparison
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> player1, List<Goalieseasons> player2, int baseS) {
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
goalies.add(convertGoalie(player1, baseS)); // adds career data for goalie one
goalies.add(convertGoalie(player2, baseS)); // adds career data for goalie two
return goalies; // returns compiled and transformed goalie career data
} // transformGoalies(career sum)
// transforms, sums and returns a goalie's career stats
public ConvertedGoalie convertGoalie(List<Goalieseasons> goalie, int baseS) {
ConvertedGoalie g = new ConvertedGoalie(); // will hold transformed career stats
g.setName(goalie.get(0).getPlayername()); // sets the goalie name
int minY = goalie.get(0).getSeasonid(); // used to set goalie's career span
int maxY = goalie.get(0).getSeasonid(); // used to set goalie's career span
for (Goalieseasons p : goalie) { // loops through all a goalie's active seasons
List<Goalieseasons> temp = new ArrayList<Goalieseasons>(); // will hold individual season data
temp.add(p); // adds current season
g.addAll(transformGoalies(temp, (p.getSeasonid()), baseS)); // adds current transformed season to transformed career total
if (p.getSeasonid() < minY) minY = p.getSeasonid(); // sets oldest year goalie was active
if (p.getSeasonid() > maxY) maxY = p.getSeasonid(); // sets most recent year goalie was active
} // for (season)
g.setCareerSpan(minY, maxY); // sets the span of seasons the goalie was active
return g; // return transformed and compiled goalie career data
} // convertGoalie(career sum)
} // class BenchwarmerController
| src/com/benchwarmer/spring/BenchwarmerController.java | /**
* BenchwarmerController is the main controller for the NHL Time Machine web application.
* It handles all request mapping, as well as flow control and access to utility classes.
*
* @author Dan Bonham
* @version 1.0.0
* @since 2017-08-26
*/
package com.benchwarmer.spring;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.benchwarmer.spring.service.GoalieSeasonsService;
import com.benchwarmer.spring.service.PlayerService;
import com.benchwarmer.spring.model.Goalieseasons;
import com.benchwarmer.spring.model.Player;
import com.benchwarmer.spring.service.SeasonService;
import com.benchwarmer.spring.model.Season;
import com.benchwarmer.spring.service.SkaterSeasonsService;
import com.benchwarmer.spring.model.Skaterseasons;
@Controller
@SessionAttributes({"playerbios", "searchableplayers", "seasons", "skater", "baseS", "targetS", "min", "sort", "pageNum", "players", "goalies"})
public class BenchwarmerController {
@Autowired private SeasonService seasonService;
@Autowired private SkaterSeasonsService skaterService;
@Autowired private GoalieSeasonsService goalieService;
@Autowired private PlayerService playerService;
@ModelAttribute("playerbios") public List<Player> playerbios() { return playerService.playerList(); } // used to populate player select inputs
@ModelAttribute("seasons") public List<Season> seasons() { return seasonService.seasonList(); } // used to populate season select inputs
@ModelAttribute("baseS") public int baseS() { return 20162017; } // holds base season for stat transformation - the season to transform
@ModelAttribute("targetS") public int targetS() { return 20162017; } // holds target season for stat transformation - the production levels to transform to
@ModelAttribute("min") public int min() { return 20; } // used to filter results by a minimum number of player games played
@ModelAttribute("sort") public String sort() { return "pts"; } // used to hold the column currently used to sort the data
@ModelAttribute("pageNum") public int pageNum() { return 1; } // used to hold the current table data page - pagination
@ModelAttribute("players") public List<ConvertedSkater> players() { return transformStats(skaterService.skaterList(20162017, 20), 20162017, 20162017); } // holds the skater transformation result sets
@ModelAttribute("goalies") public List<ConvertedGoalie> goalies() { return transformGoalies(goalieService.goalieList(20162017, 20), 20162017, 20162017); } // holds the goalie transformation result sets
@ModelAttribute("searchableplayers") // ensures player bio data is only accessed once and can then be searched by playerid
public Map<Integer, Player> searchableplayers(@ModelAttribute("playerbios") List<Player> playerbios) { // retrieves all player bios from db
Map<Integer, Player> players = new HashMap<Integer, Player>(); // creates new hashmap with playerid as key and player bio as value
for(Player p : playerbios) players.put(p.getPlayerid(), p); // adds each player bio to map with key added
return players; // returns new player bio hashmap
} // searchableplayers()
@RequestMapping({"/welcome"}) // handles initial loading of the application
public String welcome(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "welcome";
} // welcome()
@RequestMapping({"/intro"}) // handles initial loading of the application
public String intro(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "intro";
} // intro()
@RequestMapping({"/timemachine"}) // handles initial loading of the application
public String timemachine(@ModelAttribute("seasons") List<Season> seasons, @ModelAttribute("baseS") int baseS, @ModelAttribute("targetS") int targetS, @ModelAttribute("min") int min) {
return "timemachine";
} // timemachine()
@RequestMapping(value = "/skaters") // handles view for skater transformation menu with default values
public String skaters(Model model) {
model.addAttribute("baseS", "20162017");
model.addAttribute("targetS", "20162017");
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
model.addAttribute("min", 20);
return "skaters";
} // skaters()
@RequestMapping(value = "/goalies") // handles view for goalie transformation menu with default values
public String goalies(Model model) {
model.addAttribute("baseS", "20162017");
model.addAttribute("targetS", "20162017");
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
model.addAttribute("min", 20);
return "goalies";
} // goalies()
@RequestMapping(value = "/comparator") // handles view for player comparator menu with default values
public String comparator(Model model, @ModelAttribute("playerbios") List<Player> playerbios, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
model.addAttribute("baseS", "20162017");
model.addAttribute("p1", searchableplayers.get(8478550));
model.addAttribute("p2", searchableplayers.get(8476453));
model.addAttribute("sort", "pts");
model.addAttribute("pageNum", 1);
return "comparator";
}// comparator()
@RequestMapping(value = "/skatertable", method = RequestMethod.GET) // handles view for the presentation of skater transformation data
public String skatertable(@RequestParam Map<String, String> params, Model model, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("seasons") List<Season> seasons) {
int targetSeason = Integer.parseInt(params.get("targetSeason")); // retrieves target season for transformation from get request
int min = Integer.parseInt(params.get("min")); // retrieves minimum games played for filtering the transformation from get request
int baseSeason; // will hold user-specified base season
if (params.get("baseSeason").equals("0")) { // retrieves base season for transformation from get request
baseSeason = 0; // value used when the user wishes to transform skater data from all available seasons
players = new ArrayList<ConvertedSkater>(); // prepares for new result set
for (Season s : seasons) // gets skater data for each season
players.addAll(transformStats(skaterService.skaterList(s.getSeasonid(), min), s.getSeasonid(), targetSeason)); // transforms skater data
} // if (season==0)
else { // handles individual season transformation requests
baseSeason = Integer.parseInt(params.get("baseSeason")); // retrieves requested base season from get
players = transformStats(skaterService.skaterList(baseSeason, min), baseSeason, targetSeason); // transforms base season skater data
if (params.containsKey("include")) { // determines whether the user has requested to include skater data from target season for comparison
players.addAll(transformStats(skaterService.skaterList(targetSeason, min), targetSeason, targetSeason)); // transforms target season skater data
} // if (include)
} // else
sortSkaters(players, params.get("sort")); // retrieves user-specified sort column and sorts skater data
model.addAttribute("players", players); // adds newly created skater transformation data to model
model.addAttribute("skaters", players.subList(0, 25)); // limits data to first 25 results - used for pagination
model.addAttribute("baseS", baseSeason); // sets user-specified base season to model
model.addAttribute("targetS", targetSeason); // sets user-specified target season to model
model.addAttribute("min", min); // sets user-specified minimum games played for filtering to model
return "skatertable"; // directs to skater table view
}// skatertable()
@RequestMapping(value = "/goalietable", method = RequestMethod.GET) // handles view for the presentation of goalie transformation data
public String goalietable(@RequestParam Map<String, String> params, Model model, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("seasons") List<Season> seasons) {
int targetSeason = Integer.parseInt(params.get("targetSeason")); // retrieves target season for transformation from get request
int min = Integer.parseInt(params.get("min")); // retrieves minimum games played for filtering the transformation from get request
int baseSeason; // will hold user-specified base season
if (params.get("baseSeason").equals("0")) { // retrieves base season for transformation from get request
baseSeason = 0; // values used when the user wishes to transform goalie data from all available seasons
goalies = new ArrayList<ConvertedGoalie>(); // prepares for new result set
for (Season s : seasons) // gets skater data for each season
goalies.addAll(transformGoalies(goalieService.goalieList(s.getSeasonid(), min), s.getSeasonid(), targetSeason)); // transforms goalie data
} // if (season==0)
else { // handles individual season transformation requests
baseSeason= Integer.parseInt(params.get("baseSeason")); // retrieves requested base season from get
goalies = transformGoalies(goalieService.goalieList(baseSeason, min), baseSeason, targetSeason); // transforms base season goalie data
if (params.containsKey("include")) { // determines whether the user has requested to include goalie data from target season for comparison
goalies.addAll(transformGoalies(goalieService.goalieList(targetSeason, min), targetSeason, targetSeason)); // transforms target season goalie data
} // if (include)
} // else
sortGoalies(goalies, params.get("sort")); // retrieves user-specified sort column and sorts goalie data
model.addAttribute("goalies", goalies); // adds newly created goalie transformation data to model
model.addAttribute("current", goalies.subList(0, 25)); // limits data to first 25 results - used for pagination
model.addAttribute("baseS", baseSeason); // sets user-specified base season to model
model.addAttribute("targetS", targetSeason); // sets user-specified target season to model
model.addAttribute("min", min); // sets user-specified minimum games played for filtering to model
return "goalietable"; // directs to goalie table view
} // goalietable()
@RequestMapping(value = "/validatecomparator", method = RequestMethod.GET)
public @ResponseBody String validatecomparator(@RequestParam("player1") String player1, @RequestParam("player2") String player2, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
String result;
Player p1 = searchableplayers.get(Integer.parseInt(player1)); // retrieves user-specified player to be used for comparison
Player p2 = searchableplayers.get(Integer.parseInt(player2)); // retrieves user-specified player to be used for comparison
if ((p1.getPosition().equals("G") && !p2.getPosition().equals("G")) || (p2.getPosition().equals("G") && !p1.getPosition().equals("G"))) { // handles incomparable data
result = "false";
} // if (incomparable data)
else result = "true";
return result;
} // validatecomparator()
@RequestMapping(value = "/comptable", method = RequestMethod.GET) // handles view for the presentation of player comparison data
public String comptable(HttpServletRequest request, @RequestParam Map<String, String> params, Model model, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("searchableplayers") Map<Integer, Player> searchableplayers) {
int baseSeason = Integer.parseInt(params.get("baseSeason")); // retrieves user-specified base season to be used for player comparison
Player p1 = searchableplayers.get(Integer.parseInt(params.get("player1"))); // retrieves user-specified player to be used for comparison
Player p2 = searchableplayers.get(Integer.parseInt(params.get("player2"))); // retrieves user-specified player to be used for comparison
if ((p1.getPosition().equals("G") && !p2.getPosition().equals("G")) || (p2.getPosition().equals("G") && !p1.getPosition().equals("G"))) { // handles incomparable data
String referer = request.getHeader("Referer");
return "redirect:" + referer;
} // if (incomparable data)
if (!p1.getPosition().equals("G")) { // handles skater comparisons
List<Skaterseasons> p1Seasons = skaterService.playerSeasons(p1.getPlayerid()); // gets data for all applicable seasons for first skater
List<Skaterseasons> p2Seasons = skaterService.playerSeasons(p2.getPlayerid()); // gets data for all applicable seasons for second skater
if (params.containsKey("include")) { // determines whether the user has specified to display individual season data
players = transformStats(p1Seasons, baseSeason); // transforms skater one seasons to base year
players.addAll(transformStats(p2Seasons, baseSeason)); // transforms skater two seasons to base year
} // if (include)
else { // handles skater data transformed and presented by complete career
players = transformStats(p1Seasons, p2Seasons, baseSeason); // transforms both skater's data
} // else
sortSkaters(players, params.get("sort")); // sorts skater data based on user-specified column
model.addAttribute("targetS", String.valueOf(baseSeason)); // sets user-specified base season to model (uses targetS variable bc comparison data is calculated differently)
model.addAttribute("p1", p1); // adds user-specified first comparable skater to model
model.addAttribute("p2", p2); // adds user-specified second comparable skater to model
model.addAttribute("players", players); // adds newly created skater transformation data to model
if (players.size() > 25) model.addAttribute("skaters", players.subList(0, 25)); // limits result set to first 25 skaters - pagination
else model.addAttribute("skaters", players); // adds all skaters if less than 25 results
return "skatertable"; // directs to skater table view
} // if (skater)
else { // handles goalie comparisons
List<Goalieseasons> p1Seasons = goalieService.goalieSeasons(p1.getPlayerid()); // gets data for all applicable seasons for first goalie
List<Goalieseasons> p2Seasons = goalieService.goalieSeasons(p2.getPlayerid()); // gets data for all applicable seasons for second goalie
if (params.containsKey("include")) { // determines whether the user has specified to display individual season data
goalies = transformGoalies(p1Seasons, baseSeason); // transforms goalie one seasons to base year
goalies.addAll(transformGoalies(p2Seasons, baseSeason)); // transforms goalie two seasons to base year
} // if (include)
else { // handles goalie data transformed and presented by complete career
goalies = transformGoalies(p1Seasons, p2Seasons, baseSeason); // transforms both goalie's data
} // else
sortGoalies(goalies, params.get("sort")); // sorts goalie data based on user-specified column
model.addAttribute("targetS", String.valueOf(baseSeason)); // sets user-specified base season to model (uses targetS variable bc comparison data is calculated differently)
model.addAttribute("p1", p1); // adds user-specified first comparable goalie to model
model.addAttribute("p2", p2); // adds user-specified second comparable goalie to model
model.addAttribute("goalies", goalies); // adds newly created goalie transformation data to model
if (goalies.size() > 25) model.addAttribute("current", goalies.subList(0, 25)); // limits result set to first 25 goalies - pagination
else model.addAttribute("current", goalies); // adds all goalies if less than 25 results
return "goalietable"; // directs to goalie table view
} // else
} // comptable()
@RequestMapping(value = "/sortskater", method = RequestMethod.GET) // handles the user-requested sorting of skater data
public String sortskater(Model model, @RequestParam Map<String, String> params, @ModelAttribute("players") List<ConvertedSkater> players, @ModelAttribute("sort") String sort, @ModelAttribute("pageNum") int pageNum) {
sort = params.get("sort"); // retrieves user-specified sort column from get
pageNum = Integer.parseInt(params.get("pageNum")); // retrieves current table page number - current location in data set
sortSkaters(players, sort); // sorts skater data based on specified column
if (players.size() > 25*pageNum) model.addAttribute("skaters", players.subList(25*pageNum-25, 25*pageNum)); // limits data set to 25 results - pagination
else model.addAttribute("skaters", players.subList(25*pageNum-25, players.size())); // adds all skaters if less than 25 results
model.addAttribute("sort", sort); // sets user-specified sort column to model
model.addAttribute("pageNum", pageNum); // sets current data location (in table) to model
return "skatertable"; // directs to skater table view
} // sortskater()
@RequestMapping(value = "/sortgoalie", method = RequestMethod.GET) // handles the user-requested sorting of goalie data
public String sortgoalie(Model model, @RequestParam Map<String, String> params, @ModelAttribute("goalies") List<ConvertedGoalie> goalies, @ModelAttribute("sort") String sort, @ModelAttribute("pageNum") int pageNum) {
sort = params.get("sort"); // retrieves user-specified sort column from get
pageNum = Integer.parseInt(params.get("pageNum")); // retrieves current table page number - current location in data set
sortGoalies(goalies, params.get("sort")); // sorts goalie data based on specified column
if (goalies.size() > 25*pageNum) model.addAttribute("current", goalies.subList(25*pageNum-25, 25*pageNum)); // limits data set to 25 results - pagination
else model.addAttribute("current", goalies.subList(25*pageNum-25, goalies.size())); // adds all goalies if less than 25 results
model.addAttribute("sort", sort); // sets user-specified sort column to model
model.addAttribute("pageNum", pageNum); // sets current data location (in table) to model
return "goalietable"; // directs to goalie table view
} // sortgoalie()
// sorts skater data set based on specified column
public void sortSkaters(List<ConvertedSkater> skaters, String column) {
skaters.sort(ConvertedSkater.getSort(column)); // sorts skaters based on specified column
for(int i = 0; i < skaters.size(); i++) skaters.get(i).setRank(i+1); // adds skater rank based on new sort
} // sortSkaters()
// sorts goalie data set based on specified column
public void sortGoalies(List<ConvertedGoalie> goalies, String column) {
goalies.sort(ConvertedGoalie.getSort(column)); // sorts goalies based on specified column
for(int i = 0; i < goalies.size(); i++) goalies.get(i).setRank(i+1); // adds goalie rank based on new sort
} // sortGoalies()
// transforms individual season skater data to specified era and returns result
public List<ConvertedSkater> transformStats(List<Skaterseasons> players, int baseS, int targetS) {
Season baseSeason = seasonService.getSeason(baseS).get(0); // retrieves data for base season
Season targetSeason = seasonService.getSeason(targetS).get(0); // retrieves data for target season
float evAdj = targetSeason.getEvgGp() / baseSeason.getEvgGp(); // calculates even strength goals adjustment
float ppAdj = targetSeason.getPpgGp() / baseSeason.getPpgGp(); // calculates power play goals adjustment
float shAdj = targetSeason.getShgGp() / baseSeason.getShgGp(); // calculates short handed goals adjustment
float sAdj = targetSeason.getSGp() / baseSeason.getSGp(); // calculates shots adjustment
float pimAdj = targetSeason.getPimGp() / baseSeason.getPimGp(); // calculates penalty minutes adjustment
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
for(Skaterseasons p : players) { // loops through and transforms each skater season applicable
int evg = (int)((p.getGoals()-p.getPpg()-p.getShg())*evAdj); // calculates skater's transformed even strength goals
int eva = (int)((p.getAssists()-p.getPpa()-p.getSha())*evAdj); // calculates skater's transformed even strength assists
int ppg = (int)(p.getPpg()*ppAdj); // calculates skater's transformed power play goals
int ppa = (int)(p.getPpa()*ppAdj); // calculates skater's transformed power play assists
int shg = (int)(p.getShg()*shAdj); // calculates skater's transformed short handed goals
int sha = (int)(p.getSha()*shAdj); // calculates skater's transformed short handed assists
int pim = (int)(p.getPim()*pimAdj); // calculates skater's transformed penalty minutes
int s = (int)(p.getShots()*sAdj); // calculates skater's transformed shots
int g = evg + ppg + shg; // sums skater's transformed total goals
int a = eva + ppa + sha; // sums skater's transformed total assists
int pts = evg + ppg + shg + eva + ppa + sha; // sums skater's total points
int evp = evg + eva; // sums skater's transformed total even strength points
int ppp = ppg + ppa; // sums skater's transformed total power play points
int shp = shg + sha; // sums skater's transformed total short handed points
float gpg = g / p.getGp(); // calculates skater's transformed goals per game
float apg = a / p.getGp(); // calculates skater's transformed assists per game
float pperg = pts / p.getGp(); // calculates skater's transformed points per game
skaters.add(new ConvertedSkater(p.getPlayername(), p.getSeasonid(), p.getGp(), evg, eva, ppg, ppa, shg, sha, pim, s, g, a, pts, evp, ppp, shp, gpg, apg, pperg)); // adds transformed skater season to result set
} // for (skater season)
return skaters; // returns transformed skater data
} // transformStats(individual season)
// transforms individual season goalie data to specified era and returns result
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> players, int baseS, int targetS) {
Season baseSeason = seasonService.getSeason(baseS).get(0); // retrieves data for base season
Season targetSeason = seasonService.getSeason(targetS).get(0); // retrieves data for target season
float sAdj = (1.0f*targetSeason.getSGp()) / (1.0f*baseSeason.getSGp()); // calculates shots adjustment
float svAdj = ((targetSeason.getS()*1.0f - 1.0f*targetSeason.getG()) / (1.0f*targetSeason.getS())) / ((baseSeason.getS()*1.0f - 1.0f*baseSeason.getG()) / (1.0f*baseSeason.getS())); // calculates save percentage adjustment
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
for(Goalieseasons p : players) { // loops through and transforms each goalie season applicable
if (p.getSa() > 0 && p.getSv() > 0) { // removes seasons where the goalie did not make a save
int w = (int)(p.getW() - p.getSow()); // calculates goalie's transformed wins
int l = (int)(p.getL() - p.getSol()); // calculates goalie's transformed losses
int sa = (int)(p.getSa() * sAdj); // calculates goalie's transformed shots against
float svpct = (1.0f*p.getSv())/(1.0f*p.getSa()); // calculates goalie's transformed save percentage
int sv = (int)(1.0f*sa * svpct); // calculates goalie's transformed saves
sv = (int)(1.0f*sv * svAdj);
goalies.add(new ConvertedGoalie(p.getPlayername(), p.getSeasonid(), p.getGp(), p.getToi(), w, l, sa, sv/*, sa60, gaa, svpct*/)); // adds transformed goalie season to result set
} // if (no data)
} // for (goalie season)
return goalies; // returns transformed goalie data
} // transformGoalies(individual season)
// transforms each season of career skater data to specified era and returns result
public List<ConvertedSkater> transformStats(List<Skaterseasons> players, int baseS) {
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
for (Skaterseasons p : players) { // loops through each season of skater data
List<Skaterseasons> temp = new ArrayList<Skaterseasons>(); // temporarily holds individual season skater data
temp.add(p); // adds current season of data
skaters.addAll(transformStats(temp, (p.getSeasonid()), baseS)); // adds current transformed season to skater's transformed career stats
} // for (season)
return skaters; // returns transformed skater career
}// transformStats(career seasons)
// transforms each season of career goalie data to specified era and returns result
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> players, int baseS) {
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
for (Goalieseasons p : players) { // loops through each season of goalie data
List<Goalieseasons> temp = new ArrayList<Goalieseasons>(); // temporarily holds individual season goalie data
temp.add(p); // adds current season of data
goalies.addAll(transformGoalies(temp, (p.getSeasonid()), baseS)); // adds current transformed season to goalie's transformed career stats
} // for (season)
return goalies; // returns transformed goalie career
}// transformGoalies(career seasons)
// helper function compiles sum of career skater data for comparison
public List<ConvertedSkater> transformStats(List<Skaterseasons> player1, List<Skaterseasons> player2, int baseS) {
List<ConvertedSkater> skaters = new ArrayList<ConvertedSkater>(); // will hold transformed skater data
skaters.add(convertSkater(player1, baseS)); // adds career data for skater one
skaters.add(convertSkater(player2, baseS)); // adds career data for skater two
return skaters; // returns compiled and transformed skater career data
} // transformStats(career sum)
// transforms, sums and returns a skater's career stats
public ConvertedSkater convertSkater(List<Skaterseasons> skater, int baseS) {
ConvertedSkater s = new ConvertedSkater(); // will hold transformed skater stats
s.setName(skater.get(0).getPlayername()); // sets the skater name
int minY = skater.get(0).getSeasonid(); // used to set skater's career span
int maxY = skater.get(0).getSeasonid(); // used to set skater's career span
for (Skaterseasons p : skater) { // loops through all a skater's active seasons
List<Skaterseasons> temp = new ArrayList<Skaterseasons>(); // will hold individual season data
temp.add(p); // adds current season
s.addAll(transformStats(temp, (p.getSeasonid()), baseS)); // adds current transformed season to transformed career total
if (p.getSeasonid() < minY) minY = p.getSeasonid(); // sets oldest year skater was active
if (p.getSeasonid() > maxY) maxY = p.getSeasonid(); // sets most recent year skater was active
} // for (seasons)
s.setCareerSpan(minY, maxY); // sets the span of seasons the skater was active
return s; // return transformed and compiled skater career data
} // convertSkater(career)
// helper function compiles sum of career goalie data for comparison
public List<ConvertedGoalie> transformGoalies(List<Goalieseasons> player1, List<Goalieseasons> player2, int baseS) {
List<ConvertedGoalie> goalies = new ArrayList<ConvertedGoalie>(); // will hold transformed goalie data
goalies.add(convertGoalie(player1, baseS)); // adds career data for goalie one
goalies.add(convertGoalie(player2, baseS)); // adds career data for goalie two
return goalies; // returns compiled and transformed goalie career data
} // transformGoalies(career sum)
// transforms, sums and returns a goalie's career stats
public ConvertedGoalie convertGoalie(List<Goalieseasons> goalie, int baseS) {
ConvertedGoalie g = new ConvertedGoalie(); // will hold transformed career stats
g.setName(goalie.get(0).getPlayername()); // sets the goalie name
int minY = goalie.get(0).getSeasonid(); // used to set goalie's career span
int maxY = goalie.get(0).getSeasonid(); // used to set goalie's career span
for (Goalieseasons p : goalie) { // loops through all a goalie's active seasons
List<Goalieseasons> temp = new ArrayList<Goalieseasons>(); // will hold individual season data
temp.add(p); // adds current season
g.addAll(transformGoalies(temp, (p.getSeasonid()), baseS)); // adds current transformed season to transformed career total
if (p.getSeasonid() < minY) minY = p.getSeasonid(); // sets oldest year goalie was active
if (p.getSeasonid() > maxY) maxY = p.getSeasonid(); // sets most recent year goalie was active
} // for (season)
g.setCareerSpan(minY, maxY); // sets the span of seasons the goalie was active
return g; // return transformed and compiled goalie career data
} // convertGoalie(career sum)
} // class BenchwarmerController
| Added dummy value to baseS so table caption displays correctly | src/com/benchwarmer/spring/BenchwarmerController.java | Added dummy value to baseS so table caption displays correctly |
|
Java | apache-2.0 | 4ff79fe62a0a6bbda868fb34c913b77954cb8d94 | 0 | tomaswolf/gerrit-gitblit-plugin,tomaswolf/gerrit-gitblit-plugin | // Copyright (C) 2014 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.googlesource.gerrit.plugins.gitblit;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.util.IO;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.mime.MimeUtilFileTypeRegistry;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import eu.medsea.mimeutil.MimeType;
@Singleton
public class StaticResourcesServlet extends HttpServlet {
private static final long serialVersionUID = 5262736289985705065L;
/**
* The resource must either be in one of the allowed subdirectories, or must match the filename pattern. If neither is true, we return a 404.
* There's a whole lot of other stuff there that we don't want to expose.
*/
private static final Set<String> ALLOWED_SUBDIRECTORIES = ImmutableSet.of("bootstrap", "flotr2", "fontawesome");
private static final Pattern ALLOWED_FILE_NAMES = Pattern.compile("^(?:gitblit\\.properties|.*\\.(?:png|css|js|swf))$");
private final MimeUtilFileTypeRegistry mimeDetector;
private final File gerritPluginDirectory;
private final AtomicLong lastModified = new AtomicLong(-1L);
@Inject
public StaticResourcesServlet(final MimeUtilFileTypeRegistry mimeDetector, final SitePaths sitePaths) {
super();
this.mimeDetector = mimeDetector;
this.gerritPluginDirectory = sitePaths.plugins_dir;
}
@Override
protected long getLastModified(HttpServletRequest request) {
long result = lastModified.get();
if (result < 0) {
// Simply return the time the plugin was put into Gerrit's plugin directory.
File[] plugins = gerritPluginDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File directory, String fileName) {
return fileName != null && fileName.startsWith("gitblit") && fileName.endsWith(".jar");
}
});
result = 0L;
if (plugins != null && plugins.length > 0) {
for (File f : plugins) {
result = Math.max(result, f.lastModified());
}
}
lastModified.set(result);
}
return result;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.service(new FixedGuiceHttpServletRequest(request), response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Extract the filename from the request
String resourcePath = request.getPathInfo(); // Is already relative to /static!
if (request.getRequestURI().endsWith("/clippy.swf")) {
resourcePath = "/clippy.swf";
}
if (Strings.isNullOrEmpty(resourcePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Must not contain any navigation
String[] segments = resourcePath.substring(1).split("/");
for (String segment : segments) {
if (segment.equals("..")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid path");
return;
}
}
String fileName = segments[segments.length - 1];
if (Strings.isNullOrEmpty(fileName)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Restrict to the few known subdirectories.
if (segments.length > 1 && !ALLOWED_SUBDIRECTORIES.contains(segments[0])) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} else if (segments.length == 1 && !ALLOWED_FILE_NAMES.matcher(fileName).matches()) {
// Only allow the known filetypes: we have only png, css, js, swf, and gitblit.properties.
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// We just happen to know that all our static data files are small, so it's OK to read them fully into memory
byte[] bytes = null;
try (InputStream data = getClass().getResourceAsStream(resourcePath)) {
if (data == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
bytes = IO.readWholeStream(data, 0).array();
}
if (bytes == null) {
// Should not occur since we don't catch the possible IOException above. Nevertheless, let's be paranoid.
bytes = new byte[0];
}
String contentType = null;
// Compare https://gerrit-review.googlesource.com/#/c/67000/
if (fileName.toLowerCase().endsWith(".js")) {
contentType = "application/javascript";
} else if (fileName.toLowerCase().endsWith(".css")) {
contentType = "text/css";
} else {
MimeType mimeType = mimeDetector.getMimeType(fileName, bytes);
contentType = mimeType != null ? mimeType.toString() : "application/octet-stream";
}
response.setContentType(contentType);
long lastModified = getLastModified(request);
if (lastModified > 0) {
response.setDateHeader("Last-Modified", lastModified);
}
response.setHeader("Content-Length", Integer.toString(bytes.length));
try (OutputStream out = response.getOutputStream()) {
out.write(bytes, 0, bytes.length);
}
}
}
| src/main/java/com/googlesource/gerrit/plugins/gitblit/StaticResourcesServlet.java | // Copyright (C) 2014 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.googlesource.gerrit.plugins.gitblit;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.util.IO;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.mime.MimeUtilFileTypeRegistry;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import eu.medsea.mimeutil.MimeType;
@Singleton
public class StaticResourcesServlet extends HttpServlet {
private static final long serialVersionUID = 5262736289985705065L;
/**
* The resource must either be in one of the allowed subdirectories, or must match the filename pattern. If neither is true, we return a 404.
* There's a whole lot of other stuff there that we don't want to expose.
*/
private static final Set<String> ALLOWED_SUBDIRECTORIES = ImmutableSet.of("bootstrap", "flotr2", "fontawesome");
private static final Pattern ALLOWED_FILE_NAMES = Pattern.compile("^(?:gitblit\\.properties|.*\\.(?:png|css|js|swf))$");
private final MimeUtilFileTypeRegistry mimeDetector;
private final File gerritPluginDirectory;
private final AtomicLong lastModified = new AtomicLong(-1L);
@Inject
public StaticResourcesServlet(final MimeUtilFileTypeRegistry mimeDetector, final SitePaths sitePaths) {
super();
this.mimeDetector = mimeDetector;
this.gerritPluginDirectory = sitePaths.plugins_dir;
}
@Override
protected long getLastModified(HttpServletRequest request) {
long result = lastModified.get();
if (result < 0) {
// Simply return the time the plugin was put into Gerrit's plugin directory.
File[] plugins = gerritPluginDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File directory, String fileName) {
return fileName != null && fileName.startsWith("gitblit") && fileName.endsWith(".jar");
}
});
result = 0L;
if (plugins != null && plugins.length > 0) {
for (File f : plugins) {
result = Math.max(result, f.lastModified());
}
}
lastModified.set(result);
}
return result;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.service(new FixedGuiceHttpServletRequest(request), response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Extract the filename from the request
String resourcePath = request.getPathInfo(); // Is already relative to /static!
if (request.getRequestURI().endsWith("/clippy.swf")) {
resourcePath = "/clippy.swf";
}
if (Strings.isNullOrEmpty(resourcePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Must not contain any navigation
String[] segments = resourcePath.substring(1).split("/");
for (String segment : segments) {
if (segment.equals("..")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid path");
return;
}
}
String fileName = segments[segments.length - 1];
if (Strings.isNullOrEmpty(fileName)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Restrict to the few known subdirectories.
if (segments.length > 1 && !ALLOWED_SUBDIRECTORIES.contains(segments[0])) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} else if (segments.length == 1 && !ALLOWED_FILE_NAMES.matcher(fileName).matches()) {
// Only allow the known filetypes: we have only png, css, js, swf, and gitblit.properties.
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// We just happen to know that all our static data files are small, so it's OK to read them fully into memory
byte[] bytes = null;
try (InputStream data = getClass().getResourceAsStream(resourcePath)) {
if (data == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
bytes = IO.readWholeStream(data, 0).array();
}
if (bytes == null) {
// Should not occur since we don't catch the possible IOException above. Nevertheless, let's be paranoid.
bytes = new byte[0];
}
String contentType = null;
// Compare https://gerrit-review.googlesource.com/#/c/67000/
if (fileName.toLowerCase().endsWith(".js")) {
contentType = "application/javascript";
} else if (fileName.toLowerCase().endsWith(".css")) {
contentType = "text/css";
} else {
MimeType mimeType = mimeDetector.getMimeType(fileName, bytes);
if (mimeType != null) {
contentType = mimeType.toString();
}
}
response.setContentType(contentType);
long lastModified = getLastModified(request);
if (lastModified > 0) {
response.setDateHeader("Last-Modified", lastModified);
}
response.setHeader("Content-Length", Integer.toString(bytes.length));
try (OutputStream out = response.getOutputStream()) {
out.write(bytes, 0, bytes.length);
}
}
}
| Provide a default Mime type | src/main/java/com/googlesource/gerrit/plugins/gitblit/StaticResourcesServlet.java | Provide a default Mime type |
|
Java | apache-2.0 | 61a42d1bbe075fe3a8a743b9df75154997b8be66 | 0 | spotify/styx,spotify/styx,spotify/styx | /*-
* -\-\-
* Spotify Styx Common
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.styx.storage;
import static com.github.npathai.hamcrestopt.OptionalMatchers.hasValue;
import static com.spotify.styx.model.Schedule.DAYS;
import static com.spotify.styx.model.Schedule.HOURS;
import static com.spotify.styx.storage.DatastoreStorage.PROPERTY_CONFIG_RESOURCES_SYNC_ENABLED;
import static com.spotify.styx.testdata.TestData.FULL_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.WORKFLOW_INSTANCE;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
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 static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.bigtable.repackaged.com.google.common.collect.ImmutableList;
import com.google.bigtable.repackaged.com.google.common.collect.ImmutableMap;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.EntityQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyQuery;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StringValue;
import com.google.cloud.datastore.Transaction;
import com.google.cloud.datastore.testing.LocalDatastoreHelper;
import com.google.common.collect.ImmutableSet;
import com.spotify.styx.model.Backfill;
import com.spotify.styx.model.ExecutionDescription;
import com.spotify.styx.model.StyxConfig;
import com.spotify.styx.model.Workflow;
import com.spotify.styx.model.WorkflowConfiguration;
import com.spotify.styx.model.WorkflowConfiguration.Secret;
import com.spotify.styx.model.WorkflowId;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.model.WorkflowState;
import com.spotify.styx.state.Message;
import com.spotify.styx.state.Message.MessageLevel;
import com.spotify.styx.state.RunState;
import com.spotify.styx.state.RunState.State;
import com.spotify.styx.state.StateData;
import com.spotify.styx.state.Trigger;
import com.spotify.styx.util.Shard;
import com.spotify.styx.util.TriggerInstantSpec;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DatastoreStorageTest {
static final WorkflowId WORKFLOW_ID1 = WorkflowId.create("component", "endpoint1");
static final WorkflowId WORKFLOW_ID2 = WorkflowId.create("component", "endpoint2");
static final WorkflowId WORKFLOW_ID3 = WorkflowId.create("component2", "pointless");
static final WorkflowInstance WORKFLOW_INSTANCE1 = WorkflowInstance.create(WORKFLOW_ID1, "2016-09-01");
static final WorkflowInstance WORKFLOW_INSTANCE2 = WorkflowInstance.create(WORKFLOW_ID2, "2016-09-01");
static final WorkflowInstance WORKFLOW_INSTANCE3 = WorkflowInstance.create(WORKFLOW_ID3, "2016-09-01");
static final Instant TIMESTAMP = Instant.parse("2017-01-01T00:00:00Z");
static final RunState RUN_STATE = RunState.create(WORKFLOW_INSTANCE1, State.NEW,
StateData.zero(), TIMESTAMP, 42L);
static final RunState RUN_STATE1 = RunState.create(WORKFLOW_INSTANCE1, State.NEW,
StateData.zero(), TIMESTAMP, 43L);
static final RunState RUN_STATE2 = RunState.create(WORKFLOW_INSTANCE2, State.NEW,
StateData.zero(), TIMESTAMP, 84L);
static final RunState RUN_STATE3 = RunState.create(WORKFLOW_INSTANCE3, State.NEW,
StateData.zero(), TIMESTAMP, 17L);
static final RunState FULLY_POPULATED_RUNSTATE = RunState.create(WORKFLOW_INSTANCE, State.QUEUED,
StateData.newBuilder()
.tries(17)
.consecutiveFailures(89)
.retryCost(2.0)
.retryDelayMillis(4711L)
.lastExit(13)
.trigger(Trigger.adhoc("foobar"))
.executionId("foo-bar-17")
.executionDescription(ExecutionDescription.builder()
.dockerImage("foo/bar:34234")
.dockerArgs("foo", "the", "bar", "baz")
.dockerTerminationLogging(true)
.secret(Secret.create("foobar", "/var/quux/baz"))
.serviceAccount("[email protected]")
.commitSha("2d2bfa926b94508de5aab47b5f305659ead2274a")
.build())
.resourceIds(ImmutableSet.of("GLOBAL_STYX_CLUSTER", "foo-resource", "bar-resource"))
.addMessage(Message.info("foo"))
.addMessage(Message.warning("bar"))
.addMessage(Message.error("baz"))
.addMessage(Message.create(MessageLevel.UNKNOWN, "quux"))
.build(),
TIMESTAMP,
42L);
static final WorkflowId WORKFLOW_ID = WorkflowId.create("dockerComp", "dockerEndpoint");
static final WorkflowConfiguration WORKFLOW_CONFIGURATION =
WorkflowConfiguration.builder()
.id(WORKFLOW_ID.id())
.schedule(DAYS)
.build();
static final Workflow WORKFLOW = Workflow.create(WORKFLOW_ID.componentId(),
WORKFLOW_CONFIGURATION);
private static final String COUNTER_ID1 = "counter-id1";
private static LocalDatastoreHelper helper;
private DatastoreStorage storage;
private Datastore datastore;
@Mock TransactionFunction<String, FooException> transactionFunction;
@Mock Function<Transaction, DatastoreStorageTransaction> storageTransactionFactory;
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: the datastore emulator behavior wrt conflicts etc differs from the real datastore
helper = LocalDatastoreHelper.create(1.0); // 100% global consistency
helper.start();
}
@AfterClass
public static void tearDownClass() throws Exception {
if (helper != null) {
try {
helper.stop(org.threeten.bp.Duration.ofSeconds(30));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
@Before
public void setUp() throws Exception {
datastore = helper.getOptions().getService();
storage = new DatastoreStorage(datastore, Duration.ZERO);
}
@After
public void tearDown() throws Exception {
// clear datastore after each test
KeyQuery query = Query.newKeyQueryBuilder().build();
final QueryResults<Key> keys = datastore.run(query);
while (keys.hasNext()) {
datastore.delete(keys.next());
}
}
@Test
public void shouldPersistWorkflows() throws Exception {
Workflow workflow = Workflow.create("test",
FULL_WORKFLOW_CONFIGURATION);
storage.store(workflow);
Optional<Workflow> retrieved = storage.workflow(workflow.id());
assertThat(retrieved, is(Optional.of(workflow)));
}
@Test
public void shouldDeleteWorkflows() throws Exception {
final Workflow workflow = Workflow.create("foo", WORKFLOW_CONFIGURATION);
storage.store(workflow);
storage.store(Workflow.create("bar", WORKFLOW_CONFIGURATION));
assertThat(entitiesOfKind(DatastoreStorage.KIND_WORKFLOW), hasSize(2));
storage.delete(workflow.id());
assertThat(entitiesOfKind(DatastoreStorage.KIND_WORKFLOW), hasSize(1));
}
@Test
public void shouldPersistNextScheduledRun() throws Exception {
Instant instant = Instant.parse("2016-03-14T14:00:00Z");
Instant offset = instant.plus(1, ChronoUnit.DAYS);
TriggerInstantSpec spec = TriggerInstantSpec.create(instant, offset);
storage.store(WORKFLOW);
storage.updateNextNaturalTrigger(WORKFLOW.id(), spec);
final Map<Workflow, TriggerInstantSpec> result = storage.workflowsWithNextNaturalTrigger();
assertThat(result.values().size(), is(1));
assertThat(result, hasEntry(WORKFLOW, spec));
}
@Test
public void shouldReturnEmptyOptionalWhenWorkflowIdDoesNotExist() throws Exception {
Optional<Workflow> retrieved = storage.workflow(WorkflowId.create("foo", "bar"));
assertThat(retrieved, is(Optional.empty()));
}
@Test
public void shouldReturnEmptyWorkflowStateExceptEnabledWhenWorkflowStateDoesNotExist() throws Exception {
final Workflow workflow = Workflow.create("foo",
WORKFLOW_CONFIGURATION);
storage.store(workflow);
WorkflowState retrieved = storage.workflowState(workflow.id());
assertThat(retrieved, is(WorkflowState.patchEnabled(false)));
}
@Test
public void shouldStoreWorkflowEnabledFlag() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, true);
assertTrue(storage.enabled(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
}
@Test
public void shouldStoreWorkflowEnabledFlagsSeparately() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.store(workflow(WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, true);
assertTrue(storage.enabled(WORKFLOW_ID1));
assertTrue(storage.enabled(WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
assertTrue(storage.enabled(WORKFLOW_ID2));
}
@Test
public void shouldReturnEnabledWorkflows() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.store(workflow(WORKFLOW_ID2));
storage.store(workflow(WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, false);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID2, true);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1, WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID3, true);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1, WORKFLOW_ID2, WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID1, false);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID2, WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID2, false);
storage.setEnabled(WORKFLOW_ID3, false);
assertThat(storage.enabled(), is(empty()));
}
@Test
public void workflowShouldBeDisabledByDefault() throws Exception {
boolean enabled = storage.enabled(WORKFLOW_ID1);
assertFalse(enabled);
}
@Test
public void shouldRetainAllWorkflowSettings() throws Exception {
WorkflowId id = WORKFLOW.id();
storage.store(WORKFLOW);
storage.setEnabled(id, true);
Optional<Workflow> workflow = storage.workflow(id);
boolean enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertTrue(enabled);
storage.setEnabled(id, false);
workflow = storage.workflow(id);
enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertFalse(enabled);
storage.store(WORKFLOW);
workflow = storage.workflow(id);
enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertFalse(enabled);
}
@Test
public void shouldWriteActiveWorkflowInstanceWithState() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, RUN_STATE1);
List<Entity> activeInstances = entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE);
assertThat(activeInstances, hasSize(1));
Entity instance = activeInstances.get(0);
assertThat(instance.getLong(DatastoreStorage.PROPERTY_COUNTER), is(RUN_STATE1.counter()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_COMPONENT), is(WORKFLOW_INSTANCE.workflowId().componentId()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_WORKFLOW), is(WORKFLOW_INSTANCE.workflowId().id()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_PARAMETER), is(WORKFLOW_INSTANCE.parameter()));
}
@Test
public void testFullPersistentStatePersistence() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE);
final RunState read = storage
.readActiveStates(WORKFLOW_INSTANCE.workflowId().componentId())
.get(WORKFLOW_INSTANCE);
assertThat(read, is(FULLY_POPULATED_RUNSTATE));
}
@Test
public void shouldDeleteActiveWorkflowInstance() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
storage.deleteActiveState(WORKFLOW_INSTANCE1);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
}
@Test
public void shouldReturnAllActiveStates() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
final Map<WorkflowInstance, RunState> activeStates = storage.readActiveStates();
assertThat(activeStates, is(ImmutableMap.of(
WORKFLOW_INSTANCE1, RUN_STATE,
WORKFLOW_INSTANCE2, RUN_STATE2)));
}
@Test
public void shouldReturnAllActiveStatesForAComponent() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
storage.writeActiveState(WORKFLOW_INSTANCE3, RUN_STATE3);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
final Map<WorkflowInstance, RunState> activeStates =
storage.readActiveStates(WORKFLOW_ID1.componentId());
assertThat(activeStates, is(ImmutableMap.of(WORKFLOW_INSTANCE2, RUN_STATE2)));
}
@Test
public void shouldReturnAllActiveStatesForATriggerId() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
final Map<WorkflowInstance, RunState> activeStates =
storage.activeStatesByTriggerId("foobar");
assertThat(activeStates, is(ImmutableMap.of(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE)));
}
@Test
public void shouldReturnActiveStateForWFI() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
final Optional<RunState> activeStates =
storage.readActiveState(WORKFLOW_INSTANCE2);
assertThat(activeStates, is(Optional.of(RUN_STATE2)));
}
@Test
public void shouldWriteActiveStatesWithSamePartitionAsSeparateEntities() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
}
private List<Entity> entitiesOfKind(String kind) {
Datastore datastore = helper.getOptions().getService();
EntityQuery query = Query.newEntityQueryBuilder().setKind(kind).build();
QueryResults<Entity> keys = datastore.run(query);
List<Entity> entities = new ArrayList<>();
while (keys.hasNext()) {
entities.add(keys.next());
}
return entities;
}
@Test
public void allFieldsAreSetWhenRetrievingWorkflowState() throws Exception {
storage.store(WORKFLOW);
Instant instant = Instant.parse("2016-03-14T14:00:00Z");
Instant offset = instant.plus(1, ChronoUnit.DAYS);
TriggerInstantSpec spec = TriggerInstantSpec.create(instant, offset);
storage.updateNextNaturalTrigger(WORKFLOW.id(), spec);
WorkflowState state = WorkflowState.builder()
.enabled(true)
.nextNaturalTrigger(instant)
.nextNaturalOffsetTrigger(offset)
.build();
storage.patchState(WORKFLOW.id(), state);
WorkflowState retrieved = storage.workflowState(WORKFLOW.id());
assertThat(retrieved, is(state));
}
@Test
public void getsGlobalDockerRunnerId() throws Exception {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_DOCKER_RUNNER_ID, "foobar")
.build();
helper.getOptions().getService().put(config);
assertThat(storage.config().globalDockerRunnerId(), is("foobar"));
}
@Test
public void getsResourcesSyncEnabled() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(PROPERTY_CONFIG_RESOURCES_SYNC_ENABLED, true)
.build();
helper.getOptions().getService().put(config);
assertThat(storage.config().resourcesSyncEnabled(), is(true));
}
@Test
public void shouldReturnEmptyClientBlacklist() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_CLIENT_BLACKLIST,
ImmutableList.of()).build();
helper.getOptions().getService().put(config);
assertThat(storage.config().clientBlacklist(), is(empty()));
}
@Test
public void shouldReturnClientBlacklist() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_CLIENT_BLACKLIST,
ImmutableList.of(StringValue.of("v1"), StringValue.of("v2"), StringValue.of("v3")))
.build();
helper.getOptions().getService().put(config);
List<String> blacklist = storage.config().clientBlacklist();
assertThat(blacklist.size(), is(3));
assertThat(blacklist.get(0), is("v1"));
assertThat(blacklist.get(1), is("v2"));
assertThat(blacklist.get(2), is("v3"));
}
@Test
public void shouldReturnAllWorkflows() throws Exception {
assertThat(storage.workflows().isEmpty(), is(true));
Workflow workflow1 = workflow(WORKFLOW_ID1);
Workflow workflow2 = workflow(WORKFLOW_ID2);
Workflow workflow3 = workflow(WORKFLOW_ID3);
storage.store(workflow1);
storage.store(workflow2);
storage.store(workflow3);
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, false);
storage.updateNextNaturalTrigger(WORKFLOW_ID3, TriggerInstantSpec.create(TIMESTAMP, TIMESTAMP.plus(Duration.ofHours(1))));
assertThat(storage.workflows().size(), is(3));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID1, workflow1));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID2, workflow2));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID3, workflow3));
}
@Test
public void shouldReturnAllWorkflowsInComponent() throws Exception {
String componentId = "component";
Workflow workflow1 = workflow(WORKFLOW_ID1);
Workflow workflow2 = workflow(WORKFLOW_ID2);
Workflow workflow3 = workflow(WORKFLOW_ID3);
assertThat(workflow1.componentId(), is(componentId));
assertThat(workflow2.componentId(), is(componentId));
assertThat(workflow3.componentId(), not(componentId));
storage.store(workflow1);
storage.store(workflow2);
storage.store(workflow3);
List<Workflow> l = storage.workflows(componentId);
assertThat(l, hasSize(2));
assertThat(l, hasItem(workflow1));
assertThat(l, hasItem(workflow2));
}
@Test
public void shouldReturnEmptyListIfComponentDoesNotExist() throws Exception {
String componentId = "component";
List<Workflow> l = storage.workflows(componentId);
assertThat(l, hasSize(0));
}
@Test
public void testDefaultConfig() {
final StyxConfig expectedConfig = StyxConfig.newBuilder()
.globalDockerRunnerId("default")
.globalEnabled(true)
.debugEnabled(false)
.resourcesSyncEnabled(false)
.executionGatingEnabled(false)
.build();
assertThat(storage.config(), is(expectedConfig));
}
@Test
public void shouldStoreAndReadBackfill() throws Exception {
final Backfill backfill = Backfill.newBuilder()
.id("backfill-2")
.start(Instant.parse("2017-01-01T00:00:00Z"))
.end(Instant.parse("2017-01-02T00:00:00Z"))
.workflowId(WorkflowId.create("component", "workflow2"))
.concurrency(2)
.nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
.schedule(DAYS)
.build();
storage.storeBackfill(backfill);
assertThat(storage.getBackfill(backfill.id()), equalTo(Optional.of(backfill)));
}
@Test
public void shouldStoreAndReadBackfillWithDescription() throws Exception {
final Backfill backfill = Backfill.newBuilder()
.id("backfill-2")
.start(Instant.parse("2017-01-01T00:00:00Z"))
.end(Instant.parse("2017-01-02T00:00:00Z"))
.workflowId(WorkflowId.create("component", "workflow2"))
.concurrency(2)
.description("Description")
.nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
.schedule(DAYS)
.build();
storage.storeBackfill(backfill);
assertThat(storage.getBackfill(backfill.id()), equalTo(Optional.of(backfill)));
}
private Workflow workflow(WorkflowId workflowId) {
return Workflow.create(
workflowId.componentId(),
WorkflowConfiguration.builder()
.id(workflowId.id())
.schedule(HOURS)
.build());
}
@Test
public void runInTransactionShouldCallFunctionAndCommit() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
when(transactionFunction.apply(any())).thenReturn("foo");
String result = storage.runInTransaction(transactionFunction);
assertThat(result, is("foo"));
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).commit();
verify(storageTransaction, never()).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnFailure() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final Exception expectedException = new FooException();
when(transactionFunction.apply(any())).thenThrow(expectedException);
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (FooException e) {
// Verify that we can throw a user defined checked exception type inside the transaction
// body and catch it
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction, never()).commit();
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnPreCommitConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final Exception expectedException = new DatastoreException(10, "", "");
when(transactionFunction.apply(any())).thenThrow(expectedException);
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertTrue(e.isConflict());
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction, never()).commit();
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnCommitConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final DatastoreException datastoreException = new DatastoreException(1, "", "");
final TransactionException expectedException = new TransactionException(datastoreException);
when(transactionFunction.apply(any())).thenReturn("");
doThrow(expectedException).when(storageTransaction).commit();
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldThrowIfRollbackFailsAfterConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
when(transactionFunction.apply(any())).thenReturn("");
final DatastoreException datastoreException = new DatastoreException(1, "", "");
doThrow(new TransactionException(datastoreException)).when(storageTransaction).commit();
final TransactionException expectedException = new TransactionException(datastoreException);
doThrow(expectedException).when(storageTransaction).rollback();
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertFalse(e.isConflict());
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldThrowIfDatastoreNewTransactionFails() throws Exception {
Datastore datastore = mock(Datastore.class);
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
when(datastore.newTransaction()).thenThrow(new DatastoreException(1, "", ""));
when(transactionFunction.apply(any())).thenReturn("");
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertFalse(e.isConflict());
}
verify(transactionFunction, never()).apply(any());
}
@Test
public void shouldReturnShardsForCounter() throws Exception {
storage.runInTransaction(tx -> {
tx.store(Shard.create(COUNTER_ID1, 1, 3));
return null;
});
final Map<Integer, Long> map = storage.shardsForCounter(COUNTER_ID1);
assertEquals(1, map.size());
assertTrue(map.containsKey(1));
assertEquals(3, map.get(1).longValue());
}
private static class FooException extends Exception {
}
}
| styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java | /*-
* -\-\-
* Spotify Styx Common
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.styx.storage;
import static com.github.npathai.hamcrestopt.OptionalMatchers.hasValue;
import static com.spotify.styx.model.Schedule.DAYS;
import static com.spotify.styx.model.Schedule.HOURS;
import static com.spotify.styx.storage.DatastoreStorage.PROPERTY_CONFIG_RESOURCES_SYNC_ENABLED;
import static com.spotify.styx.testdata.TestData.FULL_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.WORKFLOW_INSTANCE;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.bigtable.repackaged.com.google.common.collect.ImmutableList;
import com.google.bigtable.repackaged.com.google.common.collect.ImmutableMap;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.EntityQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyQuery;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StringValue;
import com.google.cloud.datastore.Transaction;
import com.google.cloud.datastore.testing.LocalDatastoreHelper;
import com.google.common.collect.ImmutableSet;
import com.spotify.styx.model.Backfill;
import com.spotify.styx.model.ExecutionDescription;
import com.spotify.styx.model.StyxConfig;
import com.spotify.styx.model.Workflow;
import com.spotify.styx.model.WorkflowConfiguration;
import com.spotify.styx.model.WorkflowConfiguration.Secret;
import com.spotify.styx.model.WorkflowId;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.model.WorkflowState;
import com.spotify.styx.state.Message;
import com.spotify.styx.state.Message.MessageLevel;
import com.spotify.styx.state.RunState;
import com.spotify.styx.state.RunState.State;
import com.spotify.styx.state.StateData;
import com.spotify.styx.state.Trigger;
import com.spotify.styx.util.TriggerInstantSpec;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DatastoreStorageTest {
static final WorkflowId WORKFLOW_ID1 = WorkflowId.create("component", "endpoint1");
static final WorkflowId WORKFLOW_ID2 = WorkflowId.create("component", "endpoint2");
static final WorkflowId WORKFLOW_ID3 = WorkflowId.create("component2", "pointless");
static final WorkflowInstance WORKFLOW_INSTANCE1 = WorkflowInstance.create(WORKFLOW_ID1, "2016-09-01");
static final WorkflowInstance WORKFLOW_INSTANCE2 = WorkflowInstance.create(WORKFLOW_ID2, "2016-09-01");
static final WorkflowInstance WORKFLOW_INSTANCE3 = WorkflowInstance.create(WORKFLOW_ID3, "2016-09-01");
static final Instant TIMESTAMP = Instant.parse("2017-01-01T00:00:00Z");
static final RunState RUN_STATE = RunState.create(WORKFLOW_INSTANCE1, State.NEW,
StateData.zero(), TIMESTAMP, 42L);
static final RunState RUN_STATE1 = RunState.create(WORKFLOW_INSTANCE1, State.NEW,
StateData.zero(), TIMESTAMP, 43L);
static final RunState RUN_STATE2 = RunState.create(WORKFLOW_INSTANCE2, State.NEW,
StateData.zero(), TIMESTAMP, 84L);
static final RunState RUN_STATE3 = RunState.create(WORKFLOW_INSTANCE3, State.NEW,
StateData.zero(), TIMESTAMP, 17L);
static final RunState FULLY_POPULATED_RUNSTATE = RunState.create(WORKFLOW_INSTANCE, State.QUEUED,
StateData.newBuilder()
.tries(17)
.consecutiveFailures(89)
.retryCost(2.0)
.retryDelayMillis(4711L)
.lastExit(13)
.trigger(Trigger.adhoc("foobar"))
.executionId("foo-bar-17")
.executionDescription(ExecutionDescription.builder()
.dockerImage("foo/bar:34234")
.dockerArgs("foo", "the", "bar", "baz")
.dockerTerminationLogging(true)
.secret(Secret.create("foobar", "/var/quux/baz"))
.serviceAccount("[email protected]")
.commitSha("2d2bfa926b94508de5aab47b5f305659ead2274a")
.build())
.resourceIds(ImmutableSet.of("GLOBAL_STYX_CLUSTER", "foo-resource", "bar-resource"))
.addMessage(Message.info("foo"))
.addMessage(Message.warning("bar"))
.addMessage(Message.error("baz"))
.addMessage(Message.create(MessageLevel.UNKNOWN, "quux"))
.build(),
TIMESTAMP,
42L);
static final WorkflowId WORKFLOW_ID = WorkflowId.create("dockerComp", "dockerEndpoint");
static final WorkflowConfiguration WORKFLOW_CONFIGURATION =
WorkflowConfiguration.builder()
.id(WORKFLOW_ID.id())
.schedule(DAYS)
.build();
static final Workflow WORKFLOW = Workflow.create(WORKFLOW_ID.componentId(),
WORKFLOW_CONFIGURATION);
private static LocalDatastoreHelper helper;
private DatastoreStorage storage;
private Datastore datastore;
@Mock TransactionFunction<String, FooException> transactionFunction;
@Mock Function<Transaction, DatastoreStorageTransaction> storageTransactionFactory;
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: the datastore emulator behavior wrt conflicts etc differs from the real datastore
helper = LocalDatastoreHelper.create(1.0); // 100% global consistency
helper.start();
}
@AfterClass
public static void tearDownClass() throws Exception {
if (helper != null) {
try {
helper.stop(org.threeten.bp.Duration.ofSeconds(30));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
@Before
public void setUp() throws Exception {
datastore = helper.getOptions().getService();
storage = new DatastoreStorage(datastore, Duration.ZERO);
}
@After
public void tearDown() throws Exception {
// clear datastore after each test
KeyQuery query = Query.newKeyQueryBuilder().build();
final QueryResults<Key> keys = datastore.run(query);
while (keys.hasNext()) {
datastore.delete(keys.next());
}
}
@Test
public void shouldPersistWorkflows() throws Exception {
Workflow workflow = Workflow.create("test",
FULL_WORKFLOW_CONFIGURATION);
storage.store(workflow);
Optional<Workflow> retrieved = storage.workflow(workflow.id());
assertThat(retrieved, is(Optional.of(workflow)));
}
@Test
public void shouldDeleteWorkflows() throws Exception {
final Workflow workflow = Workflow.create("foo", WORKFLOW_CONFIGURATION);
storage.store(workflow);
storage.store(Workflow.create("bar", WORKFLOW_CONFIGURATION));
assertThat(entitiesOfKind(DatastoreStorage.KIND_WORKFLOW), hasSize(2));
storage.delete(workflow.id());
assertThat(entitiesOfKind(DatastoreStorage.KIND_WORKFLOW), hasSize(1));
}
@Test
public void shouldPersistNextScheduledRun() throws Exception {
Instant instant = Instant.parse("2016-03-14T14:00:00Z");
Instant offset = instant.plus(1, ChronoUnit.DAYS);
TriggerInstantSpec spec = TriggerInstantSpec.create(instant, offset);
storage.store(WORKFLOW);
storage.updateNextNaturalTrigger(WORKFLOW.id(), spec);
final Map<Workflow, TriggerInstantSpec> result = storage.workflowsWithNextNaturalTrigger();
assertThat(result.values().size(), is(1));
assertThat(result, hasEntry(WORKFLOW, spec));
}
@Test
public void shouldReturnEmptyOptionalWhenWorkflowIdDoesNotExist() throws Exception {
Optional<Workflow> retrieved = storage.workflow(WorkflowId.create("foo", "bar"));
assertThat(retrieved, is(Optional.empty()));
}
@Test
public void shouldReturnEmptyWorkflowStateExceptEnabledWhenWorkflowStateDoesNotExist() throws Exception {
final Workflow workflow = Workflow.create("foo",
WORKFLOW_CONFIGURATION);
storage.store(workflow);
WorkflowState retrieved = storage.workflowState(workflow.id());
assertThat(retrieved, is(WorkflowState.patchEnabled(false)));
}
@Test
public void shouldStoreWorkflowEnabledFlag() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, true);
assertTrue(storage.enabled(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
}
@Test
public void shouldStoreWorkflowEnabledFlagsSeparately() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.store(workflow(WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, true);
assertTrue(storage.enabled(WORKFLOW_ID1));
assertTrue(storage.enabled(WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID1, false);
assertFalse(storage.enabled(WORKFLOW_ID1));
assertTrue(storage.enabled(WORKFLOW_ID2));
}
@Test
public void shouldReturnEnabledWorkflows() throws Exception {
storage.store(workflow(WORKFLOW_ID1));
storage.store(workflow(WORKFLOW_ID2));
storage.store(workflow(WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, false);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1));
storage.setEnabled(WORKFLOW_ID2, true);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1, WORKFLOW_ID2));
storage.setEnabled(WORKFLOW_ID3, true);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID1, WORKFLOW_ID2, WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID1, false);
assertThat(storage.enabled(), containsInAnyOrder(WORKFLOW_ID2, WORKFLOW_ID3));
storage.setEnabled(WORKFLOW_ID2, false);
storage.setEnabled(WORKFLOW_ID3, false);
assertThat(storage.enabled(), is(empty()));
}
@Test
public void workflowShouldBeDisabledByDefault() throws Exception {
boolean enabled = storage.enabled(WORKFLOW_ID1);
assertFalse(enabled);
}
@Test
public void shouldRetainAllWorkflowSettings() throws Exception {
WorkflowId id = WORKFLOW.id();
storage.store(WORKFLOW);
storage.setEnabled(id, true);
Optional<Workflow> workflow = storage.workflow(id);
boolean enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertTrue(enabled);
storage.setEnabled(id, false);
workflow = storage.workflow(id);
enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertFalse(enabled);
storage.store(WORKFLOW);
workflow = storage.workflow(id);
enabled = storage.enabled(id);
assertThat(workflow, hasValue(WORKFLOW));
assertFalse(enabled);
}
@Test
public void shouldWriteActiveWorkflowInstanceWithState() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, RUN_STATE1);
List<Entity> activeInstances = entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE);
assertThat(activeInstances, hasSize(1));
Entity instance = activeInstances.get(0);
assertThat(instance.getLong(DatastoreStorage.PROPERTY_COUNTER), is(RUN_STATE1.counter()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_COMPONENT), is(WORKFLOW_INSTANCE.workflowId().componentId()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_WORKFLOW), is(WORKFLOW_INSTANCE.workflowId().id()));
assertThat(instance.getString(DatastoreStorage.PROPERTY_PARAMETER), is(WORKFLOW_INSTANCE.parameter()));
}
@Test
public void testFullPersistentStatePersistence() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE);
final RunState read = storage
.readActiveStates(WORKFLOW_INSTANCE.workflowId().componentId())
.get(WORKFLOW_INSTANCE);
assertThat(read, is(FULLY_POPULATED_RUNSTATE));
}
@Test
public void shouldDeleteActiveWorkflowInstance() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
storage.deleteActiveState(WORKFLOW_INSTANCE1);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
}
@Test
public void shouldReturnAllActiveStates() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
final Map<WorkflowInstance, RunState> activeStates = storage.readActiveStates();
assertThat(activeStates, is(ImmutableMap.of(
WORKFLOW_INSTANCE1, RUN_STATE,
WORKFLOW_INSTANCE2, RUN_STATE2)));
}
@Test
public void shouldReturnAllActiveStatesForAComponent() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
storage.writeActiveState(WORKFLOW_INSTANCE3, RUN_STATE3);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
final Map<WorkflowInstance, RunState> activeStates =
storage.readActiveStates(WORKFLOW_ID1.componentId());
assertThat(activeStates, is(ImmutableMap.of(WORKFLOW_INSTANCE2, RUN_STATE2)));
}
@Test
public void shouldReturnAllActiveStatesForATriggerId() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
final Map<WorkflowInstance, RunState> activeStates =
storage.activeStatesByTriggerId("foobar");
assertThat(activeStates, is(ImmutableMap.of(WORKFLOW_INSTANCE, FULLY_POPULATED_RUNSTATE)));
}
@Test
public void shouldReturnActiveStateForWFI() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(1));
final Optional<RunState> activeStates =
storage.readActiveState(WORKFLOW_INSTANCE2);
assertThat(activeStates, is(Optional.of(RUN_STATE2)));
}
@Test
public void shouldWriteActiveStatesWithSamePartitionAsSeparateEntities() throws Exception {
storage.writeActiveState(WORKFLOW_INSTANCE1, RUN_STATE);
storage.writeActiveState(WORKFLOW_INSTANCE2, RUN_STATE2);
assertThat(entitiesOfKind(DatastoreStorage.KIND_ACTIVE_WORKFLOW_INSTANCE), hasSize(2));
}
private List<Entity> entitiesOfKind(String kind) {
Datastore datastore = helper.getOptions().getService();
EntityQuery query = Query.newEntityQueryBuilder().setKind(kind).build();
QueryResults<Entity> keys = datastore.run(query);
List<Entity> entities = new ArrayList<>();
while (keys.hasNext()) {
entities.add(keys.next());
}
return entities;
}
@Test
public void allFieldsAreSetWhenRetrievingWorkflowState() throws Exception {
storage.store(WORKFLOW);
Instant instant = Instant.parse("2016-03-14T14:00:00Z");
Instant offset = instant.plus(1, ChronoUnit.DAYS);
TriggerInstantSpec spec = TriggerInstantSpec.create(instant, offset);
storage.updateNextNaturalTrigger(WORKFLOW.id(), spec);
WorkflowState state = WorkflowState.builder()
.enabled(true)
.nextNaturalTrigger(instant)
.nextNaturalOffsetTrigger(offset)
.build();
storage.patchState(WORKFLOW.id(), state);
WorkflowState retrieved = storage.workflowState(WORKFLOW.id());
assertThat(retrieved, is(state));
}
@Test
public void getsGlobalDockerRunnerId() throws Exception {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_DOCKER_RUNNER_ID, "foobar")
.build();
helper.getOptions().getService().put(config);
assertThat(storage.config().globalDockerRunnerId(), is("foobar"));
}
@Test
public void getsResourcesSyncEnabled() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(PROPERTY_CONFIG_RESOURCES_SYNC_ENABLED, true)
.build();
helper.getOptions().getService().put(config);
assertThat(storage.config().resourcesSyncEnabled(), is(true));
}
@Test
public void shouldReturnEmptyClientBlacklist() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_CLIENT_BLACKLIST,
ImmutableList.of()).build();
helper.getOptions().getService().put(config);
assertThat(storage.config().clientBlacklist(), is(empty()));
}
@Test
public void shouldReturnClientBlacklist() {
Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
.set(DatastoreStorage.PROPERTY_CONFIG_CLIENT_BLACKLIST,
ImmutableList.of(StringValue.of("v1"), StringValue.of("v2"), StringValue.of("v3")))
.build();
helper.getOptions().getService().put(config);
List<String> blacklist = storage.config().clientBlacklist();
assertThat(blacklist.size(), is(3));
assertThat(blacklist.get(0), is("v1"));
assertThat(blacklist.get(1), is("v2"));
assertThat(blacklist.get(2), is("v3"));
}
@Test
public void shouldReturnAllWorkflows() throws Exception {
assertThat(storage.workflows().isEmpty(), is(true));
Workflow workflow1 = workflow(WORKFLOW_ID1);
Workflow workflow2 = workflow(WORKFLOW_ID2);
Workflow workflow3 = workflow(WORKFLOW_ID3);
storage.store(workflow1);
storage.store(workflow2);
storage.store(workflow3);
storage.setEnabled(WORKFLOW_ID1, true);
storage.setEnabled(WORKFLOW_ID2, false);
storage.updateNextNaturalTrigger(WORKFLOW_ID3, TriggerInstantSpec.create(TIMESTAMP, TIMESTAMP.plus(Duration.ofHours(1))));
assertThat(storage.workflows().size(), is(3));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID1, workflow1));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID2, workflow2));
assertThat(storage.workflows(), hasEntry(WORKFLOW_ID3, workflow3));
}
@Test
public void shouldReturnAllWorkflowsInComponent() throws Exception {
String componentId = "component";
Workflow workflow1 = workflow(WORKFLOW_ID1);
Workflow workflow2 = workflow(WORKFLOW_ID2);
Workflow workflow3 = workflow(WORKFLOW_ID3);
assertThat(workflow1.componentId(), is(componentId));
assertThat(workflow2.componentId(), is(componentId));
assertThat(workflow3.componentId(), not(componentId));
storage.store(workflow1);
storage.store(workflow2);
storage.store(workflow3);
List<Workflow> l = storage.workflows(componentId);
assertThat(l, hasSize(2));
assertThat(l, hasItem(workflow1));
assertThat(l, hasItem(workflow2));
}
@Test
public void shouldReturnEmptyListIfComponentDoesNotExist() throws Exception {
String componentId = "component";
List<Workflow> l = storage.workflows(componentId);
assertThat(l, hasSize(0));
}
@Test
public void testDefaultConfig() {
final StyxConfig expectedConfig = StyxConfig.newBuilder()
.globalDockerRunnerId("default")
.globalEnabled(true)
.debugEnabled(false)
.resourcesSyncEnabled(false)
.executionGatingEnabled(false)
.build();
assertThat(storage.config(), is(expectedConfig));
}
@Test
public void shouldStoreAndReadBackfill() throws Exception {
final Backfill backfill = Backfill.newBuilder()
.id("backfill-2")
.start(Instant.parse("2017-01-01T00:00:00Z"))
.end(Instant.parse("2017-01-02T00:00:00Z"))
.workflowId(WorkflowId.create("component", "workflow2"))
.concurrency(2)
.nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
.schedule(DAYS)
.build();
storage.storeBackfill(backfill);
assertThat(storage.getBackfill(backfill.id()), equalTo(Optional.of(backfill)));
}
@Test
public void shouldStoreAndReadBackfillWithDescription() throws Exception {
final Backfill backfill = Backfill.newBuilder()
.id("backfill-2")
.start(Instant.parse("2017-01-01T00:00:00Z"))
.end(Instant.parse("2017-01-02T00:00:00Z"))
.workflowId(WorkflowId.create("component", "workflow2"))
.concurrency(2)
.description("Description")
.nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
.schedule(DAYS)
.build();
storage.storeBackfill(backfill);
assertThat(storage.getBackfill(backfill.id()), equalTo(Optional.of(backfill)));
}
private Workflow workflow(WorkflowId workflowId) {
return Workflow.create(
workflowId.componentId(),
WorkflowConfiguration.builder()
.id(workflowId.id())
.schedule(HOURS)
.build());
}
@Test
public void runInTransactionShouldCallFunctionAndCommit() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
when(transactionFunction.apply(any())).thenReturn("foo");
String result = storage.runInTransaction(transactionFunction);
assertThat(result, is("foo"));
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).commit();
verify(storageTransaction, never()).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnFailure() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final Exception expectedException = new FooException();
when(transactionFunction.apply(any())).thenThrow(expectedException);
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (FooException e) {
// Verify that we can throw a user defined checked exception type inside the transaction
// body and catch it
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction, never()).commit();
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnPreCommitConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final Exception expectedException = new DatastoreException(10, "", "");
when(transactionFunction.apply(any())).thenThrow(expectedException);
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertTrue(e.isConflict());
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction, never()).commit();
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldCallFunctionAndRollbackOnCommitConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
final DatastoreException datastoreException = new DatastoreException(1, "", "");
final TransactionException expectedException = new TransactionException(datastoreException);
when(transactionFunction.apply(any())).thenReturn("");
doThrow(expectedException).when(storageTransaction).commit();
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldThrowIfRollbackFailsAfterConflict() throws Exception {
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
final Transaction transaction = datastore.newTransaction();
final DatastoreStorageTransaction storageTransaction = spy(new DatastoreStorageTransaction(transaction));
when(storageTransactionFactory.apply(any())).thenReturn(storageTransaction);
when(transactionFunction.apply(any())).thenReturn("");
final DatastoreException datastoreException = new DatastoreException(1, "", "");
doThrow(new TransactionException(datastoreException)).when(storageTransaction).commit();
final TransactionException expectedException = new TransactionException(datastoreException);
doThrow(expectedException).when(storageTransaction).rollback();
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertFalse(e.isConflict());
assertThat(e, is(expectedException));
}
verify(transactionFunction).apply(storageTransaction);
verify(storageTransaction).rollback();
}
@Test
public void runInTransactionShouldThrowIfDatastoreNewTransactionFails() throws Exception {
Datastore datastore = mock(Datastore.class);
final DatastoreStorage storage = new DatastoreStorage(datastore, Duration.ZERO, storageTransactionFactory);
when(datastore.newTransaction()).thenThrow(new DatastoreException(1, "", ""));
when(transactionFunction.apply(any())).thenReturn("");
try {
storage.runInTransaction(transactionFunction);
fail("Expected exception!");
} catch (TransactionException e) {
assertFalse(e.isConflict());
}
verify(transactionFunction, never()).apply(any());
}
private static class FooException extends Exception {
}
}
| Add test for fetching shards from storage
| styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java | Add test for fetching shards from storage |
|
Java | apache-2.0 | f86e8f8c125b2368b1f8ee4decee70bf80d7b4d7 | 0 | d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor | /**
* Copyright 2016 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.server.resources;
import com.google.common.collect.ImmutableMap;
import com.netflix.conductor.core.config.Configuration;
import com.netflix.conductor.metrics.Monitors;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.histogram.PercentileTimer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.InputStream;
import java.time.Duration;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @author Oleksiy Lysak
*
*/
@Singleton
@Path("/v1")
@Api(value = "/v1", produces = MediaType.APPLICATION_JSON, tags = "Status Info")
@Produces({MediaType.APPLICATION_JSON})
public class InfoResource {
private static Logger logger = LoggerFactory.getLogger(InfoResource.class);
private final String prefix = "deluxe.conductor.";
private String fullVersion;
private Configuration config;
@Inject
public InfoResource(Configuration config) {
this.config = config;
try {
InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/conductor-core.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
String version = prop.getProperty("Implementation-Version");
String change = prop.getProperty("Change");
fullVersion = config.getProperty("APP.VERSION", version + "-" + change);
} catch (Exception e) {
logger.error("Failed to read conductor-core.properties" + e.getMessage(), e);
}
}
@GET
@Path("/status")
@ApiOperation(value = "Get the status")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> status() {
return Collections.singletonMap("version", fullVersion);
}
@GET
@Path("/dependencies")
@ApiOperation(value = "Get the dependencies")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> dependencies() {
List<Object> endpoints = new ArrayList<>();
endpoints.add(config.getProperty("conductor.auth.url", ""));
endpoints.add("events.service." + config.getProperty("TLD", "local"));
endpoints.add("vault.service." + config.getProperty("TLD", "local"));
List<Map<String, Object>> dependencies = new ArrayList<>();
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "auth")
.put("version", "v1")
.put("scheme", "https")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "vault")
.put("version", "v1")
.put("scheme", "http")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "events")
.put("version", "v1")
.put("scheme", "nats")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "*")
.put("version", "v1")
.put("scheme", "http")
.put("external", false)
.build());
Map<String, Object> result = new HashMap<>();
result.put("version", fullVersion);
result.put("endpoints", endpoints);
result.put("dependencies", dependencies);
return result;
}
@GET
@Path("/metrics")
@ApiOperation(value = "Get the metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> metrics() {
Map<String, Object> output = new TreeMap<>();
// Counters
output.putAll(getCounters());
output.putAll(getTodayCounters());
// Gauges to track in progress tasks, workflows, etc...
output.putAll(getGauges());
// Timers
output.putAll(getTimers());
output.putAll(getAverageExecutionTimes());
return output;
}
private Map<String, Object> getCounters() {
Map<String, Object> output = new HashMap<>();
// Map counter names to metric names
Map<String, String> counterMap = new HashMap<>();
counterMap.put("workflow_completion", "workflows_completed");
counterMap.put("workflow_failure", "workflows_failed");
counterMap.put("workflow_start", "workflows_started");
counterMap.put("workflow_cancel", "workflows_canceled");
counterMap.put("workflow_restart", "workflows_restarted");
// Counters
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
counters.forEach((name, map) -> {
if (counterMap.containsKey(name)) {
output.put(prefix + counterMap.get(name), sum(map));
}
});
return output;
}
private Map<String, Object> getTodayCounters() {
Map<String, Object> output = new HashMap<>();
// Map counter names to metric names
Map<String, String> todayMap = new HashMap<>();
todayMap.put("workflow_completion", "workflows_completed_today");
todayMap.put("workflow_start", "workflows_started_today");
// Counters
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
final LocalDate today = LocalDate.now();
counters.forEach((name, map) -> {
// Workflows Started or Completed Today
if (todayMap.containsKey(name)) {
final long sum = map.entrySet().stream()
.filter(e -> e.getKey().containsKey("date"))
.mapToLong(e -> {
final LocalDate value = LocalDate.parse(e.getKey().get("date"));
return today.isEqual(value) ? e.getValue().count() : 0;
})
.sum();
output.put(prefix + todayMap.get(name), sum);
}
});
return output;
}
private Map<String, Object> getGauges() {
Map<String, Object> output = new HashMap<>();
// Map gauge names to metric names
Map<String, String> gaugeMap = new HashMap<>();
gaugeMap.put("workflow_in_progress", "workflows_in_progress");
gaugeMap.put("task_in_progress", "tasks_in_progress");
// Output gauges
final Map<String, Map<Map<String, String>, AtomicLong>> gauges = Monitors.getGauges();
gauges.forEach((name, map) -> {
if (gaugeMap.containsKey(name)) {
final long value = map.values().stream().mapToLong(v -> v.get()).sum();
output.put(prefix + gaugeMap.get(name), value);
}
});
return output;
}
private Map<String, Object> getTimers() {
Map<String, Object> output = new HashMap<>();
// Map timer names to metric names
Map<String, String> timerMap = new HashMap<>();
timerMap.put("task_queue_wait", "avg_task_queue_wait_ms");
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
// Basic timers
timers.forEach((name, map) -> {
map.forEach((tags, timer) -> {
if (timerMap.containsKey(name)) {
final long avgMs = Duration.ofNanos(timer.totalTime()).toMillis() / timer.count();
output.put(prefix + timerMap.get(name), avgMs);
}
});
});
return output;
}
private Map<String, Object> getAverageExecutionTimes() {
Map<String, Object> output = new HashMap<>();
Map<String, String> executionMap = new HashMap<>();
executionMap.put("http_task_execution", "avg_http_task_execution_ms");
executionMap.put("task_execution", "avg_task_execution_ms");
executionMap.put("workflow_execution", "avg_workflow_execution_ms");
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
timers.forEach((name, map) -> {
if (executionMap.containsKey(name)) {
long totalCount = 0;
long totalTime = 0;
Iterator<Map.Entry<Map<String, String>, PercentileTimer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Map<String, String>, PercentileTimer> entry = iterator.next();
PercentileTimer timer = entry.getValue();
totalCount += timer.count();
totalTime += Duration.ofNanos(timer.totalTime()).toMillis();
}
output.put(prefix + executionMap.get(name), totalTime / totalCount);
}
});
return output;
}
@GET
@Path("/metrics/all")
@ApiOperation(value = "Get all available metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> debugMetrics() {
Map<String, Object> output = new TreeMap<>();
output.putAll(getAllCounterData());
output.putAll(getAllGaugeData());
output.putAll(getAllTimerData());
return output;
}
@GET
@Path("/metrics/counters")
@ApiOperation(value = "Get the counter metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> counters() {
return new TreeMap<>(getAllCounterData());
}
@GET
@Path("/metrics/gauges")
@ApiOperation(value = "Get the gauge metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> gauges() {
return new TreeMap<>(getAllGaugeData());
}
@GET
@Path("/metrics/timers")
@ApiOperation(value = "Get the timer metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> timers() {
return new TreeMap<>(getAllTimerData());
}
private Map<String, Object> getAllCounterData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
counters.forEach((name, map) -> {
map.forEach((tags, counter) -> {
output.put(name + "." + joinTags(tags) + ".counter", counter.count());
});
});
return output;
}
private Map<String, Object> getAllGaugeData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, AtomicLong>> gauges = Monitors.getGauges();
gauges.forEach((name, map) -> {
map.forEach((tags, value) -> {
output.put(name + "." + joinTags(tags) + ".value", value.get());
});
});
return output;
}
private Map<String, Object> getAllTimerData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
timers.forEach((name, map) -> {
map.forEach((tags, timer) -> {
String key = joinTags(tags);
output.put(name + "." + key + ".count", timer.count());
output.put(name + "." + key + ".totalTime", timer.totalTime());
});
});
return output;
}
private String joinTags(Map<String, String> tags) {
// Concatenate all tags into single line: tag1.tag2.tagX excluding class name
return tags.entrySet().stream()
.filter(entry -> !entry.getKey().equals("class"))
.map(Map.Entry::getValue).collect(Collectors.joining("."));
}
// Return the sum of the Counter values in m
private long sum(Map<Map<String, String>, Counter> m) {
return m.values().stream().map(c -> {return c.count();}).mapToLong(i -> i).sum();
}
private Set<String> getMainWorkfowNames() {
return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
"deluxe.dependencygraph.assembly.conformancegroup.process", // Sherlock V1 Assembly Conformance
"deluxe.dependencygraph.conformancegroup.process", // Sherlock V1 Conformance
"deluxe.dependencygraph.sourcewait.process", // Sherlock V2 Sourcewait
"deluxe.dependencygraph.execute.process", // Sherlock V2 Execute
"deluxe.deluxeone.sky.compliance.process", // Sky Compliance
"deluxe.delivery.itune.process" // iTune
)));
}
// Given a workflow name such as deluxe.eventhandler.delivery.itunes.subscribemsg.datamovement.1.0.0
// return the name with the version number trimmed, as deluxe.eventhandler.delivery.itunes.subscribemsg.datamovement
private String trimWorkflowVersion(String workflowName) {
Pattern pattern = Pattern.compile("([a-zA-Z_.]+)*");
Matcher matcher = pattern.matcher(workflowName);
if (matcher.find()) {
String match = matcher.group(1);
if (match.endsWith(".")) {
match = match.substring(0, match.length() - 1);
}
return match;
} else {
return workflowName;
}
}
}
| jersey/src/main/java/com/netflix/conductor/server/resources/InfoResource.java | /**
* Copyright 2016 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.server.resources;
import com.google.common.collect.ImmutableMap;
import com.netflix.conductor.core.config.Configuration;
import com.netflix.conductor.metrics.Monitors;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.histogram.PercentileTimer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.InputStream;
import java.time.Duration;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @author Oleksiy Lysak
*
*/
@Singleton
@Path("/v1")
@Api(value = "/v1", produces = MediaType.APPLICATION_JSON, tags = "Status Info")
@Produces({MediaType.APPLICATION_JSON})
public class InfoResource {
private static Logger logger = LoggerFactory.getLogger(InfoResource.class);
private final String prefix = "deluxe.conductor.";
private String fullVersion;
private Configuration config;
@Inject
public InfoResource(Configuration config) {
this.config = config;
try {
InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/conductor-core.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
String version = prop.getProperty("Implementation-Version");
String change = prop.getProperty("Change");
fullVersion = config.getProperty("APP.VERSION", version + "-" + change);
} catch (Exception e) {
logger.error("Failed to read conductor-core.properties" + e.getMessage(), e);
}
}
@GET
@Path("/status")
@ApiOperation(value = "Get the status")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> status() {
return Collections.singletonMap("version", fullVersion);
}
@GET
@Path("/dependencies")
@ApiOperation(value = "Get the dependencies")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> dependencies() {
List<Object> endpoints = new ArrayList<>();
endpoints.add(config.getProperty("conductor.auth.url", ""));
endpoints.add("events.service." + config.getProperty("TLD", "local"));
endpoints.add("vault.service." + config.getProperty("TLD", "local"));
List<Map<String, Object>> dependencies = new ArrayList<>();
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "auth")
.put("version", "v1")
.put("scheme", "https")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "vault")
.put("version", "v1")
.put("scheme", "http")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "events")
.put("version", "v1")
.put("scheme", "nats")
.put("external", false)
.build());
dependencies.add(ImmutableMap.<String, Object>builder()
.put("name", "*")
.put("version", "v1")
.put("scheme", "http")
.put("external", false)
.build());
Map<String, Object> result = new HashMap<>();
result.put("version", fullVersion);
result.put("endpoints", endpoints);
result.put("dependencies", dependencies);
return result;
}
@GET
@Path("/metrics")
@ApiOperation(value = "Get the metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> metrics() {
Map<String, Object> output = new TreeMap<>();
// Counters
output.putAll(getCounters());
output.putAll(getTodayCounters());
// Gauges to track in progress tasks, workflows, etc...
output.putAll(getGauges());
// Timers
output.putAll(getTimers());
output.putAll(getAverageExecutionTimes());
return output;
}
private Map<String, Object> getCounters() {
Map<String, Object> output = new HashMap<>();
// Map counter names to metric names
Map<String, String> counterMap = new HashMap<>();
counterMap.put("workflow_completion", "workflows_completed");
counterMap.put("workflow_failure", "workflows_failed");
counterMap.put("workflow_start", "workflows_started");
counterMap.put("workflow_cancel", "workflows_canceled");
counterMap.put("workflow_restart", "workflows_restarted");
// Counters
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
counters.forEach((name, map) -> {
if (counterMap.containsKey(name)) {
output.put(prefix + counterMap.get(name), sum(map));
}
});
return output;
}
private Map<String, Object> getTodayCounters() {
Map<String, Object> output = new HashMap<>();
// Map counter names to metric names
Map<String, String> todayMap = new HashMap<>();
todayMap.put("workflow_completion", "workflows_completed_today");
todayMap.put("workflow_start", "workflows_started_today");
// Counters
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
final LocalDate today = LocalDate.now();
counters.forEach((name, map) -> {
// Workflows Started or Completed Today
if (todayMap.containsKey(name)) {
final long sum = map.entrySet().stream()
.filter(e -> e.getKey().containsKey("date"))
.mapToLong(e -> {
final LocalDate value = LocalDate.parse(e.getKey().get("date"));
return today.isEqual(value) ? e.getValue().count() : 0;
})
.sum();
output.put(prefix + todayMap.get(name), sum);
}
});
return output;
}
private Map<String, Object> getGauges() {
Map<String, Object> output = new HashMap<>();
// Map gauge names to metric names
Map<String, String> gaugeMap = new HashMap<>();
gaugeMap.put("workflow_in_progress", "workflows_in_progress");
gaugeMap.put("task_in_progress", "tasks_in_progress");
// Output gauges
final Map<String, Map<Map<String, String>, AtomicLong>> gauges = Monitors.getGauges();
gauges.forEach((name, map) -> {
if (gaugeMap.containsKey(name)) {
final long value = map.values().stream().mapToLong(v -> v.get()).sum();
output.put(prefix + gaugeMap.get(name), value);
}
});
return output;
}
private Map<String, Object> getTimers() {
Map<String, Object> output = new HashMap<>();
// Map timer names to metric names
Map<String, String> timerMap = new HashMap<>();
timerMap.put("task_queue_wait", "avg_task_queue_wait_ms");
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
// Basic timers
timers.forEach((name, map) -> {
map.forEach((tags, timer) -> {
if (timerMap.containsKey(name)) {
final long avgMs = Duration.ofNanos(timer.totalTime()).toMillis() / timer.count();
output.put(prefix + timerMap.get(name), avgMs);
}
});
});
return output;
}
private Map<String, Object> getAverageExecutionTimes() {
Map<String, Object> output = new HashMap<>();
Map<String, String> executionMap = new HashMap<>();
executionMap.put("http_task_execution", "avg_http_task_execution_ms");
executionMap.put("task_execution", "avg_task_execution_ms");
executionMap.put("workflow_execution", "avg_workflow_execution_ms");
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
timers.forEach((name, map) -> {
if (executionMap.containsKey(name)) {
long totalCount = 0;
long totalTime = 0;
Iterator<Map.Entry<Map<String, String>, PercentileTimer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Map<String, String>, PercentileTimer> entry = iterator.next();
PercentileTimer timer = entry.getValue();
totalCount += timer.count();
totalTime += Duration.ofNanos(timer.totalTime()).toMillis();
}
output.put(prefix + executionMap.get(name), totalTime / totalCount);
}
});
return output;
}
@GET
@Path("/metrics/all")
@ApiOperation(value = "Get all available metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> debugMetrics() {
Map<String, Object> output = new TreeMap<>();
output.putAll(getAllCounterData());
output.putAll(getAllGaugeData());
output.putAll(getAllTimerData());
return output;
}
@GET
@Path("/metrics/counters")
@ApiOperation(value = "Get the counter metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> counters() {
return new TreeMap<>(getAllCounterData());
}
@GET
@Path("/metrics/gauges")
@ApiOperation(value = "Get the gauge metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> gauges() {
return new TreeMap<>(getAllGaugeData());
}
@GET
@Path("/metrics/timers")
@ApiOperation(value = "Get the timer metrics")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> timers() {
return new TreeMap<>(getAllTimerData());
}
private Map<String, Object> getAllCounterData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, Counter>> counters = Monitors.getCounters();
counters.forEach((name, map) -> {
map.forEach((tags, counter) -> {
output.put(name + "." + joinTags(tags) + ".counter", counter.count());
});
});
return output;
}
private Map<String, Object> getAllGaugeData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, AtomicLong>> gauges = Monitors.getGauges();
gauges.forEach((name, map) -> {
map.forEach((tags, value) -> {
output.put(name + "." + joinTags(tags) + ".value", value.get());
});
});
return output;
}
private Map<String, Object> getAllTimerData() {
Map<String, Object> output = new HashMap<>();
final Map<String, Map<Map<String, String>, PercentileTimer>> timers = Monitors.getTimers();
timers.forEach((name, map) -> {
map.forEach((tags, timer) -> {
String key = joinTags(tags);
output.put(name + "." + key + ".count", timer.count());
output.put(name + "." + key + ".totalTime", timer.totalTime());
});
});
return output;
}
private String joinTags(Map<String, String> tags) {
// Concatenate all tags into single line: tag1.tag2.tagX excluding class name
return tags.entrySet().stream()
.filter(entry -> !entry.getKey().equals("class"))
.map(Map.Entry::getValue).collect(Collectors.joining("."));
}
// Return the sum of the Counter values in m
private long sum(Map<Map<String, String>, Counter> m) {
return m.values().stream().map(c -> {return c.count();}).mapToLong(i -> i).sum();
}
private Set<String> getMainWorkfowNames() {
return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
"deluxe.dependencygraph.assembly.conformancegroup.process", // Sherlock V1 Assembly Conformance
"deluxe.dependencygraph.conformancegroup.process", // Sherlock V1 Conformance
"deluxe.dependencygraph.sourcewait.process", // Sherlock V2 Sourcewait
"deluxe.dependencygraph.execute.process", // Sherlock V2 Execute
"deluxe.deluxeone.sky.compliance.process", // Sky Compliance
"deluxe.delivery.itune.process" // iTune
)));
}
private String trimWorkflowVersion(String workflowName) {
Pattern pattern = Pattern.compile("([a-zA-Z.]+)*");
Matcher matcher = pattern.matcher(workflowName);
if (matcher.find()) {
String match = matcher.group(1);
if (match.endsWith(".")) {
match = match.substring(0, match.length() - 1);
}
return match;
} else {
return workflowName;
}
}
}
| Allow underscores in workflow names
| jersey/src/main/java/com/netflix/conductor/server/resources/InfoResource.java | Allow underscores in workflow names |
|
Java | apache-2.0 | 2d2b78d3b63154d4cdb2da80e659f8bbbc40a296 | 0 | quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus | package io.quarkus.test.common;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.ServiceLoader;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import io.quarkus.runtime.configuration.ConfigUtils;
import io.quarkus.runtime.configuration.QuarkusConfigFactory;
import io.quarkus.test.common.http.TestHTTPResourceManager;
import io.smallrye.config.SmallRyeConfig;
public class NativeImageLauncher implements Closeable {
private static final int DEFAULT_PORT = 8081;
private static final long DEFAULT_IMAGE_WAIT_TIME = 60;
private final Class<?> testClass;
private final String profile;
private Process quarkusProcess;
private final int port;
private final long imageWaitTime;
private final Map<String, String> systemProps = new HashMap<>();
private List<NativeImageStartedNotifier> startedNotifiers;
private NativeImageLauncher(Class<?> testClass, Config config) {
this(testClass,
config.getValue("quarkus.http.test-port", OptionalInt.class).orElse(DEFAULT_PORT),
config.getValue("quarkus.test.native-image-wait-time", OptionalLong.class).orElse(DEFAULT_IMAGE_WAIT_TIME),
config.getOptionalValue("quarkus.test.native-image-profile", String.class)
.orElse(null));
}
public NativeImageLauncher(Class<?> testClass) {
// todo: accessing run time config from here doesn't make sense
this(testClass, installAndGetSomeConfig());
}
private static Config installAndGetSomeConfig() {
final SmallRyeConfig config = ConfigUtils.configBuilder(false).build();
QuarkusConfigFactory.setConfig(config);
final ConfigProviderResolver cpr = ConfigProviderResolver.instance();
try {
final Config installed = cpr.getConfig();
if (installed != config) {
cpr.releaseConfig(installed);
}
} catch (IllegalStateException ignored) {
}
return config;
}
public NativeImageLauncher(Class<?> testClass, int port, long imageWaitTime, String profile) {
this.testClass = testClass;
this.port = port;
this.imageWaitTime = imageWaitTime;
List<NativeImageStartedNotifier> startedNotifiers = new ArrayList<>();
for (NativeImageStartedNotifier i : ServiceLoader.load(NativeImageStartedNotifier.class)) {
startedNotifiers.add(i);
}
this.startedNotifiers = startedNotifiers;
this.profile = profile;
}
public void start() throws IOException {
System.setProperty("test.url", TestHTTPResourceManager.getUri());
String path = System.getProperty("native.image.path");
if (path == null) {
path = guessPath(testClass);
}
List<String> args = new ArrayList<>();
args.add(path);
args.add("-Dquarkus.http.port=" + port);
args.add("-Dtest.url=" + TestHTTPResourceManager.getUri());
args.add("-Dquarkus.log.file.path=" + PropertyTestUtil.getLogFileLocation());
if (profile != null) {
args.add("-Dquarkus.profile=" + profile);
}
for (Map.Entry<String, String> e : systemProps.entrySet()) {
args.add("-D" + e.getKey() + "=" + e.getValue());
}
System.out.println("Executing " + args);
quarkusProcess = Runtime.getRuntime().exec(args.toArray(new String[args.size()]));
new Thread(new ProcessReader(quarkusProcess.getInputStream())).start();
new Thread(new ProcessReader(quarkusProcess.getErrorStream())).start();
waitForQuarkus();
}
private static String guessPath(Class<?> testClass) {
//ok, lets make a guess
//this is a horrible hack, but it is intended to make this work in IDE's
ClassLoader cl = testClass.getClassLoader();
if (cl instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) cl).getURLs();
for (URL url : urls) {
final String applicationNativeImagePath = guessPath(url);
if (applicationNativeImagePath != null) {
return applicationNativeImagePath;
}
}
} else {
// try the CodeSource way
final CodeSource codeSource = testClass.getProtectionDomain().getCodeSource();
if (codeSource != null) {
final URL codeSourceLocation = codeSource.getLocation();
final String applicationNativeImagePath = guessPath(codeSourceLocation);
if (applicationNativeImagePath != null) {
return applicationNativeImagePath;
}
}
}
throw new RuntimeException(
"Unable to automatically find native image, please set the native.image.path to the native executable you wish to test");
}
private static String guessPath(final URL url) {
if (url == null) {
return null;
}
if (url.getProtocol().equals("file") && url.getPath().endsWith("test-classes/")) {
//we have the maven test classes dir
File testClasses = new File(url.getPath());
for (File file : testClasses.getParentFile().listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
} else if (url.getProtocol().equals("file") && url.getPath().endsWith("test/")) {
//we have the gradle test classes dir, build/classes/java/test
File testClasses = new File(url.getPath());
for (File file : testClasses.getParentFile().getParentFile().getParentFile().listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
} else if (url.getProtocol().equals("file") && url.getPath().contains("/target/surefire/")) {
//this will make mvn failsafe:integration-test work
String path = url.getPath();
int index = path.lastIndexOf("/target/");
File targetDir = new File(path.substring(0, index) + "/target/");
for (File file : targetDir.listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
}
return null;
}
private static void logGuessedPath(String guessedPath) {
System.err.println("======================================================================================");
System.err.println(" native.image.path was not set, making a guess for the correct path of native image");
System.err.println(" guessed path: " + guessedPath);
System.err.println("======================================================================================");
}
private void waitForQuarkus() {
long bailout = System.currentTimeMillis() + imageWaitTime * 1000;
while (System.currentTimeMillis() < bailout) {
if (!quarkusProcess.isAlive()) {
throw new RuntimeException("Failed to start native image, process has exited");
}
try {
Thread.sleep(100);
for (NativeImageStartedNotifier i : startedNotifiers) {
if (i.isNativeImageStarted()) {
return;
}
}
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress("localhost", port));
return;
}
} catch (Exception expected) {
}
}
throw new RuntimeException("Unable to start native image in " + imageWaitTime + "s");
}
public void addSystemProperties(Map<String, String> systemProps) {
this.systemProps.putAll(systemProps);
}
private static final class ProcessReader implements Runnable {
private final InputStream inputStream;
private ProcessReader(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
byte[] b = new byte[100];
int i;
try {
while ((i = inputStream.read(b)) > 0) {
System.out.print(new String(b, 0, i, StandardCharsets.UTF_8));
}
} catch (IOException e) {
//ignore
}
}
}
@Override
public void close() {
quarkusProcess.destroy();
}
}
| test-framework/common/src/main/java/io/quarkus/test/common/NativeImageLauncher.java | package io.quarkus.test.common;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.ServiceLoader;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import io.quarkus.runtime.configuration.ConfigUtils;
import io.quarkus.runtime.configuration.QuarkusConfigFactory;
import io.quarkus.test.common.http.TestHTTPResourceManager;
import io.smallrye.config.SmallRyeConfig;
public class NativeImageLauncher implements Closeable {
private static final int DEFAULT_PORT = 8081;
private static final long DEFAULT_IMAGE_WAIT_TIME = 60;
private final Class<?> testClass;
private final String profile;
private Process quarkusProcess;
private final int port;
private final long imageWaitTime;
private final Map<String, String> systemProps = new HashMap<>();
private List<NativeImageStartedNotifier> startedNotifiers;
private NativeImageLauncher(Class<?> testClass, Config config) {
this(testClass,
config.getValue("quarkus.http.test-port", OptionalInt.class).orElse(DEFAULT_PORT),
config.getValue("quarkus.test.native-image-wait-time", OptionalLong.class).orElse(DEFAULT_IMAGE_WAIT_TIME),
config.getOptionalValue("quarkus.test.native-image-profile", String.class)
.orElse(null));
}
public NativeImageLauncher(Class<?> testClass) {
// todo: accessing run time config from here doesn't make sense
this(testClass, installAndGetSomeConfig());
}
private static Config installAndGetSomeConfig() {
final SmallRyeConfig config = ConfigUtils.configBuilder(false).build();
QuarkusConfigFactory.setConfig(config);
final ConfigProviderResolver cpr = ConfigProviderResolver.instance();
try {
final Config installed = cpr.getConfig();
if (installed != config) {
cpr.releaseConfig(installed);
}
} catch (IllegalStateException ignored) {
}
return config;
}
public NativeImageLauncher(Class<?> testClass, int port, long imageWaitTime, String profile) {
this.testClass = testClass;
this.port = port;
this.imageWaitTime = imageWaitTime;
List<NativeImageStartedNotifier> startedNotifiers = new ArrayList<>();
for (NativeImageStartedNotifier i : ServiceLoader.load(NativeImageStartedNotifier.class)) {
startedNotifiers.add(i);
}
this.startedNotifiers = startedNotifiers;
this.profile = profile;
}
public void start() throws IOException {
System.setProperty("test.url", TestHTTPResourceManager.getUri());
String path = System.getProperty("native.image.path");
if (path == null) {
path = guessPath(testClass);
}
List<String> args = new ArrayList<>();
args.add(path);
args.add("-Dquarkus.http.port=" + port);
args.add("-Dtest.url=" + TestHTTPResourceManager.getUri());
args.add("-Dquarkus.log.file.path=" + PropertyTestUtil.getLogFileLocation());
if (profile != null) {
args.add("-Dquarkus.profile=" + profile);
}
for (Map.Entry<String, String> e : systemProps.entrySet()) {
args.add("-D" + e.getKey() + "=" + e.getValue());
}
System.out.println("Executing " + args);
quarkusProcess = Runtime.getRuntime().exec(args.toArray(new String[args.size()]));
new Thread(new ProcessReader(quarkusProcess.getInputStream())).start();
new Thread(new ProcessReader(quarkusProcess.getErrorStream())).start();
waitForQuarkus();
}
private static String guessPath(Class<?> testClass) {
//ok, lets make a guess
//this is a horrible hack, but it is intended to make this work in IDE's
ClassLoader cl = testClass.getClassLoader();
if (cl instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) cl).getURLs();
for (URL url : urls) {
if (url.getProtocol().equals("file") && url.getPath().endsWith("test-classes/")) {
//we have the maven test classes dir
File testClasses = new File(url.getPath());
for (File file : testClasses.getParentFile().listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
} else if (url.getProtocol().equals("file") && url.getPath().endsWith("test/")) {
//we have the gradle test classes dir, build/classes/java/test
File testClasses = new File(url.getPath());
for (File file : testClasses.getParentFile().getParentFile().getParentFile().listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
} else if (url.getProtocol().equals("file") && url.getPath().contains("/target/surefire/")) {
//this will make mvn failsafe:integration-test work
String path = url.getPath();
int index = path.lastIndexOf("/target/");
File targetDir = new File(path.substring(0, index) + "/target/");
for (File file : targetDir.listFiles()) {
if (file.getName().endsWith("-runner")) {
logGuessedPath(file.getAbsolutePath());
return file.getAbsolutePath();
}
}
}
}
}
throw new RuntimeException(
"Unable to automatically find native image, please set the native.image.path to the native executable you wish to test");
}
private static void logGuessedPath(String guessedPath) {
System.err.println("======================================================================================");
System.err.println(" native.image.path was not set, making a guess for the correct path of native image");
System.err.println(" guessed path: " + guessedPath);
System.err.println("======================================================================================");
}
private void waitForQuarkus() {
long bailout = System.currentTimeMillis() + imageWaitTime * 1000;
while (System.currentTimeMillis() < bailout) {
if (!quarkusProcess.isAlive()) {
throw new RuntimeException("Failed to start native image, process has exited");
}
try {
Thread.sleep(100);
for (NativeImageStartedNotifier i : startedNotifiers) {
if (i.isNativeImageStarted()) {
return;
}
}
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress("localhost", port));
return;
}
} catch (Exception expected) {
}
}
throw new RuntimeException("Unable to start native image in " + imageWaitTime + "s");
}
public void addSystemProperties(Map<String, String> systemProps) {
this.systemProps.putAll(systemProps);
}
private static final class ProcessReader implements Runnable {
private final InputStream inputStream;
private ProcessReader(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
byte[] b = new byte[100];
int i;
try {
while ((i = inputStream.read(b)) > 0) {
System.out.print(new String(b, 0, i, StandardCharsets.UTF_8));
}
} catch (IOException e) {
//ignore
}
}
}
@Override
public void close() {
quarkusProcess.destroy();
}
}
| issue#7535 Enhance the NativeImageLauncher, used by the NativeImage test extension, to support guessing the application's native image path on Java 11+ runtimes
| test-framework/common/src/main/java/io/quarkus/test/common/NativeImageLauncher.java | issue#7535 Enhance the NativeImageLauncher, used by the NativeImage test extension, to support guessing the application's native image path on Java 11+ runtimes |
|
Java | apache-2.0 | b59e22a260e5224bd42ea4c730b5c4cc93ec978c | 0 | gurbuzali/hazelcast-jet,gurbuzali/hazelcast-jet | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.impl.metrics;
import com.hazelcast.core.Member;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.impl.JetClientInstanceImpl;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.util.UuidUtil;
import com.hazelcast.version.MemberVersion;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import java.util.concurrent.ExecutionException;
import java.util.stream.StreamSupport;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
public class ReadMetricsTest extends JetTestSupport {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void when_readMetricsAsync() {
JetInstance inst = createJetMember();
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
assertTrueEventually(() -> {
Member member = inst.getHazelcastInstance().getCluster().getLocalMember();
MetricsResultSet result = client.readMetricsAsync(member, 0).get();
assertFalse(result.collections().isEmpty());
assertTrue(
StreamSupport.stream(result.collections().get(0).spliterator(), false)
.anyMatch(m -> m.key().equals("[metric=cluster.size]"))
);
// immediate next call should not return empty result
result = client.readMetricsAsync(member, result.nextSequence()).get();
assertFalse(result.collections().isEmpty());
}, 30);
}
@Test
public void when_invalidUUID() throws ExecutionException, InterruptedException {
JetInstance inst = createJetMember();
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
Address addr = inst.getCluster().getLocalMember().getAddress();
MemberVersion ver = inst.getCluster().getLocalMember().getVersion();
MemberImpl member = new MemberImpl(addr, ver, false, UuidUtil.newUnsecureUuidString());
exception.expectCause(Matchers.instanceOf(IllegalArgumentException.class));
client.readMetricsAsync(member, 0).get();
}
@Test
public void when_metricsDisabled() throws ExecutionException, InterruptedException {
JetConfig cfg = new JetConfig();
cfg.getMetricsConfig().setEnabled(false);
JetInstance inst = createJetMember(cfg);
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
exception.expectCause(Matchers.instanceOf(IllegalArgumentException.class));
MetricsResultSet resultSet = client.readMetricsAsync(inst.getCluster().getLocalMember(), 0).get();
}
}
| hazelcast-jet-core/src/test/java/com/hazelcast/jet/impl/metrics/ReadMetricsTest.java | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.impl.metrics;
import com.hazelcast.core.Member;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.impl.JetClientInstanceImpl;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.util.UuidUtil;
import com.hazelcast.version.MemberVersion;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import java.util.concurrent.ExecutionException;
import java.util.stream.StreamSupport;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
public class ReadMetricsTest extends JetTestSupport {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void when_readMetricsAsync() {
JetInstance inst = createJetMember();
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
assertTrueEventually(() -> {
Member member = inst.getHazelcastInstance().getCluster().getLocalMember();
MetricsResultSet result = client.readMetricsAsync(member, 0).get();
assertFalse(result.collections().isEmpty());
assertTrue(
StreamSupport.stream(result.collections().get(0).spliterator(), false)
.anyMatch(m -> m.key().equals("[metric=os.processCpuLoad]"))
);
// immediate next call should not return empty result
result = client.readMetricsAsync(member, result.nextSequence()).get();
assertFalse(result.collections().isEmpty());
}, 30);
}
@Test
public void when_invalidUUID() throws ExecutionException, InterruptedException {
JetInstance inst = createJetMember();
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
Address addr = inst.getCluster().getLocalMember().getAddress();
MemberVersion ver = inst.getCluster().getLocalMember().getVersion();
MemberImpl member = new MemberImpl(addr, ver, false, UuidUtil.newUnsecureUuidString());
exception.expectCause(Matchers.instanceOf(IllegalArgumentException.class));
client.readMetricsAsync(member, 0).get();
}
@Test
public void when_metricsDisabled() throws ExecutionException, InterruptedException {
JetConfig cfg = new JetConfig();
cfg.getMetricsConfig().setEnabled(false);
JetInstance inst = createJetMember(cfg);
JetClientInstanceImpl client = (JetClientInstanceImpl) createJetClient();
exception.expectCause(Matchers.instanceOf(IllegalArgumentException.class));
MetricsResultSet resultSet = client.readMetricsAsync(inst.getCluster().getLocalMember(), 0).get();
}
}
| Use a different metric as os.processCpuLoad is missing in JDK 9 | hazelcast-jet-core/src/test/java/com/hazelcast/jet/impl/metrics/ReadMetricsTest.java | Use a different metric as os.processCpuLoad is missing in JDK 9 |
|
Java | apache-2.0 | b7acb03ba0044fa14650af3a5b1139ad2a8e9730 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2004 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.springframework.beans.factory.support;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.core.CollectionFactory;
/**
* Abstract BeanFactory superclass that implements default bean creation,
* with the full capabilities specified by the RootBeanDefinition class.
* Implements the AutowireCapableBeanFactory interface. Like the base class
* AbstractBeanFactory, this superclass does not assume a listable bean factory.
*
* <p>Provides bean creation (with constructor resolution), property population,
* wiring (including autowiring), and initialization. Handles runtime bean
* references, resolves managed collections, calls initialization methods, etc.
* Supports autowiring constructors, properties by name, and properties by type.
*
* <p>The main template method to be implemented by subclasses is
* <code>findMatchingBeans</code, used for autowiring by type. In case of
* a factory which is capable of searching its bean definitions, matching
* beans will typically be implemented through such a search. For other
* factory styles, simplified matching algorithms can be implemented.
*
* <p>Note that this class does <i>not</i> assume or implement bean definition
* registry capabilities. See DefaultListableBeanFactory for an implementation
* of the ListableBeanFactory and BeanDefinitionRegistry interfaces, which
* represent the API respectively SPI view on such a factory.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 13.02.2004
* @see #findMatchingBeans
* @see AbstractBeanFactory#createBean
* @see RootBeanDefinition
* @see DefaultListableBeanFactory
* @see org.springframework.beans.factory.ListableBeanFactory
* @see org.springframework.beans.factory.support.BeanDefinitionRegistry
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
/**
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set ignoreDependencyTypes = new HashSet();
/**
* Create a new AbstractAutowireCapableBeanFactory.
*/
public AbstractAutowireCapableBeanFactory() {
super();
ignoreDependencyType(BeanFactory.class);
}
/**
* Create a new AbstractAutowireCapableBeanFactory with the given parent.
* @param parentBeanFactory parent bean factory, or null if none
*/
public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
/**
* Set the instantiation strategy to use for creating bean instances.
* Default is CglibSubclassingInstantiationStrategy.
* @see CglibSubclassingInstantiationStrategy
*/
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
this.instantiationStrategy = instantiationStrategy;
}
/**
* Ignore the given dependency type for autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, just the BeanFactory interface is ignored.
* For further types to ignore, invoke this method for each type.
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContext
* @see org.springframework.context.ApplicationContextAware
*/
public void ignoreDependencyType(Class type) {
this.ignoreDependencyTypes.add(type);
}
/**
* Return the set of classes that will get ignored for autowiring.
*/
public Set getIgnoredDependencyTypes() {
return ignoreDependencyTypes;
}
//---------------------------------------------------------------------
// Implementation of AutowireCapableBeanFactory interface
//---------------------------------------------------------------------
public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck)
throws BeansException {
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd).getWrappedInstance();
}
else {
Object bean = this.instantiationStrategy.instantiate(bd, null, this);
populateBean(bean.getClass().getName(), bd, createBeanWrapper(bean));
return bean;
}
}
public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException {
if (autowireMode != AUTOWIRE_BY_NAME && autowireMode != AUTOWIRE_BY_TYPE) {
throw new IllegalArgumentException("Just constants AUTOWIRE_BY_NAME and AUTOWIRE_BY_TYPE allowed");
}
RootBeanDefinition bd = new RootBeanDefinition(existingBean.getClass(), autowireMode, dependencyCheck);
populateBean(existingBean.getClass().getName(), bd, createBeanWrapper(existingBean));
}
public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
RootBeanDefinition bd = getMergedBeanDefinition(beanName, true);
applyPropertyValues(beanName, bd, createBeanWrapper(existingBean), bd.getPropertyValues());
}
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
return applyBeanPostProcessorsBeforeInitialization(existingBean, beanName, null);
}
/**
* Apply BeanPostProcessors to the given bean instance,
* invoking their postProcessBeforeInitialization methods.
* The returned bean instance may be a wrapper around the original.
* @param bean the bean instance
* @param beanName the name of the bean
* @param mergedBeanDefinition the corresponding bean definition,
* for checking destroy methods (can be null)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessBeforeInitialization
*/
public Object applyBeanPostProcessorsBeforeInitialization(
Object bean, String beanName, RootBeanDefinition mergedBeanDefinition) throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Invoking BeanPostProcessors before initialization of bean '" + beanName + "'");
}
Object result = bean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
throw new BeanCreationException(beanName,
"postProcessBeforeInitialization method of BeanPostProcessor [" + beanProcessor +
"] returned null for bean [" + result + "] with name [" + beanName + "]");
}
}
return result;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
return applyBeanPostProcessorsAfterInitialization(existingBean, beanName, null);
}
/**
* Apply BeanPostProcessors to the given bean instance,
* invoking their postProcessAfterInitialization methods.
* The returned bean instance may be a wrapper around the original.
* @param bean the bean instance
* @param beanName the name of the bean
* @param mergedBeanDefinition the corresponding bean definition,
* for checking destroy methods (can be null)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessAfterInitialization
*/
public Object applyBeanPostProcessorsAfterInitialization(
Object bean, String beanName, RootBeanDefinition mergedBeanDefinition) throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Invoking BeanPostProcessors after initialization of bean '" + beanName + "'");
}
Object result = bean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
throw new BeanCreationException(beanName,
"postProcessAfterInitialization method of BeanPostProcessor [" + beanProcessor +
"] returned null for bean [" + result + "] with name [" + beanName + "]");
}
}
return result;
}
//---------------------------------------------------------------------
// Implementation of AbstractBeanFactory's createBean method
//---------------------------------------------------------------------
/**
* Delegates to full createBean version with allowEagerCaching=true.
* @see #createBean(String, RootBeanDefinition, Object[], boolean)
*/
protected Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)
throws BeansException {
return createBean(beanName, mergedBeanDefinition, args, true);
}
/**
* Create a bean instance for the given bean definition.
* @param beanName name of the bean
* @param mergedBeanDefinition the bean definition for the bean
* @param args arguments to use if this is a prototype constructed by a factory method.
* In this case, this will override any args specified in the bean definitions.
* This parameter should be null otherwise.
* @param allowEagerCaching whether eager caching of singletons is allowed
* (typically true for normal beans, but false for inner beans)
* @return a new instance of the bean
* @throws BeansException in case of errors
*/
protected Object createBean(
String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args, boolean allowEagerCaching)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName +
"' with merged definition [" + mergedBeanDefinition + "]");
}
if (mergedBeanDefinition.getDependsOn() != null) {
for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
// Guarantee initialization of beans that the current one depends on.
getBean(mergedBeanDefinition.getDependsOn()[i]);
}
}
BeanWrapper instanceWrapper = null;
Object bean = null;
Object originalBean = null;
String errorMessage = null;
boolean eagerlyCached = false;
try {
// Instantiate the bean.
errorMessage = "Instantiation of bean failed";
if (mergedBeanDefinition.getFactoryMethodName() != null) {
instanceWrapper = instantiateUsingFactoryMethod(beanName, mergedBeanDefinition, args);
}
else if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mergedBeanDefinition.hasConstructorArgumentValues() ) {
instanceWrapper = autowireConstructor(beanName, mergedBeanDefinition);
}
else {
// No special handling: simply use no-arg constructor.
Object beanInstance = this.instantiationStrategy.instantiate(mergedBeanDefinition, beanName, this);
instanceWrapper = createBeanWrapper(beanInstance);
initBeanWrapper(instanceWrapper);
}
bean = instanceWrapper.getWrappedInstance();
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
if (allowEagerCaching && mergedBeanDefinition.isSingleton()) {
addSingleton(beanName, bean);
eagerlyCached = true;
}
// Initialize the bean instance.
errorMessage = "Initialization of bean failed";
populateBean(beanName, mergedBeanDefinition, instanceWrapper);
if (bean instanceof BeanNameAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanName on BeanNameAware bean '" + beanName + "'");
}
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanFactoryAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanFactory on BeanFactoryAware bean '" + beanName + "'");
}
((BeanFactoryAware) bean).setBeanFactory(this);
}
originalBean = bean;
bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName, mergedBeanDefinition);
invokeInitMethods(beanName, bean, mergedBeanDefinition);
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName, mergedBeanDefinition);
}
catch (BeanCreationException ex) {
if (eagerlyCached) {
removeSingleton(beanName);
}
throw ex;
}
catch (Throwable ex) {
if (eagerlyCached) {
removeSingleton(beanName);
}
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, errorMessage, ex);
}
// Register bean as disposable, and also as dependent on specified "dependsOn" beans.
registerDisposableBeanIfNecessary(beanName, originalBean, mergedBeanDefinition);
return bean;
}
/**
* Instantiate the bean using a named factory method. The method may be static, if the
* mergedBeanDefinition parameter specifies a class, rather than a factoryBean, or
* an instance variable on a factory object itself configured using Dependency Injection.
* <p>Implementation requires iterating over the static or instance methods with the
* name specified in the RootBeanDefinition (the method may be overloaded) and trying
* to match with the parameters. We don't have the types attached to constructor args,
* so trial and error is the only way to go here. The args array may contain argument
* values passed in programmatically via the overloaded getBean() method.
*/
protected BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args) throws BeansException {
ConstructorArgumentValues cargs = mergedBeanDefinition.getConstructorArgumentValues();
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
int expectedArgCount = 0;
// We don't have arguments passed in programmatically, so we need to resolve the
// arguments specified in the constructor arguments held in the bean definition.
if (args == null) {
expectedArgCount = cargs.getArgumentCount();
resolveConstructorArguments(beanName, mergedBeanDefinition, cargs, resolvedValues);
}
else {
// If we have constructor args, don't need to resolve them.
expectedArgCount = args.length;
}
BeanWrapper bw = createBeanWrapper(null);
initBeanWrapper(bw);
boolean isStatic = true;
Class factoryClass = null;
Object factoryBean = null;
if (mergedBeanDefinition.getFactoryBeanName() != null) {
factoryBean = getBean(mergedBeanDefinition.getFactoryBeanName());
factoryClass = factoryBean.getClass();
isStatic = false;
}
else {
// It's a static factory method on the bean class.
factoryClass = mergedBeanDefinition.getBeanClass();
}
// Try all methods with this name to see if they match constructor arguments.
for (int i = 0; i < factoryClass.getMethods().length; i++) {
Method factoryMethod = factoryClass.getMethods()[i];
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
factoryMethod.getName().equals(mergedBeanDefinition.getFactoryMethodName()) &&
factoryMethod.getParameterTypes().length == expectedArgCount) {
Class[] argTypes = factoryMethod.getParameterTypes();
try {
// try to create the required arguments
if (args == null) {
args = createArgumentArray(beanName, mergedBeanDefinition, resolvedValues, bw, argTypes);
}
}
catch (Exception ex) {
// If we failed to match this method, swallow the exception and keep trying new overloaded
// factory methods...
continue;
}
// If we get here, we found a factory method.
Object beanInstance =
this.instantiationStrategy.instantiate(
mergedBeanDefinition, beanName, this, factoryBean, factoryMethod, args);
// TODO: If we got to here, we could cache the resolved Method in the RootBeanDefinition
// for efficiency on future creation, but that would need to be synchronized.
bw.setWrappedInstance(beanInstance);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' instantiated via factory method '" + factoryMethod + "'");
}
return bw;
}
} // for each method
// If we get here, we didn't match any method.
throw new BeanDefinitionStoreException(
"Cannot find matching factory method '" + mergedBeanDefinition.getFactoryMethodName() +
"' on class [" + factoryClass.getName() + "]");
}
/**
* "autowire constructor" (with constructor arguments by type) behavior.
* Also applied if explicit constructor argument values are specified,
* matching all remaining arguments with beans from the bean factory.
* <p>This corresponds to constructor injection: In this mode, a Spring
* bean factory is able to host components that expect constructor-based
* dependency resolution.
* @param beanName name of the bean to autowire by type
* @param mergedBeanDefinition bean definition to update through autowiring
* @return BeanWrapper for the new instance
*/
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mergedBeanDefinition)
throws BeansException {
ConstructorArgumentValues cargs = mergedBeanDefinition.getConstructorArgumentValues();
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
BeanWrapper bw = createBeanWrapper(null);
initBeanWrapper(bw);
int minNrOfArgs = 0;
if (cargs != null) {
minNrOfArgs = resolveConstructorArguments(beanName, mergedBeanDefinition, cargs, resolvedValues);
}
Constructor[] constructors = mergedBeanDefinition.getBeanClass().getDeclaredConstructors();
AutowireUtils.sortConstructors(constructors);
Constructor constructorToUse = null;
Object[] argsToUse = null;
int minTypeDiffWeight = Integer.MAX_VALUE;
for (int i = 0; i < constructors.length; i++) {
try {
Constructor constructor = constructors[i];
if (constructor.getParameterTypes().length < minNrOfArgs) {
throw new BeanCreationException(mergedBeanDefinition.getResourceDescription(), beanName,
minNrOfArgs + " constructor arguments specified but no matching constructor found in bean '" +
beanName + "' (hint: specify index arguments for simple parameters to avoid type ambiguities)");
}
Class[] argTypes = constructor.getParameterTypes();
Object[] args = createArgumentArray(beanName, mergedBeanDefinition, resolvedValues, bw, argTypes);
int typeDiffWeight = AutowireUtils.getTypeDifferenceWeight(argTypes, args);
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = constructor;
argsToUse = args;
minTypeDiffWeight = typeDiffWeight;
}
}
catch (BeansException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring constructor [" + constructors[i] + "] of bean '" + beanName +
"': could not satisfy dependencies", ex);
}
if (i == constructors.length - 1 && constructorToUse == null) {
// all constructors tried
throw ex;
}
else {
// swallow and try next constructor
}
}
}
if (constructorToUse == null) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, "Could not resolve matching constructor");
}
Object beanInstance = this.instantiationStrategy.instantiate(
mergedBeanDefinition, beanName, this, constructorToUse, argsToUse);
bw.setWrappedInstance(beanInstance);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' instantiated via constructor [" + constructorToUse + "]");
}
return bw;
}
/**
* Resolve the constructor arguments for this bean into the resolvedValues object.
* This may involve looking up other beans.
* This method is also used for handling invocations of static factory methods.
*/
private int resolveConstructorArguments(
String beanName, RootBeanDefinition mergedBeanDefinition,
ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
int minNrOfArgs;
minNrOfArgs = cargs.getArgumentCount();
for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
int index = ((Integer) entry.getKey()).intValue();
if (index < 0) {
throw new BeanCreationException(mergedBeanDefinition.getResourceDescription(), beanName,
"Invalid constructor argument index: " + index);
}
if (index > minNrOfArgs) {
minNrOfArgs = index + 1;
}
String argName = "constructor argument with index " + index;
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) entry.getValue();
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, argName, valueHolder.getValue());
resolvedValues.addIndexedArgumentValue(index, resolvedValue, valueHolder.getType());
}
for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) {
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) it.next();
String argName = "constructor argument";
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, argName, valueHolder.getValue());
resolvedValues.addGenericArgumentValue(resolvedValue, valueHolder.getType());
}
return minNrOfArgs;
}
/**
* Create an array of arguments to invoke a Constructor or static factory method,
* given the resolved constructor arguments values.
*/
private Object[] createArgumentArray(
String beanName, RootBeanDefinition mergedBeanDefinition,
ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class[] argTypes)
throws UnsatisfiedDependencyException {
Object[] args = new Object[argTypes.length];
Set usedValueHolders = new HashSet(argTypes.length);
for (int j = 0; j < argTypes.length; j++) {
ConstructorArgumentValues.ValueHolder valueHolder = resolvedValues.getArgumentValue(j, argTypes[j]);
if (valueHolder != null && !usedValueHolders.contains(valueHolder)) {
// Do not consider the same value definition multiple times!
usedValueHolders.add(valueHolder);
if (bw instanceof BeanWrapperImpl) {
// Synchronize if custom editors are registered.
// Necessary because PropertyEditors are not thread-safe.
if (!getCustomEditors().isEmpty()) {
synchronized (getCustomEditors()) {
args[j] = ((BeanWrapperImpl) bw).doTypeConversionIfNecessary(valueHolder.getValue(), argTypes[j]);
}
}
else {
args[j] = ((BeanWrapperImpl) bw).doTypeConversionIfNecessary(valueHolder.getValue(), argTypes[j]);
}
}
else {
// Fallback: a BeanWrapper that oes not support type conversion
// for given values (currently BeanWrapperImpl is needed for this).
if (argTypes[j].isInstance(valueHolder.getValue())) {
args[j] = valueHolder.getValue();
}
else {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"Could not convert constructor argument value [" + valueHolder.getValue() +
"] to required type [" + argTypes[j].getName() + "] because BeanWrapper [" + bw +
"] does not support type conversion for given values (BeanWrapperImpl needed)");
}
}
}
else {
if (mergedBeanDefinition.getResolvedAutowireMode() != RootBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"Did you specify the correct bean references as generic constructor arguments?");
}
Map matchingBeans = findMatchingBeans(argTypes[j]);
if (matchingBeans == null || matchingBeans.size() != 1) {
int matchingBeansCount = (matchingBeans != null ? matchingBeans.size() : 0);
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"There are " + matchingBeansCount + " beans of type [" + argTypes[j] +
"] for autowiring constructor. There should have been 1 to be able to " +
"autowire constructor of bean '" + beanName + "'.");
}
String autowiredBeanName = (String) matchingBeans.keySet().iterator().next();
Object autowiredBean = matchingBeans.values().iterator().next();
args[j] = autowiredBean;
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(autowiredBeanName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' via constructor to bean named '" + matchingBeans.keySet().iterator().next() + "'");
}
}
}
return args;
}
/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* @param beanName name of the bean
* @param mergedBeanDefinition the bean definition for the bean
* @param bw BeanWrapper with bean instance
*/
protected void populateBean(String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw)
throws BeansException {
PropertyValues pvs = mergedBeanDefinition.getPropertyValues();
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues mpvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mergedBeanDefinition, bw, mpvs);
}
// Add property values based on autowire by type if applicable.
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mergedBeanDefinition, bw, mpvs);
}
pvs = mpvs;
}
dependencyCheck(beanName, mergedBeanDefinition, bw, pvs);
applyPropertyValues(beanName, mergedBeanDefinition, bw, pvs);
}
/**
* Fills in any missing property values with references to
* other beans in this factory if autowire is set to "byName".
* @param beanName name of the bean we're wiring up.
* Useful for debugging messages; not used functionally.
* @param mergedBeanDefinition bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByName(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, MutablePropertyValues pvs)
throws BeansException {
String[] propertyNames = unsatisfiedObjectProperties(mergedBeanDefinition, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.addPropertyValue(propertyName, bean);
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(propertyName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
/**
* Abstract method defining "autowire by type" (bean properties by type) behavior.
* <p>This is like PicoContainer default, in which there must be exactly one bean
* of the property type in the bean factory. This makes bean factories simple to
* configure for small namespaces, but doesn't work as well as standard Spring
* behavior for bigger applications.
* @param beanName name of the bean to autowire by type
* @param mergedBeanDefinition bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByType(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, MutablePropertyValues pvs)
throws BeansException {
String[] propertyNames = unsatisfiedObjectProperties(mergedBeanDefinition, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
// look for a matching type
Class requiredType = bw.getPropertyDescriptor(propertyName).getPropertyType();
Map matchingBeans = findMatchingBeans(requiredType);
if (matchingBeans != null && matchingBeans.size() == 1) {
String autowiredBeanName = (String) matchingBeans.keySet().iterator().next();
Object autowiredBean = matchingBeans.values().iterator().next();
pvs.addPropertyValue(propertyName, autowiredBean);
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(autowiredBeanName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" +
matchingBeans.keySet().iterator().next() + "'");
}
}
else if (matchingBeans != null && matchingBeans.size() > 1) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, propertyName,
"There are " + matchingBeans.size() + " beans of type [" + requiredType +
"] for autowire by type. There should have been 1 to be able to autowire property '" +
propertyName + "' of bean '" + beanName + "'.");
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by type: no matching bean found");
}
}
}
}
/**
* Return an array of object-type property names that are unsatisfied.
* These are probably unsatisfied references to other beans in the
* factory. Does not include simple properties like primitives or Strings.
* @param mergedBeanDefinition the bean definition the bean was created with
* @param bw the BeanWrapper the bean was created with
* @return an array of object-type property names that are unsatisfied
* @see org.springframework.beans.BeanUtils#isSimpleProperty
*/
protected String[] unsatisfiedObjectProperties(RootBeanDefinition mergedBeanDefinition, BeanWrapper bw) {
Set result = new TreeSet();
PropertyValues pvs = mergedBeanDefinition.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
Set ignoreTypes = getIgnoredDependencyTypes();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null &&
!ignoreTypes.contains(pds[i].getPropertyType()) &&
!pvs.contains(pds[i].getName()) &&
!BeanUtils.isSimpleProperty(pds[i].getPropertyType())) {
result.add(pds[i].getName());
}
}
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Perform a dependency check that all properties exposed have been set,
* if desired. Dependency checks can be objects (collaborating beans),
* simple (primitives and String), or all (both).
* @param beanName the name of the bean
* @param mergedBeanDefinition the bean definition the bean was created with
* @param bw the BeanWrapper the bean was created with
* @param pvs the property values to be applied to the bean
*/
protected void dependencyCheck(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, PropertyValues pvs)
throws UnsatisfiedDependencyException {
int dependencyCheck = mergedBeanDefinition.getDependencyCheck();
if (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_NONE) {
return;
}
Set ignoreTypes = getIgnoredDependencyTypes();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null &&
!ignoreTypes.contains(pds[i].getPropertyType()) &&
!pvs.contains(pds[i].getName())) {
boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType());
boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) ||
(isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
(!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
if (unsatisfied) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, pds[i].getName(),
"Set this property value or disable dependency checking for this bean.");
}
}
}
}
/**
* Apply the given property values, resolving any runtime references
* to other beans in this bean factory. Must use deep copy, so we
* don't permanently modify this property.
* @param beanName bean name passed for better exception information
* @param bw BeanWrapper wrapping the target object
* @param pvs new property values
*/
private void applyPropertyValues(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, PropertyValues pvs)
throws BeansException {
if (pvs == null) {
return;
}
// Create a deep copy, resolving any references for values.
MutablePropertyValues deepCopy = new MutablePropertyValues();
PropertyValue[] pvArray = pvs.getPropertyValues();
for (int i = 0; i < pvArray.length; i++) {
PropertyValue pv = pvArray[i];
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, pv.getName(), pv.getValue());
deepCopy.addPropertyValue(pvArray[i].getName(), resolvedValue);
}
// Set our (possibly massaged) deep copy.
try {
// Synchronize if custom editors are registered.
// Necessary because PropertyEditors are not thread-safe.
if (!getCustomEditors().isEmpty()) {
synchronized (this) {
bw.setPropertyValues(deepCopy);
}
}
else {
bw.setPropertyValues(deepCopy);
}
}
catch (BeansException ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
/**
* Given a PropertyValue, return a value, resolving any references to other
* beans in the factory if necessary. The value could be:
* <li>A BeanDefinition, which leads to the creation of a corresponding
* new bean instance. Singleton flags and names of such "inner beans"
* are always ignored: Inner beans are anonymous prototypes.
* <li>A RuntimeBeanReference, which must be resolved.
* <li>A ManagedList. This is a special collection that may contain
* RuntimeBeanReferences or Collections that will need to be resolved.
* <li>A ManagedSet. May also contain RuntimeBeanReferences or
* Collections that will need to be resolved.
* <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
* or Collection that will need to be resolved.
* <li>An ordinary object or null, in which case it's left alone.
*/
protected Object resolveValueIfNecessary(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Object value)
throws BeansException {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBeanDefinition(beanName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
// Resolve plain BeanDefinition, without contained name: use dummy name.
BeanDefinition bd = (BeanDefinition) value;
return resolveInnerBeanDefinition(beanName, "(inner bean)", bd);
}
else if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(beanName, mergedBeanDefinition, argName, ref);
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(beanName, mergedBeanDefinition, argName, (List) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(beanName, mergedBeanDefinition, argName, (Set) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(beanName, mergedBeanDefinition, argName, (Map) value);
}
else {
// no need to resolve value
return value;
}
}
/**
* Resolve an inner bean definition.
*/
private Object resolveInnerBeanDefinition(String beanName, String innerBeanName, BeanDefinition innerBd)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Resolving inner bean definition '" + innerBeanName + "' of bean '" + beanName + "'");
}
RootBeanDefinition mergedInnerBd = getMergedBeanDefinition(innerBeanName, innerBd);
Object innerBean = createBean(innerBeanName, mergedInnerBd, null, false);
if (mergedInnerBd.isSingleton()) {
registerDependentBean(innerBeanName, beanName);
}
return getObjectForSharedInstance(innerBeanName, innerBean);
}
/**
* Resolve a reference to another bean in the factory.
*/
private Object resolveReference(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, RuntimeBeanReference ref)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Resolving reference from property '" + argName + "' in bean '" +
beanName + "' to bean '" + ref.getBeanName() + "'");
}
try {
if (ref.isToParent()) {
if (getParentBeanFactory() == null) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName,
"Can't resolve reference to bean '" + ref.getBeanName() +
"' in parent factory: no parent factory available");
}
return getParentBeanFactory().getBean(ref.getBeanName());
}
else {
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(ref.getBeanName(), beanName);
}
return getBean(ref.getBeanName());
}
}
catch (BeansException ex) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName,
"Can't resolve reference to bean '" + ref.getBeanName() +
"' while setting property '" + argName + "'", ex);
}
}
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private List resolveManagedList(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, List ml)
throws BeansException {
List resolved = new ArrayList(ml.size());
for (int i = 0; i < ml.size(); i++) {
resolved.add(
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
ml.get(i)));
}
return resolved;
}
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private Set resolveManagedSet(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Set ms)
throws BeansException {
Set resolved = CollectionFactory.createLinkedSetIfPossible(ms.size());
int i = 0;
for (Iterator it = ms.iterator(); it.hasNext();) {
resolved.add(
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
it.next()));
i++;
}
return resolved;
}
/**
* For each element in the ManagedMap, resolve reference if necessary.
*/
private Map resolveManagedMap(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Map mm)
throws BeansException {
Map resolved = CollectionFactory.createLinkedMapIfPossible(mm.size());
Iterator keys = mm.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
resolved.put(
key,
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + key + BeanWrapper.PROPERTY_KEY_SUFFIX,
mm.get(key)));
}
return resolved;
}
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* <p>To be called by createBean implementations of concrete subclasses.
* @param beanName the bean has in the factory. Used for debug output.
* @param bean new bean instance we may need to initialize
* @param mergedBeanDefinition the bean definition that the bean was created with
* (can also be null, if initializing )
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
* @see #createBean
*/
protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition)
throws Throwable {
if (bean instanceof InitializingBean) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with beanName '" + beanName + "'");
}
((InitializingBean) bean).afterPropertiesSet();
}
if (mergedBeanDefinition != null && mergedBeanDefinition.getInitMethodName() != null) {
invokeCustomInitMethod(beanName, bean, mergedBeanDefinition.getInitMethodName());
}
}
/**
* Invoke the specified custom init method on the given bean.
* Called by invokeInitMethods.
* <p>Can be overridden in subclasses for custom resolution of init
* methods with arguments.
* @param beanName the bean has in the factory. Used for debug output.
* @param bean new bean instance we may need to initialize
* @param initMethodName the name of the custom init method
* @see #invokeInitMethods
*/
protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
throws Throwable {
if (logger.isDebugEnabled()) {
logger.debug("Invoking custom init method '" + initMethodName +
"' on bean with beanName '" + beanName + "'");
}
try {
Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
if (initMethod == null) {
throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
"' on bean with name '" + beanName + "'");
}
if (!Modifier.isPublic(initMethod.getModifiers())) {
initMethod.setAccessible(true);
}
initMethod.invoke(bean, (Object[]) null);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
//---------------------------------------------------------------------
// Abstract method to be implemented by concrete subclasses
//---------------------------------------------------------------------
/**
* Find bean instances that match the required type. Called by autowiring.
* If a subclass cannot obtain information about bean names by type,
* a corresponding exception should be thrown.
* @param requiredType the type of the beans to look up
* @return a Map of bean names and bean instances that match the required type,
* or null if none found
* @throws BeansException in case of errors
* @see #autowireByType
* @see #autowireConstructor
*/
protected abstract Map findMatchingBeans(Class requiredType) throws BeansException;
}
| src/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java | /*
* Copyright 2002-2004 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.springframework.beans.factory.support;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.core.CollectionFactory;
/**
* Abstract BeanFactory superclass that implements default bean creation,
* with the full capabilities specified by the RootBeanDefinition class.
* Implements the AutowireCapableBeanFactory interface. Like the base class
* AbstractBeanFactory, this superclass does not assume a listable bean factory.
*
* <p>Provides bean creation (with constructor resolution), property population,
* wiring (including autowiring), and initialization. Handles runtime bean
* references, resolves managed collections, calls initialization methods, etc.
* Supports autowiring constructors, properties by name, and properties by type.
*
* <p>The main template method to be implemented by subclasses is
* <code>findMatchingBeans</code, used for autowiring by type. In case of
* a factory which is capable of searching its bean definitions, matching
* beans will typically be implemented through such a search. For other
* factory styles, simplified matching algorithms can be implemented.
*
* <p>Note that this class does <i>not</i> assume or implement bean definition
* registry capabilities. See DefaultListableBeanFactory for an implementation
* of the ListableBeanFactory and BeanDefinitionRegistry interfaces, which
* represent the API respectively SPI view on such a factory.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 13.02.2004
* @see #findMatchingBeans
* @see AbstractBeanFactory#createBean
* @see RootBeanDefinition
* @see DefaultListableBeanFactory
* @see org.springframework.beans.factory.ListableBeanFactory
* @see org.springframework.beans.factory.support.BeanDefinitionRegistry
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
/**
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set ignoreDependencyTypes = new HashSet();
/**
* Create a new AbstractAutowireCapableBeanFactory.
*/
public AbstractAutowireCapableBeanFactory() {
super();
ignoreDependencyType(BeanFactory.class);
}
/**
* Create a new AbstractAutowireCapableBeanFactory with the given parent.
* @param parentBeanFactory parent bean factory, or null if none
*/
public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
/**
* Set the instantiation strategy to use for creating bean instances.
* Default is CglibSubclassingInstantiationStrategy.
* @see CglibSubclassingInstantiationStrategy
*/
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
this.instantiationStrategy = instantiationStrategy;
}
/**
* Ignore the given dependency type for autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, just the BeanFactory interface is ignored.
* For further types to ignore, invoke this method for each type.
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContext
* @see org.springframework.context.ApplicationContextAware
*/
public void ignoreDependencyType(Class type) {
this.ignoreDependencyTypes.add(type);
}
/**
* Return the set of classes that will get ignored for autowiring.
*/
public Set getIgnoredDependencyTypes() {
return ignoreDependencyTypes;
}
//---------------------------------------------------------------------
// Implementation of AutowireCapableBeanFactory interface
//---------------------------------------------------------------------
public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck)
throws BeansException {
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd).getWrappedInstance();
}
else {
Object bean = this.instantiationStrategy.instantiate(bd, null, this);
populateBean(bean.getClass().getName(), bd, createBeanWrapper(bean));
return bean;
}
}
public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException {
if (autowireMode != AUTOWIRE_BY_NAME && autowireMode != AUTOWIRE_BY_TYPE) {
throw new IllegalArgumentException("Just constants AUTOWIRE_BY_NAME and AUTOWIRE_BY_TYPE allowed");
}
RootBeanDefinition bd = new RootBeanDefinition(existingBean.getClass(), autowireMode, dependencyCheck);
populateBean(existingBean.getClass().getName(), bd, createBeanWrapper(existingBean));
}
public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
RootBeanDefinition bd = getMergedBeanDefinition(beanName, true);
applyPropertyValues(beanName, bd, createBeanWrapper(existingBean), bd.getPropertyValues());
}
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
return applyBeanPostProcessorsBeforeInitialization(existingBean, beanName, null);
}
/**
* Apply BeanPostProcessors to the given bean instance,
* invoking their postProcessBeforeInitialization methods.
* The returned bean instance may be a wrapper around the original.
* @param bean the bean instance
* @param beanName the name of the bean
* @param mergedBeanDefinition the corresponding bean definition,
* for checking destroy methods (can be null)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessBeforeInitialization
*/
public Object applyBeanPostProcessorsBeforeInitialization(
Object bean, String beanName, RootBeanDefinition mergedBeanDefinition) throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Invoking BeanPostProcessors before initialization of bean '" + beanName + "'");
}
Object result = bean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
throw new BeanCreationException(beanName,
"postProcessBeforeInitialization method of BeanPostProcessor [" + beanProcessor +
"] returned null for bean [" + result + "] with name [" + beanName + "]");
}
}
return result;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
return applyBeanPostProcessorsAfterInitialization(existingBean, beanName, null);
}
/**
* Apply BeanPostProcessors to the given bean instance,
* invoking their postProcessAfterInitialization methods.
* The returned bean instance may be a wrapper around the original.
* @param bean the bean instance
* @param beanName the name of the bean
* @param mergedBeanDefinition the corresponding bean definition,
* for checking destroy methods (can be null)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessAfterInitialization
*/
public Object applyBeanPostProcessorsAfterInitialization(
Object bean, String beanName, RootBeanDefinition mergedBeanDefinition) throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Invoking BeanPostProcessors after initialization of bean '" + beanName + "'");
}
Object result = bean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
throw new BeanCreationException(beanName,
"postProcessAfterInitialization method of BeanPostProcessor [" + beanProcessor +
"] returned null for bean [" + result + "] with name [" + beanName + "]");
}
}
return result;
}
//---------------------------------------------------------------------
// Implementation of AbstractBeanFactory's createBean method
//---------------------------------------------------------------------
/**
* Delegates to full createBean version with allowEagerCaching=true.
* @see #createBean(String, RootBeanDefinition, Object[], boolean)
*/
protected Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)
throws BeansException {
return createBean(beanName, mergedBeanDefinition, args, true);
}
/**
* Create a bean instance for the given bean definition.
* @param beanName name of the bean
* @param mergedBeanDefinition the bean definition for the bean
* @param args arguments to use if this is a prototype constructed by a factory method.
* In this case, this will override any args specified in the bean definitions.
* This parameter should be null otherwise.
* @param allowEagerCaching whether eager caching of singletons is allowed
* (typically true for normal beans, but false for inner beans)
* @return a new instance of the bean
* @throws BeansException in case of errors
*/
protected Object createBean(
String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args, boolean allowEagerCaching)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName +
"' with merged definition [" + mergedBeanDefinition + "]");
}
if (mergedBeanDefinition.getDependsOn() != null) {
for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
// Guarantee initialization of beans that the current one depends on.
getBean(mergedBeanDefinition.getDependsOn()[i]);
}
}
BeanWrapper instanceWrapper = null;
Object bean = null;
Object originalBean = null;
String errorMessage = null;
boolean eagerlyCached = false;
try {
// Instantiate the bean.
errorMessage = "Instantiation of bean failed";
if (mergedBeanDefinition.getFactoryMethodName() != null) {
instanceWrapper = instantiateUsingFactoryMethod(beanName, mergedBeanDefinition, args);
}
else if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mergedBeanDefinition.hasConstructorArgumentValues() ) {
instanceWrapper = autowireConstructor(beanName, mergedBeanDefinition);
}
else {
// No special handling: simply use no-arg constructor.
Object beanInstance = this.instantiationStrategy.instantiate(mergedBeanDefinition, beanName, this);
instanceWrapper = createBeanWrapper(beanInstance);
initBeanWrapper(instanceWrapper);
}
bean = instanceWrapper.getWrappedInstance();
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
if (allowEagerCaching && mergedBeanDefinition.isSingleton()) {
addSingleton(beanName, bean);
eagerlyCached = true;
}
// Initialize the bean instance.
errorMessage = "Initialization of bean failed";
populateBean(beanName, mergedBeanDefinition, instanceWrapper);
if (bean instanceof BeanNameAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanName on BeanNameAware bean '" + beanName + "'");
}
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanFactoryAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanFactory on BeanFactoryAware bean '" + beanName + "'");
}
((BeanFactoryAware) bean).setBeanFactory(this);
}
originalBean = bean;
bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName, mergedBeanDefinition);
invokeInitMethods(beanName, bean, mergedBeanDefinition);
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName, mergedBeanDefinition);
}
catch (BeanCreationException ex) {
if (eagerlyCached) {
removeSingleton(beanName);
}
throw ex;
}
catch (Throwable ex) {
if (eagerlyCached) {
removeSingleton(beanName);
}
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, errorMessage, ex);
}
// Register bean as disposable, and also as dependent on specified "dependsOn" beans.
registerDisposableBeanIfNecessary(beanName, originalBean, mergedBeanDefinition);
return bean;
}
/**
* Instantiate the bean using a named factory method. The method may be static, if the
* mergedBeanDefinition parameter specifies a class, rather than a factoryBean, or
* an instance variable on a factory object itself configured using Dependency Injection.
* <p>Implementation requires iterating over the static or instance methods with the
* name specified in the RootBeanDefinition (the method may be overloaded) and trying
* to match with the parameters. We don't have the types attached to constructor args,
* so trial and error is the only way to go here. The args array may contain argument
* values passed in programmatically via the overloaded getBean() method.
*/
protected BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args) throws BeansException {
ConstructorArgumentValues cargs = mergedBeanDefinition.getConstructorArgumentValues();
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
int expectedArgCount = 0;
// We don't have arguments passed in programmatically, so we need to resolve the
// arguments specified in the constructor arguments held in the bean definition.
if (args == null) {
expectedArgCount = cargs.getArgumentCount();
resolveConstructorArguments(beanName, mergedBeanDefinition, cargs, resolvedValues);
}
else {
// If we have constructor args, don't need to resolve them.
expectedArgCount = args.length;
}
BeanWrapper bw = createBeanWrapper(null);
initBeanWrapper(bw);
boolean isStatic = true;
Class factoryClass = null;
Object factoryBean = null;
if (mergedBeanDefinition.getFactoryBeanName() != null) {
factoryBean = getBean(mergedBeanDefinition.getFactoryBeanName());
factoryClass = factoryBean.getClass();
isStatic = false;
}
else {
// It's a static factory method on the bean class.
factoryClass = mergedBeanDefinition.getBeanClass();
}
// Try all methods with this name to see if they match constructor arguments.
for (int i = 0; i < factoryClass.getMethods().length; i++) {
Method factoryMethod = factoryClass.getMethods()[i];
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
factoryMethod.getName().equals(mergedBeanDefinition.getFactoryMethodName()) &&
factoryMethod.getParameterTypes().length == expectedArgCount) {
Class[] argTypes = factoryMethod.getParameterTypes();
try {
// try to create the required arguments
if (args == null) {
args = createArgumentArray(beanName, mergedBeanDefinition, resolvedValues, bw, argTypes);
}
}
catch (Exception ex) {
// If we failed to match this method, swallow the exception and keep trying new overloaded
// factory methods...
continue;
}
// If we get here, we found a factory method.
Object beanInstance =
this.instantiationStrategy.instantiate(
mergedBeanDefinition, beanName, this, factoryBean, factoryMethod, args);
// TODO: If we got to here, we could cache the resolved Method in the RootBeanDefinition
// for efficiency on future creation, but that would need to be synchronized.
bw.setWrappedInstance(beanInstance);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' instantiated via factory method '" + factoryMethod + "'");
}
return bw;
}
} // for each method
// If we get here, we didn't match any method.
throw new BeanDefinitionStoreException(
"Cannot find matching factory method '" + mergedBeanDefinition.getFactoryMethodName() +
"' on class [" + factoryClass.getName() + "]");
}
/**
* "autowire constructor" (with constructor arguments by type) behavior.
* Also applied if explicit constructor argument values are specified,
* matching all remaining arguments with beans from the bean factory.
* <p>This corresponds to constructor injection: In this mode, a Spring
* bean factory is able to host components that expect constructor-based
* dependency resolution.
* @param beanName name of the bean to autowire by type
* @param mergedBeanDefinition bean definition to update through autowiring
* @return BeanWrapper for the new instance
*/
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mergedBeanDefinition)
throws BeansException {
ConstructorArgumentValues cargs = mergedBeanDefinition.getConstructorArgumentValues();
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
BeanWrapper bw = createBeanWrapper(null);
initBeanWrapper(bw);
int minNrOfArgs = 0;
if (cargs != null) {
minNrOfArgs = resolveConstructorArguments(beanName, mergedBeanDefinition, cargs, resolvedValues);
}
Constructor[] constructors = mergedBeanDefinition.getBeanClass().getDeclaredConstructors();
AutowireUtils.sortConstructors(constructors);
Constructor constructorToUse = null;
Object[] argsToUse = null;
int minTypeDiffWeight = Integer.MAX_VALUE;
for (int i = 0; i < constructors.length; i++) {
try {
Constructor constructor = constructors[i];
if (constructor.getParameterTypes().length < minNrOfArgs) {
throw new BeanCreationException(mergedBeanDefinition.getResourceDescription(), beanName,
minNrOfArgs + " constructor arguments specified but no matching constructor found in bean '" +
beanName + "' (hint: specify index arguments for simple parameters to avoid type ambiguities)");
}
Class[] argTypes = constructor.getParameterTypes();
Object[] args = createArgumentArray(beanName, mergedBeanDefinition, resolvedValues, bw, argTypes);
int typeDiffWeight = AutowireUtils.getTypeDifferenceWeight(argTypes, args);
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = constructor;
argsToUse = args;
minTypeDiffWeight = typeDiffWeight;
}
}
catch (BeansException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring constructor [" + constructors[i] + "] of bean '" + beanName +
"': could not satisfy dependencies", ex);
}
if (i == constructors.length - 1 && constructorToUse == null) {
// all constructors tried
throw ex;
}
else {
// swallow and try next constructor
}
}
}
if (constructorToUse == null) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, "Could not resolve matching constructor");
}
Object beanInstance = this.instantiationStrategy.instantiate(
mergedBeanDefinition, beanName, this, constructorToUse, argsToUse);
bw.setWrappedInstance(beanInstance);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' instantiated via constructor [" + constructorToUse + "]");
}
return bw;
}
/**
* Resolve the constructor arguments for this bean into the resolvedValues object.
* This may involve looking up other beans.
* This method is also used for handling invocations of static factory methods.
*/
private int resolveConstructorArguments(
String beanName, RootBeanDefinition mergedBeanDefinition,
ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
int minNrOfArgs;
minNrOfArgs = cargs.getArgumentCount();
for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
int index = ((Integer) entry.getKey()).intValue();
if (index < 0) {
throw new BeanCreationException(mergedBeanDefinition.getResourceDescription(), beanName,
"Invalid constructor argument index: " + index);
}
if (index > minNrOfArgs) {
minNrOfArgs = index + 1;
}
String argName = "constructor argument with index " + index;
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) entry.getValue();
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, argName, valueHolder.getValue());
resolvedValues.addIndexedArgumentValue(index, resolvedValue, valueHolder.getType());
}
for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) {
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) it.next();
String argName = "constructor argument";
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, argName, valueHolder.getValue());
resolvedValues.addGenericArgumentValue(resolvedValue, valueHolder.getType());
}
return minNrOfArgs;
}
/**
* Create an array of arguments to invoke a Constructor or static factory method,
* given the resolved constructor arguments values.
*/
private Object[] createArgumentArray(
String beanName, RootBeanDefinition mergedBeanDefinition,
ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class[] argTypes)
throws UnsatisfiedDependencyException {
Object[] args = new Object[argTypes.length];
Set usedValueHolders = new HashSet(argTypes.length);
for (int j = 0; j < argTypes.length; j++) {
ConstructorArgumentValues.ValueHolder valueHolder = resolvedValues.getArgumentValue(j, argTypes[j]);
if (valueHolder != null && !usedValueHolders.contains(valueHolder)) {
// Do not consider the same value definition multiple times!
usedValueHolders.add(valueHolder);
if (bw instanceof BeanWrapperImpl) {
// Synchronize if custom editors are registered.
// Necessary because PropertyEditors are not thread-safe.
if (!getCustomEditors().isEmpty()) {
synchronized (getCustomEditors()) {
args[j] = ((BeanWrapperImpl) bw).doTypeConversionIfNecessary(valueHolder.getValue(), argTypes[j]);
}
}
else {
args[j] = ((BeanWrapperImpl) bw).doTypeConversionIfNecessary(valueHolder.getValue(), argTypes[j]);
}
}
else {
// Fallback: a BeanWrapper that oes not support type conversion
// for given values (currently BeanWrapperImpl is needed for this).
if (argTypes[j].isInstance(valueHolder.getValue())) {
args[j] = valueHolder.getValue();
}
else {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"Could not convert constructor argument value [" + valueHolder.getValue() +
"] to required type [" + argTypes[j].getName() + "] because BeanWrapper [" + bw +
"] does not support type conversion for given values (BeanWrapperImpl needed)");
}
}
}
else {
if (mergedBeanDefinition.getResolvedAutowireMode() != RootBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"Did you specify the correct bean references as generic constructor arguments?");
}
Map matchingBeans = findMatchingBeans(argTypes[j]);
if (matchingBeans == null || matchingBeans.size() != 1) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, j, argTypes[j],
"There are " + matchingBeans.size() + " beans of type [" + argTypes[j] +
"] for autowiring constructor. There should have been 1 to be able to " +
"autowire constructor of bean '" + beanName + "'.");
}
String autowiredBeanName = (String) matchingBeans.keySet().iterator().next();
Object autowiredBean = matchingBeans.values().iterator().next();
args[j] = autowiredBean;
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(autowiredBeanName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' via constructor to bean named '" + matchingBeans.keySet().iterator().next() + "'");
}
}
}
return args;
}
/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* @param beanName name of the bean
* @param mergedBeanDefinition the bean definition for the bean
* @param bw BeanWrapper with bean instance
*/
protected void populateBean(String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw)
throws BeansException {
PropertyValues pvs = mergedBeanDefinition.getPropertyValues();
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues mpvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mergedBeanDefinition, bw, mpvs);
}
// Add property values based on autowire by type if applicable.
if (mergedBeanDefinition.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mergedBeanDefinition, bw, mpvs);
}
pvs = mpvs;
}
dependencyCheck(beanName, mergedBeanDefinition, bw, pvs);
applyPropertyValues(beanName, mergedBeanDefinition, bw, pvs);
}
/**
* Fills in any missing property values with references to
* other beans in this factory if autowire is set to "byName".
* @param beanName name of the bean we're wiring up.
* Useful for debugging messages; not used functionally.
* @param mergedBeanDefinition bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByName(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, MutablePropertyValues pvs)
throws BeansException {
String[] propertyNames = unsatisfiedObjectProperties(mergedBeanDefinition, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.addPropertyValue(propertyName, bean);
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(propertyName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
/**
* Abstract method defining "autowire by type" (bean properties by type) behavior.
* <p>This is like PicoContainer default, in which there must be exactly one bean
* of the property type in the bean factory. This makes bean factories simple to
* configure for small namespaces, but doesn't work as well as standard Spring
* behavior for bigger applications.
* @param beanName name of the bean to autowire by type
* @param mergedBeanDefinition bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByType(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, MutablePropertyValues pvs)
throws BeansException {
String[] propertyNames = unsatisfiedObjectProperties(mergedBeanDefinition, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
// look for a matching type
Class requiredType = bw.getPropertyDescriptor(propertyName).getPropertyType();
Map matchingBeans = findMatchingBeans(requiredType);
if (matchingBeans != null && matchingBeans.size() == 1) {
String autowiredBeanName = (String) matchingBeans.keySet().iterator().next();
Object autowiredBean = matchingBeans.values().iterator().next();
pvs.addPropertyValue(propertyName, autowiredBean);
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(autowiredBeanName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" +
matchingBeans.keySet().iterator().next() + "'");
}
}
else if (matchingBeans != null && matchingBeans.size() > 1) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, propertyName,
"There are " + matchingBeans.size() + " beans of type [" + requiredType +
"] for autowire by type. There should have been 1 to be able to autowire property '" +
propertyName + "' of bean '" + beanName + "'.");
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by type: no matching bean found");
}
}
}
}
/**
* Return an array of object-type property names that are unsatisfied.
* These are probably unsatisfied references to other beans in the
* factory. Does not include simple properties like primitives or Strings.
* @param mergedBeanDefinition the bean definition the bean was created with
* @param bw the BeanWrapper the bean was created with
* @return an array of object-type property names that are unsatisfied
* @see org.springframework.beans.BeanUtils#isSimpleProperty
*/
protected String[] unsatisfiedObjectProperties(RootBeanDefinition mergedBeanDefinition, BeanWrapper bw) {
Set result = new TreeSet();
PropertyValues pvs = mergedBeanDefinition.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
Set ignoreTypes = getIgnoredDependencyTypes();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null &&
!ignoreTypes.contains(pds[i].getPropertyType()) &&
!pvs.contains(pds[i].getName()) &&
!BeanUtils.isSimpleProperty(pds[i].getPropertyType())) {
result.add(pds[i].getName());
}
}
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Perform a dependency check that all properties exposed have been set,
* if desired. Dependency checks can be objects (collaborating beans),
* simple (primitives and String), or all (both).
* @param beanName the name of the bean
* @param mergedBeanDefinition the bean definition the bean was created with
* @param bw the BeanWrapper the bean was created with
* @param pvs the property values to be applied to the bean
*/
protected void dependencyCheck(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, PropertyValues pvs)
throws UnsatisfiedDependencyException {
int dependencyCheck = mergedBeanDefinition.getDependencyCheck();
if (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_NONE) {
return;
}
Set ignoreTypes = getIgnoredDependencyTypes();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null &&
!ignoreTypes.contains(pds[i].getPropertyType()) &&
!pvs.contains(pds[i].getName())) {
boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType());
boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) ||
(isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
(!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
if (unsatisfied) {
throw new UnsatisfiedDependencyException(
mergedBeanDefinition.getResourceDescription(), beanName, pds[i].getName(),
"Set this property value or disable dependency checking for this bean.");
}
}
}
}
/**
* Apply the given property values, resolving any runtime references
* to other beans in this bean factory. Must use deep copy, so we
* don't permanently modify this property.
* @param beanName bean name passed for better exception information
* @param bw BeanWrapper wrapping the target object
* @param pvs new property values
*/
private void applyPropertyValues(
String beanName, RootBeanDefinition mergedBeanDefinition, BeanWrapper bw, PropertyValues pvs)
throws BeansException {
if (pvs == null) {
return;
}
// Create a deep copy, resolving any references for values.
MutablePropertyValues deepCopy = new MutablePropertyValues();
PropertyValue[] pvArray = pvs.getPropertyValues();
for (int i = 0; i < pvArray.length; i++) {
PropertyValue pv = pvArray[i];
Object resolvedValue =
resolveValueIfNecessary(beanName, mergedBeanDefinition, pv.getName(), pv.getValue());
deepCopy.addPropertyValue(pvArray[i].getName(), resolvedValue);
}
// Set our (possibly massaged) deep copy.
try {
// Synchronize if custom editors are registered.
// Necessary because PropertyEditors are not thread-safe.
if (!getCustomEditors().isEmpty()) {
synchronized (this) {
bw.setPropertyValues(deepCopy);
}
}
else {
bw.setPropertyValues(deepCopy);
}
}
catch (BeansException ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
/**
* Given a PropertyValue, return a value, resolving any references to other
* beans in the factory if necessary. The value could be:
* <li>A BeanDefinition, which leads to the creation of a corresponding
* new bean instance. Singleton flags and names of such "inner beans"
* are always ignored: Inner beans are anonymous prototypes.
* <li>A RuntimeBeanReference, which must be resolved.
* <li>A ManagedList. This is a special collection that may contain
* RuntimeBeanReferences or Collections that will need to be resolved.
* <li>A ManagedSet. May also contain RuntimeBeanReferences or
* Collections that will need to be resolved.
* <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
* or Collection that will need to be resolved.
* <li>An ordinary object or null, in which case it's left alone.
*/
protected Object resolveValueIfNecessary(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Object value)
throws BeansException {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBeanDefinition(beanName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
// Resolve plain BeanDefinition, without contained name: use dummy name.
BeanDefinition bd = (BeanDefinition) value;
return resolveInnerBeanDefinition(beanName, "(inner bean)", bd);
}
else if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(beanName, mergedBeanDefinition, argName, ref);
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(beanName, mergedBeanDefinition, argName, (List) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(beanName, mergedBeanDefinition, argName, (Set) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(beanName, mergedBeanDefinition, argName, (Map) value);
}
else {
// no need to resolve value
return value;
}
}
/**
* Resolve an inner bean definition.
*/
private Object resolveInnerBeanDefinition(String beanName, String innerBeanName, BeanDefinition innerBd)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Resolving inner bean definition '" + innerBeanName + "' of bean '" + beanName + "'");
}
RootBeanDefinition mergedInnerBd = getMergedBeanDefinition(innerBeanName, innerBd);
Object innerBean = createBean(innerBeanName, mergedInnerBd, null, false);
if (mergedInnerBd.isSingleton()) {
registerDependentBean(innerBeanName, beanName);
}
return getObjectForSharedInstance(innerBeanName, innerBean);
}
/**
* Resolve a reference to another bean in the factory.
*/
private Object resolveReference(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, RuntimeBeanReference ref)
throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Resolving reference from property '" + argName + "' in bean '" +
beanName + "' to bean '" + ref.getBeanName() + "'");
}
try {
if (ref.isToParent()) {
if (getParentBeanFactory() == null) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName,
"Can't resolve reference to bean '" + ref.getBeanName() +
"' in parent factory: no parent factory available");
}
return getParentBeanFactory().getBean(ref.getBeanName());
}
else {
if (mergedBeanDefinition.isSingleton()) {
registerDependentBean(ref.getBeanName(), beanName);
}
return getBean(ref.getBeanName());
}
}
catch (BeansException ex) {
throw new BeanCreationException(
mergedBeanDefinition.getResourceDescription(), beanName,
"Can't resolve reference to bean '" + ref.getBeanName() +
"' while setting property '" + argName + "'", ex);
}
}
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private List resolveManagedList(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, List ml)
throws BeansException {
List resolved = new ArrayList(ml.size());
for (int i = 0; i < ml.size(); i++) {
resolved.add(
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
ml.get(i)));
}
return resolved;
}
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private Set resolveManagedSet(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Set ms)
throws BeansException {
Set resolved = CollectionFactory.createLinkedSetIfPossible(ms.size());
int i = 0;
for (Iterator it = ms.iterator(); it.hasNext();) {
resolved.add(
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
it.next()));
i++;
}
return resolved;
}
/**
* For each element in the ManagedMap, resolve reference if necessary.
*/
private Map resolveManagedMap(
String beanName, RootBeanDefinition mergedBeanDefinition, String argName, Map mm)
throws BeansException {
Map resolved = CollectionFactory.createLinkedMapIfPossible(mm.size());
Iterator keys = mm.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
resolved.put(
key,
resolveValueIfNecessary(
beanName, mergedBeanDefinition,
argName + BeanWrapper.PROPERTY_KEY_PREFIX + key + BeanWrapper.PROPERTY_KEY_SUFFIX,
mm.get(key)));
}
return resolved;
}
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* <p>To be called by createBean implementations of concrete subclasses.
* @param beanName the bean has in the factory. Used for debug output.
* @param bean new bean instance we may need to initialize
* @param mergedBeanDefinition the bean definition that the bean was created with
* (can also be null, if initializing )
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
* @see #createBean
*/
protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition)
throws Throwable {
if (bean instanceof InitializingBean) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with beanName '" + beanName + "'");
}
((InitializingBean) bean).afterPropertiesSet();
}
if (mergedBeanDefinition != null && mergedBeanDefinition.getInitMethodName() != null) {
invokeCustomInitMethod(beanName, bean, mergedBeanDefinition.getInitMethodName());
}
}
/**
* Invoke the specified custom init method on the given bean.
* Called by invokeInitMethods.
* <p>Can be overridden in subclasses for custom resolution of init
* methods with arguments.
* @param beanName the bean has in the factory. Used for debug output.
* @param bean new bean instance we may need to initialize
* @param initMethodName the name of the custom init method
* @see #invokeInitMethods
*/
protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
throws Throwable {
if (logger.isDebugEnabled()) {
logger.debug("Invoking custom init method '" + initMethodName +
"' on bean with beanName '" + beanName + "'");
}
try {
Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
if (initMethod == null) {
throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
"' on bean with name '" + beanName + "'");
}
if (!Modifier.isPublic(initMethod.getModifiers())) {
initMethod.setAccessible(true);
}
initMethod.invoke(bean, (Object[]) null);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
//---------------------------------------------------------------------
// Abstract method to be implemented by concrete subclasses
//---------------------------------------------------------------------
/**
* Find bean instances that match the required type. Called by autowiring.
* If a subclass cannot obtain information about bean names by type,
* a corresponding exception should be thrown.
* @param requiredType the type of the beans to look up
* @return a Map of bean names and bean instances that match the required type,
* or null if none found
* @throws BeansException in case of errors
* @see #autowireByType
* @see #autowireConstructor
*/
protected abstract Map findMatchingBeans(Class requiredType) throws BeansException;
}
| fixed count determination for exception message of matching beans check
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@5448 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| src/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java | fixed count determination for exception message of matching beans check |
|
Java | apache-2.0 | 786aab37d9d8f17b78866643885ebd8edf429e05 | 0 | jpechane/debezium,debezium/debezium,jpechane/debezium,debezium/debezium,debezium/debezium,jpechane/debezium,jpechane/debezium,debezium/debezium | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.transforms.filter;
import org.apache.kafka.connect.connector.ConnectRecord;
/**
* The interface serves as an abstraction of expression language engine.
*
* @author Jiri Pechanec
*/
public interface Engine {
/**
* Pre-compiles the expression for repeated execution.
* The method is called once upon the engine initialization.
*
* @param expression
*/
void configure(String language, String expression);
/**
* Evaluates whether the record matches the predicate expression.
*
* @param record to be evaluated
* @return true if the input argument matches the predicate expression, otherwise false
*/
boolean eval(ConnectRecord<?> record);
}
| debezium-core/src/main/java/io/debezium/transforms/filter/Engine.java | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.transforms.filter;
import org.apache.kafka.connect.connector.ConnectRecord;
/**
* The interface serves as an abstraction of expression language engine.
*
* @author Jiri Pechanec
*/
public interface Engine {
/**
* Pre-compiles the expression for repeated execution.
* The method is called once upon the engine initialization.
*
* @param expression
*/
void configure(String language, String expression);
/**
* Evaluates whether the record should be filtered out or not by executing the expression.
*
* @param record to be evaluated
* @return true to keep the record, false to remove it
*/
boolean eval(ConnectRecord<?> record);
}
| DBZ-1782 JavaDoc improvements;
As per Chris's suggestions.
Co-Authored-By: Chris Cranford <[email protected]> | debezium-core/src/main/java/io/debezium/transforms/filter/Engine.java | DBZ-1782 JavaDoc improvements; |
|
Java | apache-2.0 | fbbd014c3346e890f125e36c5b10701b52f0a87f | 0 | firebase/FirebaseUI-Android,firebase/FirebaseUI-Android,samtstern/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,firebase/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,samtstern/FirebaseUI-Android,JosefHruska/FirebaseUI-Android,JosefHruska/FirebaseUI-Android,samtstern/FirebaseUI-Android,firebase/FirebaseUI-Android | package com.firebase.ui.auth.util.signincontainer;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils ;
import android.util.Log;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.AuthUI.IdpConfig;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.R;
import com.firebase.ui.auth.ResultCodes;
import com.firebase.ui.auth.ui.ExtraConstants;
import com.firebase.ui.auth.ui.FlowParameters;
import com.firebase.ui.auth.ui.FragmentHelper;
import com.firebase.ui.auth.ui.TaskFailureLogger;
import com.firebase.ui.auth.ui.User;
import com.firebase.ui.auth.ui.email.RegisterEmailActivity;
import com.firebase.ui.auth.ui.idp.AuthMethodPickerActivity;
import com.firebase.ui.auth.ui.phone.PhoneVerificationActivity;
import com.firebase.ui.auth.util.GoogleApiHelper;
import com.firebase.ui.auth.util.GoogleSignInHelper;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.CredentialRequest;
import com.google.android.gms.auth.api.credentials.CredentialRequestResult;
import com.google.android.gms.auth.api.credentials.IdentityProviders;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.auth.TwitterAuthProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Attempts to acquire a credential from Smart Lock for Passwords to sign in
* an existing account. If this succeeds, an attempt is made to sign the user in
* with this credential. If it does not, the
* {@link AuthMethodPickerActivity authentication method picker activity}
* is started, unless only email is supported, in which case the
* {@link RegisterEmailActivity} is started.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SignInDelegate extends SmartLockBase<CredentialRequestResult> {
private static final String TAG = "SignInDelegate";
private static final int RC_CREDENTIALS_READ = 2;
private static final int RC_IDP_SIGNIN = 3;
private static final int RC_AUTH_METHOD_PICKER = 4;
private static final int RC_EMAIL_FLOW = 5;
private static final int RC_PHONE_FLOW = 6;
private Credential mCredential;
public static void delegate(FragmentActivity activity, FlowParameters params) {
FragmentManager fm = activity.getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag(TAG);
if (!(fragment instanceof SignInDelegate)) {
SignInDelegate result = new SignInDelegate();
result.setArguments(FragmentHelper.getFlowParamsBundle(params));
fm.beginTransaction().add(result, TAG).disallowAddToBackStack().commit();
}
}
public static SignInDelegate getInstance(FragmentActivity activity) {
Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(TAG);
if (fragment instanceof SignInDelegate) {
return (SignInDelegate) fragment;
} else {
return null;
}
}
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
if (savedInstance != null) {
// We already have a running instance of this fragment
return;
}
FlowParameters flowParams = mHelper.getFlowParams();
if (flowParams.enableCredentials) {
mHelper.showLoadingDialog(R.string.progress_dialog_loading);
mGoogleApiClient = new GoogleApiClient.Builder(getContext().getApplicationContext())
.addConnectionCallbacks(this)
.addApi(Auth.CREDENTIALS_API)
.enableAutoManage(getActivity(), GoogleApiHelper.getSafeAutoManageId(), this)
.build();
mGoogleApiClient.connect();
mHelper.getCredentialsApi()
.request(mGoogleApiClient,
new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setAccountTypes(getSupportedAccountTypes().toArray(new String[0]))
.build())
.setResultCallback(this);
} else {
startAuthMethodChoice();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// It doesn't matter what we put here, we just don't want outState to be empty
outState.putBoolean(ExtraConstants.HAS_EXISTING_INSTANCE, true);
super.onSaveInstanceState(outState);
}
@Override
public void onResult(@NonNull CredentialRequestResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
// Auto sign-in success
handleCredential(result.getCredential());
return;
} else {
if (status.hasResolution()) {
try {
if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) {
mHelper.startIntentSenderForResult(
status.getResolution().getIntentSender(),
RC_CREDENTIALS_READ);
return;
}
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Failed to send Credentials intent.", e);
}
} else {
Log.e(TAG, "Status message:\n" + status.getStatusMessage());
}
}
startAuthMethodChoice();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
// We only care about onResult
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RC_CREDENTIALS_READ:
if (resultCode == ResultCodes.OK) {
// credential selected from SmartLock, log in with that credential
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
handleCredential(credential);
} else {
// Smart lock selector cancelled, go to the AuthMethodPicker screen
startAuthMethodChoice();
}
break;
case RC_IDP_SIGNIN:
case RC_AUTH_METHOD_PICKER:
case RC_EMAIL_FLOW:
finish(resultCode, data);
break;
default:
IdpSignInContainer signInContainer = IdpSignInContainer.getInstance(getActivity());
if (signInContainer != null) {
signInContainer.onActivityResult(requestCode, resultCode, data);
}
}
}
private List<String> getSupportedAccountTypes() {
List<String> accounts = new ArrayList<>();
for (AuthUI.IdpConfig idpConfig : mHelper.getFlowParams().providerInfo) {
@AuthUI.SupportedProvider String providerId = idpConfig.getProviderId();
if (providerId.equals(GoogleAuthProvider.PROVIDER_ID)
|| providerId.equals(FacebookAuthProvider.PROVIDER_ID)
|| providerId.equals(TwitterAuthProvider.PROVIDER_ID)) {
accounts.add(providerIdToAccountType(providerId));
}
}
return accounts;
}
private String getEmailFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getId();
}
private String getAccountTypeFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getAccountType();
}
private String getPasswordFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getPassword();
}
private void handleCredential(Credential credential) {
mCredential = credential;
String email = getEmailFromCredential();
String password = getPasswordFromCredential();
if (!TextUtils.isEmpty(email)) {
if (TextUtils.isEmpty(password)) {
// log in with id/provider
redirectToIdpSignIn(email, getAccountTypeFromCredential());
} else {
// Sign in with the email/password retrieved from SmartLock
signInWithEmailAndPassword(email, password);
}
}
}
private void startAuthMethodChoice() {
FlowParameters flowParams = mHelper.getFlowParams();
List<AuthUI.IdpConfig> idpConfigs = flowParams.providerInfo;
Map<String, IdpConfig> providerIdToConfig = new HashMap<>();
for (IdpConfig providerConfig : idpConfigs) {
providerIdToConfig.put(providerConfig.getProviderId(), providerConfig);
}
List<IdpConfig> visibleProviders = idpConfigs;
// If there is only one provider selected, launch the flow directly
if (visibleProviders.size() == 1) {
String firstProvider = visibleProviders.get(0).getProviderId();
if (firstProvider.equals(EmailAuthProvider.PROVIDER_ID)) {
// Go directly to email flow
startActivityForResult(
RegisterEmailActivity.createIntent(getContext(), flowParams),
RC_EMAIL_FLOW);
} else if (firstProvider.equals(PhoneAuthProvider.PROVIDER_ID)) {
// Go directly to phone flow
startActivityForResult(
PhoneVerificationActivity.createIntent(getContext(), flowParams, null),
RC_PHONE_FLOW);
} else {
// Launch IDP flow
redirectToIdpSignIn(null, providerIdToAccountType(firstProvider));
}
} else {
startActivityForResult(
AuthMethodPickerActivity.createIntent(
getContext(),
flowParams),
RC_AUTH_METHOD_PICKER);
}
mHelper.dismissDialog();
}
/**
* Begin sign in process with email and password from a SmartLock credential. On success, finish
* with {@link ResultCodes#OK RESULT_OK}. On failure, delete the credential from SmartLock (if
* applicable) and then launch the auth method picker flow.
*/
private void signInWithEmailAndPassword(String email, String password) {
final IdpResponse response =
new IdpResponse.Builder(EmailAuthProvider.PROVIDER_ID, email).build();
mHelper.getFirebaseAuth()
.signInWithEmailAndPassword(email, password)
.addOnFailureListener(new TaskFailureLogger(
TAG, "Error signing in with email and password"))
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
finish(ResultCodes.OK, response.toIntent());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof FirebaseAuthInvalidUserException) {
// In this case the credential saved in SmartLock was not
// a valid credential, we should delete it from SmartLock
// before continuing.
deleteCredentialAndRedirect();
} else {
startAuthMethodChoice();
}
}
});
}
/**
* Delete the last credential retrieved from SmartLock and then redirect to the auth method
* choice flow.
*/
private void deleteCredentialAndRedirect() {
if (mCredential == null) {
Log.w(TAG, "deleteCredentialAndRedirect: null credential");
startAuthMethodChoice();
return;
}
GoogleSignInHelper.getInstance(getActivity())
.delete(mCredential)
.addOnCompleteListener(new OnCompleteListener<Status>() {
@Override
public void onComplete(@NonNull Task<Status> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "deleteCredential:failure", task.getException());
}
startAuthMethodChoice();
}
});
}
private void redirectToIdpSignIn(String email, String accountType) {
if (TextUtils.isEmpty(accountType)) {
startActivityForResult(
RegisterEmailActivity.createIntent(
getContext(),
mHelper.getFlowParams(),
email),
RC_EMAIL_FLOW);
return;
}
if (accountType.equals(IdentityProviders.GOOGLE)
|| accountType.equals(IdentityProviders.FACEBOOK)
|| accountType.equals(IdentityProviders.TWITTER)) {
IdpSignInContainer.signIn(
getActivity(),
mHelper.getFlowParams(),
new User.Builder(email)
.setProvider(accountTypeToProviderId(accountType))
.build());
} else {
Log.w(TAG, "Unknown provider: " + accountType);
startActivityForResult(
AuthMethodPickerActivity.createIntent(
getContext(),
mHelper.getFlowParams()),
RC_IDP_SIGNIN);
mHelper.dismissDialog();
}
}
}
| auth/src/main/java/com/firebase/ui/auth/util/signincontainer/SignInDelegate.java | package com.firebase.ui.auth.util.signincontainer;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils ;
import android.util.Log;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.AuthUI.IdpConfig;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.R;
import com.firebase.ui.auth.ResultCodes;
import com.firebase.ui.auth.ui.ExtraConstants;
import com.firebase.ui.auth.ui.FlowParameters;
import com.firebase.ui.auth.ui.FragmentHelper;
import com.firebase.ui.auth.ui.TaskFailureLogger;
import com.firebase.ui.auth.ui.User;
import com.firebase.ui.auth.ui.email.RegisterEmailActivity;
import com.firebase.ui.auth.ui.idp.AuthMethodPickerActivity;
import com.firebase.ui.auth.util.GoogleApiHelper;
import com.firebase.ui.auth.util.GoogleSignInHelper;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.CredentialRequest;
import com.google.android.gms.auth.api.credentials.CredentialRequestResult;
import com.google.android.gms.auth.api.credentials.IdentityProviders;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.TwitterAuthProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Attempts to acquire a credential from Smart Lock for Passwords to sign in
* an existing account. If this succeeds, an attempt is made to sign the user in
* with this credential. If it does not, the
* {@link AuthMethodPickerActivity authentication method picker activity}
* is started, unless only email is supported, in which case the
* {@link RegisterEmailActivity} is started.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SignInDelegate extends SmartLockBase<CredentialRequestResult> {
private static final String TAG = "SignInDelegate";
private static final int RC_CREDENTIALS_READ = 2;
private static final int RC_IDP_SIGNIN = 3;
private static final int RC_AUTH_METHOD_PICKER = 4;
private static final int RC_EMAIL_FLOW = 5;
private Credential mCredential;
public static void delegate(FragmentActivity activity, FlowParameters params) {
FragmentManager fm = activity.getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag(TAG);
if (!(fragment instanceof SignInDelegate)) {
SignInDelegate result = new SignInDelegate();
result.setArguments(FragmentHelper.getFlowParamsBundle(params));
fm.beginTransaction().add(result, TAG).disallowAddToBackStack().commit();
}
}
public static SignInDelegate getInstance(FragmentActivity activity) {
Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(TAG);
if (fragment instanceof SignInDelegate) {
return (SignInDelegate) fragment;
} else {
return null;
}
}
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
if (savedInstance != null) {
// We already have a running instance of this fragment
return;
}
FlowParameters flowParams = mHelper.getFlowParams();
if (flowParams.enableCredentials) {
mHelper.showLoadingDialog(R.string.progress_dialog_loading);
mGoogleApiClient = new GoogleApiClient.Builder(getContext().getApplicationContext())
.addConnectionCallbacks(this)
.addApi(Auth.CREDENTIALS_API)
.enableAutoManage(getActivity(), GoogleApiHelper.getSafeAutoManageId(), this)
.build();
mGoogleApiClient.connect();
mHelper.getCredentialsApi()
.request(mGoogleApiClient,
new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setAccountTypes(getSupportedAccountTypes().toArray(new String[0]))
.build())
.setResultCallback(this);
} else {
startAuthMethodChoice();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// It doesn't matter what we put here, we just don't want outState to be empty
outState.putBoolean(ExtraConstants.HAS_EXISTING_INSTANCE, true);
super.onSaveInstanceState(outState);
}
@Override
public void onResult(@NonNull CredentialRequestResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
// Auto sign-in success
handleCredential(result.getCredential());
return;
} else {
if (status.hasResolution()) {
try {
if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) {
mHelper.startIntentSenderForResult(
status.getResolution().getIntentSender(),
RC_CREDENTIALS_READ);
return;
}
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Failed to send Credentials intent.", e);
}
} else {
Log.e(TAG, "Status message:\n" + status.getStatusMessage());
}
}
startAuthMethodChoice();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
// We only care about onResult
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RC_CREDENTIALS_READ:
if (resultCode == ResultCodes.OK) {
// credential selected from SmartLock, log in with that credential
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
handleCredential(credential);
} else {
// Smart lock selector cancelled, go to the AuthMethodPicker screen
startAuthMethodChoice();
}
break;
case RC_IDP_SIGNIN:
case RC_AUTH_METHOD_PICKER:
case RC_EMAIL_FLOW:
finish(resultCode, data);
break;
default:
IdpSignInContainer signInContainer = IdpSignInContainer.getInstance(getActivity());
if (signInContainer != null) {
signInContainer.onActivityResult(requestCode, resultCode, data);
}
}
}
private List<String> getSupportedAccountTypes() {
List<String> accounts = new ArrayList<>();
for (AuthUI.IdpConfig idpConfig : mHelper.getFlowParams().providerInfo) {
@AuthUI.SupportedProvider String providerId = idpConfig.getProviderId();
if (providerId.equals(GoogleAuthProvider.PROVIDER_ID)
|| providerId.equals(FacebookAuthProvider.PROVIDER_ID)
|| providerId.equals(TwitterAuthProvider.PROVIDER_ID)) {
accounts.add(providerIdToAccountType(providerId));
}
}
return accounts;
}
private String getEmailFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getId();
}
private String getAccountTypeFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getAccountType();
}
private String getPasswordFromCredential() {
if (mCredential == null) {
return null;
}
return mCredential.getPassword();
}
private void handleCredential(Credential credential) {
mCredential = credential;
String email = getEmailFromCredential();
String password = getPasswordFromCredential();
if (!TextUtils.isEmpty(email)) {
if (TextUtils.isEmpty(password)) {
// log in with id/provider
redirectToIdpSignIn(email, getAccountTypeFromCredential());
} else {
// Sign in with the email/password retrieved from SmartLock
signInWithEmailAndPassword(email, password);
}
}
}
private void startAuthMethodChoice() {
FlowParameters flowParams = mHelper.getFlowParams();
List<AuthUI.IdpConfig> idpConfigs = flowParams.providerInfo;
Map<String, IdpConfig> providerIdToConfig = new HashMap<>();
for (IdpConfig providerConfig : idpConfigs) {
providerIdToConfig.put(providerConfig.getProviderId(), providerConfig);
}
List<IdpConfig> visibleProviders = idpConfigs;
// If the only provider is Email, immediately launch the email flow. Otherwise, launch
// the auth method picker screen.
if (visibleProviders.size() == 1) {
if (visibleProviders.get(0).getProviderId().equals(EmailAuthProvider.PROVIDER_ID)) {
startActivityForResult(
RegisterEmailActivity.createIntent(getContext(), flowParams),
RC_EMAIL_FLOW);
} else {
redirectToIdpSignIn(null, providerIdToAccountType(
visibleProviders.get(0).getProviderId()));
}
} else {
startActivityForResult(
AuthMethodPickerActivity.createIntent(
getContext(),
flowParams),
RC_AUTH_METHOD_PICKER);
}
mHelper.dismissDialog();
}
/**
* Begin sign in process with email and password from a SmartLock credential. On success, finish
* with {@link ResultCodes#OK RESULT_OK}. On failure, delete the credential from SmartLock (if
* applicable) and then launch the auth method picker flow.
*/
private void signInWithEmailAndPassword(String email, String password) {
final IdpResponse response =
new IdpResponse.Builder(EmailAuthProvider.PROVIDER_ID, email).build();
mHelper.getFirebaseAuth()
.signInWithEmailAndPassword(email, password)
.addOnFailureListener(new TaskFailureLogger(
TAG, "Error signing in with email and password"))
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
finish(ResultCodes.OK, response.toIntent());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof FirebaseAuthInvalidUserException) {
// In this case the credential saved in SmartLock was not
// a valid credential, we should delete it from SmartLock
// before continuing.
deleteCredentialAndRedirect();
} else {
startAuthMethodChoice();
}
}
});
}
/**
* Delete the last credential retrieved from SmartLock and then redirect to the auth method
* choice flow.
*/
private void deleteCredentialAndRedirect() {
if (mCredential == null) {
Log.w(TAG, "deleteCredentialAndRedirect: null credential");
startAuthMethodChoice();
return;
}
GoogleSignInHelper.getInstance(getActivity())
.delete(mCredential)
.addOnCompleteListener(new OnCompleteListener<Status>() {
@Override
public void onComplete(@NonNull Task<Status> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "deleteCredential:failure", task.getException());
}
startAuthMethodChoice();
}
});
}
private void redirectToIdpSignIn(String email, String accountType) {
if (TextUtils.isEmpty(accountType)) {
startActivityForResult(
RegisterEmailActivity.createIntent(
getContext(),
mHelper.getFlowParams(),
email),
RC_EMAIL_FLOW);
return;
}
if (accountType.equals(IdentityProviders.GOOGLE)
|| accountType.equals(IdentityProviders.FACEBOOK)
|| accountType.equals(IdentityProviders.TWITTER)) {
IdpSignInContainer.signIn(
getActivity(),
mHelper.getFlowParams(),
new User.Builder(email)
.setProvider(accountTypeToProviderId(accountType))
.build());
} else {
Log.w(TAG, "Unknown provider: " + accountType);
startActivityForResult(
AuthMethodPickerActivity.createIntent(
getContext(),
mHelper.getFlowParams()),
RC_IDP_SIGNIN);
mHelper.dismissDialog();
}
}
}
| Fix case when only phone auth selected.
Bug: 62309027
Change-Id: Iccbdb2a34e8c0b14c6fcf186005e0f1a68ea180e
| auth/src/main/java/com/firebase/ui/auth/util/signincontainer/SignInDelegate.java | Fix case when only phone auth selected. |
|
Java | apache-2.0 | fbb4a9cffd6faf0bfe7ae29f05db15edcc92419d | 0 | gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit | // Copyright (C) 2017 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.google.gerrit.server.notedb.rebuild;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.reviewdb.server.ReviewDbUtil.unwrapDb;
import static com.google.gerrit.server.notedb.ConfigNotesMigration.SECTION_NOTE_DB;
import static com.google.gerrit.server.notedb.NotesMigrationState.NOTE_DB_UNFUSED;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_NO_SEQUENCE;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY;
import static com.google.gerrit.server.notedb.NotesMigrationState.WRITE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Ordering;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Streams;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gerrit.common.FormatUtil;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.reviewdb.server.ReviewDbWrapper;
import com.google.gerrit.server.InternalUser;
import com.google.gerrit.server.Sequences;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.LockFailureException;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.notedb.ConfigNotesMigration;
import com.google.gerrit.server.notedb.NoteDbTable;
import com.google.gerrit.server.notedb.NotesMigration;
import com.google.gerrit.server.notedb.NotesMigrationState;
import com.google.gerrit.server.notedb.PrimaryStorageMigrator;
import com.google.gerrit.server.notedb.RepoSequence;
import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException;
import com.google.gerrit.server.util.ManualRequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.io.NullOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** One stop shop for migrating a site's change storage from ReviewDb to NoteDb. */
public class NoteDbMigrator implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(NoteDbMigrator.class);
private static final String AUTO_MIGRATE = "autoMigrate";
public static boolean getAutoMigrate(Config cfg) {
return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, false);
}
private static void setAutoMigrate(Config cfg, boolean autoMigrate) {
cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, autoMigrate);
}
public static class Builder {
private final Config cfg;
private final SitePaths sitePaths;
private final SchemaFactory<ReviewDb> schemaFactory;
private final GitRepositoryManager repoManager;
private final AllProjectsName allProjects;
private final InternalUser.Factory userFactory;
private final ThreadLocalRequestContext requestContext;
private final ChangeRebuilder rebuilder;
private final WorkQueue workQueue;
private final NotesMigration globalNotesMigration;
private final PrimaryStorageMigrator primaryStorageMigrator;
private int threads;
private ImmutableList<Project.NameKey> projects = ImmutableList.of();
private ImmutableList<Change.Id> changes = ImmutableList.of();
private OutputStream progressOut = NullOutputStream.INSTANCE;
private NotesMigrationState stopAtState;
private boolean trial;
private boolean forceRebuild;
private int sequenceGap = -1;
private boolean autoMigrate;
@Inject
Builder(
@GerritServerConfig Config cfg,
SitePaths sitePaths,
SchemaFactory<ReviewDb> schemaFactory,
GitRepositoryManager repoManager,
AllProjectsName allProjects,
ThreadLocalRequestContext requestContext,
InternalUser.Factory userFactory,
ChangeRebuilder rebuilder,
WorkQueue workQueue,
NotesMigration globalNotesMigration,
PrimaryStorageMigrator primaryStorageMigrator) {
this.cfg = cfg;
this.sitePaths = sitePaths;
this.schemaFactory = schemaFactory;
this.repoManager = repoManager;
this.allProjects = allProjects;
this.requestContext = requestContext;
this.userFactory = userFactory;
this.rebuilder = rebuilder;
this.workQueue = workQueue;
this.globalNotesMigration = globalNotesMigration;
this.primaryStorageMigrator = primaryStorageMigrator;
}
/**
* Set the number of threads used by parallelizable phases of the migration, such as rebuilding
* all changes.
*
* <p>Not all phases are parallelizable, and calling {@link #rebuild()} directly will do
* substantial work in the calling thread regardless of the number of threads configured.
*
* <p>By default, all work is done in the calling thread.
*
* @param threads thread count; if less than 2, all work happens in the calling thread.
* @return this.
*/
public Builder setThreads(int threads) {
this.threads = threads;
return this;
}
/**
* Limit the set of projects that are processed.
*
* <p>Incompatible with {@link #setChanges(Collection)}.
*
* <p>By default, all projects will be processed.
*
* @param projects set of projects; if null or empty, all projects will be processed.
* @return this.
*/
public Builder setProjects(@Nullable Collection<Project.NameKey> projects) {
this.projects = projects != null ? ImmutableList.copyOf(projects) : ImmutableList.of();
return this;
}
/**
* Limit the set of changes that are processed.
*
* <p>Incompatible with {@link #setProjects(Collection)}.
*
* <p>By default, all changes will be processed.
*
* @param changes set of changes; if null or empty, all changes will be processed.
* @return this.
*/
public Builder setChanges(@Nullable Collection<Change.Id> changes) {
this.changes = changes != null ? ImmutableList.copyOf(changes) : ImmutableList.of();
return this;
}
/**
* Set output stream for progress monitors.
*
* <p>By default, there is no progress monitor output (although there may be other logs).
*
* @param progressOut output stream.
* @return this.
*/
public Builder setProgressOut(OutputStream progressOut) {
this.progressOut = checkNotNull(progressOut);
return this;
}
/**
* Stop at a specific migration state, for testing only.
*
* @param stopAtState state to stop at.
* @return this.
*/
@VisibleForTesting
public Builder setStopAtStateForTesting(NotesMigrationState stopAtState) {
this.stopAtState = stopAtState;
return this;
}
/**
* Rebuild in "trial mode": configure Gerrit to write to and read from NoteDb, but leave
* ReviewDb as the source of truth for all changes.
*
* <p>By default, trial mode is off, and NoteDb is the source of truth for all changes following
* the migration.
*
* @param trial whether to rebuild in trial mode.
* @return this.
*/
public Builder setTrialMode(boolean trial) {
this.trial = trial;
return this;
}
/**
* Rebuild all changes in NoteDb from ReviewDb, even if Gerrit is currently configured to read
* from NoteDb.
*
* <p>Only supported if ReviewDb is still the source of truth for all changes.
*
* <p>By default, force rebuilding is off.
*
* @param forceRebuild whether to force rebuilding.
* @return this.
*/
public Builder setForceRebuild(boolean forceRebuild) {
this.forceRebuild = forceRebuild;
return this;
}
/**
* Gap between ReviewDb change sequence numbers and NoteDb.
*
* <p>If NoteDb sequences are enabled in a running server, there is a race between the migration
* step that calls {@code nextChangeId()} to seed the ref, and other threads that call {@code
* nextChangeId()} to create new changes. In order to prevent these operations stepping on one
* another, we use this value to skip some predefined sequence numbers. This is strongly
* recommended in a running server.
*
* <p>If the migration takes place offline, there is no race with other threads, and this option
* may be set to 0. However, admins may still choose to use a gap, for example to make it easier
* to distinguish changes that were created before and after the NoteDb migration.
*
* <p>By default, uses the value from {@code noteDb.changes.initialSequenceGap} in {@code
* gerrit.config}, which defaults to 1000.
*
* @param sequenceGap sequence gap size; if negative, use the default.
* @return this.
*/
public Builder setSequenceGap(int sequenceGap) {
this.sequenceGap = sequenceGap;
return this;
}
/**
* Enable auto-migration on subsequent daemon launches.
*
* <p>If true, prior to running any migration steps, sets the necessary configuration in {@code
* gerrit.config} to make {@code gerrit.war daemon} retry the migration on next startup, if it
* fails.
*
* @param autoMigrate whether to set auto-migration config.
* @return this.
*/
public Builder setAutoMigrate(boolean autoMigrate) {
this.autoMigrate = autoMigrate;
return this;
}
public NoteDbMigrator build() throws MigrationException {
return new NoteDbMigrator(
sitePaths,
schemaFactory,
repoManager,
allProjects,
requestContext,
userFactory,
rebuilder,
globalNotesMigration,
primaryStorageMigrator,
threads > 1
? MoreExecutors.listeningDecorator(workQueue.createQueue(threads, "RebuildChange"))
: MoreExecutors.newDirectExecutorService(),
projects,
changes,
progressOut,
stopAtState,
trial,
forceRebuild,
sequenceGap >= 0 ? sequenceGap : Sequences.getChangeSequenceGap(cfg),
autoMigrate);
}
}
private final FileBasedConfig gerritConfig;
private final SchemaFactory<ReviewDb> schemaFactory;
private final GitRepositoryManager repoManager;
private final AllProjectsName allProjects;
private final ThreadLocalRequestContext requestContext;
private final InternalUser.Factory userFactory;
private final ChangeRebuilder rebuilder;
private final NotesMigration globalNotesMigration;
private final PrimaryStorageMigrator primaryStorageMigrator;
private final ListeningExecutorService executor;
private final ImmutableList<Project.NameKey> projects;
private final ImmutableList<Change.Id> changes;
private final OutputStream progressOut;
private final NotesMigrationState stopAtState;
private final boolean trial;
private final boolean forceRebuild;
private final int sequenceGap;
private final boolean autoMigrate;
private NoteDbMigrator(
SitePaths sitePaths,
SchemaFactory<ReviewDb> schemaFactory,
GitRepositoryManager repoManager,
AllProjectsName allProjects,
ThreadLocalRequestContext requestContext,
InternalUser.Factory userFactory,
ChangeRebuilder rebuilder,
NotesMigration globalNotesMigration,
PrimaryStorageMigrator primaryStorageMigrator,
ListeningExecutorService executor,
ImmutableList<Project.NameKey> projects,
ImmutableList<Change.Id> changes,
OutputStream progressOut,
NotesMigrationState stopAtState,
boolean trial,
boolean forceRebuild,
int sequenceGap,
boolean autoMigrate)
throws MigrationException {
if (!changes.isEmpty() && !projects.isEmpty()) {
throw new MigrationException("Cannot set both changes and projects");
}
if (sequenceGap < 0) {
throw new MigrationException("Sequence gap must be non-negative: " + sequenceGap);
}
this.schemaFactory = schemaFactory;
this.rebuilder = rebuilder;
this.repoManager = repoManager;
this.allProjects = allProjects;
this.requestContext = requestContext;
this.userFactory = userFactory;
this.globalNotesMigration = globalNotesMigration;
this.primaryStorageMigrator = primaryStorageMigrator;
this.gerritConfig = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.detect());
this.executor = executor;
this.projects = projects;
this.changes = changes;
this.progressOut = progressOut;
this.stopAtState = stopAtState;
this.trial = trial;
this.forceRebuild = forceRebuild;
this.sequenceGap = sequenceGap;
this.autoMigrate = autoMigrate;
}
@Override
public void close() {
executor.shutdownNow();
}
public void migrate() throws OrmException, IOException {
if (!changes.isEmpty() || !projects.isEmpty()) {
throw new MigrationException(
"Cannot set changes or projects during full migration; call rebuild() instead");
}
Optional<NotesMigrationState> maybeState = loadState();
if (!maybeState.isPresent()) {
throw new MigrationException("Could not determine initial migration state");
}
NotesMigrationState state = maybeState.get();
if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) > 0) {
throw new MigrationException(
"Migration has already progressed past the endpoint of the \"trial mode\" state;"
+ " NoteDb is already the primary storage for some changes");
}
if (forceRebuild && state.compareTo(READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY) > 0) {
throw new MigrationException(
"Cannot force rebuild changes; NoteDb is already the primary storage for some changes");
}
if (autoMigrate) {
if (trial) {
throw new MigrationException("Auto-migration cannot be used with trial mode");
}
enableAutoMigrate();
}
boolean rebuilt = false;
while (state.compareTo(NOTE_DB_UNFUSED) < 0) {
if (state.equals(stopAtState)) {
return;
}
boolean stillNeedsRebuild = forceRebuild && !rebuilt;
if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) >= 0) {
if (stillNeedsRebuild && state == READ_WRITE_NO_SEQUENCE) {
// We're at the end state of trial mode, but still need a rebuild due to forceRebuild. Let
// the loop go one more time.
} else {
return;
}
}
switch (state) {
case REVIEW_DB:
state = turnOnWrites(state);
break;
case WRITE:
state = rebuildAndEnableReads(state);
rebuilt = true;
break;
case READ_WRITE_NO_SEQUENCE:
if (stillNeedsRebuild) {
state = rebuildAndEnableReads(state);
rebuilt = true;
} else {
state = enableSequences(state);
}
break;
case READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY:
if (stillNeedsRebuild) {
state = rebuildAndEnableReads(state);
rebuilt = true;
} else {
state = setNoteDbPrimary(state);
}
break;
case READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY:
// The only way we can get here is if there was a failure on a previous run of
// setNoteDbPrimary, since that method moves to NOTE_DB_UNFUSED if it completes
// successfully. Assume that not all changes were converted and re-run the step.
// migrateToNoteDbPrimary is a relatively fast no-op for already-migrated changes, so this
// isn't actually repeating work.
state = setNoteDbPrimary(state);
break;
case NOTE_DB_UNFUSED:
// Done!
break;
case NOTE_DB:
// TODO(dborowitz): Allow this state once FileRepository supports fused updates.
// Until then, fallthrough and throw.
default:
throw new MigrationException(
"Migration out of the following state is not supported:\n" + state.toText());
}
}
}
private NotesMigrationState turnOnWrites(NotesMigrationState prev) throws IOException {
return saveState(prev, WRITE);
}
private NotesMigrationState rebuildAndEnableReads(NotesMigrationState prev)
throws OrmException, IOException {
rebuild();
return saveState(prev, READ_WRITE_NO_SEQUENCE);
}
private NotesMigrationState enableSequences(NotesMigrationState prev)
throws OrmException, IOException {
try (ReviewDb db = schemaFactory.open()) {
@SuppressWarnings("deprecation")
RepoSequence seq =
new RepoSequence(
repoManager,
allProjects,
Sequences.NAME_CHANGES,
// If sequenceGap is 0, this writes into the sequence ref the same ID that is returned
// by the call to seq.next() below. If we actually used this as a change ID, that
// would be a problem, but we just discard it, so this is safe.
() -> db.nextChangeId() + sequenceGap - 1,
1);
seq.next();
}
return saveState(prev, READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY);
}
private NotesMigrationState setNoteDbPrimary(NotesMigrationState prev)
throws MigrationException, OrmException, IOException {
checkState(
projects.isEmpty() && changes.isEmpty(),
"Should not have attempted setNoteDbPrimary with a subset of changes");
checkState(
prev == READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY
|| prev == READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY,
"Unexpected start state for setNoteDbPrimary: %s",
prev);
// Before changing the primary storage of old changes, ensure new changes are created with
// NoteDb primary.
prev = saveState(prev, READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY);
Stopwatch sw = Stopwatch.createStarted();
log.info("Setting primary storage to NoteDb");
List<Change.Id> allChanges;
try (ReviewDb db = unwrapDb(schemaFactory.open())) {
allChanges = Streams.stream(db.changes().all()).map(Change::getId).collect(toList());
}
try (ContextHelper contextHelper = new ContextHelper()) {
List<ListenableFuture<Boolean>> futures =
allChanges
.stream()
.map(
id ->
executor.submit(
() -> {
try (ManualRequestContext ctx = contextHelper.open()) {
primaryStorageMigrator.migrateToNoteDbPrimary(id);
return true;
} catch (Exception e) {
log.error("Error migrating primary storage for " + id, e);
return false;
}
}))
.collect(toList());
boolean ok = futuresToBoolean(futures, "Error migrating primary storage");
double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
log.info(
String.format(
"Migrated primary storage of %d changes in %.01fs (%.01f/s)\n",
allChanges.size(), t, allChanges.size() / t));
if (!ok) {
throw new MigrationException("Migrating primary storage for some changes failed, see log");
}
}
return disableReviewDb(prev);
}
private NotesMigrationState disableReviewDb(NotesMigrationState prev) throws IOException {
return saveState(prev, NOTE_DB_UNFUSED, c -> setAutoMigrate(c, false));
}
private Optional<NotesMigrationState> loadState() throws IOException {
try {
gerritConfig.load();
return NotesMigrationState.forNotesMigration(new ConfigNotesMigration(gerritConfig));
} catch (ConfigInvalidException | IllegalArgumentException e) {
log.warn("error reading NoteDb migration options from " + gerritConfig.getFile(), e);
return Optional.empty();
}
}
private NotesMigrationState saveState(
NotesMigrationState expectedOldState, NotesMigrationState newState) throws IOException {
return saveState(expectedOldState, newState, c -> {});
}
private NotesMigrationState saveState(
NotesMigrationState expectedOldState,
NotesMigrationState newState,
Consumer<Config> additionalUpdates)
throws IOException {
synchronized (globalNotesMigration) {
// This read-modify-write is racy. We're counting on the fact that no other Gerrit operation
// modifies gerrit.config, and hoping that admins don't either.
Optional<NotesMigrationState> actualOldState = loadState();
if (!actualOldState.equals(Optional.of(expectedOldState))) {
throw new MigrationException(
"Cannot move to new state:\n"
+ newState.toText()
+ "\n\n"
+ "Expected this state in gerrit.config:\n"
+ expectedOldState.toText()
+ "\n\n"
+ (actualOldState.isPresent()
? "But found this state:\n" + actualOldState.get().toText()
: "But could not parse the current state"));
}
ConfigNotesMigration.setConfigValues(gerritConfig, newState.migration());
additionalUpdates.accept(gerritConfig);
gerritConfig.save();
// Only set in-memory state once it's been persisted to storage.
globalNotesMigration.setFrom(newState.migration());
return newState;
}
}
private void enableAutoMigrate() throws MigrationException {
try {
gerritConfig.load();
setAutoMigrate(gerritConfig, true);
gerritConfig.save();
} catch (ConfigInvalidException | IOException e) {
throw new MigrationException("Error saving auto-migration config", e);
}
}
public void rebuild() throws MigrationException, OrmException {
if (!globalNotesMigration.commitChangeWrites()) {
throw new MigrationException("Cannot rebuild without noteDb.changes.write=true");
}
Stopwatch sw = Stopwatch.createStarted();
log.info("Rebuilding changes in NoteDb");
List<ListenableFuture<Boolean>> futures = new ArrayList<>();
try (ContextHelper contextHelper = new ContextHelper()) {
ImmutableListMultimap<Project.NameKey, Change.Id> changesByProject =
getChangesByProject(contextHelper.getReviewDb());
List<Project.NameKey> projectNames =
Ordering.usingToString().sortedCopy(changesByProject.keySet());
for (Project.NameKey project : projectNames) {
ListenableFuture<Boolean> future =
executor.submit(
() -> {
try {
return rebuildProject(contextHelper.getReviewDb(), changesByProject, project);
} catch (Exception e) {
log.error("Error rebuilding project " + project, e);
return false;
}
});
futures.add(future);
}
boolean ok = futuresToBoolean(futures, "Error rebuilding projects");
double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
log.info(
String.format(
"Rebuilt %d changes in %.01fs (%.01f/s)\n",
changesByProject.size(), t, changesByProject.size() / t));
if (!ok) {
throw new MigrationException("Rebuilding some changes failed, see log");
}
}
}
private ImmutableListMultimap<Project.NameKey, Change.Id> getChangesByProject(ReviewDb db)
throws OrmException {
// Memoize all changes so we can close the db connection and allow other threads to use the full
// connection pool.
SetMultimap<Project.NameKey, Change.Id> out =
MultimapBuilder.treeKeys(comparing(Project.NameKey::get))
.treeSetValues(comparing(Change.Id::get))
.build();
if (!projects.isEmpty()) {
return byProject(db.changes().all(), c -> projects.contains(c.getProject()), out);
}
if (!changes.isEmpty()) {
return byProject(db.changes().get(changes), c -> true, out);
}
return byProject(db.changes().all(), c -> true, out);
}
private static ImmutableListMultimap<Project.NameKey, Change.Id> byProject(
Iterable<Change> changes,
Predicate<Change> pred,
SetMultimap<Project.NameKey, Change.Id> out) {
Streams.stream(changes).filter(pred).forEach(c -> out.put(c.getProject(), c.getId()));
return ImmutableListMultimap.copyOf(out);
}
private boolean rebuildProject(
ReviewDb db,
ImmutableListMultimap<Project.NameKey, Change.Id> allChanges,
Project.NameKey project) {
checkArgument(allChanges.containsKey(project));
boolean ok = true;
ProgressMonitor pm =
new TextProgressMonitor(
new PrintWriter(new BufferedWriter(new OutputStreamWriter(progressOut, UTF_8))));
pm.beginTask(FormatUtil.elide(project.get(), 50), allChanges.get(project).size());
try {
Collection<Change.Id> changes = allChanges.get(project);
for (Change.Id changeId : changes) {
// Update one change at a time, which ends up creating one NoteDbUpdateManager per change as
// well. This turns out to be no more expensive than batching, since each NoteDb operation
// is only writing single loose ref updates and loose objects. Plus we have to do one
// ReviewDb transaction per change due to the AtomicUpdate, so if we somehow batched NoteDb
// operations, ReviewDb would become the bottleneck.
try {
rebuilder.rebuild(db, changeId);
} catch (NoPatchSetsException e) {
log.warn(e.getMessage());
} catch (RepositoryNotFoundException e) {
log.warn("Repository {} not found while rebuilding change {}", project, changeId);
} catch (ConflictingUpdateException e) {
log.warn(
"Rebuilding detected a conflicting ReviewDb update for change {};"
+ " will be auto-rebuilt at runtime",
changeId);
} catch (LockFailureException e) {
log.warn(
"Rebuilding detected a conflicting NoteDb update for change {};"
+ " will be auto-rebuilt at runtime",
changeId);
} catch (Throwable t) {
log.error("Failed to rebuild change " + changeId, t);
ok = false;
}
pm.update(1);
}
} finally {
pm.endTask();
}
return ok;
}
private static boolean futuresToBoolean(List<ListenableFuture<Boolean>> futures, String errMsg) {
try {
return Futures.allAsList(futures).get().stream().allMatch(b -> b);
} catch (InterruptedException | ExecutionException e) {
log.error(errMsg, e);
return false;
}
}
private class ContextHelper implements AutoCloseable {
private final Thread callingThread;
private ReviewDb db;
ContextHelper() {
callingThread = Thread.currentThread();
}
ManualRequestContext open() throws OrmException {
return new ManualRequestContext(
userFactory.create(),
// Reuse the same lazily-opened ReviewDb on the original calling thread, otherwise open
// SchemaFactory in the normal way.
Thread.currentThread().equals(callingThread) ? this::getReviewDb : schemaFactory,
requestContext);
}
synchronized ReviewDb getReviewDb() throws OrmException {
if (db == null) {
db =
new ReviewDbWrapper(unwrapDb(schemaFactory.open())) {
@Override
public void close() {
// Closed by ContextHelper#close.
}
};
}
return db;
}
@Override
public synchronized void close() {
if (db != null) {
db.close();
}
}
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/NoteDbMigrator.java | // Copyright (C) 2017 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.google.gerrit.server.notedb.rebuild;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.reviewdb.server.ReviewDbUtil.unwrapDb;
import static com.google.gerrit.server.notedb.ConfigNotesMigration.SECTION_NOTE_DB;
import static com.google.gerrit.server.notedb.NotesMigrationState.NOTE_DB_UNFUSED;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_NO_SEQUENCE;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY;
import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY;
import static com.google.gerrit.server.notedb.NotesMigrationState.WRITE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Ordering;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Streams;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gerrit.common.FormatUtil;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.reviewdb.server.ReviewDbWrapper;
import com.google.gerrit.server.InternalUser;
import com.google.gerrit.server.Sequences;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.LockFailureException;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.notedb.ConfigNotesMigration;
import com.google.gerrit.server.notedb.NoteDbTable;
import com.google.gerrit.server.notedb.NotesMigration;
import com.google.gerrit.server.notedb.NotesMigrationState;
import com.google.gerrit.server.notedb.PrimaryStorageMigrator;
import com.google.gerrit.server.notedb.RepoSequence;
import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException;
import com.google.gerrit.server.util.ManualRequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.io.NullOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** One stop shop for migrating a site's change storage from ReviewDb to NoteDb. */
public class NoteDbMigrator implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(NoteDbMigrator.class);
private static final String AUTO_MIGRATE = "autoMigrate";
public static boolean getAutoMigrate(Config cfg) {
return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, false);
}
private static void setAutoMigrate(Config cfg, boolean autoMigrate) {
cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, autoMigrate);
}
public static class Builder {
private final Config cfg;
private final SitePaths sitePaths;
private final SchemaFactory<ReviewDb> schemaFactory;
private final GitRepositoryManager repoManager;
private final AllProjectsName allProjects;
private final InternalUser.Factory userFactory;
private final ThreadLocalRequestContext requestContext;
private final ChangeRebuilder rebuilder;
private final WorkQueue workQueue;
private final NotesMigration globalNotesMigration;
private final PrimaryStorageMigrator primaryStorageMigrator;
private int threads;
private ImmutableList<Project.NameKey> projects = ImmutableList.of();
private ImmutableList<Change.Id> changes = ImmutableList.of();
private OutputStream progressOut = NullOutputStream.INSTANCE;
private NotesMigrationState stopAtState;
private boolean trial;
private boolean forceRebuild;
private int sequenceGap = -1;
private boolean autoMigrate;
@Inject
Builder(
@GerritServerConfig Config cfg,
SitePaths sitePaths,
SchemaFactory<ReviewDb> schemaFactory,
GitRepositoryManager repoManager,
AllProjectsName allProjects,
ThreadLocalRequestContext requestContext,
InternalUser.Factory userFactory,
ChangeRebuilder rebuilder,
WorkQueue workQueue,
NotesMigration globalNotesMigration,
PrimaryStorageMigrator primaryStorageMigrator) {
this.cfg = cfg;
this.sitePaths = sitePaths;
this.schemaFactory = schemaFactory;
this.repoManager = repoManager;
this.allProjects = allProjects;
this.requestContext = requestContext;
this.userFactory = userFactory;
this.rebuilder = rebuilder;
this.workQueue = workQueue;
this.globalNotesMigration = globalNotesMigration;
this.primaryStorageMigrator = primaryStorageMigrator;
}
/**
* Set the number of threads used by parallelizable phases of the migration, such as rebuilding
* all changes.
*
* <p>Not all phases are parallelizable, and calling {@link #rebuild()} directly will do
* substantial work in the calling thread regardless of the number of threads configured.
*
* <p>By default, all work is done in the calling thread.
*
* @param threads thread count; if less than 2, all work happens in the calling thread.
* @return this.
*/
public Builder setThreads(int threads) {
this.threads = threads;
return this;
}
/**
* Limit the set of projects that are processed.
*
* <p>Incompatible with {@link #setChanges(Collection)}.
*
* <p>By default, all projects will be processed.
*
* @param projects set of projects; if null or empty, all projects will be processed.
* @return this.
*/
public Builder setProjects(@Nullable Collection<Project.NameKey> projects) {
this.projects = projects != null ? ImmutableList.copyOf(projects) : ImmutableList.of();
return this;
}
/**
* Limit the set of changes that are processed.
*
* <p>Incompatible with {@link #setProjects(Collection)}.
*
* <p>By default, all changes will be processed.
*
* @param changes set of changes; if null or empty, all changes will be processed.
* @return this.
*/
public Builder setChanges(@Nullable Collection<Change.Id> changes) {
this.changes = changes != null ? ImmutableList.copyOf(changes) : ImmutableList.of();
return this;
}
/**
* Set output stream for progress monitors.
*
* <p>By default, there is no progress monitor output (although there may be other logs).
*
* @param progressOut output stream.
* @return this.
*/
public Builder setProgressOut(OutputStream progressOut) {
this.progressOut = checkNotNull(progressOut);
return this;
}
/**
* Stop at a specific migration state, for testing only.
*
* @param stopAtState state to stop at.
* @return this.
*/
@VisibleForTesting
public Builder setStopAtStateForTesting(NotesMigrationState stopAtState) {
this.stopAtState = stopAtState;
return this;
}
/**
* Rebuild in "trial mode": configure Gerrit to write to and read from NoteDb, but leave
* ReviewDb as the source of truth for all changes.
*
* <p>By default, trial mode is off, and NoteDb is the source of truth for all changes following
* the migration.
*
* @param trial whether to rebuild in trial mode.
* @return this.
*/
public Builder setTrialMode(boolean trial) {
this.trial = trial;
return this;
}
/**
* Rebuild all changes in NoteDb from ReviewDb, even if Gerrit is currently configured to read
* from NoteDb.
*
* <p>Only supported if ReviewDb is still the source of truth for all changes.
*
* <p>By default, force rebuilding is off.
*
* @param forceRebuild whether to force rebuilding.
* @return this.
*/
public Builder setForceRebuild(boolean forceRebuild) {
this.forceRebuild = forceRebuild;
return this;
}
/**
* Gap between ReviewDb change sequence numbers and NoteDb.
*
* <p>If NoteDb sequences are enabled in a running server, there is a race between the migration
* step that calls {@code nextChangeId()} to seed the ref, and other threads that call {@code
* nextChangeId()} to create new changes. In order to prevent these operations stepping on one
* another, we use this value to skip some predefined sequence numbers. This is strongly
* recommended in a running server.
*
* <p>If the migration takes place offline, there is no race with other threads, and this option
* may be set to 0. However, admins may still choose to use a gap, for example to make it easier
* to distinguish changes that were created before and after the NoteDb migration.
*
* <p>By default, uses the value from {@code noteDb.changes.initialSequenceGap} in {@code
* gerrit.config}, which defaults to 1000.
*
* @param sequenceGap sequence gap size; if negative, use the default.
* @return this.
*/
public Builder setSequenceGap(int sequenceGap) {
this.sequenceGap = sequenceGap;
return this;
}
/**
* Enable auto-migration on subsequent daemon launches.
*
* <p>If true, prior to running any migration steps, sets the necessary configuration in {@code
* gerrit.config} to make {@code gerrit.war daemon} retry the migration on next startup, if it
* fails.
*
* @param autoMigrate whether to set auto-migration config.
* @return this.
*/
public Builder setAutoMigrate(boolean autoMigrate) {
this.autoMigrate = autoMigrate;
return this;
}
public NoteDbMigrator build() throws MigrationException {
return new NoteDbMigrator(
sitePaths,
schemaFactory,
repoManager,
allProjects,
requestContext,
userFactory,
rebuilder,
globalNotesMigration,
primaryStorageMigrator,
threads > 1
? MoreExecutors.listeningDecorator(workQueue.createQueue(threads, "RebuildChange"))
: MoreExecutors.newDirectExecutorService(),
projects,
changes,
progressOut,
stopAtState,
trial,
forceRebuild,
sequenceGap >= 0 ? sequenceGap : Sequences.getChangeSequenceGap(cfg),
autoMigrate);
}
}
private final FileBasedConfig gerritConfig;
private final SchemaFactory<ReviewDb> schemaFactory;
private final GitRepositoryManager repoManager;
private final AllProjectsName allProjects;
private final ThreadLocalRequestContext requestContext;
private final InternalUser.Factory userFactory;
private final ChangeRebuilder rebuilder;
private final NotesMigration globalNotesMigration;
private final PrimaryStorageMigrator primaryStorageMigrator;
private final ListeningExecutorService executor;
private final ImmutableList<Project.NameKey> projects;
private final ImmutableList<Change.Id> changes;
private final OutputStream progressOut;
private final NotesMigrationState stopAtState;
private final boolean trial;
private final boolean forceRebuild;
private final int sequenceGap;
private final boolean autoMigrate;
private NoteDbMigrator(
SitePaths sitePaths,
SchemaFactory<ReviewDb> schemaFactory,
GitRepositoryManager repoManager,
AllProjectsName allProjects,
ThreadLocalRequestContext requestContext,
InternalUser.Factory userFactory,
ChangeRebuilder rebuilder,
NotesMigration globalNotesMigration,
PrimaryStorageMigrator primaryStorageMigrator,
ListeningExecutorService executor,
ImmutableList<Project.NameKey> projects,
ImmutableList<Change.Id> changes,
OutputStream progressOut,
NotesMigrationState stopAtState,
boolean trial,
boolean forceRebuild,
int sequenceGap,
boolean autoMigrate)
throws MigrationException {
if (!changes.isEmpty() && !projects.isEmpty()) {
throw new MigrationException("Cannot set both changes and projects");
}
if (sequenceGap < 0) {
throw new MigrationException("Sequence gap must be non-negative: " + sequenceGap);
}
this.schemaFactory = schemaFactory;
this.rebuilder = rebuilder;
this.repoManager = repoManager;
this.allProjects = allProjects;
this.requestContext = requestContext;
this.userFactory = userFactory;
this.globalNotesMigration = globalNotesMigration;
this.primaryStorageMigrator = primaryStorageMigrator;
this.gerritConfig = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.detect());
this.executor = executor;
this.projects = projects;
this.changes = changes;
this.progressOut = progressOut;
this.stopAtState = stopAtState;
this.trial = trial;
this.forceRebuild = forceRebuild;
this.sequenceGap = sequenceGap;
this.autoMigrate = autoMigrate;
}
@Override
public void close() {
executor.shutdownNow();
}
public void migrate() throws OrmException, IOException {
if (!changes.isEmpty() || !projects.isEmpty()) {
throw new MigrationException(
"Cannot set changes or projects during full migration; call rebuild() instead");
}
Optional<NotesMigrationState> maybeState = loadState();
if (!maybeState.isPresent()) {
throw new MigrationException("Could not determine initial migration state");
}
NotesMigrationState state = maybeState.get();
if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) > 0) {
throw new MigrationException(
"Migration has already progressed past the endpoint of the \"trial mode\" state;"
+ " NoteDb is already the primary storage for some changes");
}
if (forceRebuild && state.compareTo(READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY) > 0) {
throw new MigrationException(
"Cannot force rebuild changes; NoteDb is already the primary storage for some changes");
}
if (autoMigrate) {
if (trial) {
throw new MigrationException("Auto-migration cannot be used with trial mode");
}
enableAutoMigrate();
}
boolean rebuilt = false;
while (state.compareTo(NOTE_DB_UNFUSED) < 0) {
if (state.equals(stopAtState)) {
return;
}
boolean stillNeedsRebuild = forceRebuild && !rebuilt;
if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) >= 0) {
if (stillNeedsRebuild && state == READ_WRITE_NO_SEQUENCE) {
// We're at the end state of trial mode, but still need a rebuild due to forceRebuild. Let
// the loop go one more time.
} else {
return;
}
}
switch (state) {
case REVIEW_DB:
state = turnOnWrites(state);
break;
case WRITE:
state = rebuildAndEnableReads(state);
rebuilt = true;
break;
case READ_WRITE_NO_SEQUENCE:
if (stillNeedsRebuild) {
state = rebuildAndEnableReads(state);
rebuilt = true;
} else {
state = enableSequences(state);
}
break;
case READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY:
if (stillNeedsRebuild) {
state = rebuildAndEnableReads(state);
rebuilt = true;
} else {
state = setNoteDbPrimary(state);
}
break;
case READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY:
// The only way we can get here is if there was a failure on a previous run of
// setNoteDbPrimary, since that method moves to NOTE_DB_UNFUSED if it completes
// successfully. Assume that not all changes were converted and re-run the step.
// migrateToNoteDbPrimary is a relatively fast no-op for already-migrated changes, so this
// isn't actually repeating work.
state = setNoteDbPrimary(state);
break;
case NOTE_DB_UNFUSED:
// Done!
break;
case NOTE_DB:
// TODO(dborowitz): Allow this state once FileRepository supports fused updates.
// Until then, fallthrough and throw.
default:
throw new MigrationException(
"Migration out of the following state is not supported:\n" + state.toText());
}
}
}
private NotesMigrationState turnOnWrites(NotesMigrationState prev) throws IOException {
return saveState(prev, WRITE);
}
private NotesMigrationState rebuildAndEnableReads(NotesMigrationState prev)
throws OrmException, IOException {
rebuild();
return saveState(prev, READ_WRITE_NO_SEQUENCE);
}
private NotesMigrationState enableSequences(NotesMigrationState prev)
throws OrmException, IOException {
try (ReviewDb db = schemaFactory.open()) {
@SuppressWarnings("deprecation")
RepoSequence seq =
new RepoSequence(
repoManager,
allProjects,
Sequences.NAME_CHANGES,
// If sequenceGap is 0, this writes into the sequence ref the same ID that is returned
// by the call to seq.next() below. If we actually used this as a change ID, that
// would be a problem, but we just discard it, so this is safe.
() -> db.nextChangeId() + sequenceGap - 1,
1);
seq.next();
}
return saveState(prev, READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY);
}
private NotesMigrationState setNoteDbPrimary(NotesMigrationState prev)
throws MigrationException, OrmException, IOException {
checkState(
projects.isEmpty() && changes.isEmpty(),
"Should not have attempted setNoteDbPrimary with a subset of changes");
checkState(
prev == READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY
|| prev == READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY,
"Unexpected start state for setNoteDbPrimary: %s",
prev);
// Before changing the primary storage of old changes, ensure new changes are created with
// NoteDb primary.
prev = saveState(prev, READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY);
Stopwatch sw = Stopwatch.createStarted();
log.info("Setting primary storage to NoteDb");
List<Change.Id> allChanges;
try (ReviewDb db = unwrapDb(schemaFactory.open())) {
allChanges = Streams.stream(db.changes().all()).map(Change::getId).collect(toList());
}
try (ContextHelper contextHelper = new ContextHelper()) {
List<ListenableFuture<Boolean>> futures =
allChanges
.stream()
.map(
id ->
executor.submit(
() -> {
try (ManualRequestContext ctx = contextHelper.open()) {
primaryStorageMigrator.migrateToNoteDbPrimary(id);
return true;
} catch (Exception e) {
log.error("Error migrating primary storage for " + id, e);
return false;
}
}))
.collect(toList());
boolean ok = futuresToBoolean(futures, "Error migrating primary storage");
double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
log.info(
String.format(
"Migrated primary storage of %d changes in %.01fs (%.01f/s)\n",
allChanges.size(), t, allChanges.size() / t));
if (!ok) {
throw new MigrationException("Migrating primary storage for some changes failed, see log");
}
}
return disableReviewDb(prev);
}
private NotesMigrationState disableReviewDb(NotesMigrationState prev) throws IOException {
return saveState(prev, NOTE_DB_UNFUSED, c -> setAutoMigrate(c, false));
}
private Optional<NotesMigrationState> loadState() throws IOException {
try {
gerritConfig.load();
return NotesMigrationState.forNotesMigration(new ConfigNotesMigration(gerritConfig));
} catch (ConfigInvalidException | IllegalArgumentException e) {
log.warn("error reading NoteDb migration options from " + gerritConfig.getFile(), e);
return Optional.empty();
}
}
private NotesMigrationState saveState(
NotesMigrationState expectedOldState, NotesMigrationState newState) throws IOException {
return saveState(expectedOldState, newState, c -> {});
}
private NotesMigrationState saveState(
NotesMigrationState expectedOldState,
NotesMigrationState newState,
Consumer<Config> additionalUpdates)
throws IOException {
synchronized (globalNotesMigration) {
// This read-modify-write is racy. We're counting on the fact that no other Gerrit operation
// modifies gerrit.config, and hoping that admins don't either.
Optional<NotesMigrationState> actualOldState = loadState();
if (!actualOldState.equals(Optional.of(expectedOldState))) {
throw new MigrationException(
"Cannot move to new state:\n"
+ newState.toText()
+ "\n\n"
+ "Expected this state in gerrit.config:\n"
+ expectedOldState.toText()
+ "\n\n"
+ (actualOldState.isPresent()
? "But found this state:\n" + actualOldState.get().toText()
: "But could not parse the current state"));
}
ConfigNotesMigration.setConfigValues(gerritConfig, newState.migration());
additionalUpdates.accept(gerritConfig);
gerritConfig.save();
// Only set in-memory state once it's been persisted to storage.
globalNotesMigration.setFrom(newState.migration());
return newState;
}
}
private void enableAutoMigrate() throws MigrationException {
try {
gerritConfig.load();
setAutoMigrate(gerritConfig, true);
gerritConfig.save();
} catch (ConfigInvalidException | IOException e) {
throw new MigrationException("Error saving auto-migration config", e);
}
}
public void rebuild() throws MigrationException, OrmException {
if (!globalNotesMigration.commitChangeWrites()) {
throw new MigrationException("Cannot rebuild without noteDb.changes.write=true");
}
Stopwatch sw = Stopwatch.createStarted();
log.info("Rebuilding changes in NoteDb");
List<ListenableFuture<Boolean>> futures = new ArrayList<>();
try (ContextHelper contextHelper = new ContextHelper()) {
ImmutableListMultimap<Project.NameKey, Change.Id> changesByProject =
getChangesByProject(contextHelper.getReviewDb());
List<Project.NameKey> projectNames =
Ordering.usingToString().sortedCopy(changesByProject.keySet());
for (Project.NameKey project : projectNames) {
ListenableFuture<Boolean> future =
executor.submit(
() -> {
try {
return rebuildProject(contextHelper.getReviewDb(), changesByProject, project);
} catch (Exception e) {
log.error("Error rebuilding project " + project, e);
return false;
}
});
futures.add(future);
}
boolean ok = futuresToBoolean(futures, "Error rebuilding projects");
double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
log.info(
String.format(
"Rebuilt %d changes in %.01fs (%.01f/s)\n",
changesByProject.size(), t, changesByProject.size() / t));
if (!ok) {
throw new MigrationException("Rebuilding some changes failed, see log");
}
}
}
private ImmutableListMultimap<Project.NameKey, Change.Id> getChangesByProject(ReviewDb db)
throws OrmException {
// Memoize all changes so we can close the db connection and allow other threads to use the full
// connection pool.
SetMultimap<Project.NameKey, Change.Id> out =
MultimapBuilder.treeKeys(comparing(Project.NameKey::get))
.treeSetValues(comparing(Change.Id::get))
.build();
if (!projects.isEmpty()) {
return byProject(db.changes().all(), c -> projects.contains(c.getProject()), out);
}
if (!changes.isEmpty()) {
return byProject(db.changes().get(changes), c -> true, out);
}
return byProject(db.changes().all(), c -> true, out);
}
private static ImmutableListMultimap<Project.NameKey, Change.Id> byProject(
Iterable<Change> changes,
Predicate<Change> pred,
SetMultimap<Project.NameKey, Change.Id> out) {
Streams.stream(changes).filter(pred).forEach(c -> out.put(c.getProject(), c.getId()));
return ImmutableListMultimap.copyOf(out);
}
private boolean rebuildProject(
ReviewDb db,
ImmutableListMultimap<Project.NameKey, Change.Id> allChanges,
Project.NameKey project) {
checkArgument(allChanges.containsKey(project));
boolean ok = true;
ProgressMonitor pm =
new TextProgressMonitor(
new PrintWriter(new BufferedWriter(new OutputStreamWriter(progressOut, UTF_8))));
pm.beginTask(FormatUtil.elide(project.get(), 50), allChanges.get(project).size());
try {
for (Change.Id changeId : allChanges.get(project)) {
// Update one change at a time, which ends up creating one NoteDbUpdateManager per change as
// well. This turns out to be no more expensive than batching, since each NoteDb operation
// is only writing single loose ref updates and loose objects. Plus we have to do one
// ReviewDb transaction per change due to the AtomicUpdate, so if we somehow batched NoteDb
// operations, ReviewDb would become the bottleneck.
try {
rebuilder.rebuild(db, changeId);
} catch (NoPatchSetsException e) {
log.warn(e.getMessage());
} catch (ConflictingUpdateException e) {
log.warn(
"Rebuilding detected a conflicting ReviewDb update for change {};"
+ " will be auto-rebuilt at runtime",
changeId);
} catch (LockFailureException e) {
log.warn(
"Rebuilding detected a conflicting NoteDb update for change {};"
+ " will be auto-rebuilt at runtime",
changeId);
} catch (Throwable t) {
log.error("Failed to rebuild change " + changeId, t);
ok = false;
}
pm.update(1);
}
} finally {
pm.endTask();
}
return ok;
}
private static boolean futuresToBoolean(List<ListenableFuture<Boolean>> futures, String errMsg) {
try {
return Futures.allAsList(futures).get().stream().allMatch(b -> b);
} catch (InterruptedException | ExecutionException e) {
log.error(errMsg, e);
return false;
}
}
private class ContextHelper implements AutoCloseable {
private final Thread callingThread;
private ReviewDb db;
ContextHelper() {
callingThread = Thread.currentThread();
}
ManualRequestContext open() throws OrmException {
return new ManualRequestContext(
userFactory.create(),
// Reuse the same lazily-opened ReviewDb on the original calling thread, otherwise open
// SchemaFactory in the normal way.
Thread.currentThread().equals(callingThread) ? this::getReviewDb : schemaFactory,
requestContext);
}
synchronized ReviewDb getReviewDb() throws OrmException {
if (db == null) {
db =
new ReviewDbWrapper(unwrapDb(schemaFactory.open())) {
@Override
public void close() {
// Closed by ContextHelper#close.
}
};
}
return db;
}
@Override
public synchronized void close() {
if (db != null) {
db.close();
}
}
}
}
| NoteDbMigrator: Skip changes where the repo doesn't exist
These simply cannot be migrated. They weren't accessible in the UI
anyway, so this is something of an improvement.
Change-Id: I637f590eb27d9397d4df3c79af033c2d891e47de
| gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/NoteDbMigrator.java | NoteDbMigrator: Skip changes where the repo doesn't exist |
|
Java | apache-2.0 | 0350af33be08a488b7adf72e58a647cdeed6f07a | 0 | nedap/archie | /*
* ADL2-core
* Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com)
*
* This file is part of ADL2-core.
*
* ADL2-core 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 com.nedap.archie.serializer.adl.constraints;
import com.google.common.base.Joiner;
import com.nedap.archie.aom.*;
import com.nedap.archie.serializer.adl.ADLDefinitionSerializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.nedap.archie.serializer.adl.ArchetypeSerializeUtils.buildOccurrences;
/**
* @author Marko Pipan
*/
public class CComplexObjectSerializer<T extends CComplexObject> extends ConstraintSerializer<T> {
public CComplexObjectSerializer(ADLDefinitionSerializer serializer) {
super(serializer);
}
@Override
public void serialize(T cobj) {
builder.indent().newline();
builder.append(cobj.getRmTypeName());
if (cobj.getNodeId() != null) {
builder.append("[").append(cobj.getNodeId()).append("]");
}
builder.append(" ");
if (cobj.getOccurrences() != null) {
builder.append("occurrences matches {");
buildOccurrences(builder, cobj.getOccurrences());
builder.append("} ");
}
if (cobj.getAttributes().isEmpty() && cobj.getAttributeTuples().isEmpty()) {
builder.lineComment(serializer.getTermText(cobj));
} else {
builder.append("matches {");
builder.lineComment(serializer.getTermText(cobj));
buildAttributesAndTuples(cobj);
builder.append("}");
}
builder.unindent();
}
private void buildAttributesAndTuples(T cobj) {
builder.indent().newline();
Set<String> tupleAttributes = getTupleAttributeNames(cobj);
cobj.getAttributes().stream()
.filter(a -> !tupleAttributes.contains(a.getRmAttributeName()))
.forEach(this::buildAttribute);
cobj.getAttributeTuples().forEach(this::buildTuple);
builder.unindent().newline();
}
private Set<String> getTupleAttributeNames(T cobj) {
return cobj.getAttributeTuples().stream()
.flatMap(cat -> cat.getMembers().stream())
.map(CAttribute::getRmAttributeName)
.collect(Collectors.toSet());
}
private void buildAttribute(CAttribute cattr) {
builder.tryNewLine();
if (cattr.getRmAttributeName() != null) {
builder.append(cattr.getRmAttributeName());
} else {
builder.append(cattr.getDifferentialPath());
}
if (cattr.getExistence() != null) {
builder.append(" existence matches {");
buildOccurrences(builder, cattr.getExistence());
builder.append("}");
}
if (cattr.getCardinality() != null) {
builder.append(" cardinality matches {");
appendCardinality(cattr.getCardinality());
builder.append("}");
}
if (!cattr.getChildren().isEmpty()) {
builder.append(" matches ");
buildAttributeChildConstraints(cattr);
}
}
private void buildTuple(CAttributeTuple cAttributeTuple) {
builder.tryNewLine();
builder.append("[");
List<String> members = cAttributeTuple.getMembers().stream()
.map(CAttribute::getRmAttributeName)
.collect(Collectors.toList());
builder.append(Joiner.on(", ").join(members));
builder.append("] matches {");
builder.indent();
for (int i = 0; i < cAttributeTuple.getTuples().size(); i++) {
CPrimitiveTuple cObjectTuple = cAttributeTuple.getTuples().get(i);
builder.newline();
builder.append("[");
for (int j = 0; j < cObjectTuple.getMembers().size(); j++) {
builder.append("{");
serializer.appendCObject(cObjectTuple.getMembers().get(j));
builder.append("}");
if (j < cObjectTuple.getMembers().size() - 1) {
builder.append(", ");
}
}
builder.append("]");
if (i < cAttributeTuple.getTuples().size() - 1) {
builder.append(",");
}
}
builder.unindent().newline();
builder.append("}");
}
private void buildAttributeChildConstraints(CAttribute cattr) {
List<CObject> children = filterNonEmptyChildren(cattr.getChildren());
boolean indent = !children.isEmpty() &&
(children.size() > 1 || !(children.get(0) instanceof CPrimitiveObject));
builder.append("{");
children.forEach(serializer::appendCObject);
if (children.isEmpty()) {
builder.append("*");
}
if (indent) {
builder.newline();
}
builder.append("}");
if (!indent && !children.isEmpty()) {
String commentText = serializer.getSimpleCommentText(children.get(0));
if (commentText != null) {
builder.lineComment(commentText);
}
}
}
private List<CObject> filterNonEmptyChildren(List<CObject> children) {
return children.stream()
.filter(child -> !serializer.isEmpty(child))
.collect(Collectors.toList());
}
private void appendCardinality(Cardinality card) {
buildOccurrences(builder, card.getInterval());
List<String> tags = new ArrayList<>();
if (!card.isOrdered()) {
tags.add("unordered");
}
if (card.isUnique()) {
tags.add("unique");
}
if (!tags.isEmpty()) {
builder.append("; ").append(Joiner.on("; ").join(tags));
}
}
}
| src/main/java/com/nedap/archie/serializer/adl/constraints/CComplexObjectSerializer.java | /*
* ADL2-core
* Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com)
*
* This file is part of ADL2-core.
*
* ADL2-core 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 com.nedap.archie.serializer.adl.constraints;
import com.google.common.base.Joiner;
import com.nedap.archie.aom.*;
import com.nedap.archie.serializer.adl.ADLDefinitionSerializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.nedap.archie.serializer.adl.ArchetypeSerializeUtils.buildOccurrences;
/**
* @author Marko Pipan
*/
public class CComplexObjectSerializer<T extends CComplexObject> extends ConstraintSerializer<T> {
public CComplexObjectSerializer(ADLDefinitionSerializer serializer) {
super(serializer);
}
@Override
public void serialize(T cobj) {
builder.indent().newline();
builder.append(cobj.getRmTypeName());
if (cobj.getNodeId() != null) {
builder.append("[").append(cobj.getNodeId()).append("]");
}
builder.append(" ");
if (cobj.getOccurrences() != null) {
builder.append("occurrences matches {");
buildOccurrences(builder, cobj.getOccurrences());
builder.append("} ");
}
if (cobj.getAttributes().isEmpty() && cobj.getAttributeTuples().isEmpty()) {
builder.lineComment(serializer.getTermText(cobj));
} else {
builder.append("matches {");
builder.lineComment(serializer.getTermText(cobj));
buildAttributesAndTuples(cobj);
builder.append("}");
}
builder.unindent();
}
private void buildAttributesAndTuples(T cobj) {
builder.indent().newline();
Set<String> tupleAttributes = getTupleAttributeNames(cobj);
cobj.getAttributes().stream()
.filter(a -> !tupleAttributes.contains(a.getRmAttributeName()))
.forEach(this::buildAttribute);
cobj.getAttributeTuples().forEach(this::buildTuple);
builder.unindent().newline();
}
private Set<String> getTupleAttributeNames(T cobj) {
return cobj.getAttributeTuples().stream()
.flatMap(cat -> cat.getMembers().stream())
.map(CAttribute::getRmAttributeName)
.collect(Collectors.toSet());
}
private void buildAttribute(CAttribute cattr) {
builder.tryNewLine();
if (cattr.getRmAttributeName() != null) {
builder.append(cattr.getRmAttributeName());
} else {
builder.append(cattr.getDifferentialPath());
}
if (cattr.getExistence() != null) {
builder.append(" existence matches {");
buildOccurrences(builder, cattr.getExistence());
builder.append("}");
}
if (cattr.getCardinality() != null) {
builder.append(" cardinality matches {");
appendCardinality(cattr.getCardinality());
builder.append("}");
}
if (!cattr.getChildren().isEmpty()) {
builder.append(" matches ");
buildAttributeChildConstraints(cattr);
}
}
private void buildTuple(CAttributeTuple cAttributeTuple) {
builder.tryNewLine();
builder.append("[");
List<String> members = cAttributeTuple.getMembers().stream()
.map(CAttribute::getRmAttributeName)
.collect(Collectors.toList());
builder.append(Joiner.on(", ").join(members));
builder.append("] matches {");
builder.indent();
for (int i = 0; i < cAttributeTuple.getTuples().size(); i++) {
CPrimitiveTuple cObjectTuple = cAttributeTuple.getTuples().get(i);
builder.newline();
builder.append("[");
for (int j = 0; j < cObjectTuple.getMembers().size(); j++) {
builder.append("{");
serializer.appendCObject(cObjectTuple.getMembers().get(j));
builder.append("}");
if (j < cObjectTuple.getMembers().size() - 1) {
builder.append(", ");
}
}
builder.append("]");
if (i < cAttributeTuple.getTuples().size() - 1) {
builder.append(",");
}
}
builder.unindent().newline();
builder.append("}");
}
private void buildAttributeChildConstraints(CAttribute cattr) {
List<CObject> children = filterNonEmptyChildren(cattr.getChildren());
boolean indent = !children.isEmpty() &&
(children.size() > 1 || !(children.get(0) instanceof CPrimitiveObject));
builder.append("{");
children.forEach(serializer::appendCObject);
if (children.isEmpty()) {
builder.append("*");
}
if (indent) {
builder.newline();
}
builder.append("}");
if (!indent && !children.isEmpty()) {
String commentText = serializer.getSimpleCommentText(children.get(0));
if (commentText != null) {
builder.lineComment(commentText);
}
}
}
private List<CObject> filterNonEmptyChildren(List<CObject> children) {
return children.stream()
.filter(child -> !serializer.isEmpty(child))
.collect(Collectors.toList());
}
private void appendCardinality(Cardinality card) {
buildOccurrences(builder, card.getInterval());
List<String> tags = new ArrayList<>();
if (!card.isOrdered()) {
tags.add("unordered");
}
if (card.isUnique()) {
tags.add("unique");
}
if (!tags.isEmpty()) {
builder.append("; ").append(Joiner.on(", ").join(tags));
}
}
}
| Both unique and ordered in occurrences should be prepended by a ';', not a ','
| src/main/java/com/nedap/archie/serializer/adl/constraints/CComplexObjectSerializer.java | Both unique and ordered in occurrences should be prepended by a ';', not a ',' |
|
Java | apache-2.0 | e6bccbacbdd0628d36ee46beef5f076fde2c784e | 0 | google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.conscrypt;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
/**
* Supports SSL session caches.
*/
abstract class AbstractSessionContext implements SSLSessionContext {
/**
* Maximum lifetime of a session (in seconds) after which it's considered invalid and should not
* be used to for new connections.
*/
private static final int DEFAULT_SESSION_TIMEOUT_SECONDS = 8 * 60 * 60;
volatile int maximumSize;
volatile int timeout = DEFAULT_SESSION_TIMEOUT_SECONDS;
final long sslCtxNativePointer = NativeCrypto.SSL_CTX_new();
/** Identifies OpenSSL sessions. */
static final int OPEN_SSL = 1;
/** Identifies OpenSSL sessions with OCSP stapled data. */
static final int OPEN_SSL_WITH_OCSP = 2;
/** Identifies OpenSSL sessions with TLS SCT data. */
static final int OPEN_SSL_WITH_TLS_SCT = 3;
private final Map<ByteArray, SSLSession> sessions
= new LinkedHashMap<ByteArray, SSLSession>() {
@Override
protected boolean removeEldestEntry(
Map.Entry<ByteArray, SSLSession> eldest) {
boolean remove = maximumSize > 0 && size() > maximumSize;
if (remove) {
remove(eldest.getKey());
sessionRemoved(eldest.getValue());
}
return false;
}
};
/**
* Constructs a new session context.
*
* @param maximumSize of cache
*/
AbstractSessionContext(int maximumSize) {
this.maximumSize = maximumSize;
}
/**
* Returns the collection of sessions ordered from oldest to newest
*/
private Iterator<SSLSession> sessionIterator() {
synchronized (sessions) {
SSLSession[] array = sessions.values().toArray(
new SSLSession[sessions.size()]);
return Arrays.asList(array).iterator();
}
}
@Override
public final Enumeration<byte[]> getIds() {
final Iterator<SSLSession> i = sessionIterator();
return new Enumeration<byte[]>() {
private SSLSession next;
@Override
public boolean hasMoreElements() {
if (next != null) {
return true;
}
while (i.hasNext()) {
SSLSession session = i.next();
if (session.isValid()) {
next = session;
return true;
}
}
next = null;
return false;
}
@Override
public byte[] nextElement() {
if (hasMoreElements()) {
byte[] id = next.getId();
next = null;
return id;
}
throw new NoSuchElementException();
}
};
}
@Override
public final int getSessionCacheSize() {
return maximumSize;
}
@Override
public final int getSessionTimeout() {
return timeout;
}
/**
* Makes sure cache size is < maximumSize.
*/
protected void trimToSize() {
synchronized (sessions) {
int size = sessions.size();
if (size > maximumSize) {
int removals = size - maximumSize;
Iterator<SSLSession> i = sessions.values().iterator();
do {
SSLSession session = i.next();
i.remove();
sessionRemoved(session);
} while (--removals > 0);
}
}
}
@Override
public void setSessionTimeout(int seconds)
throws IllegalArgumentException {
if (seconds < 0) {
throw new IllegalArgumentException("seconds < 0");
}
timeout = seconds;
synchronized (sessions) {
Iterator<SSLSession> i = sessions.values().iterator();
while (i.hasNext()) {
SSLSession session = i.next();
// SSLSession's know their context and consult the
// timeout as part of their validity condition.
if (!session.isValid()) {
i.remove();
sessionRemoved(session);
}
}
}
}
/**
* Called when a session is removed. Used by ClientSessionContext
* to update its host-and-port based cache.
*/
protected abstract void sessionRemoved(SSLSession session);
@Override
public final void setSessionCacheSize(int size)
throws IllegalArgumentException {
if (size < 0) {
throw new IllegalArgumentException("size < 0");
}
int oldMaximum = maximumSize;
maximumSize = size;
// Trim cache to size if necessary.
if (size < oldMaximum) {
trimToSize();
}
}
/**
* Converts the given session to bytes.
*
* @return session data as bytes or null if the session can't be converted
*/
public byte[] toBytes(SSLSession session) {
// TODO: Support SSLSessionImpl, too.
if (!(session instanceof OpenSSLSessionImpl)) {
return null;
}
OpenSSLSessionImpl sslSession = (OpenSSLSessionImpl) session;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream daos = new DataOutputStream(baos);
daos.writeInt(OPEN_SSL_WITH_TLS_SCT); // session type ID
// Session data.
byte[] data = sslSession.getEncoded();
daos.writeInt(data.length);
daos.write(data);
// Certificates.
Certificate[] certs = session.getPeerCertificates();
daos.writeInt(certs.length);
for (Certificate cert : certs) {
data = cert.getEncoded();
daos.writeInt(data.length);
daos.write(data);
}
List<byte[]> ocspResponses = sslSession.getStatusResponses();
daos.writeInt(ocspResponses.size());
for (byte[] ocspResponse : ocspResponses) {
daos.writeInt(ocspResponse.length);
daos.write(ocspResponse);
}
byte[] tlsSctData = sslSession.getTlsSctData();
if (tlsSctData != null) {
daos.writeInt(tlsSctData.length);
daos.write(tlsSctData);
} else {
daos.writeInt(0);
}
// TODO: local certificates?
return baos.toByteArray();
} catch (IOException e) {
System.err.println("Failed to convert saved SSL Session: " + e.getMessage());
return null;
} catch (CertificateEncodingException e) {
log(e);
return null;
}
}
private static void checkRemaining(ByteBuffer buf, int length) throws IOException {
if (length < 0) {
throw new IOException("Length is negative: " + length);
}
if (length > buf.remaining()) {
throw new IOException(
"Length of blob is longer than available: " + length + " > " + buf.remaining());
}
}
/**
* Creates a session from the given bytes.
*
* @return a session or null if the session can't be converted
*/
public OpenSSLSessionImpl toSession(byte[] data, String host, int port) {
ByteBuffer buf = ByteBuffer.wrap(data);
try {
int type = buf.getInt();
if (type != OPEN_SSL && type != OPEN_SSL_WITH_OCSP && type != OPEN_SSL_WITH_TLS_SCT) {
throw new IOException("Unexpected type ID: " + type);
}
int length = buf.getInt();
checkRemaining(buf, length);
byte[] sessionData = new byte[length];
buf.get(sessionData);
int count = buf.getInt();
checkRemaining(buf, count);
X509Certificate[] certs = new X509Certificate[count];
for (int i = 0; i < count; i++) {
length = buf.getInt();
checkRemaining(buf, length);
byte[] certData = new byte[length];
buf.get(certData);
try {
certs[i] = OpenSSLX509Certificate.fromX509Der(certData);
} catch (Exception e) {
throw new IOException("Can not read certificate " + i + "/" + count);
}
}
byte[] ocspData = null;
if (type >= OPEN_SSL_WITH_OCSP) {
// We only support one OCSP response now, but in the future
// we may support RFC 6961 which has multiple.
int countOcspResponses = buf.getInt();
checkRemaining(buf, countOcspResponses);
if (countOcspResponses >= 1) {
int ocspLength = buf.getInt();
checkRemaining(buf, ocspLength);
ocspData = new byte[ocspLength];
buf.get(ocspData);
// Skip the rest of the responses.
for (int i = 1; i < countOcspResponses; i++) {
ocspLength = buf.getInt();
checkRemaining(buf, ocspLength);
buf.position(buf.position() + ocspLength);
}
}
}
byte[] tlsSctData = null;
if (type == OPEN_SSL_WITH_TLS_SCT) {
int tlsSctDataLength = buf.getInt();
checkRemaining(buf, tlsSctDataLength);
if (tlsSctDataLength > 0) {
tlsSctData = new byte[tlsSctDataLength];
buf.get(tlsSctData);
}
}
if (buf.remaining() != 0) {
log(new AssertionError("Read entire session, but data still remains; rejecting"));
return null;
}
return new OpenSSLSessionImpl(sessionData, host, port, certs, ocspData, tlsSctData,
this);
} catch (IOException e) {
log(e);
return null;
} catch (BufferUnderflowException e) {
log(e);
return null;
}
}
protected SSLSession wrapSSLSessionIfNeeded(SSLSession session) {
if (session instanceof AbstractOpenSSLSession) {
return Platform.wrapSSLSession((AbstractOpenSSLSession) session);
} else {
return session;
}
}
@Override
public SSLSession getSession(byte[] sessionId) {
if (sessionId == null) {
throw new NullPointerException("sessionId == null");
}
ByteArray key = new ByteArray(sessionId);
SSLSession session;
synchronized (sessions) {
session = sessions.get(key);
}
if (session != null && session.isValid()) {
return wrapSSLSessionIfNeeded(session);
}
return null;
}
void putSession(SSLSession session) {
byte[] id = session.getId();
if (id.length == 0) {
return;
}
ByteArray key = new ByteArray(id);
synchronized (sessions) {
sessions.put(key, session);
}
}
static void log(Throwable t) {
System.out.println("Error inflating SSL session: "
+ (t.getMessage() != null ? t.getMessage() : t.getClass().getName()));
}
@Override
protected void finalize() throws Throwable {
try {
NativeCrypto.SSL_CTX_free(sslCtxNativePointer);
} finally {
super.finalize();
}
}
}
| common/src/main/java/org/conscrypt/AbstractSessionContext.java | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.conscrypt;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
/**
* Supports SSL session caches.
*/
abstract class AbstractSessionContext implements SSLSessionContext {
/**
* Maximum lifetime of a session (in seconds) after which it's considered invalid and should not
* be used to for new connections.
*/
private static final int DEFAULT_SESSION_TIMEOUT_SECONDS = 8 * 60 * 60;
volatile int maximumSize;
volatile int timeout = DEFAULT_SESSION_TIMEOUT_SECONDS;
final long sslCtxNativePointer = NativeCrypto.SSL_CTX_new();
/** Identifies OpenSSL sessions. */
static final int OPEN_SSL = 1;
/** Identifies OpenSSL sessions with OCSP stapled data. */
static final int OPEN_SSL_WITH_OCSP = 2;
/** Identifies OpenSSL sessions with TLS SCT data. */
static final int OPEN_SSL_WITH_TLS_SCT = 3;
private final Map<ByteArray, SSLSession> sessions
= new LinkedHashMap<ByteArray, SSLSession>() {
@Override
protected boolean removeEldestEntry(
Map.Entry<ByteArray, SSLSession> eldest) {
boolean remove = maximumSize > 0 && size() > maximumSize;
if (remove) {
remove(eldest.getKey());
sessionRemoved(eldest.getValue());
}
return false;
}
};
/**
* Constructs a new session context.
*
* @param maximumSize of cache
*/
AbstractSessionContext(int maximumSize) {
this.maximumSize = maximumSize;
}
/**
* Returns the collection of sessions ordered from oldest to newest
*/
private Iterator<SSLSession> sessionIterator() {
synchronized (sessions) {
SSLSession[] array = sessions.values().toArray(
new SSLSession[sessions.size()]);
return Arrays.asList(array).iterator();
}
}
@Override
public final Enumeration<byte[]> getIds() {
final Iterator<SSLSession> i = sessionIterator();
return new Enumeration<byte[]>() {
private SSLSession next;
@Override
public boolean hasMoreElements() {
if (next != null) {
return true;
}
while (i.hasNext()) {
SSLSession session = i.next();
if (session.isValid()) {
next = session;
return true;
}
}
next = null;
return false;
}
@Override
public byte[] nextElement() {
if (hasMoreElements()) {
byte[] id = next.getId();
next = null;
return id;
}
throw new NoSuchElementException();
}
};
}
@Override
public final int getSessionCacheSize() {
return maximumSize;
}
@Override
public final int getSessionTimeout() {
return timeout;
}
/**
* Makes sure cache size is < maximumSize.
*/
protected void trimToSize() {
synchronized (sessions) {
int size = sessions.size();
if (size > maximumSize) {
int removals = size - maximumSize;
Iterator<SSLSession> i = sessions.values().iterator();
do {
SSLSession session = i.next();
i.remove();
sessionRemoved(session);
} while (--removals > 0);
}
}
}
@Override
public void setSessionTimeout(int seconds)
throws IllegalArgumentException {
if (seconds < 0) {
throw new IllegalArgumentException("seconds < 0");
}
timeout = seconds;
synchronized (sessions) {
Iterator<SSLSession> i = sessions.values().iterator();
while (i.hasNext()) {
SSLSession session = i.next();
// SSLSession's know their context and consult the
// timeout as part of their validity condition.
if (!session.isValid()) {
i.remove();
sessionRemoved(session);
}
}
}
}
/**
* Called when a session is removed. Used by ClientSessionContext
* to update its host-and-port based cache.
*/
protected abstract void sessionRemoved(SSLSession session);
@Override
public final void setSessionCacheSize(int size)
throws IllegalArgumentException {
if (size < 0) {
throw new IllegalArgumentException("size < 0");
}
int oldMaximum = maximumSize;
maximumSize = size;
// Trim cache to size if necessary.
if (size < oldMaximum) {
trimToSize();
}
}
/**
* Converts the given session to bytes.
*
* @return session data as bytes or null if the session can't be converted
*/
byte[] toBytes(SSLSession session) {
// TODO: Support SSLSessionImpl, too.
if (!(session instanceof OpenSSLSessionImpl)) {
return null;
}
OpenSSLSessionImpl sslSession = (OpenSSLSessionImpl) session;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream daos = new DataOutputStream(baos);
daos.writeInt(OPEN_SSL_WITH_TLS_SCT); // session type ID
// Session data.
byte[] data = sslSession.getEncoded();
daos.writeInt(data.length);
daos.write(data);
// Certificates.
Certificate[] certs = session.getPeerCertificates();
daos.writeInt(certs.length);
for (Certificate cert : certs) {
data = cert.getEncoded();
daos.writeInt(data.length);
daos.write(data);
}
List<byte[]> ocspResponses = sslSession.getStatusResponses();
daos.writeInt(ocspResponses.size());
for (byte[] ocspResponse : ocspResponses) {
daos.writeInt(ocspResponse.length);
daos.write(ocspResponse);
}
byte[] tlsSctData = sslSession.getTlsSctData();
if (tlsSctData != null) {
daos.writeInt(tlsSctData.length);
daos.write(tlsSctData);
} else {
daos.writeInt(0);
}
// TODO: local certificates?
return baos.toByteArray();
} catch (IOException e) {
System.err.println("Failed to convert saved SSL Session: " + e.getMessage());
return null;
} catch (CertificateEncodingException e) {
log(e);
return null;
}
}
private static void checkRemaining(ByteBuffer buf, int length) throws IOException {
if (length < 0) {
throw new IOException("Length is negative: " + length);
}
if (length > buf.remaining()) {
throw new IOException(
"Length of blob is longer than available: " + length + " > " + buf.remaining());
}
}
/**
* Creates a session from the given bytes.
*
* @return a session or null if the session can't be converted
*/
public OpenSSLSessionImpl toSession(byte[] data, String host, int port) {
ByteBuffer buf = ByteBuffer.wrap(data);
try {
int type = buf.getInt();
if (type != OPEN_SSL && type != OPEN_SSL_WITH_OCSP && type != OPEN_SSL_WITH_TLS_SCT) {
throw new IOException("Unexpected type ID: " + type);
}
int length = buf.getInt();
checkRemaining(buf, length);
byte[] sessionData = new byte[length];
buf.get(sessionData);
int count = buf.getInt();
checkRemaining(buf, count);
X509Certificate[] certs = new X509Certificate[count];
for (int i = 0; i < count; i++) {
length = buf.getInt();
checkRemaining(buf, length);
byte[] certData = new byte[length];
buf.get(certData);
try {
certs[i] = OpenSSLX509Certificate.fromX509Der(certData);
} catch (Exception e) {
throw new IOException("Can not read certificate " + i + "/" + count);
}
}
byte[] ocspData = null;
if (type >= OPEN_SSL_WITH_OCSP) {
// We only support one OCSP response now, but in the future
// we may support RFC 6961 which has multiple.
int countOcspResponses = buf.getInt();
checkRemaining(buf, countOcspResponses);
if (countOcspResponses >= 1) {
int ocspLength = buf.getInt();
checkRemaining(buf, ocspLength);
ocspData = new byte[ocspLength];
buf.get(ocspData);
// Skip the rest of the responses.
for (int i = 1; i < countOcspResponses; i++) {
ocspLength = buf.getInt();
checkRemaining(buf, ocspLength);
buf.position(buf.position() + ocspLength);
}
}
}
byte[] tlsSctData = null;
if (type == OPEN_SSL_WITH_TLS_SCT) {
int tlsSctDataLength = buf.getInt();
checkRemaining(buf, tlsSctDataLength);
if (tlsSctDataLength > 0) {
tlsSctData = new byte[tlsSctDataLength];
buf.get(tlsSctData);
}
}
if (buf.remaining() != 0) {
log(new AssertionError("Read entire session, but data still remains; rejecting"));
return null;
}
return new OpenSSLSessionImpl(sessionData, host, port, certs, ocspData, tlsSctData,
this);
} catch (IOException e) {
log(e);
return null;
} catch (BufferUnderflowException e) {
log(e);
return null;
}
}
protected SSLSession wrapSSLSessionIfNeeded(SSLSession session) {
if (session instanceof AbstractOpenSSLSession) {
return Platform.wrapSSLSession((AbstractOpenSSLSession) session);
} else {
return session;
}
}
@Override
public SSLSession getSession(byte[] sessionId) {
if (sessionId == null) {
throw new NullPointerException("sessionId == null");
}
ByteArray key = new ByteArray(sessionId);
SSLSession session;
synchronized (sessions) {
session = sessions.get(key);
}
if (session != null && session.isValid()) {
return wrapSSLSessionIfNeeded(session);
}
return null;
}
void putSession(SSLSession session) {
byte[] id = session.getId();
if (id.length == 0) {
return;
}
ByteArray key = new ByteArray(id);
synchronized (sessions) {
sessions.put(key, session);
}
}
static void log(Throwable t) {
System.out.println("Error inflating SSL session: "
+ (t.getMessage() != null ? t.getMessage() : t.getClass().getName()));
}
@Override
protected void finalize() throws Throwable {
try {
NativeCrypto.SSL_CTX_free(sslCtxNativePointer);
} finally {
super.finalize();
}
}
}
| Fix AbstractSessionContextTest for CTS running (#71)
Make the AbstractSessionContext#toBytes public for testing.
Change-Id: I4a3698108cda6f868f62349a5eac693c08595f40 | common/src/main/java/org/conscrypt/AbstractSessionContext.java | Fix AbstractSessionContextTest for CTS running (#71) |
|
Java | apache-2.0 | 8871fbde36b6462bb203433391cce05d7d0c82d0 | 0 | real-comp/prime | package com.realcomp.data.schema;
import com.realcomp.data.MultiFieldOperation;
import com.realcomp.data.Operation;
import com.realcomp.data.record.Record;
import com.realcomp.data.record.reader.RecordReader;
import com.realcomp.data.record.writer.RecordWriter;
import com.realcomp.data.schema.xml.RecordReaderConverter;
import com.realcomp.data.schema.xml.RecordWriterConverter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
/**
*
* @author krenfro
*/
@XStreamAlias("file-schema")
public class FileSchema {
protected static final Logger logger = Logger.getLogger(FileSchema.class.getName());
@XStreamAsAttribute
protected String name;
@XStreamAsAttribute
protected String version;
@XStreamConverter(RecordReaderConverter.class)
protected RecordReader reader;
@XStreamConverter(RecordWriterConverter.class)
protected RecordWriter writer;
protected List<Operation> beforeFirst;
protected List<Operation> before;
protected List<Operation> after;
protected List<Operation> afterLast;
protected List<SchemaField> fields;
@XStreamImplicit
protected List<Classifier> classifiers;
public FileSchema(){
fields = new ArrayList<SchemaField>();
classifiers = new ArrayList<Classifier>();
}
public FileSchema(FileSchema copy) throws SchemaException{
fields = new ArrayList<SchemaField>();
classifiers = new ArrayList<Classifier>();
this.name = copy.name;
this.version = copy.version;
setFields(copy.getFields());
setClassifiers(copy.getClassifiers());
setBeforeFirstOperations(copy.getBeforeFirstOperations());
setBeforeOperations(copy.getBeforeOperations());
setAfterLastOperations(copy.getAfterLastOperations());
setAfterOperations(copy.getAfterOperations());
}
public RecordReader getReader() throws SchemaException{
if (reader != null)
reader.setSchema(this);
return reader;
}
public void setReader(RecordReader reader) throws SchemaException{
if (reader == null)
throw new IllegalArgumentException("reader is null");
this.reader = reader;
this.reader.setSchema(this);
}
public RecordWriter getWriter() throws SchemaException{
if (writer != null)
writer.setSchema(this);
return writer;
}
public void setWriter(RecordWriter writer) throws SchemaException{
if (writer == null)
throw new IllegalArgumentException("writer is null");
this.writer = writer;
this.writer.setSchema(this);
}
public List<Classifier> getClassifiers() {
if (classifiers == null)
classifiers = new ArrayList<Classifier>();
return classifiers;
}
public void setClassifiers(List<Classifier> classifiers) throws SchemaException{
if (classifiers == null)
throw new IllegalArgumentException("classifiers is null");
this.classifiers.clear();
for (Classifier c: classifiers)
addClassifier(c);
}
public void addClassifier(Classifier classifier) throws SchemaException{
if (classifier == null)
throw new IllegalArgumentException("classifier is null");
if (classifier.getFields() == null)
throw new SchemaException("no fields specified for the classifier");
if (classifier.getFields().isEmpty())
throw new SchemaException("no fields specified for the classifier");
classifiers.add(classifier);
}
/**
* Classify some data and return the List of SchemaFields that should be used to parse the data.
* If no classifiers have been specified, or there is not a classifier match, the
* default Field list is returned.
*
* @param data not null
* @return the List of SchemaFields that should be used to parse the data.
*/
public List<SchemaField> classify(String data){
if (data == null)
throw new IllegalArgumentException("data is null");
for (Classifier c: classifiers){
if (c.supports(data))
return c.getFields();
}
return fields;
}
/**
* Classify a record and return the layout (List of SchemaFields) that match.
* If multiple SchemaFields are defined that contain Fields named in the Record,
* then the layout defined first in the Schema will be returned.
*
* @param record
* @return
* @throws SchemaException if no defined layout supports the Record
*/
public List<SchemaField> classify(Record record) throws SchemaException{
if (record == null)
throw new IllegalArgumentException("record is null");
List<SchemaField> result = null;
for (Classifier c: classifiers){
if (c.supports(record)){
if (result == null)
result = c.getFields();
else if (result.size() < c.getFields().size())
result = c.getFields();
}
}
if (result == null){
Classifier defaultClassifier = new Classifier();
defaultClassifier.setFields(fields);
if (defaultClassifier.supports(record))
result = fields;
}
if (result == null)
throw new SchemaException("Unable to find layout that supports Record: " + record);
return result;
}
public SchemaField getField(String name){
if (name == null)
throw new IllegalArgumentException("name is null");
for (SchemaField field: fields)
if (field.getName().equals(name))
return field;
return null;
}
/**
*
* @return all SchemaFields defined for this Schema
*/
public List<SchemaField> getFields() {
return fields;
}
/**
* @param fields not null nor empty.
* @throws SchemaException if there is already a field with the same name as one of the fields
*/
public void setFields(List<SchemaField> fields) throws SchemaException{
if (fields == null)
throw new IllegalArgumentException("fields is null");
if (fields.isEmpty())
throw new IllegalArgumentException("fields is empty");
this.fields.clear();
for (SchemaField field: fields)
addField(field);
}
/**
* Add a field to the schema
* @param field
* @throws SchemaException if there is already a field with the same name
*/
public void addField(SchemaField field) throws SchemaException{
if (field == null)
throw new IllegalArgumentException("field is null");
verifyUniqueName(field.getName());
fields.add(new SchemaField(field));
}
protected void verifyUniqueName(String name) throws SchemaException{
if (name == null)
throw new IllegalArgumentException("name is null");
for (SchemaField existing: fields)
if (name.equals(existing.getName()))
throw new SchemaException(
String.format(
"A field with name [%s] is already defined in schema [%s].",
name,
this.toString()));
}
/**
*
* @return optional name for this schema, or null
*/
public String getName() {
return name;
}
/**
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return all Operations to perform on all fields after fields specific operations are
* finished, or null if none specified.
*
*/
public List<Operation> getAfterOperations() {
return after;
}
/**
* Set all Operations to perform on all fields after all field specific operations are finished.
* @param after null will clear existing list
*/
public void setAfterOperations(List<Operation> after) {
if (after == null){
this.after = null;
}
else{
if (this.after != null)
this.after.clear();
for (Operation op: after)
addAfterOperation(op);
}
}
/**
* Add an Operation to the after operations group, to be run after all field specific
* Operations are performed.
* @param op not null
*/
public void addAfterOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (after == null)
after = new ArrayList<Operation>();
this.after.add(op);
}
/**
* @return all Operations to perform after all records have been processed, or null
* if none specified.
*
*/
public List<Operation> getAfterLastOperations() {
return afterLast;
}
/**
* Set all Operations to perform after all records have been processed.
* @param afterLast null will clear existing list
*/
public void setAfterLastOperations(List<Operation> afterLast) {
if (afterLast == null){
this.afterLast = null;
}
else{
if (this.afterLast != null)
this.afterLast.clear();
for (Operation op: afterLast)
addAfterOperation(op);
}
}
/**
* Add an Operation to the afterLast operations group, to be run after all records
* have been processed.
* @param op not null
*/
public void addAfterLastOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (afterLast == null)
afterLast = new ArrayList<Operation>();
this.afterLast.add(op);
}
/**
*
* @return all Operations to perform on all fields before any field specific Operations are
* performed, or null if none specified.
*/
public List<Operation> getBeforeOperations() {
return before;
}
/**
* Set all Operations to perform on all fields before any field specific Operations are
* performed.
* @param before null will clear list
*/
public void setBeforeOperations(List<Operation> before) {
if (before == null){
this.before = null;
}
else{
if (this.before != null)
this.before.clear();
for (Operation op: before)
addBeforeOperation(op);
}
}
/**
* Add an Operation to the before operations group, to be run before all field specific
* Operations are performed.
* @param op not null, not a MultiFieldOperation
*/
public void addBeforeOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (op instanceof MultiFieldOperation)
throw new IllegalArgumentException(
"You cannot specify a MultiFieldOperation as a 'before' operation");
if (before == null)
before = new ArrayList<Operation>();
this.before.add(op);
}
/**
*
* @return all Operations to perform before any records are processed, or null
* if none specified.
*/
public List<Operation> getBeforeFirstOperations() {
return beforeFirst;
}
/**
* Set all Operations to perform before any records are processed.
* @param beforeFirst null will clear list
*/
public void setBeforeFirstOperations(List<Operation> beforeFirst) {
if (beforeFirst == null){
this.beforeFirst = null;
}
else{
if (this.beforeFirst != null)
this.beforeFirst.clear();
for (Operation op: beforeFirst)
addBeforeFirstOperation(op);
}
}
/**
* Add an Operation to the beforeFirst operations group, to be run before any records
* are processed.
* @param op not null, not a MultiFieldOperation
*/
public void addBeforeFirstOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (op instanceof MultiFieldOperation)
throw new IllegalArgumentException(
"You cannot specify a MultiFieldOperation as a 'beforeFirst' operation");
if (beforeFirst == null)
beforeFirst = new ArrayList<Operation>();
this.beforeFirst.add(op);
}
/**
* @return optional version for this Schema, or null.
*/
public String getVersion() {
return version;
}
/**
* @param version
*/
public void setVersion(String version) {
this.version = version;
}
public boolean isKeyField(SchemaField field){
for (Operation op: field.getOperations()){
if (op instanceof com.realcomp.data.validation.field.Key)
return true;
}
return false;
}
public boolean isForeignKeyField(SchemaField field){
for (Operation op: field.getOperations()){
if (op instanceof com.realcomp.data.validation.field.ForeignKey)
return true;
}
return false;
}
/**
*
* @return all 'key' SchemaFields, in the order defined by this FileSchema
*/
public List<SchemaField> getKeyFields(){
List<SchemaField> keyFields = new ArrayList<SchemaField>();
for (SchemaField f: fields){
if (isKeyField(f))
keyFields.add(f);
}
return keyFields;
}
/**
*
* @return all 'foreign key' SchemaFields, in the order defined by this FileSchema
*/
public List<SchemaField> getForeignKeyFields(){
List<SchemaField> foreignKeyFields = new ArrayList<SchemaField>();
for (SchemaField f: fields){
if (isForeignKeyField(f))
foreignKeyFields.add(f);
}
return foreignKeyFields;
}
/**
* List of Strings pulled from Fields in a Record that are marked as 'Keys'.
*
* @param record not null
* @return list of Key fields, as Strings, from the specified record.
*/
public List<String> getKeys(Record record){
List<String> key = new ArrayList<String>();
for (SchemaField f: getKeyFields()){
Object value = record.get(f.getName());
//Note: a key value may be NULL if the Record is not fully constructed.
//For example, if a ValidationException is thrown during Record creation, the
//Record creator may try to construct a helpful message using schema.toString(record).
if (value != null)
key.add(value.toString());
}
return key;
}
/**
* A superior Record.toString() that uses this schema's knowledge of the Record to
* output a pipe "|" delimited string of the Record's keys, in the order defined
* in the schema.
*
* If no keys are defined in the schema, then return Record.toString().
*
* @see Record#toString()
* @param record
* @return Pipe delimited String of the Record's keys
*/
public String toString(Record record){
List<String> keys = getKeys(record);
String retVal = null;
if (keys.isEmpty()){
try {
StringBuilder s = new StringBuilder();
List<SchemaField> fields = classify(record);
boolean needDelimiter = false;
for (SchemaField field: classify(record)){
if (needDelimiter)
s.append("|");
needDelimiter = true;
s.append(record.get(field.getName()));
}
retVal = s.toString();
}
catch (SchemaException ex) {
retVal = record.toString(); //this shouldn't happen.
}
}
else{
retVal = StringUtils.join(keys, "|");
}
return retVal;
}
@Override
public String toString(){
StringBuilder s = new StringBuilder(name);
if (version != null && !version.isEmpty())
s.append(" (").append(version).append(")");
return s.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FileSchema other = (FileSchema) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name))
return false;
if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version))
return false;
if (this.reader != other.reader && (this.reader == null || !this.reader.equals(other.reader)))
return false;
if (this.writer != other.writer && (this.writer == null || !this.writer.equals(other.writer)))
return false;
if (this.beforeFirst != other.beforeFirst && (this.beforeFirst == null || !this.beforeFirst.equals(other.beforeFirst)))
return false;
if (this.before != other.before && (this.before == null || !this.before.equals(other.before)))
return false;
if (this.after != other.after && (this.after == null || !this.after.equals(other.after)))
return false;
if (this.afterLast != other.afterLast && (this.afterLast == null || !this.afterLast.equals(other.afterLast)))
return false;
if (this.fields != other.fields && (this.fields == null || !this.fields.equals(other.fields)))
return false;
if (this.classifiers != other.classifiers && (this.classifiers == null || !this.classifiers.equals(other.classifiers)))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 19 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 19 * hash + (this.version != null ? this.version.hashCode() : 0);
hash = 19 * hash + (this.reader != null ? this.reader.hashCode() : 0);
hash = 19 * hash + (this.writer != null ? this.writer.hashCode() : 0);
hash = 19 * hash + (this.beforeFirst != null ? this.beforeFirst.hashCode() : 0);
hash = 19 * hash + (this.before != null ? this.before.hashCode() : 0);
hash = 19 * hash + (this.after != null ? this.after.hashCode() : 0);
hash = 19 * hash + (this.afterLast != null ? this.afterLast.hashCode() : 0);
hash = 19 * hash + (this.fields != null ? this.fields.hashCode() : 0);
hash = 19 * hash + (this.classifiers != null ? this.classifiers.hashCode() : 0);
return hash;
}
}
| src/main/java/com/realcomp/data/schema/FileSchema.java | package com.realcomp.data.schema;
import com.realcomp.data.MultiFieldOperation;
import com.realcomp.data.Operation;
import com.realcomp.data.record.Record;
import com.realcomp.data.record.reader.RecordReader;
import com.realcomp.data.record.writer.RecordWriter;
import com.realcomp.data.schema.xml.RecordReaderConverter;
import com.realcomp.data.schema.xml.RecordWriterConverter;
import com.realcomp.data.validation.ValidationException;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
/**
*
* @author krenfro
*/
@XStreamAlias("file-schema")
public class FileSchema {
protected static final Logger logger = Logger.getLogger(FileSchema.class.getName());
@XStreamAsAttribute
protected String name;
@XStreamAsAttribute
protected String version;
@XStreamConverter(RecordReaderConverter.class)
protected RecordReader reader;
@XStreamConverter(RecordWriterConverter.class)
protected RecordWriter writer;
protected List<Operation> beforeFirst;
protected List<Operation> before;
protected List<Operation> after;
protected List<Operation> afterLast;
protected List<SchemaField> fields;
@XStreamImplicit
protected List<Classifier> classifiers;
public FileSchema(){
fields = new ArrayList<SchemaField>();
classifiers = new ArrayList<Classifier>();
}
public FileSchema(FileSchema copy) throws SchemaException{
fields = new ArrayList<SchemaField>();
classifiers = new ArrayList<Classifier>();
this.name = copy.name;
this.version = copy.version;
setFields(copy.getFields());
setClassifiers(copy.getClassifiers());
setBeforeFirstOperations(copy.getBeforeFirstOperations());
setBeforeOperations(copy.getBeforeOperations());
setAfterLastOperations(copy.getAfterLastOperations());
setAfterOperations(copy.getAfterOperations());
}
public RecordReader getReader() throws SchemaException{
if (reader != null)
reader.setSchema(this);
return reader;
}
public void setReader(RecordReader reader) throws SchemaException{
if (reader == null)
throw new IllegalArgumentException("reader is null");
this.reader = reader;
this.reader.setSchema(this);
}
public RecordWriter getWriter() throws SchemaException{
if (writer != null)
writer.setSchema(this);
return writer;
}
public void setWriter(RecordWriter writer) throws SchemaException{
if (writer == null)
throw new IllegalArgumentException("writer is null");
this.writer = writer;
this.writer.setSchema(this);
}
public List<Classifier> getClassifiers() {
if (classifiers == null)
classifiers = new ArrayList<Classifier>();
return classifiers;
}
public void setClassifiers(List<Classifier> classifiers) throws SchemaException{
if (classifiers == null)
throw new IllegalArgumentException("classifiers is null");
this.classifiers.clear();
for (Classifier c: classifiers)
addClassifier(c);
}
public void addClassifier(Classifier classifier) throws SchemaException{
if (classifier == null)
throw new IllegalArgumentException("classifier is null");
if (classifier.getFields() == null)
throw new SchemaException("no fields specified for the classifier");
if (classifier.getFields().isEmpty())
throw new SchemaException("no fields specified for the classifier");
classifiers.add(classifier);
}
/**
* Classify some data and return the List of SchemaFields that should be used to parse the data.
* If no classifiers have been specified, or there is not a classifier match, the
* default Field list is returned.
*
* @param data not null
* @return the List of SchemaFields that should be used to parse the data.
*/
public List<SchemaField> classify(String data){
if (data == null)
throw new IllegalArgumentException("data is null");
for (Classifier c: classifiers){
if (c.supports(data))
return c.getFields();
}
return fields;
}
/**
* Classify a record and return the layout (List of SchemaFields) that match.
* If multiple SchemaFields are defined that contain Fields named in the Record,
* then the layout defined first in the Schema will be returned.
*
* @param record
* @return
* @throws SchemaException if no defined layout supports the Record
*/
public List<SchemaField> classify(Record record) throws SchemaException{
if (record == null)
throw new IllegalArgumentException("record is null");
List<SchemaField> result = null;
for (Classifier c: classifiers){
if (c.supports(record)){
if (result == null)
result = c.getFields();
else if (result.size() < c.getFields().size())
result = c.getFields();
}
}
if (result == null){
Classifier defaultClassifier = new Classifier();
defaultClassifier.setFields(fields);
if (defaultClassifier.supports(record))
result = fields;
}
if (result == null)
throw new SchemaException("Unable to find layout that supports Record: " + record);
return result;
}
public SchemaField getField(String name){
if (name == null)
throw new IllegalArgumentException("name is null");
for (SchemaField field: fields)
if (field.getName().equals(name))
return field;
return null;
}
/**
*
* @return all SchemaFields defined for this Schema
*/
public List<SchemaField> getFields() {
return fields;
}
/**
* @param fields not null nor empty.
* @throws SchemaException if there is already a field with the same name as one of the fields
*/
public void setFields(List<SchemaField> fields) throws SchemaException{
if (fields == null)
throw new IllegalArgumentException("fields is null");
if (fields.isEmpty())
throw new IllegalArgumentException("fields is empty");
this.fields.clear();
for (SchemaField field: fields)
addField(field);
}
/**
* Add a field to the schema
* @param field
* @throws SchemaException if there is already a field with the same name
*/
public void addField(SchemaField field) throws SchemaException{
if (field == null)
throw new IllegalArgumentException("field is null");
verifyUniqueName(field.getName());
fields.add(new SchemaField(field));
}
protected void verifyUniqueName(String name) throws SchemaException{
if (name == null)
throw new IllegalArgumentException("name is null");
for (SchemaField existing: fields)
if (name.equals(existing.getName()))
throw new SchemaException(
String.format(
"A field with name [%s] is already defined in schema [%s].",
name,
this.toString()));
}
/**
*
* @return optional name for this schema, or null
*/
public String getName() {
return name;
}
/**
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return all Operations to perform on all fields after fields specific operations are
* finished, or null if none specified.
*
*/
public List<Operation> getAfterOperations() {
return after;
}
/**
* Set all Operations to perform on all fields after all field specific operations are finished.
* @param after null will clear existing list
*/
public void setAfterOperations(List<Operation> after) {
if (after == null){
this.after = null;
}
else{
if (this.after != null)
this.after.clear();
for (Operation op: after)
addAfterOperation(op);
}
}
/**
* Add an Operation to the after operations group, to be run after all field specific
* Operations are performed.
* @param op not null
*/
public void addAfterOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (after == null)
after = new ArrayList<Operation>();
this.after.add(op);
}
/**
* @return all Operations to perform after all records have been processed, or null
* if none specified.
*
*/
public List<Operation> getAfterLastOperations() {
return afterLast;
}
/**
* Set all Operations to perform after all records have been processed.
* @param afterLast null will clear existing list
*/
public void setAfterLastOperations(List<Operation> afterLast) {
if (afterLast == null){
this.afterLast = null;
}
else{
if (this.afterLast != null)
this.afterLast.clear();
for (Operation op: afterLast)
addAfterOperation(op);
}
}
/**
* Add an Operation to the afterLast operations group, to be run after all records
* have been processed.
* @param op not null
*/
public void addAfterLastOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (afterLast == null)
afterLast = new ArrayList<Operation>();
this.afterLast.add(op);
}
/**
*
* @return all Operations to perform on all fields before any field specific Operations are
* performed, or null if none specified.
*/
public List<Operation> getBeforeOperations() {
return before;
}
/**
* Set all Operations to perform on all fields before any field specific Operations are
* performed.
* @param before null will clear list
*/
public void setBeforeOperations(List<Operation> before) {
if (before == null){
this.before = null;
}
else{
if (this.before != null)
this.before.clear();
for (Operation op: before)
addBeforeOperation(op);
}
}
/**
* Add an Operation to the before operations group, to be run before all field specific
* Operations are performed.
* @param op not null, not a MultiFieldOperation
*/
public void addBeforeOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (op instanceof MultiFieldOperation)
throw new IllegalArgumentException(
"You cannot specify a MultiFieldOperation as a 'before' operation");
if (before == null)
before = new ArrayList<Operation>();
this.before.add(op);
}
/**
*
* @return all Operations to perform before any records are processed, or null
* if none specified.
*/
public List<Operation> getBeforeFirstOperations() {
return beforeFirst;
}
/**
* Set all Operations to perform before any records are processed.
* @param beforeFirst null will clear list
*/
public void setBeforeFirstOperations(List<Operation> beforeFirst) {
if (beforeFirst == null){
this.beforeFirst = null;
}
else{
if (this.beforeFirst != null)
this.beforeFirst.clear();
for (Operation op: beforeFirst)
addBeforeFirstOperation(op);
}
}
/**
* Add an Operation to the beforeFirst operations group, to be run before any records
* are processed.
* @param op not null, not a MultiFieldOperation
*/
public void addBeforeFirstOperation(Operation op){
if (op == null)
throw new IllegalArgumentException("op is null");
if (op instanceof MultiFieldOperation)
throw new IllegalArgumentException(
"You cannot specify a MultiFieldOperation as a 'beforeFirst' operation");
if (beforeFirst == null)
beforeFirst = new ArrayList<Operation>();
this.beforeFirst.add(op);
}
/**
* @return optional version for this Schema, or null.
*/
public String getVersion() {
return version;
}
/**
* @param version
*/
public void setVersion(String version) {
this.version = version;
}
public boolean isKeyField(SchemaField field){
for (Operation op: field.getOperations()){
if (op instanceof com.realcomp.data.validation.field.Key)
return true;
}
return false;
}
public boolean isForeignKeyField(SchemaField field){
for (Operation op: field.getOperations()){
if (op instanceof com.realcomp.data.validation.field.ForeignKey)
return true;
}
return false;
}
/**
*
* @return all 'key' SchemaFields, in the order defined by this FileSchema
*/
public List<SchemaField> getKeyFields(){
List<SchemaField> keyFields = new ArrayList<SchemaField>();
for (SchemaField f: fields){
if (isKeyField(f))
keyFields.add(f);
}
return keyFields;
}
/**
*
* @return all 'foreign key' SchemaFields, in the order defined by this FileSchema
*/
public List<SchemaField> getForeignKeyFields(){
List<SchemaField> foreignKeyFields = new ArrayList<SchemaField>();
for (SchemaField f: fields){
if (isForeignKeyField(f))
foreignKeyFields.add(f);
}
return foreignKeyFields;
}
/**
* List of Strings pulled from Fields in a Record that are marked as 'Keys'.
*
* @param record not null
* @return list of Key fields, as Strings, from the specified record.
*/
public List<String> getKeys(Record record){
List<String> key = new ArrayList<String>();
for (SchemaField f: getKeyFields()){
Object value = record.get(f.getName());
//Note: a key value may be NULL if the Record is not fully constructed.
//For example, if a ValidationException is thrown during Record creation, the
//Record creator may try to construct a helpful message using schema.toString(record).
if (value != null)
key.add(value.toString());
}
return key;
}
/**
* A superior Record.toString() that uses this schema's knowledge of the Record to
* output a pipe "|" delimited string of the Record's keys, in the order defined
* in the schema.
*
* If no keys are defined in the schema, then return Record.toString().
*
* @see Record#toString()
* @param record
* @return Pipe delimited String of the Record's keys
*/
public String toString(Record record){
List<String> keys = getKeys(record);
return keys.isEmpty() ? record.toString() : StringUtils.join(keys, "|");
}
@Override
public String toString(){
StringBuilder s = new StringBuilder(name);
if (version != null && !version.isEmpty())
s.append(" (").append(version).append(")");
return s.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FileSchema other = (FileSchema) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name))
return false;
if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version))
return false;
if (this.reader != other.reader && (this.reader == null || !this.reader.equals(other.reader)))
return false;
if (this.writer != other.writer && (this.writer == null || !this.writer.equals(other.writer)))
return false;
if (this.beforeFirst != other.beforeFirst && (this.beforeFirst == null || !this.beforeFirst.equals(other.beforeFirst)))
return false;
if (this.before != other.before && (this.before == null || !this.before.equals(other.before)))
return false;
if (this.after != other.after && (this.after == null || !this.after.equals(other.after)))
return false;
if (this.afterLast != other.afterLast && (this.afterLast == null || !this.afterLast.equals(other.afterLast)))
return false;
if (this.fields != other.fields && (this.fields == null || !this.fields.equals(other.fields)))
return false;
if (this.classifiers != other.classifiers && (this.classifiers == null || !this.classifiers.equals(other.classifiers)))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 19 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 19 * hash + (this.version != null ? this.version.hashCode() : 0);
hash = 19 * hash + (this.reader != null ? this.reader.hashCode() : 0);
hash = 19 * hash + (this.writer != null ? this.writer.hashCode() : 0);
hash = 19 * hash + (this.beforeFirst != null ? this.beforeFirst.hashCode() : 0);
hash = 19 * hash + (this.before != null ? this.before.hashCode() : 0);
hash = 19 * hash + (this.after != null ? this.after.hashCode() : 0);
hash = 19 * hash + (this.afterLast != null ? this.afterLast.hashCode() : 0);
hash = 19 * hash + (this.fields != null ? this.fields.hashCode() : 0);
hash = 19 * hash + (this.classifiers != null ? this.classifiers.hashCode() : 0);
return hash;
}
}
| Improved toString(Record) method to print the fields in the order defined by the schema if no 'key' fields are provided.
git-svn-id: 6eb46abda3d72486edc10a922244fdfbbb521eb9@2121 cb9be8fc-bb24-4f4f-8dc9-9fc556ea96d8
| src/main/java/com/realcomp/data/schema/FileSchema.java | Improved toString(Record) method to print the fields in the order defined by the schema if no 'key' fields are provided. |
|
Java | apache-2.0 | c780bf4f748031b0e729b8323c972bf56122e4fd | 0 | stevespringett/dependency-track,stevespringett/dependency-track,stevespringett/dependency-track | /*
* This file is part of Dependency-Track.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package org.dependencytrack.model;
import alpine.json.TrimmedStringDeserializer;
import alpine.validation.RegexSequence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.github.packageurl.PackageURL;
import org.apache.commons.lang3.StringUtils;
import org.dependencytrack.persistence.PackageURLStringConverter;
import org.dependencytrack.resources.v1.serializers.CustomPackageURLSerializer;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Convert;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.FetchGroup;
import javax.jdo.annotations.FetchGroups;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.Order;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
/**
* Model class for tracking individual components.
*
* @author Steve Springett
* @since 3.0.0
*/
@PersistenceCapable
@FetchGroups({
@FetchGroup(name = "ALL", members = {
@Persistent(name = "resolvedLicense"),
@Persistent(name = "parent"),
@Persistent(name = "children"),
@Persistent(name = "scans"),
@Persistent(name = "boms"),
@Persistent(name = "vulnerabilities"),
})
})
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Component implements Serializable {
private static final long serialVersionUID = 6841650046433674702L;
/**
* Defines JDO fetch groups for this class.
*/
public enum FetchGroup {
ALL
}
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
@JsonIgnore
private long id;
@Persistent
@Column(name = "GROUP", jdbcType = "VARCHAR")
@Index(name = "COMPONENT_GROUP_IDX")
@Size(max = 255)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The group may only contain printable characters")
private String group;
@Persistent
@Column(name = "NAME", jdbcType = "VARCHAR", allowsNull = "false")
@Index(name = "COMPONENT_NAME_IDX")
@NotBlank
@Size(min = 1, max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The name may only contain printable characters")
private String name;
@Persistent
@Column(name = "VERSION", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The version may only contain printable characters")
private String version;
@Persistent
@Column(name = "CLASSIFIER", jdbcType = "VARCHAR")
@Index(name = "COMPONENT_CLASSIFIER_IDX")
@Extension(vendorName = "datanucleus", key = "enum-check-constraint", value = "true")
private Classifier classifier;
@Persistent
@Column(name = "FILENAME", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.FS_DIRECTORY_NAME, message = "The specified filename is not valid and cannot be used as a filename")
private String filename;
@Persistent
@Column(name = "EXTENSION", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.FS_FILE_NAME, message = "The specified filename extension is not valid and cannot be used as a extension")
private String extension;
@Persistent
@Index(name = "COMPONENT_MD5_IDX")
@Column(name = "MD5", jdbcType = "VARCHAR", length = 32)
@Pattern(regexp = RegexSequence.Definition.HASH_MD5, message = "The MD5 hash must be a valid 32 character HEX number")
private String md5;
@Persistent
@Index(name = "COMPONENT_SHA1_IDX")
@Column(name = "SHA1", jdbcType = "VARCHAR", length = 40)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA1, message = "The SHA1 hash must be a valid 40 character HEX number")
private String sha1;
@Persistent
@Index(name = "COMPONENT_SHA256_IDX")
@Column(name = "SHA_256", jdbcType = "VARCHAR", length = 64)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA256, message = "The SHA-256 hash must be a valid 64 character HEX number")
private String sha256;
@Persistent
@Index(name = "COMPONENT_SHA512_IDX")
@Column(name = "SHA_512", jdbcType = "VARCHAR", length = 128)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA512, message = "The SHA-512 hash must be a valid 128 character HEX number")
private String sha512;
@Persistent
@Index(name = "COMPONENT_SHA3_256_IDX")
@Column(name = "SHA3_256", jdbcType = "VARCHAR", length = 64)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA256, message = "The SHA3-256 hash must be a valid 64 character HEX number")
private String sha3_256;
@Persistent
@Index(name = "COMPONENT_SHA3_512_IDX")
@Column(name = "SHA3_512", jdbcType = "VARCHAR", length = 128)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA512, message = "The SHA3-512 hash must be a valid 128 character HEX number")
private String sha3_512;
@Persistent
@Size(max = 255)
//Patterns obtained from https://csrc.nist.gov/schema/cpe/2.3/cpe-naming_2.3.xsd
@Pattern(regexp = "(cpe:2\\.3:[aho\\*\\-](:(((\\?*|\\*?)([a-zA-Z0-9\\-\\._]|(\\\\[\\\\\\*\\?!\"#$$%&'\\(\\)\\+,/:;<=>@\\[\\]\\^`\\{\\|}~]))+(\\?*|\\*?))|[\\*\\-])){5}(:(([a-zA-Z]{2,3}(-([a-zA-Z]{2}|[0-9]{3}))?)|[\\*\\-]))(:(((\\?*|\\*?)([a-zA-Z0-9\\-\\._]|(\\\\[\\\\\\*\\?!\"#$$%&'\\(\\)\\+,/:;<=>@\\[\\]\\^`\\{\\|}~]))+(\\?*|\\*?))|[\\*\\-])){4})|([c][pP][eE]:/[AHOaho]?(:[A-Za-z0-9\\._\\-~%]*){0,6})", message = "The CPE must conform to the CPE v2.2 or v2.3 specification defined by NIST")
private String cpe;
@Persistent(defaultFetchGroup = "true")
@Size(max = 255)
@Pattern(regexp = RegexSequence.Definition.HTTP_URI, message = "The Package URL (purl) must be a valid URI and conform to https://github.com/package-url/purl-spec")
@Convert(PackageURLStringConverter.class)
@JsonSerialize(using = CustomPackageURLSerializer.class)
private PackageURL purl;
@Persistent
@Column(name = "DESCRIPTION", jdbcType = "VARCHAR", length = 1024)
@Size(max = 1024)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The description may only contain printable characters")
private String description;
@Persistent
@Column(name = "COPYRIGHT", jdbcType = "VARCHAR", length = 1024)
@Size(max = 1024)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The copyright may only contain printable characters")
private String copyright;
@Persistent
@Column(name = "LICENSE", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The license may only contain printable characters")
private String license;
@Persistent(defaultFetchGroup = "true", cacheable = "false")
@Column(name = "LICENSE_ID")
private License resolvedLicense;
@Persistent
@Column(name = "PARENT_COMPONENT_ID")
private Component parent;
@Persistent(mappedBy = "parent")
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
private Collection<Component> children;
@Persistent
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
@JsonIgnore
private List<Scan> scans;
@Persistent
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
@JsonIgnore
private List<Bom> boms;
@Persistent(table = "COMPONENTS_VULNERABILITIES")
@Join(column = "COMPONENT_ID")
@Element(column = "VULNERABILITY_ID")
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
private List<Vulnerability> vulnerabilities;
@Persistent(customValueStrategy = "uuid")
@Unique(name = "COMPONENT_UUID_IDX")
@Column(name = "UUID", jdbcType = "VARCHAR", length = 36, allowsNull = "false")
@NotNull
private UUID uuid;
private transient ComponentMetrics metrics;
private transient RepositoryMetaComponent repositoryMeta;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = StringUtils.abbreviate(group, 255);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = StringUtils.abbreviate(name, 255);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = StringUtils.abbreviate(version, 255);
}
public Classifier getClassifier() {
return classifier;
}
public void setClassifier(Classifier classifier) {
this.classifier = classifier;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = StringUtils.abbreviate(filename, 255);
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = StringUtils.abbreviate(extension, 255);
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getSha1() {
return sha1;
}
public void setSha1(String sha1) {
this.sha1 = sha1;
}
public String getSha256() {
return sha256;
}
public void setSha256(String sha256) {
this.sha256 = sha256;
}
public String getSha512() {
return sha512;
}
public void setSha512(String sha512) {
this.sha512 = sha512;
}
public String getSha3_256() {
return sha3_256;
}
public void setSha3_256(String sha3_256) {
this.sha3_256 = sha3_256;
}
public String getSha3_512() {
return sha3_512;
}
public void setSha3_512(String sha3_512) {
this.sha3_512 = sha3_512;
}
public String getCpe() {
return cpe;
}
public void setCpe(String cpe) {
this.cpe = StringUtils.abbreviate(cpe, 255);
}
public PackageURL getPurl() {
return purl;
}
public void setPurl(PackageURL purl) {
this.purl = purl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = StringUtils.abbreviate(description, 1024);
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = StringUtils.abbreviate(copyright, 1024);
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = StringUtils.abbreviate(license, 255);
}
public License getResolvedLicense() {
return resolvedLicense;
}
public void setResolvedLicense(License resolvedLicense) {
this.resolvedLicense = resolvedLicense;
}
public Component getParent() {
return parent;
}
public void setParent(Component parent) {
this.parent = parent;
}
public Collection<Component> getChildren() {
return children;
}
public void setChildren(Collection<Component> children) {
this.children = children;
}
public List<Scan> getScans() {
return scans;
}
public void setScans(List<Scan> scans) {
this.scans = scans;
}
public List<Bom> getBoms() {
return boms;
}
public void setBoms(List<Bom> boms) {
this.boms = boms;
}
public List<Vulnerability> getVulnerabilities() {
return vulnerabilities;
}
public void setVulnerabilities(List<Vulnerability> vulnerabilities) {
this.vulnerabilities = vulnerabilities;
}
public void addVulnerability(Vulnerability vulnerability) {
vulnerabilities.add(vulnerability);
}
public void removeVulnerability(Vulnerability vulnerability) {
this.vulnerabilities.remove(vulnerability);
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public ComponentMetrics getMetrics() {
return metrics;
}
public void setMetrics(ComponentMetrics metrics) {
this.metrics = metrics;
}
public RepositoryMetaComponent getRepositoryMeta() {
return repositoryMeta;
}
public void setRepositoryMeta(RepositoryMetaComponent repositoryMeta) {
this.repositoryMeta = repositoryMeta;
}
@Override
public String toString() {
if (getPurl() != null) {
return getPurl().canonicalize();
} else {
StringBuilder sb = new StringBuilder();
if (getGroup() != null) {
sb.append(getGroup()).append(" : ");
}
sb.append(getName());
if (getVersion() != null) {
sb.append(" : ").append(getVersion());
}
return sb.toString();
}
}
}
| src/main/java/org/dependencytrack/model/Component.java | /*
* This file is part of Dependency-Track.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package org.dependencytrack.model;
import alpine.json.TrimmedStringDeserializer;
import alpine.validation.RegexSequence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.github.packageurl.PackageURL;
import org.apache.commons.lang3.StringUtils;
import org.dependencytrack.persistence.PackageURLStringConverter;
import org.dependencytrack.resources.v1.serializers.CustomPackageURLSerializer;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Convert;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.FetchGroup;
import javax.jdo.annotations.FetchGroups;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.Order;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
/**
* Model class for tracking individual components.
*
* @author Steve Springett
* @since 3.0.0
*/
@PersistenceCapable
@FetchGroups({
@FetchGroup(name = "ALL", members = {
@Persistent(name = "resolvedLicense"),
@Persistent(name = "parent"),
@Persistent(name = "children"),
@Persistent(name = "evidence"),
@Persistent(name = "scans"),
@Persistent(name = "boms"),
@Persistent(name = "vulnerabilities"),
})
})
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Component implements Serializable {
private static final long serialVersionUID = 6841650046433674702L;
/**
* Defines JDO fetch groups for this class.
*/
public enum FetchGroup {
ALL
}
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
@JsonIgnore
private long id;
@Persistent
@Column(name = "GROUP", jdbcType = "VARCHAR")
@Index(name = "COMPONENT_GROUP_IDX")
@Size(max = 255)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The group may only contain printable characters")
private String group;
@Persistent
@Column(name = "NAME", jdbcType = "VARCHAR", allowsNull = "false")
@Index(name = "COMPONENT_NAME_IDX")
@NotBlank
@Size(min = 1, max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The name may only contain printable characters")
private String name;
@Persistent
@Column(name = "VERSION", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The version may only contain printable characters")
private String version;
@Persistent
@Column(name = "CLASSIFIER", jdbcType = "VARCHAR")
@Index(name = "COMPONENT_CLASSIFIER_IDX")
@Extension(vendorName = "datanucleus", key = "enum-check-constraint", value = "true")
private Classifier classifier;
@Persistent
@Column(name = "FILENAME", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.FS_DIRECTORY_NAME, message = "The specified filename is not valid and cannot be used as a filename")
private String filename;
@Persistent
@Column(name = "EXTENSION", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.FS_FILE_NAME, message = "The specified filename extension is not valid and cannot be used as a extension")
private String extension;
@Persistent
@Index(name = "COMPONENT_MD5_IDX")
@Column(name = "MD5", jdbcType = "VARCHAR", length = 32)
@Pattern(regexp = RegexSequence.Definition.HASH_MD5, message = "The MD5 hash must be a valid 32 character HEX number")
private String md5;
@Persistent
@Index(name = "COMPONENT_SHA1_IDX")
@Column(name = "SHA1", jdbcType = "VARCHAR", length = 40)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA1, message = "The SHA1 hash must be a valid 40 character HEX number")
private String sha1;
@Persistent
@Index(name = "COMPONENT_SHA256_IDX")
@Column(name = "SHA_256", jdbcType = "VARCHAR", length = 64)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA256, message = "The SHA-256 hash must be a valid 64 character HEX number")
private String sha256;
@Persistent
@Index(name = "COMPONENT_SHA512_IDX")
@Column(name = "SHA_512", jdbcType = "VARCHAR", length = 128)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA512, message = "The SHA-512 hash must be a valid 128 character HEX number")
private String sha512;
@Persistent
@Index(name = "COMPONENT_SHA3_256_IDX")
@Column(name = "SHA3_256", jdbcType = "VARCHAR", length = 64)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA256, message = "The SHA3-256 hash must be a valid 64 character HEX number")
private String sha3_256;
@Persistent
@Index(name = "COMPONENT_SHA3_512_IDX")
@Column(name = "SHA3_512", jdbcType = "VARCHAR", length = 128)
@Pattern(regexp = RegexSequence.Definition.HASH_SHA512, message = "The SHA3-512 hash must be a valid 128 character HEX number")
private String sha3_512;
@Persistent
@Size(max = 255)
//Patterns obtained from https://csrc.nist.gov/schema/cpe/2.3/cpe-naming_2.3.xsd
@Pattern(regexp = "(cpe:2\\.3:[aho\\*\\-](:(((\\?*|\\*?)([a-zA-Z0-9\\-\\._]|(\\\\[\\\\\\*\\?!\"#$$%&'\\(\\)\\+,/:;<=>@\\[\\]\\^`\\{\\|}~]))+(\\?*|\\*?))|[\\*\\-])){5}(:(([a-zA-Z]{2,3}(-([a-zA-Z]{2}|[0-9]{3}))?)|[\\*\\-]))(:(((\\?*|\\*?)([a-zA-Z0-9\\-\\._]|(\\\\[\\\\\\*\\?!\"#$$%&'\\(\\)\\+,/:;<=>@\\[\\]\\^`\\{\\|}~]))+(\\?*|\\*?))|[\\*\\-])){4})|([c][pP][eE]:/[AHOaho]?(:[A-Za-z0-9\\._\\-~%]*){0,6})", message = "The CPE must conform to the CPE v2.2 or v2.3 specification defined by NIST")
private String cpe;
@Persistent(defaultFetchGroup = "true")
@Size(max = 255)
@Pattern(regexp = RegexSequence.Definition.HTTP_URI, message = "The Package URL (purl) must be a valid URI and conform to https://github.com/package-url/purl-spec")
@Convert(PackageURLStringConverter.class)
@JsonSerialize(using = CustomPackageURLSerializer.class)
private PackageURL purl;
@Persistent
@Column(name = "DESCRIPTION", jdbcType = "VARCHAR", length = 1024)
@Size(max = 1024)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The description may only contain printable characters")
private String description;
@Persistent
@Column(name = "COPYRIGHT", jdbcType = "VARCHAR", length = 1024)
@Size(max = 1024)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The copyright may only contain printable characters")
private String copyright;
@Persistent
@Column(name = "LICENSE", jdbcType = "VARCHAR")
@Size(max = 255)
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS, message = "The license may only contain printable characters")
private String license;
@Persistent(defaultFetchGroup = "true", cacheable = "false")
@Column(name = "LICENSE_ID")
private License resolvedLicense;
@Persistent
@Column(name = "PARENT_COMPONENT_ID")
private Component parent;
@Persistent(mappedBy = "parent")
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
private Collection<Component> children;
@Persistent
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
@JsonIgnore
private List<Scan> scans;
@Persistent
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
@JsonIgnore
private List<Bom> boms;
@Persistent(table = "COMPONENTS_VULNERABILITIES")
@Join(column = "COMPONENT_ID")
@Element(column = "VULNERABILITY_ID")
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
private List<Vulnerability> vulnerabilities;
@Persistent(customValueStrategy = "uuid")
@Unique(name = "COMPONENT_UUID_IDX")
@Column(name = "UUID", jdbcType = "VARCHAR", length = 36, allowsNull = "false")
@NotNull
private UUID uuid;
private transient ComponentMetrics metrics;
private transient RepositoryMetaComponent repositoryMeta;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = StringUtils.abbreviate(group, 255);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = StringUtils.abbreviate(name, 255);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = StringUtils.abbreviate(version, 255);
}
public Classifier getClassifier() {
return classifier;
}
public void setClassifier(Classifier classifier) {
this.classifier = classifier;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = StringUtils.abbreviate(filename, 255);
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = StringUtils.abbreviate(extension, 255);
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getSha1() {
return sha1;
}
public void setSha1(String sha1) {
this.sha1 = sha1;
}
public String getSha256() {
return sha256;
}
public void setSha256(String sha256) {
this.sha256 = sha256;
}
public String getSha512() {
return sha512;
}
public void setSha512(String sha512) {
this.sha512 = sha512;
}
public String getSha3_256() {
return sha3_256;
}
public void setSha3_256(String sha3_256) {
this.sha3_256 = sha3_256;
}
public String getSha3_512() {
return sha3_512;
}
public void setSha3_512(String sha3_512) {
this.sha3_512 = sha3_512;
}
public String getCpe() {
return cpe;
}
public void setCpe(String cpe) {
this.cpe = StringUtils.abbreviate(cpe, 255);
}
public PackageURL getPurl() {
return purl;
}
public void setPurl(PackageURL purl) {
this.purl = purl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = StringUtils.abbreviate(description, 1024);
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = StringUtils.abbreviate(copyright, 1024);
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = StringUtils.abbreviate(license, 255);
}
public License getResolvedLicense() {
return resolvedLicense;
}
public void setResolvedLicense(License resolvedLicense) {
this.resolvedLicense = resolvedLicense;
}
public Component getParent() {
return parent;
}
public void setParent(Component parent) {
this.parent = parent;
}
public Collection<Component> getChildren() {
return children;
}
public void setChildren(Collection<Component> children) {
this.children = children;
}
public List<Scan> getScans() {
return scans;
}
public void setScans(List<Scan> scans) {
this.scans = scans;
}
public List<Bom> getBoms() {
return boms;
}
public void setBoms(List<Bom> boms) {
this.boms = boms;
}
public List<Vulnerability> getVulnerabilities() {
return vulnerabilities;
}
public void setVulnerabilities(List<Vulnerability> vulnerabilities) {
this.vulnerabilities = vulnerabilities;
}
public void addVulnerability(Vulnerability vulnerability) {
vulnerabilities.add(vulnerability);
}
public void removeVulnerability(Vulnerability vulnerability) {
this.vulnerabilities.remove(vulnerability);
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public ComponentMetrics getMetrics() {
return metrics;
}
public void setMetrics(ComponentMetrics metrics) {
this.metrics = metrics;
}
public RepositoryMetaComponent getRepositoryMeta() {
return repositoryMeta;
}
public void setRepositoryMeta(RepositoryMetaComponent repositoryMeta) {
this.repositoryMeta = repositoryMeta;
}
@Override
public String toString() {
if (getPurl() != null) {
return getPurl().canonicalize();
} else {
StringBuilder sb = new StringBuilder();
if (getGroup() != null) {
sb.append(getGroup()).append(" : ");
}
sb.append(getName());
if (getVersion() != null) {
sb.append(" : ").append(getVersion());
}
return sb.toString();
}
}
}
| Removed evidence
| src/main/java/org/dependencytrack/model/Component.java | Removed evidence |
|
Java | bsd-2-clause | 35df39c5b9aa188f25ef7aec7812a52381b009dd | 0 | mvocu/perun,mvocu/perun,martin-kuba/perun,martin-kuba/perun,mvocu/perun,zlamalp/perun,mvocu/perun,martin-kuba/perun,mvocu/perun,zlamalp/perun,mvocu/perun,zlamalp/perun,CESNET/perun,CESNET/perun,martin-kuba/perun,CESNET/perun,CESNET/perun,martin-kuba/perun,martin-kuba/perun,zlamalp/perun,CESNET/perun,mvocu/perun,zlamalp/perun,CESNET/perun,zlamalp/perun,CESNET/perun,zlamalp/perun,martin-kuba/perun | package cz.metacentrum.perun.webgui.json;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.PerunWebConstants;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.localization.WidgetTranslation;
import cz.metacentrum.perun.webgui.client.resources.LargeIcons;
import cz.metacentrum.perun.webgui.model.PerunError;
import cz.metacentrum.perun.webgui.model.PerunRequest;
import cz.metacentrum.perun.webgui.widgets.Confirm;
import java.util.HashMap;
import java.util.Map;
/**
* Class for POST requests to RPC.
*
* @author Vaclav Mach <[email protected]>
*/
public class JsonPostClient {
/**
* Perun web session
*/
private PerunWebSession session = PerunWebSession.getInstance();
/**
* JSON object to be sent
* For object format - check sources in: cz.metacentrum.perun.rpc.methods
*/
private JSONObject jsonObject;
private String json;
private boolean sendNative = false;
/**
* URL to be called, eg. "vosManager/createVo"
*/
private String url;
/**
* Custom events - onFinished, onError
*/
private JsonCallbackEvents events = new JsonCallbackEvents();
/**
* Callback name - can be anything, just for internal purpose
*/
private String callbackName = "callbackPost";
/**
* Hidden callback do not show error pop-up
*/
private boolean hidden = false;
private Map<String, PerunRequest> runningRequests = new HashMap<>();
private static Confirm c = null;
private static FlexTable layout = new FlexTable();
private static int counter = 0;
/**
* New JsonPostClient
*/
public JsonPostClient() {
if (c == null) {
layout.setWidget(0, 0, new HTML("<p>" + new Image(LargeIcons.INSTANCE.informationIcon())));
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
layout.getFlexCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
layout.getFlexCellFormatter().setAlignment(0, 1, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
layout.getFlexCellFormatter().setStyleName(0, 0, "alert-box-image");
c = new Confirm("Pending request", layout, true);
c.setNonScrollable(true);
c.setAutoHide(false);
}
}
/**
* New JsonPostClient
*
* @param events
*/
public JsonPostClient(JsonCallbackEvents events) {
this();
this.events = events;
}
/**
* Put value to output data
*
* @param key
* @param json
*/
public void put(String key, JSONValue json) {
if (jsonObject == null) {
jsonObject = new JSONObject();
}
jsonObject.put(key, json);
}
/**
* Sends data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @param json
* @return
*/
public boolean sendData(String url, JSONObject json) {
if (json == null) {
return false;
}
this.sendNative = false;
this.url = url;
this.jsonObject = json;
this.send();
return true;
}
/**
* Sends data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @return
*/
public boolean sendData(String url) {
if (jsonObject == null) {
return false;
}
this.sendNative = false;
this.url = url;
this.send();
return true;
}
/**
* Sends native data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @param json
* @return
*/
public boolean sendNativeData(String url, String json) {
if (json == null) {
return false;
}
this.sendNative = true;
this.url = url;
this.json = json;
this.send();
return true;
}
/**
* Sends the data
*/
private void send() {
final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
perunRequest.setStartTime();
// url to call
final String requestUrl = URL.encode(PerunWebSession.getInstance().getRpcUrl() + url + "?callback=" + perunRequest.getStartTime());
String data = "";
if (sendNative) {
data = json;
} else {
data = jsonObject.toString();
}
perunRequest.setManager(url.split("\\/")[0]);
perunRequest.setMethod(url.split("\\/")[1]);
perunRequest.setParamString("?callback=" + perunRequest.getStartTime() + "&" + data);
// request building
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
if (Cookies.getCookie("XSRF-TOKEN") != null) {
builder.setHeader("X-XSRF-TOKEN", Cookies.getCookie("XSRF-TOKEN"));
}
try {
// sends the request
onRequestLoadingStart();
final String payload = data;
builder.sendRequest(payload, new RequestCallback() {
@Override
public void onResponseReceived(Request req, Response resp) {
// if response = OK
if (resp.getStatusCode() == 200) {
// jso
JavaScriptObject jso = parseResponse(perunRequest.getStartTime() + "", resp.getText());
// if null - finished
if (jso == null) {
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response NULL.");
}
runningRequests.remove(requestUrl);
onRequestFinished(null);
return;
}
// if error?
PerunError error = (PerunError) jso;
if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
// not error, OK
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response not NULL, not ERROR.");
}
runningRequests.remove(requestUrl);
onRequestFinished(jso);
return;
}
// triggers onError
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response ERROR.");
}
error.setRequestURL(requestUrl);
error.setRequest(perunRequest);
error.setPostData(payload);
runningRequests.remove(requestUrl);
onRequestError(error);
return;
} else {
// if response not OK
PerunError error = new JSONObject().getJavaScriptObject().cast();
error.setErrorId("" + resp.getStatusCode());
error.setName(resp.getStatusText());
error.setErrorInfo("Server responded with HTTP error: " + resp.getStatusCode() + " - " + resp.getStatusText());
error.setObjectType("PerunError");
error.setPostData(payload);
error.setRequest(perunRequest);
error.setRequestURL(requestUrl);
if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
error.setName("Not Authorized");
error.setErrorInfo("You are not authorized to server. Your session might have expired. Please refresh the browser window to re-login.");
} else if (resp.getStatusCode() == 500) {
if (runningRequests.get(requestUrl) != null) {
// 5 minute timeout
if ((runningRequests.get(requestUrl).getDuration() / (1000 * 60)) >= 5) {
counter++;
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: "+counter);
if (!c.isShowing() && counter > 0) c.show();
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
boolean again = true;
@Override
public boolean execute() {
GetPendingRequests req = new GetPendingRequests(perunRequest.getStartTime(), new JsonCallbackEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
final PerunRequest req = jso.cast();
if ((req.getCallbackId().equals(perunRequest.getStartTime() + "")) && req.getEndTime() > 0) {
if (again) {
again = false;
counter--;
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: "+counter);
// hide notification
if (c.isShowing() && counter <= 0) c.hide();
JavaScriptObject result = req.getResult();
// if null - finished
if (result == null) {
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response NULL.");
}
runningRequests.remove(requestUrl);
onRequestFinished(null);
return;
}
// if error?
PerunError error = (PerunError) result;
if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
// not error, OK
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response not NULL, not ERROR.");
}
runningRequests.remove(requestUrl);
onRequestFinished(result);
return;
}
// triggers onError
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response ERROR.");
}
error.setRequestURL(requestUrl);
error.setRequest(perunRequest);
error.setPostData(payload);
runningRequests.remove(requestUrl);
onRequestError(error);
return;
}
}
}
});
req.retrieveData();
return again;
}
}, ((PerunWebConstants) GWT.create(PerunWebConstants.class)).pendingRequestsRefreshInterval());
return;
} else {
error.setName("ServerInternalError");
error.setErrorInfo("Server encounter internal error while processing your request. Please report this error and retry.");
}
}
} else if (resp.getStatusCode() == 503) {
error.setName("Server Temporarily Unavailable");
error.setErrorInfo("Server is temporarily unavailable. Please try again later.");
} else if (resp.getStatusCode() == 404) {
error.setName("Not found");
error.setErrorInfo("Server is probably being restarted at the moment. Please try again later.");
} else if (resp.getStatusCode() == 0) {
error.setName("Aborted");
error.setErrorInfo("Can't contact remote server, connection was lost.");
}
runningRequests.remove(requestUrl);
onRequestError(error);
return;
}
}
@Override
public void onError(Request req, Throwable exc) {
// request not sent
runningRequests.remove(requestUrl);
onRequestError(parseResponse(perunRequest.getStartTime()+"", exc.toString()));
}
});
runningRequests.put(requestUrl, perunRequest);
} catch (RequestException exc) {
// usually couldn't connect to server
onRequestError(parseResponse(perunRequest.getStartTime()+"", exc.toString()));
}
}
/**
* Parses the responce to an object.
*
* @param resp JSON string
* @return
*/
protected JavaScriptObject parseResponse(String callbackName, String resp) {
// trims the whitespace
resp = resp.trim();
// short comparing
if ((callbackName + "(null);").equalsIgnoreCase(resp)) {
return null;
}
// if starts with callbackName( and ends with ) or ); - wrapped, must be unwrapped
RegExp re = RegExp.compile("^" + callbackName + "\\((.*)\\)|\\);$");
MatchResult result = re.exec(resp);
if (result != null) {
resp = result.getGroup(1);
}
// if response = null - return null
if (resp.equals("null")) {
return null;
}
// normal object
JavaScriptObject jso = JsonUtils.parseJson(resp);
return jso;
}
/**
* Called when loading starts
*/
protected void onRequestLoadingStart() {
events.onLoadingStart();
}
/**
* Called when loading finishes
*
* @param jso
*/
protected void onRequestFinished(JavaScriptObject jso) {
events.onFinished(jso);
}
/**
* Called when error occurred.
*
* @param jso
*/
protected void onRequestError(JavaScriptObject jso) {
if (jso != null) {
PerunError e = (PerunError) jso;
if (session.getUiElements() != null) {
session.getUiElements().setLogErrorText("Error while sending request: " + e.getName());
}
if (!hidden) {
// creates a alert box
JsonErrorHandler.alertBox(e);
}
events.onError(e);
} else {
PerunError e = (PerunError) JsonUtils.parseJson("{\"errorId\":\"0\",\"name\":\"Cross-site request\",\"type\":\"" + WidgetTranslation.INSTANCE.jsonClientAlertBoxErrorCrossSiteType() + "\",\"message\":\"" + WidgetTranslation.INSTANCE.jsonClientAlertBoxErrorCrossSiteText() + "\"}").cast();
if (session.getUiElements() != null) {
session.getUiElements().setLogErrorText("Error while sending request: The response was null or cross-site request.");
}
if (!hidden) {
// creates a alert box
JsonErrorHandler.alertBox(e);
}
events.onError(null);
}
}
/**
* Set callback hidden (do not show error pop-up)
*
* @param hidden (true=hidden/false=show - default)
*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
}
| perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/json/JsonPostClient.java | package cz.metacentrum.perun.webgui.json;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.PerunWebConstants;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.localization.WidgetTranslation;
import cz.metacentrum.perun.webgui.client.resources.LargeIcons;
import cz.metacentrum.perun.webgui.model.PerunError;
import cz.metacentrum.perun.webgui.model.PerunRequest;
import cz.metacentrum.perun.webgui.widgets.Confirm;
import java.util.HashMap;
import java.util.Map;
/**
* Class for POST requests to RPC.
*
* @author Vaclav Mach <[email protected]>
*/
public class JsonPostClient {
/**
* Perun web session
*/
private PerunWebSession session = PerunWebSession.getInstance();
/**
* JSON object to be sent
* For object format - check sources in: cz.metacentrum.perun.rpc.methods
*/
private JSONObject jsonObject;
private String json;
private boolean sendNative = false;
/**
* URL to be called, eg. "vosManager/createVo"
*/
private String url;
/**
* Custom events - onFinished, onError
*/
private JsonCallbackEvents events = new JsonCallbackEvents();
/**
* Callback name - can be anything, just for internal purpose
*/
private String callbackName = "callbackPost";
/**
* Hidden callback do not show error pop-up
*/
private boolean hidden = false;
private Map<String, PerunRequest> runningRequests = new HashMap<>();
private static Confirm c = null;
private static FlexTable layout = new FlexTable();
private static int counter = 0;
/**
* New JsonPostClient
*/
public JsonPostClient() {
if (c == null) {
layout.setWidget(0, 0, new HTML("<p>" + new Image(LargeIcons.INSTANCE.informationIcon())));
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
layout.getFlexCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
layout.getFlexCellFormatter().setAlignment(0, 1, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
layout.getFlexCellFormatter().setStyleName(0, 0, "alert-box-image");
c = new Confirm("Pending request", layout, true);
c.setNonScrollable(true);
c.setAutoHide(false);
}
}
/**
* New JsonPostClient
*
* @param events
*/
public JsonPostClient(JsonCallbackEvents events) {
this();
this.events = events;
}
/**
* Put value to output data
*
* @param key
* @param json
*/
public void put(String key, JSONValue json) {
if (jsonObject == null) {
jsonObject = new JSONObject();
}
jsonObject.put(key, json);
}
/**
* Sends data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @param json
* @return
*/
public boolean sendData(String url, JSONObject json) {
if (json == null) {
return false;
}
this.sendNative = false;
this.url = url;
this.jsonObject = json;
this.send();
return true;
}
/**
* Sends data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @return
*/
public boolean sendData(String url) {
if (jsonObject == null) {
return false;
}
this.sendNative = false;
this.url = url;
this.send();
return true;
}
/**
* Sends native data.
* Returns true, if the data was send.
* After the callback is complete, it calls the events.
*
* @param json
* @return
*/
public boolean sendNativeData(String url, String json) {
if (json == null) {
return false;
}
this.sendNative = true;
this.url = url;
this.json = json;
this.send();
return true;
}
/**
* Sends the data
*/
private void send() {
final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
perunRequest.setStartTime();
// url to call
final String requestUrl = URL.encode(PerunWebSession.getInstance().getRpcUrl() + url + "?callback=" + perunRequest.getStartTime());
String data = "";
if (sendNative) {
data = json;
} else {
data = jsonObject.toString();
}
perunRequest.setManager(url.split("\\/")[0]);
perunRequest.setMethod(url.split("\\/")[1]);
perunRequest.setParamString("?callback=" + perunRequest.getStartTime() + "&" + data);
// request building
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
try {
// sends the request
onRequestLoadingStart();
final String payload = data;
builder.sendRequest(payload, new RequestCallback() {
@Override
public void onResponseReceived(Request req, Response resp) {
// if response = OK
if (resp.getStatusCode() == 200) {
// jso
JavaScriptObject jso = parseResponse(perunRequest.getStartTime() + "", resp.getText());
// if null - finished
if (jso == null) {
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response NULL.");
}
runningRequests.remove(requestUrl);
onRequestFinished(null);
return;
}
// if error?
PerunError error = (PerunError) jso;
if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
// not error, OK
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response not NULL, not ERROR.");
}
runningRequests.remove(requestUrl);
onRequestFinished(jso);
return;
}
// triggers onError
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response ERROR.");
}
error.setRequestURL(requestUrl);
error.setRequest(perunRequest);
error.setPostData(payload);
runningRequests.remove(requestUrl);
onRequestError(error);
return;
} else {
// if response not OK
PerunError error = new JSONObject().getJavaScriptObject().cast();
error.setErrorId("" + resp.getStatusCode());
error.setName(resp.getStatusText());
error.setErrorInfo("Server responded with HTTP error: " + resp.getStatusCode() + " - " + resp.getStatusText());
error.setObjectType("PerunError");
error.setPostData(payload);
error.setRequest(perunRequest);
error.setRequestURL(requestUrl);
if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
error.setName("Not Authorized");
error.setErrorInfo("You are not authorized to server. Your session might have expired. Please refresh the browser window to re-login.");
} else if (resp.getStatusCode() == 500) {
if (runningRequests.get(requestUrl) != null) {
// 5 minute timeout
if ((runningRequests.get(requestUrl).getDuration() / (1000 * 60)) >= 5) {
counter++;
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: "+counter);
if (!c.isShowing() && counter > 0) c.show();
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
boolean again = true;
@Override
public boolean execute() {
GetPendingRequests req = new GetPendingRequests(perunRequest.getStartTime(), new JsonCallbackEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
final PerunRequest req = jso.cast();
if ((req.getCallbackId().equals(perunRequest.getStartTime() + "")) && req.getEndTime() > 0) {
if (again) {
again = false;
counter--;
layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: "+counter);
// hide notification
if (c.isShowing() && counter <= 0) c.hide();
JavaScriptObject result = req.getResult();
// if null - finished
if (result == null) {
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response NULL.");
}
runningRequests.remove(requestUrl);
onRequestFinished(null);
return;
}
// if error?
PerunError error = (PerunError) result;
if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
// not error, OK
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response not NULL, not ERROR.");
}
runningRequests.remove(requestUrl);
onRequestFinished(result);
return;
}
// triggers onError
if (session.getUiElements() != null) {
session.getUiElements().setLogText("Response ERROR.");
}
error.setRequestURL(requestUrl);
error.setRequest(perunRequest);
error.setPostData(payload);
runningRequests.remove(requestUrl);
onRequestError(error);
return;
}
}
}
});
req.retrieveData();
return again;
}
}, ((PerunWebConstants) GWT.create(PerunWebConstants.class)).pendingRequestsRefreshInterval());
return;
} else {
error.setName("ServerInternalError");
error.setErrorInfo("Server encounter internal error while processing your request. Please report this error and retry.");
}
}
} else if (resp.getStatusCode() == 503) {
error.setName("Server Temporarily Unavailable");
error.setErrorInfo("Server is temporarily unavailable. Please try again later.");
} else if (resp.getStatusCode() == 404) {
error.setName("Not found");
error.setErrorInfo("Server is probably being restarted at the moment. Please try again later.");
} else if (resp.getStatusCode() == 0) {
error.setName("Aborted");
error.setErrorInfo("Can't contact remote server, connection was lost.");
}
runningRequests.remove(requestUrl);
onRequestError(error);
return;
}
}
@Override
public void onError(Request req, Throwable exc) {
// request not sent
runningRequests.remove(requestUrl);
onRequestError(parseResponse(perunRequest.getStartTime()+"", exc.toString()));
}
});
runningRequests.put(requestUrl, perunRequest);
} catch (RequestException exc) {
// usually couldn't connect to server
onRequestError(parseResponse(perunRequest.getStartTime()+"", exc.toString()));
}
}
/**
* Parses the responce to an object.
*
* @param resp JSON string
* @return
*/
protected JavaScriptObject parseResponse(String callbackName, String resp) {
// trims the whitespace
resp = resp.trim();
// short comparing
if ((callbackName + "(null);").equalsIgnoreCase(resp)) {
return null;
}
// if starts with callbackName( and ends with ) or ); - wrapped, must be unwrapped
RegExp re = RegExp.compile("^" + callbackName + "\\((.*)\\)|\\);$");
MatchResult result = re.exec(resp);
if (result != null) {
resp = result.getGroup(1);
}
// if response = null - return null
if (resp.equals("null")) {
return null;
}
// normal object
JavaScriptObject jso = JsonUtils.parseJson(resp);
return jso;
}
/**
* Called when loading starts
*/
protected void onRequestLoadingStart() {
events.onLoadingStart();
}
/**
* Called when loading finishes
*
* @param jso
*/
protected void onRequestFinished(JavaScriptObject jso) {
events.onFinished(jso);
}
/**
* Called when error occurred.
*
* @param jso
*/
protected void onRequestError(JavaScriptObject jso) {
if (jso != null) {
PerunError e = (PerunError) jso;
if (session.getUiElements() != null) {
session.getUiElements().setLogErrorText("Error while sending request: " + e.getName());
}
if (!hidden) {
// creates a alert box
JsonErrorHandler.alertBox(e);
}
events.onError(e);
} else {
PerunError e = (PerunError) JsonUtils.parseJson("{\"errorId\":\"0\",\"name\":\"Cross-site request\",\"type\":\"" + WidgetTranslation.INSTANCE.jsonClientAlertBoxErrorCrossSiteType() + "\",\"message\":\"" + WidgetTranslation.INSTANCE.jsonClientAlertBoxErrorCrossSiteText() + "\"}").cast();
if (session.getUiElements() != null) {
session.getUiElements().setLogErrorText("Error while sending request: The response was null or cross-site request.");
}
if (!hidden) {
// creates a alert box
JsonErrorHandler.alertBox(e);
}
events.onError(null);
}
}
/**
* Set callback hidden (do not show error pop-up)
*
* @param hidden (true=hidden/false=show - default)
*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
}
| feat(gui): support CSRF protection
- CSRF protection is now supported - POST requests sends a header with
CSRF token if there is a cookie with CSRF token.
| perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/json/JsonPostClient.java | feat(gui): support CSRF protection |
|
Java | bsd-2-clause | 3e1660260e0a7e9e30b26d269277a32dfeec9fd0 | 0 | jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu | /*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import ublu.util.ArgArray;
import ublu.util.Tuple;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.PrintParameterList;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
/**
* Command to manipulate jobs
*
* @author jwoehr
*/
public class CmdPpl extends Command {
{
setNameAndDescription("ppl", "/0 [--,-ppl ~@ppl] [-new,-instance] [-get[int|float|string] ~@{paramid}] | -set[int|float|string] ~@{paramid} ~@{value} : create and manipulate print parameter list");
}
/**
* What we do
*/
protected enum FUNCTIONS {
/**
* Create a PrintParameterList
*/
INSTANCE,
/**
* Get a print parameter from the PrintParameterList
*/
/**
* Set an int print parameter in the PrintParameterList
*/
SETINT,
/**
* Set a float print parameter in the PrintParameterList
*/
SETFLOAT,
/**
* Set a String print parameter in the PrintParameterList
*/
SETSTRING,
/**
* Get an int print parameter in the PrintParameterList
*/
GETINT,
/**
* Get a float print parameter in the PrintParameterList
*/
GETFLOAT,
/**
* Get a String print parameter in the PrintParameterList
*/
GETSTRING
}
/**
* Perform the work of getting a Job object and manipulating it.
*
* @param argArray the input arg array
* @return what's left of the arg array
*/
public ArgArray job(ArgArray argArray) {
FUNCTIONS function = FUNCTIONS.INSTANCE;
Tuple pplTuple = null;
PrintParameterList instancePPL = null;
int attributeId;
String stringVal;
Integer intVal;
Float floatVal;
Object getResult = null;
while (argArray.hasDashCommand()) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
setDataDestfromArgArray(argArray);
break;
// case "-from":
// String srcName = argArray.next();
// setDataSrc(DataSink.fromSinkName(srcName));
// break;
case "-getint":
function = FUNCTIONS.GETINT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getInt(pplTuple, attributeId);
break;
case "-getfloat":
function = FUNCTIONS.GETFLOAT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getFloat(pplTuple, attributeId);
break;
case "-getstring":
function = FUNCTIONS.GETSTRING;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getString(pplTuple, attributeId);
break;
case "-new":
case "-instance":
function = FUNCTIONS.INSTANCE;
instancePPL = new PrintParameterList();
break;
case "--":
case "-ppl":
pplTuple = argArray.nextTupleOrPop();
break;
case "-setint":
function = FUNCTIONS.SETINT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
intVal = argArray.nextIntMaybeQuotationTuplePopString();
setInt(pplTuple, attributeId, intVal);
break;
case "-setfloat":
function = FUNCTIONS.SETFLOAT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
floatVal = Float.parseFloat(argArray.nextMaybeQuotationTuplePopString());
setFloat(pplTuple, attributeId, floatVal);
break;
case "-setstring":
function = FUNCTIONS.SETSTRING;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
stringVal = argArray.nextMaybeQuotationTuplePopString();
setString(pplTuple, attributeId, stringVal);
break;
default:
unknownDashCommand(dashCommand);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
} else if (getCommandResult() != COMMANDRESULT.FAILURE) {
switch (function) {
case INSTANCE:
try {
put(instancePPL);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case SETFLOAT:
case SETINT:
case SETSTRING:
try {
if (pplTuple != null) {
put(pplTuple.getValue());
} else {
put(null);
}
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case GETFLOAT:
case GETINT:
case GETSTRING:
try {
put(getResult);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList value in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
}
}
return argArray;
}
private Tuple validatePPLTuple(Tuple pplTuple) {
if (pplTuple.getValue() == null) {
pplTuple.setValue(new PrintParameterList());
} else if (!(pplTuple.getValue() instanceof PrintParameterList)) {
getLogger().log(Level.SEVERE, "-ppl tuple is not a PrintParameterList in ", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
return pplTuple;
}
private void setInt(Tuple pplTuple, int attributeId, int intVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, intVal);
}
}
private void setFloat(Tuple pplTuple, int attributeId, float floatVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, floatVal);
}
}
private void setString(Tuple pplTuple, int attributeId, String stringVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, stringVal);
}
}
private Integer getInt(Tuple pplTuple, int attributeId) {
Integer result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getIntegerParameter(attributeId);
}
return result;
}
private Float getFloat(Tuple pplTuple, int attributeId) {
Float result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getFloatParameter(attributeId);
}
return result;
}
private String getString(Tuple pplTuple, int attributeId) {
String result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getStringParameter(attributeId);
}
return result;
}
@Override
public ArgArray cmd(ArgArray args) {
reinit();
return job(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
| src/ublu/command/CmdPpl.java | /*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import ublu.util.Tuple;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.PrintParameterList;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
/**
* Command to manipulate jobs
*
* @author jwoehr
*/
public class CmdPpl extends Command {
{
setNameAndDescription("ppl", "/0 [--,-ppl ~@ppl] [-new,-instance] [-get[int|float|string] ~@{paramid}] | -set[int|float|string] ~@{paramid} ~@{value} : create and manipulate print parameter list");
}
/**
* What we do
*/
protected enum FUNCTIONS {
/**
* Create a PrintParameterList
*/
INSTANCE,
/**
* Get a print parameter from the PrintParameterList
*/
/**
* Set an int print parameter in the PrintParameterList
*/
SETINT,
/**
* Set a float print parameter in the PrintParameterList
*/
SETFLOAT,
/**
* Set a String print parameter in the PrintParameterList
*/
SETSTRING,
/**
* Get an int print parameter in the PrintParameterList
*/
GETINT,
/**
* Get a float print parameter in the PrintParameterList
*/
GETFLOAT,
/**
* Get a String print parameter in the PrintParameterList
*/
GETSTRING
}
/**
* Perform the work of getting a Job object and manipulating it.
*
* @param argArray the input arg array
* @return what's left of the arg array
*/
public ArgArray job(ArgArray argArray) {
FUNCTIONS function = FUNCTIONS.INSTANCE;
Tuple pplTuple = null;
PrintParameterList instancePPL = null;
int attributeId;
String stringVal;
Integer intVal;
Float floatVal;
Object getResult = null;
while (argArray.hasDashCommand()) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
String destName = argArray.next();
setDataDest(DataSink.fromSinkName(destName));
break;
// case "-from":
// String srcName = argArray.next();
// setDataSrc(DataSink.fromSinkName(srcName));
// break;
case "-getint":
function = FUNCTIONS.GETINT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getInt(pplTuple, attributeId);
break;
case "-getfloat":
function = FUNCTIONS.GETFLOAT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getFloat(pplTuple, attributeId);
break;
case "-getstring":
function = FUNCTIONS.GETSTRING;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
getResult = getString(pplTuple, attributeId);
break;
case "-new":
case "-instance":
function = FUNCTIONS.INSTANCE;
instancePPL = new PrintParameterList();
break;
case "--":
case "-ppl":
pplTuple = argArray.nextTupleOrPop();
break;
case "-setint":
function = FUNCTIONS.SETINT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
intVal = argArray.nextIntMaybeQuotationTuplePopString();
setInt(pplTuple, attributeId, intVal);
break;
case "-setfloat":
function = FUNCTIONS.SETFLOAT;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
floatVal = Float.parseFloat(argArray.nextMaybeQuotationTuplePopString());
setFloat(pplTuple, attributeId, floatVal);
break;
case "-setstring":
function = FUNCTIONS.SETSTRING;
attributeId = argArray.nextIntMaybeQuotationTuplePopString();
stringVal = argArray.nextMaybeQuotationTuplePopString();
setString(pplTuple, attributeId, stringVal);
break;
default:
unknownDashCommand(dashCommand);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
} else if (getCommandResult() != COMMANDRESULT.FAILURE) {
switch (function) {
case INSTANCE:
try {
put(instancePPL);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case SETFLOAT:
case SETINT:
case SETSTRING:
try {
if (pplTuple != null) {
put(pplTuple.getValue());
} else {
put(null);
}
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case GETFLOAT:
case GETINT:
case GETSTRING:
try {
put(getResult);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting PrintParameterList value in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
}
}
return argArray;
}
private Tuple validatePPLTuple(Tuple pplTuple) {
if (pplTuple.getValue() == null) {
pplTuple.setValue(new PrintParameterList());
} else if (!(pplTuple.getValue() instanceof PrintParameterList)) {
getLogger().log(Level.SEVERE, "-ppl tuple is not a PrintParameterList in ", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
return pplTuple;
}
private void setInt(Tuple pplTuple, int attributeId, int intVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, intVal);
}
}
private void setFloat(Tuple pplTuple, int attributeId, float floatVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, floatVal);
}
}
private void setString(Tuple pplTuple, int attributeId, String stringVal) {
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
p.setParameter(attributeId, stringVal);
}
}
private Integer getInt(Tuple pplTuple, int attributeId) {
Integer result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getIntegerParameter(attributeId);
}
return result;
}
private Float getFloat(Tuple pplTuple, int attributeId) {
Float result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getFloatParameter(attributeId);
}
return result;
}
private String getString(Tuple pplTuple, int attributeId) {
String result = null;
pplTuple = validatePPLTuple(pplTuple);
if (getCommandResult() != COMMANDRESULT.FAILURE) {
PrintParameterList p = PrintParameterList.class
.cast(pplTuple.getValue());
result = p.getStringParameter(attributeId);
}
return result;
}
@Override
public ArgArray cmd(ArgArray args) {
reinit();
return job(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
| cleanup and setDataDest/SrcfromArgArray | src/ublu/command/CmdPpl.java | cleanup and setDataDest/SrcfromArgArray |
|
Java | bsd-3-clause | 2d105fe926f05eedbd320a70bbb5b365125d6ab9 | 0 | oranoceallaigh/smppapi,oranoceallaigh/smppapi,oranoceallaigh/smppapi | /*
* Java SMPP API
* Copyright (C) 1998 - 2002 by Oran Kelly
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* A copy of the LGPL can be viewed at http://www.gnu.org/copyleft/lesser.html
* Java SMPP API author: [email protected]
* Java SMPP API Homepage: http://smppapi.sourceforge.net/
* $Id$
*/
package ie.omk.smpp;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;
import ie.omk.smpp.event.ConnectionObserver;
import ie.omk.smpp.event.EventDispatcher;
import ie.omk.smpp.event.SimpleEventDispatcher;
import ie.omk.smpp.event.SMPPEvent;
import ie.omk.smpp.event.ReceiverExceptionEvent;
import ie.omk.smpp.event.ReceiverExitEvent;
import ie.omk.smpp.event.ReceiverStartEvent;
import ie.omk.smpp.message.AlertNotification;
import ie.omk.smpp.message.Bind;
import ie.omk.smpp.message.BindReceiver;
import ie.omk.smpp.message.BindReceiverResp;
import ie.omk.smpp.message.BindResp;
import ie.omk.smpp.message.BindTransceiver;
import ie.omk.smpp.message.BindTransceiverResp;
import ie.omk.smpp.message.BindTransmitter;
import ie.omk.smpp.message.BindTransmitterResp;
import ie.omk.smpp.message.CancelSM;
import ie.omk.smpp.message.CancelSMResp;
import ie.omk.smpp.message.DataSM;
import ie.omk.smpp.message.DataSMResp;
import ie.omk.smpp.message.DeliverSM;
import ie.omk.smpp.message.DeliverSMResp;
import ie.omk.smpp.message.EnquireLink;
import ie.omk.smpp.message.EnquireLinkResp;
import ie.omk.smpp.message.GenericNack;
import ie.omk.smpp.message.InvalidParameterValueException;
import ie.omk.smpp.message.ParamRetrieve;
import ie.omk.smpp.message.ParamRetrieveResp;
import ie.omk.smpp.message.QueryLastMsgs;
import ie.omk.smpp.message.QueryLastMsgsResp;
import ie.omk.smpp.message.QueryMsgDetails;
import ie.omk.smpp.message.QueryMsgDetailsResp;
import ie.omk.smpp.message.QuerySM;
import ie.omk.smpp.message.QuerySMResp;
import ie.omk.smpp.message.ReplaceSM;
import ie.omk.smpp.message.ReplaceSMResp;
import ie.omk.smpp.message.SMPPPacket;
import ie.omk.smpp.message.SMPPProtocolException;
import ie.omk.smpp.message.SMPPRequest;
import ie.omk.smpp.message.SMPPResponse;
import ie.omk.smpp.message.SubmitMulti;
import ie.omk.smpp.message.SubmitMultiResp;
import ie.omk.smpp.message.SubmitSM;
import ie.omk.smpp.message.SubmitSMResp;
import ie.omk.smpp.message.Unbind;
import ie.omk.smpp.message.UnbindResp;
import ie.omk.smpp.net.SmscLink;
import ie.omk.smpp.net.TcpLink;
import ie.omk.smpp.util.AlphabetEncoding;
import ie.omk.smpp.util.APIConfig;
import ie.omk.smpp.util.DefaultSequenceScheme;
import ie.omk.smpp.util.PacketFactory;
import ie.omk.smpp.util.PropertyNotFoundException;
import ie.omk.smpp.util.SequenceNumberScheme;
import ie.omk.smpp.util.SMPPDate;
import ie.omk.smpp.util.SMPPIO;
import ie.omk.smpp.version.SMPPVersion;
import ie.omk.smpp.version.VersionException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/** SMPP client connection (ESME). An SMPP Connection represents any kind of
* connection to the SMSC, be it a transmitter, receiver or transceiver. It also
* supports both synchronous and asynchronous modes of communication.
* Synchronous mode is only useful for very simple applications that use
* single-threading. Asynchronous mode is recommended for more complex
* applications, especially those that will be running many threads.
* <p><b>Important Note</b>: if you wish to use synchronous mode in a
* multi-threaded environment, it is the <u>application's</u> responsiblity to
* ensure there is only one thread executing a call to either or both of the
* <code>sendRequest</code> and <code>readNextPacket</code> methods. If there
* are concurrent calls to these methods executing, there is a strong
* possibility of the incorrect packet being returned in a particular thread and
* both the API and the application getting confused. These are the only methods
* that contain such a race condition.</p>
* @author Oran Kelly
* @version 1.0
*/
public class Connection
implements java.lang.Runnable
{
/** Get the logger for this Connection. */
protected Logger logger = Logger.getLogger("ie.omk.smpp.Connection");
/** SMPP Transmitter connection type. */
public static final int TRANSMITTER = 1;
/** SMPP Receiver connection type. */
public static final int RECEIVER = 2;
/** SMPP Transciever connection type. */
public static final int TRANSCEIVER = 3;
/** Connection state: not bound to the SMSC. */
public static final int UNBOUND = 0;
/** Connection state: waiting for successful acknowledgement to bind
* request.
*/
public static final int BINDING = 1;
/** Connection state: bound to the SMSC. */
public static final int BOUND = 2;
/** Connection state: waiting for successful acknowledgement to unbind
* request or waiting for application to respond to unbind request.
*/
public static final int UNBINDING = 3;
/** Type of this SMPP connection. */
private int connectionType = 0;
/** Packet listener thread for Asyncronous comms. */
private Thread rcvThread = null;
/** Queue of incoming packets to deliver to application before reading from
* the network. The queue is used only in syncrhonized mode. In the case
* where an application has sent a request to the SMSC and is blocked
* waiting a response and the SMSC initiates a request of it's own (an
* unbind request or an enquire_link), the API will cache the request packet
* and wait for the response to it's packet. Any other type of packet will
* be added to the packetQueue and subsequent calls to
* <code>readNextPacket</code> will clear this queue.
*/
private ArrayList packetQueue = null;
/** Object used to notify observers of SMPP events.
*/
private EventDispatcher eventDispatcher = null;
/** Byte buffer used in readNextPacketInternal. */
private byte[] buf = new byte[300];
/** Sequence numbering scheme to use for this connection. */
private SequenceNumberScheme seqNumScheme = new DefaultSequenceScheme();
/** The network link (virtual circuit) to the SMSC */
private SmscLink link = null;
/** SMPP protocol version number.
*/
protected SMPPVersion interfaceVersion = SMPPVersion.getDefaultVersion();
/** Current state of the SMPP connection.
* Possible states are UNBOUND, BINDING, BOUND and UNBINDING.
*/
private int state = UNBOUND;
/** Specify whether the listener thread will automatically ack
* enquire_link primitives received from the Smsc
*/
protected boolean ackQryLinks = true;
/** Automatically acknowledge incoming deliver_sm messages.
* Only valid for the Receiver
*/
protected boolean ackDeliverSm = false;
/** Is the user using synchronous are async communication?. */
protected boolean asyncComms = false;
/** The default alphabet to use for this connection.
*/
protected AlphabetEncoding defaultAlphabet = null;
/** Initialise a new SMPP connection object. This is a convenience
* constructor that will create a new {@link ie.omk.smpp.net.TcpLink} object
* using the host name and port provided. The connection created will use
* synchronous communications.
* @param host the hostname of the SMSC.
* @param port the port to connect to. If 0, use the default SMPP port
* number.
*/
public Connection(String host, int port)
throws java.net.UnknownHostException
{
this (new TcpLink(host, port), false);
}
/** Initialise a new SMPP connection object. This is a convenience
* constructor that will create a new {@link ie.omk.smpp.net.TcpLink} object
* using the host name and port provided.
* @param host the hostname of the SMSC.
* @param port the port to connect to. If 0, use the default SMPP port
* number.
* @param async true for asyncronous communication, false for synchronous.
*/
public Connection(String host, int port, boolean async) throws java.net.UnknownHostException {
this (new TcpLink(host, port), async);
}
/** Initialise a new SMPP connection object. The connection will use
* synchronous communications.
* @param link The network link object to the Smsc (cannot be null)
*/
public Connection(SmscLink link)
{
this (link, false);
}
/** Initialise a new SMPP connection object, specifying the type of
* communication desired. See the {@link Connection} class description for
* some required knowledge on using the Connection in syncrhonous mode.
* @param link The network link object to the Smsc (cannot be null)
* @param async true for asyncronous communication, false for synchronous.
*/
public Connection(SmscLink link, boolean async)
{
this.link = link;
this.asyncComms = async;
if (asyncComms) {
initAsyncComms();
} else {
initSyncComms();
}
}
private void initAsyncComms() {
String className = "";
try {
className = APIConfig.getInstance().getProperty(APIConfig.EVENT_DISPATCHER_CLASS);
if (className != null && !"".equals(className)) {
Class cl = Class.forName(className);
eventDispatcher = (EventDispatcher)cl.newInstance();
} else {
logger.info("EventDispatcher property value is empty.");
}
} catch (PropertyNotFoundException x) {
logger.debug("No event dispatcher specified in properties. Using default.");
} catch (ClassNotFoundException x) {
logger.error("Cannot locate event dispatcher class " + className, x);
} catch (Exception x) {
// Something wrong with the implementation.
StringBuffer errorMessage = new StringBuffer();
errorMessage.append("Event dispatcher implementation is ")
.append("incorrect.\n")
.append(className)
.append(" should implement ie.omk.smpp.event.EventDispatcher ")
.append("and have a default constructor.\n")
.append("Falling back to default implementation after ")
.append("receiving exception.");
logger.error(errorMessage.toString(), x);
} finally {
if (eventDispatcher == null)
eventDispatcher = new SimpleEventDispatcher();
}
// Initialise the event dispatcher
eventDispatcher.init();
// Create the receiver daemon thread.
createRecvThread();
}
private void initSyncComms() {
packetQueue = new ArrayList();
}
/** Create the receiver thread if asynchronous communications is on, does
* nothing otherwise.
*/
private void createRecvThread()
{
logger.info("Creating receiver thread");
rcvThread = new Thread(this, "ReceiverDaemon");
rcvThread.setDaemon(true);
}
/** Set the default alphabet of the SMSC this <code>Connection</code> is
* communicating with. Each SMSC has its own default alphabet it uses. When
* messages arrive and announce themselves with a data coding value of zero,
* that means the message is encoded in the SMSC's default alphabet. The
* smppapi assumes the GSM default alphabet as it's default alphabet. By
* setting the default alphabet on the <code>Connection</code> all packets
* returned by {@link #newInstance(int)} will use the Connection's default
* alphabet plus any packets read from the wire with a data coding value of
* zero will have their default alphabet initialised appropriately.
* @param alphabet the alphabet to use as the default for this connection
* (may be <code>null</code> in which case the API falls back to using its
* own internal default).
*/
public void setDefaultAlphabet(AlphabetEncoding alphabet) {
this.defaultAlphabet = alphabet;
}
/** Get the current alphabet this <code>Connection</code> is using as its
* default.
* @return the default alphabet for this <code>Connection</code>.
*/
public AlphabetEncoding getDefaultAlphabet() {
return (defaultAlphabet);
}
/** Set the state of this ESME.
* @see ie.omk.smpp.Connection#getState
*/
private synchronized void setState(int state)
{
logger.info("Setting state " + state);
this.state = state;
}
/** Set the SMPP version this connection will use. Setting the version is
* only a valid operation before the connection is bound. Any attempt to set
* the version after binding to the SMSC will result in an exception being
* thrown.
* @param version the SMPP version to use.
* @throws ie.omk.smpp.version.VersionException if an attempt is made to set
* the version of the connection after binding to the SMSC.
* @see ie.omk.smpp.version.SMPPVersion
*/
public void setVersion(SMPPVersion version) throws VersionException {
if (getState() != UNBOUND)
throw new VersionException("Cannot set SMPP version after binding");
if (version == null)
this.interfaceVersion = SMPPVersion.getDefaultVersion();
else
this.interfaceVersion = version;
}
/** Get the SMPP version in use by this connection. The version in use by
* the connection <b>may</b> be different to that specified before the bind
* operation as binding to the SMSC may result in an alternative SMPP
* version being negotiated. For instance, if the client sends a bind packet
* to the SMSC specifying that it supports SMPP version 3.4 but the SMSC
* returns a bind_resp stating it supports version 3.3, the Connection
* automatically sets it's internal version to use down to 3.3.
*/
public SMPPVersion getVersion() {
return (interfaceVersion);
}
/** Get the current state of the ESME. One of UNBOUND, BINDING, BOUND or
* UNBINDING.
*/
public synchronized int getState()
{
return (this.state);
}
/** Method to open the link to the SMSC. This method will connect the
* underlying SmscLink object if necessary and reset the sequence numbering
* scheme to the beginning.
* @throws java.io.IOException if an i/o error occurs while opening the
* connection.
*/
protected void openLink()
throws java.io.IOException
{
if (!this.link.isConnected()) {
logger.info("Opening network link.");
this.link.open();
if (this.seqNumScheme != null)
this.seqNumScheme.reset();
} else {
logger.debug("openLink called, link already open");
}
}
/** Close the underlying network link to the SMSC. This method calls the
* underlying link's <code>close</code> method to actually shutdown
* the network connection to the SMSC.
* @throws ie.omk.smpp.IllegalStateException if an attempt is made to close
* the connection while bound to the SMSC.
* @throws java.io.IOException if an I/O exception occurs while trying to
* close the link.
* @see ie.omk.smpp.net.SmscLink#close
*/
public void closeLink() throws IOException {
if (getState() != UNBOUND)
throw new IllegalStateException("Cannot close the link while bound to the SMSC");
if (this.link.isConnected()) {
logger.info("Shutting down the network link");
this.link.close();
} else {
logger.debug("closeLink called on an unopen connection");
}
}
/** Get the interface version.
* @see #setInterfaceVersion(SMPPVersion)
*/
public SMPPVersion getInterfaceVersion()
{
return (this.interfaceVersion);
}
/** Set the desired interface version for this connection. The default
* version is 3.3 (XXX soon to be 3.4). The bind operation may negotiate
* an eariler version of the protocol if the SC does not understand the
* version sent by the ESME. This API will not support any version eariler
* than SMPP v3.3. The interface version is encoded as follows:
* <table border="1" cellspacing="1" cellpadding="1">
* <tr><th>SMPP version</th><th>Version value</th></tr>
* <tr><td>v3.4</td><td>0x34</td></tr>
* <tr><td>v3.3</td><td>0x33</td></tr>
* <tr>
* <td colspan="2" align="center"><i>All other values reserved.</i></td>
* </tr>
* </table>
*/
public void setInterfaceVersion(SMPPVersion interfaceVersion)
{
logger.info("setInterfaceVersion " + interfaceVersion);
this.interfaceVersion = interfaceVersion;
}
/** Set the behaviour of automatically acking ENQUIRE_LINK's from the SMSC.
* By default, the listener thread will automatically ack an enquire_link
* message from the Smsc so as not to lose the connection. This
* can be turned off with this method.
* @param true to activate automatic acknowledgment, false to disable
*/
public void autoAckLink(boolean b)
{
this.ackQryLinks = b;
}
/** Set the behaviour of automatically acking Deliver_Sm's from the Smsc.
* By default the listener thread will <b>not</b> acknowledge a message.
* @param true to activate this function, false to deactivate.
*/
public void autoAckMessages(boolean b)
{
this.ackDeliverSm = b;
}
/** Check is this connection automatically acking Enquire link requests.
*/
public boolean isAckingLinks()
{
return (ackQryLinks);
}
/** Check is this connection automatically acking delivered messages
*/
public boolean isAckingMessages()
{
return (ackDeliverSm);
}
/** Acknowledge a DeliverSM command received from the Smsc.
* @param rq The deliver_sm request to respond to.
* @throws java.io.IOException If an I/O error occurs writing the response
* packet to the network connection.
*/
public void ackDeliverSm(DeliverSM rq)
throws java.io.IOException
{
DeliverSMResp rsp = new DeliverSMResp(rq);
sendResponse(rsp);
logger.info("deliver_sm_resp sent.");
}
/** Send an smpp request to the SMSC.
* No fields in the SMPPRequest packet will be altered except possibly the
* sequence number. The sequence number will be assigned the next number as
* defined by this Connection's sequence numbering scheme. If the sequence
* numbering scheme class is <code>null</code> for this Connection, no
* number will be assigned. By default, the
* {@link ie.omk.smpp.util.DefaultSequenceScheme} class is used to assign
* sequence numbers to packets.
* @param r The request packet to send to the SMSC
* @return The response packet returned by the SMSC, or null if
* asynchronous communication is being used.
* @throws java.lang.NullPointerException if <code>r</code> is null.
* @throws java.net.SocketTimeoutException If a socket timeout occurs while
* waiting for a response packet. (Only in synchronized mode).
* @throws java.io.IOException If an I/O error occurs while writing the
* request packet to the network connection.
* @throws ie.omk.smpp.UnsupportedOperationException If this connection
* type does not support operation <code>r</code>. For example, a receiver
* link does not support the submit_sm operation.
* @throws ie.omk.smpp.AlreadyBoundException If the request type is a bind
* packet and this connection is already bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous
* communications is in use and the incoming response packet violates the
* SMPP specification, this exception will be thrown.
* @see #setSeqNumScheme
*/
public SMPPResponse sendRequest(SMPPRequest r)
throws java.net.SocketTimeoutException, java.io.IOException, AlreadyBoundException, VersionException, SMPPProtocolException, UnsupportedOperationException
{
SMPPResponse resp = null;
int id = r.getCommandId();
if (this.state != BOUND)
throw new NotBoundException("Must be bound to the SMSC before "
+ "sending packets");
// Very few request types allowed by a receiver connection.
if (connectionType == RECEIVER) {
if (id != SMPPPacket.ENQUIRE_LINK && id != SMPPPacket.UNBIND)
throw new UnsupportedOperationException(
"Operation not permitted over receiver connection");
}
return (sendRequestInternal(r));
}
/** Send a request to the SMSC.
* XXX complete javadoc for this method.
* @throws ie.omk.smpp.version.VersionException if the version in use
* does not support the request being sent.
*/
protected SMPPResponse sendRequestInternal(SMPPRequest r)
throws java.net.SocketTimeoutException, java.io.IOException, AlreadyBoundException, VersionException, SMPPProtocolException {
SMPPResponse resp = null;
int id = r.getCommandId();
if (link == null)
throw new IOException("No SMSC connection.");
// Check the command is supported by the interface version..
if (!this.interfaceVersion.isSupported(id)) {
throw new VersionException("Command ID 0x"
+ Integer.toHexString(id)
+ " is not supported by SMPP "
+ this.interfaceVersion);
}
if (id == SMPPPacket.BIND_TRANSMITTER
|| id == SMPPPacket.BIND_RECEIVER
|| id == SMPPPacket.BIND_TRANSCEIVER) {
if (this.state != UNBOUND)
throw new AlreadyBoundException("Already bound to the SMSC");
openLink();
setState(BINDING);
if (asyncComms) {
if (rcvThread == null)
createRecvThread();
if (!rcvThread.isAlive())
rcvThread.start();
}
} else if (id == SMPPPacket.UNBIND) {
if (!asyncComms && packetQueue.size() > 0)
throw new IllegalStateException("Cannot unbind while there are incoming packets "
+ "waiting responses");
if (this.state != BOUND)
throw new IllegalStateException("Not currently bound");
setState(UNBINDING);
}
// XXX temporary...this should be removed once it's safe to assume that
// no packet can be submitted that has been constructed outside the
// confines of this connection's factory method.
if (r.getSequenceNum() == 0 && seqNumScheme != null)
r.setSequenceNum(seqNumScheme.nextNumber());
link.write(r);
if (!asyncComms)
resp = waitForResponsePacket(r);
return ((SMPPResponse)resp);
}
/** Wait for a response packet from the SMSC. A response packet with the
* same sequence number as <code>req</code> will be waited for from the
* SMSC. If an unexpected packet arrives, either a response packet with a
* different sequence number or a request packet, it will be queued for
* later retrieval by the application via <code>readNextPacket</code>.
* @param req the request packet to wait for a response to.
* @return A response packet with the same sequence number as
* <code>req</code>.
* @throws java.net.SocketTimeoutException if the read on the socket times
* out.
* @see #readNextPacket
* @see java.net.SocketTimeoutException
*/
protected SMPPResponse waitForResponsePacket(SMPPPacket req)
throws java.net.SocketTimeoutException, java.io.IOException, SMPPProtocolException {
try {
int id = -1;
SMPPPacket resp = null;
int expectedSeq = req.getSequenceNum();
while (true) {
resp = readNextPacketInternal();
id = resp.getCommandId();
if ((id & 0x80000000) != 0
&& resp.getSequenceNum() == expectedSeq) {
break;
} else {
logger.info("Queuing unexpected sequence numbered packet.");
if (logger.isDebugEnabled()) {
StringBuffer b = new StringBuffer("Expected:")
.append(Integer.toString(expectedSeq))
.append(" but got ")
.append(Integer.toString(resp.getSequenceNum()));
logger.debug(b.toString());
}
packetQueue.add(resp);
}
}
return ((SMPPResponse)resp);
} catch (java.net.SocketTimeoutException x) {
// Must set our state and re-throw the exception..
logger.error("Received a socket timeout exception", x);
throw x;
}
}
/** Determine if there are packets available for reading using
* <code>readNextPacket</code>. This method is only valid for synchronous
* communications...it will always return 0 if asynchronous mode is in
* use.
* @return 0 if there is no packet available for reading, 1 if there is data
* available but the call to <code>readNextPacket</code> may block or 2 if
* there is a full packet available.
*/
public int packetAvailable() {
int ret = 0;
if (!asyncComms) {
if (packetQueue.size() > 0)
ret = 2;
else if (link.available() > 0)
ret = 1;
}
return (ret);
}
/** Send an smpp response packet to the SMSC
* @param r The response packet to send to the SMSC
* @throws java.io.IOException If an I/O error occurs while writing the
* response packet to the output stream.
*/
public void sendResponse(SMPPResponse resp)
throws java.io.IOException
{
Integer key = null;
if (link == null)
throw new IOException("Connection to SMSC is not valid.");
try {
link.write(resp);
} catch (java.net.SocketTimeoutException x) {
logger.warn("Got a socket timeout exception", x);
setState(UNBOUND);
throw x;
}
if (resp.getCommandId() == SMPPPacket.UNBIND_RESP
&& resp.getCommandStatus() == 0)
setState(UNBOUND);
}
/** Bind this connection to the SMSC. An application must bind to an SMSC as
* one of transmitter, receiver or transceiver. Binding as transmitter
* allows general manipulation of messages at the SMSC including submitting
* messages for delivery, cancelling, replacing and querying the state of
* previously submitted messages. Binding as a receiver allows an
* application to receive all messages previously queued for delivery to
* it's address. The transceiver mode, which was added in version 3.4 of the
* SMPP protocol, combines the functionality of both transmitter and
* receiver into one connection type.
* <p>Note that it is only necessary to supply values for
* <code>type, systemID</code> and <code>password</code>. The other
* arguments may be left at null (or zero, as applicable).</p>
* @param type connection type to use, either {@link #TRANSMITTER},
* {@link #RECEIVER} or {@link #TRANSCEIVER}.
* @param systemID the system ID to identify as to the SMSC.
* @param password password to use to authenticate to the SMSC.
* @param systemType the system type to bind as.
* @return the bind response packet.
* @throws java.lang.IllegalArgumentException if a bad <code>type</code>
* value is supplied.
* @throws ie.omk.smpp.VersionException if an attempt is made
* to bind as transceiver while using SMPP version 3.3.
* @throws ie.omk.smpp.InvalidParameterValueException If any of systemID,
* password, system type or address range are outside allowed bounds or the
* TON or NPI is invalid.
* @throws java.io.IOException If an I/O error occurs while writing the bind
* packet to the output stream.
* @throws ie.omk.smpp.AlreadyBoundException If the Connection is already
* bound.
* @throws ie.omk.smpp.SMPPProtocolExcpetion if synchronous communication is
* in use and the incoming response packet violates the SMPP protocol.
*/
public BindResp bind(int type,
String systemID,
String password,
String systemType)
throws java.io.IOException, InvalidParameterValueException, IllegalArgumentException, AlreadyBoundException, VersionException, SMPPProtocolException
{
return (this.bind(type, systemID, password, systemType, 0, 0, null));
}
/** Bind this connection to the SMSC. An application must bind to an SMSC as
* one of transmitter, receiver or transceiver. Binding as transmitter
* allows general manipulation of messages at the SMSC including submitting
* messages for delivery, cancelling, replacing and querying the state of
* previously submitted messages. Binding as a receiver allows an
* application to receive all messages previously queued for delivery to
* it's address. The transceiver mode, which was added in version 3.4 of the
* SMPP protocol, combines the functionality of both transmitter and
* receiver into one connection type.
* <p>Note that it is only necessary to supply values for
* <code>type, systemID</code> and <code>password</code>. The other
* arguments may be left at null (or zero, as applicable).</p>
* @param type connection type to use, either {@link #TRANSMITTER},
* {@link #RECEIVER} or {@link #TRANSCEIVER}.
* @param systemID the system ID to identify as to the SMSC.
* @param password password to use to authenticate to the SMSC.
* @param systemType the system type to bind as.
* @param typeOfNum the TON of the address to bind as.
* @param numberPlan the NPI of the address to bind as.
* @param addrRange the address range regular expression to bind as.
* @return the bind response packet.
* @throws java.lang.IllegalArgumentException if a bad <code>type</code>
* value is supplied.
* @throws ie.omk.smpp.VersionException if an attempt is made
* to bind as transceiver while using SMPP version 3.3.
* @throws ie.omk.smpp.InvalidParameterValueException If any of systemID,
* password, system type or address range are outside allowed bounds.
* @throws java.io.IOException If an I/O error occurs while writing the bind
* packet to the output stream.
* @throws ie.omk.smpp.AlreadyBoundException If the Connection is already
* bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous comms is
* in use and the incoming bind response packet violates the SMPP
* specification, this exception is thrown.
*/
public BindResp bind(int type,
String systemID,
String password,
String systemType,
int typeOfNum,
int numberPlan,
String addrRange)
throws java.io.IOException, InvalidParameterValueException, IllegalArgumentException, AlreadyBoundException, VersionException, SMPPProtocolException
{
Bind bindReq = null;
switch (type) {
case TRANSMITTER:
bindReq = new BindTransmitter();
break;
case RECEIVER:
bindReq = new BindReceiver();
break;
case TRANSCEIVER:
if (this.interfaceVersion.isOlder(SMPPVersion.V34)) {
throw new VersionException("Cannot bind as "
+ "transceiver "
+ interfaceVersion.toString());
}
bindReq = new BindTransceiver();
break;
default:
throw new IllegalArgumentException("No such connection type.");
}
this.connectionType = type;
logger.info("Binding to the SMSC as type " + type);
bindReq.setVersion(interfaceVersion);
bindReq.setSystemId(systemID);
bindReq.setPassword(password);
bindReq.setSystemType(systemType);
bindReq.setAddressTon(typeOfNum);
bindReq.setAddressNpi(numberPlan);
bindReq.setAddressRange(addrRange);
return ((BindResp)sendRequestInternal(bindReq));
}
/** Unbind from the SMSC. This method will unbind the SMPP protocol
* connection from the SMSC. No further SMPP operations will be possible
* once unbound. If the calling application is using sync mode, it should be
* sure there are no incoming packets awaiting a response (check using
* {@link #packetAvailable}), otherwise an
* <code>IllegalStateException</code> may be thrown. Note that this method
* will <b>not</b> close the underlying network connection.
* @return The Unbind response packet, or null if asynchronous
* communication is being used.
* @throws ie.omk.smpp.NotBoundException if the connection is not yet
* bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous comms is
* in use and the incoming unbind_resp packet violates the SMPP
* specification, this exception is thrown.
* @throws java.io.IOException If an I/O error occurs while writing the
* unbind request or reading the unbind response.
*/
public UnbindResp unbind()
throws java.io.IOException, NotBoundException, SMPPProtocolException
{
if((state != BOUND) || !(link.isConnected()))
throw new NotBoundException();
try {
logger.info("Unbinding from the SMSC");
Unbind u = (Unbind)newInstance(SMPPPacket.UNBIND);
return ((UnbindResp)sendRequest(u));
} catch (VersionException x) {
// impossible...every version supports unbind!
throw new SMPPRuntimeException("Internal smppapi error");
} catch (BadCommandIDException x) {
// similarly impossible!
throw new SMPPRuntimeException("Internal smppapi error");
}
}
/** Unbind from the SMSC. This method is used to acknowledge an unbind
* request from the SMSC.
* @throws ie.omk.smpp.NotBoundException if the connection is not currently
* bound.
* @throws ie.omk.smpp.AlreadyBoundException if no unbind request has
* been received from the SMSC.
* @throws java.io.IOException If an I/O error occurs while writing the
* response packet to the network connection.
*/
public void unbind(UnbindResp ubr)
throws java.io.IOException, ie.omk.smpp.SMPPException
{
if (state != UNBINDING)
throw new NotBoundException("Link is not connected.");
if (!(link.isConnected()))
throw new AlreadyBoundException("No unbind request received.");
sendResponse(ubr);
}
/** Force the SMPP connection down.
* Only use this method once it's full sure that graceful unbinding and
* disconnection isn't going to work. This method cleans up it's internal
* state, forcing the network connection closed and terminating the receiver
* thread if necessary.
* <p>If you end up having to use this method to terminate a Connection, it
* is advisable not to attempt to reuse the connection at all. Create a new
* object and start from scratch. Use of this method indicates something
* seriously wrong!</p>
*/
public void force_unbind()
{
logger.warn("Attempting to force SMPP connection down.");
try {
setState(UNBOUND);
// The thread must DIE!!!!
if(rcvThread != null && rcvThread.isAlive()) {
try {
// Wait to see if the thread will terminate due to the state
// becoming UNBOUND.
Thread.sleep(1000);
} catch (InterruptedException x) {
logger.debug("Interrupted exception waiting on receiver to die", x);
}
if (rcvThread.isAlive())
logger.error("Listener thread has not died.");
rcvThread = null;
}
link.close();
} catch(IOException ix) {
logger.warn("Forced unbind caused IO exception", ix);
}
return;
}
/** Acknowledge an EnquireLink received from the Smsc
* @throws java.io.IOException If an I/O error occurs while writing to the
* network connection.
*/
public void ackEnquireLink(EnquireLink rq)
throws java.io.IOException
{
EnquireLinkResp resp = new EnquireLinkResp(rq);
sendResponse(resp);
logger.info("enquire_link_resp sent.");
}
/** Do a confidence check on the SMPP link to the SMSC.
* @return The Enquire link response packet or null if asynchronous
* communication is in use.
* @throws java.io.IOException If an I/O error occurs while writing to the
* network connection.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous
* communications is in use and the incoming enquire_link_resp packet
* violates the SMPP specification, this exception is thrown.
*/
public EnquireLinkResp enquireLink()
throws java.io.IOException, SMPPProtocolException
{
try {
EnquireLink s = (EnquireLink)newInstance(SMPPPacket.ENQUIRE_LINK);
SMPPResponse resp = sendRequest(s);
logger.debug("enquire_link request sent.");
if (resp != null)
logger.debug("enquire_link_response received.");
return ((EnquireLinkResp)resp);
} catch (BadCommandIDException x) {
throw new SMPPRuntimeException("Internal smppapi error");
}
}
/** Get the type of this SMPP connection. The connection type is one of
* TRANSMITTER, RECEIVER or TRANSCEIVER.
*/
public int getConnectionType()
{
return (connectionType);
}
/** Report whether the connection is bound or not.
* @return true if the connection is bound.
*/
public boolean isBound()
{
return (state == BOUND);
}
/** Reset this connection's sequence numbering to the beginning. The
* underlying SequenceNumberScheme's reset method is called to start from
* that sequence's 'beginning'.
* @throws ie.omk.smpp.AlreadyBoundException if the connection is
* currently bound to the SMSC.
*/
public void reset()
throws AlreadyBoundException
{
if(state == BOUND) {
logger.warn("Attempt to reset sequence numbering on a bound connection");
throw new AlreadyBoundException("Cannot reset connection while bound");
}
if (this.seqNumScheme != null)
this.seqNumScheme.reset();
logger.info("Sequence numbering reset.");
}
/** Set the sequence numbering scheme for this connection. A sequence
* numbering scheme determines what sequence number each SMPP packet will
* have. By default, {@link ie.omk.smpp.util.DefaultSequenceScheme} is used,
* which will begin with sequence number 1 and increase the number by 1 for
* each packet thereafter.
* <p>If the application sets the <code>scheme</code> to null, it is
* responsible for maintaining and setting the sequence number for each SMPP
* request it sends to the SMSC.
* @see ie.omk.smpp.util.SequenceNumberScheme
* @see ie.omk.smpp.message.SMPPPacket#setSequenceNum
*/
public void setSeqNumScheme(SequenceNumberScheme scheme) {
this.seqNumScheme = scheme;
}
/** Get the current sequence numbering scheme object being used by this
* connection.
*/
public SequenceNumberScheme getSeqNumScheme() {
return (this.seqNumScheme);
}
/** Read in the next packet from the SMSC link.
* If asynchronous communications is in use, calling this method results in
* an SMPPException as the listener thread will be hogging the input stream
* of the socket connection.
* @return The next SMPP packet from the SMSC.
* @throws java.io.IOException If an I/O error occurs while reading from
* the network connection.
* @throws ie.omk.smpp.InvalidOperationException If asynchronous comms
* is in use.
* @throws ie.omk.smpp.message.SMPPProtocolException if the incoming data
* violates the SMPP protocol specifications.
*/
public SMPPPacket readNextPacket()
throws java.io.IOException, InvalidOperationException, SMPPProtocolException
{
if (asyncComms) {
throw new InvalidOperationException("Asynchronous comms in use.");
} else {
if (packetQueue.size() > 0)
return ((SMPPPacket)packetQueue.remove(0));
else
return (readNextPacketInternal());
}
}
/** Read the next packet from the SMSC link. Internal version...handles
* special case packets like bind responses and unbind request and
* responses.
* @return The read SMPP packet, or null if the connection timed out.
* @throws java.io.IOException If an I/O error occurs while reading from
* the network connection.
*/
private SMPPPacket readNextPacketInternal()
throws java.io.IOException, SMPPProtocolException
{
try {
SMPPPacket pak = null;
int id = -1, st = -1;
this.buf = link.read(this.buf);
id = SMPPIO.bytesToInt(this.buf, 4, 4);
pak = PacketFactory.newInstance(id);
if (pak != null) {
pak.readFrom(this.buf, 0);
if (logger.isDebugEnabled()) {
StringBuffer b = new StringBuffer("Packet Received: ");
int l = pak.getLength();
int s = pak.getCommandStatus();
int n = pak.getSequenceNum();
b.append("id:").append(Integer.toHexString(id));
b.append(" len:").append(Integer.toString(l));
b.append(" st:").append(Integer.toString(s));
b.append(" sq:").append(Integer.toString(n));
logger.debug(b.toString());
}
// Special case handling for certain packet types..
st = pak.getCommandStatus();
switch (pak.getCommandId()) {
case SMPPPacket.BIND_TRANSMITTER_RESP:
case SMPPPacket.BIND_RECEIVER_RESP:
case SMPPPacket.BIND_TRANSCEIVER_RESP:
handleBindResp((BindResp)pak);
break;
case SMPPPacket.UNBIND_RESP:
handleUnbindResp((UnbindResp)pak);
break;
case SMPPPacket.UNBIND:
handleUnbind((Unbind)pak);
break;
}
if (st == 0) {
// Fix up the alphabet for this connection type if the
// packet needs it. DCS value 0 means the alphabet is in the
// default encoding of the SMSC, which varies depending on
// implementation.
if (defaultAlphabet != null && pak.getDataCoding() == 0)
pak.setAlphabet(defaultAlphabet);
}
}
return (pak);
} catch (BadCommandIDException x) {
throw new SMPPProtocolException("Unrecognised command received", x);
}
}
/** Handle an incoming bind response packet. Method is called by a few
* methods in this class that read from the incoming connection.
*/
private void handleBindResp(BindResp resp) {
if (state == BINDING && resp.getCommandStatus() == 0)
setState(BOUND);
}
/** Handle an incoming unbind packet.
*/
private void handleUnbind(Unbind req) {
logger.info("SMSC requested unbind");
setState(UNBINDING);
}
/** Handle an incoming unbind response packet.
*/
private void handleUnbindResp(UnbindResp resp) {
if (state == UNBINDING && resp.getCommandStatus() == 0) {
logger.info("Successfully unbound");
setState(UNBOUND);
}
}
/** Set the event dispatcher for this connection object. Before using the
* new event dispatcher, this method will call
* {@link EventDispatcher#init} to initialise the dispatcher. It will then
* iterate through all the observers registered with the current event
* dispatcher and register them with the new one.
* <p>It is not a particularly good idea to set the event dispatcher after
* communications have begun. However, the observer copy is guarded against
* multi-threaded access to the current event dispatcher. During the copy,
* however, events will continue to be delievered via the current
* dispatcher. Only <b>after</b> the copy is complete will the new event
* dispatcher become the active one and events begin being delivered by
* it.</p>
* <p>The caller of this method can be sure that, once this method returns,
* all new events will be handled by the new event dispatcher. However,
* there may be events that occurred before, or during the operation of, the
* call to this method which will be delivered by the old dispatcher. Once
* the new event dispatcher is in place, the {@link EventDispatcher#destroy}
* method will be called on the old dispatcher.</p>
*/
public void setEventDispatcher(EventDispatcher eventDispatcher) {
if (eventDispatcher == null)
throw new NullPointerException("Event dispatcher cannot be null");
eventDispatcher.init();
// Copy all current observers to the new event dispatcher..
synchronized (this.eventDispatcher) {
Iterator iter = this.eventDispatcher.observerIterator();
while (iter.hasNext())
eventDispatcher.addObserver((ConnectionObserver)iter.next());
}
EventDispatcher old = this.eventDispatcher;
// ..and swap out the old dispatcher.
this.eventDispatcher = eventDispatcher;
// Clean up the old dispatcher.
old.destroy();
}
/** Add a connection observer to receive SMPP events from this connection.
* If this connection is not using asynchronous communication, this method
* call has no effect.
* @param ob the ConnectionObserver implementation to add.
*/
public void addObserver(ConnectionObserver ob) {
if (eventDispatcher != null)
eventDispatcher.addObserver(ob);
}
/** Remove a connection observer from this Connection.
*/
public void removeObserver(ConnectionObserver ob) {
if (eventDispatcher != null)
eventDispatcher.removeObserver(ob);
}
/** Listener thread method for asynchronous communication.
*/
public void run()
{
SMPPPacket pak = null;
int smppEx = 0, id = 0, st = 0;
SMPPEvent exitEvent = null;
int tooManyIOEx = 5;
logger.info("Receiver thread started");
try {
tooManyIOEx =
APIConfig.getInstance().getInt(APIConfig.TOO_MANY_IO_EXCEPTIONS);
} catch (PropertyNotFoundException x) {
// just stick with the default
logger.debug("Didn't find I/O exception config. Using default of "
+ tooManyIOEx);
}
eventDispatcher.notifyObservers(this, new ReceiverStartEvent(this));
try {
while (state != UNBOUND) {
try {
pak = readNextPacketInternal();
if (pak == null) {
// XXX Send an event to the application??
continue;
}
} catch (SocketTimeoutException x) {
// is it okay to ignore this ??
logger.info("Ignoring SocketTimeoutException");
continue;
} catch (EOFException x) {
// The network connection has disappeared! Wah!
logger.error("EOFException received in daemon thread.", x);
// Will be caught by the general handler lower in this
// method.
throw x;
} catch (IOException x) {
logger.warn("I/O Exception caught", x);
ReceiverExceptionEvent ev =
new ReceiverExceptionEvent(this, x, state);
eventDispatcher.notifyObservers(this, ev);
smppEx++;
if (smppEx > tooManyIOEx) {
logger.warn("Too many IOExceptions in receiver thread", x);
throw x;
}
continue;
}
// Reset smppEx back to zero if we reach here, as packet
// reception was successful.
smppEx = 0;
id = pak.getCommandId();
st = pak.getCommandStatus();
// Handle special case packets..
switch (id) {
case SMPPPacket.DELIVER_SM:
if (ackDeliverSm)
ackDeliverSm((DeliverSM)pak);
break;
case SMPPPacket.ENQUIRE_LINK:
if (ackQryLinks)
ackEnquireLink((EnquireLink)pak);
break;
}
// Tell all the observers about the new packet
logger.info("Notifying observers of packet received");
eventDispatcher.notifyObservers(this, pak);
} // end while
// Notify observers that the thread is exiting with no error..
exitEvent = new ReceiverExitEvent(this, null, state);
} catch (Exception x) {
logger.error("Fatal exception in receiver thread", x);
exitEvent = new ReceiverExitEvent(this, x, state);
setState(UNBOUND);
} finally {
// make sure other code doesn't try to restart the rcvThread..
rcvThread = null;
}
if (exitEvent != null)
eventDispatcher.notifyObservers(this, exitEvent);
// Clean up the event dispatcher.
eventDispatcher.destroy();
}
/**
* @deprecated #ackEnquireLink
*/
public void ackLinkQuery(EnquireLink el)
throws java.io.IOException
{
ackEnquireLink(el);
}
/** Get a new instance of an SMPP packet. The packet will be initialised so
* that it uses the same SMPP version as this connection and it's sequence
* number will be initialised to using this connection's sequence numbering
* scheme.
* @param commandId the SMPP command ID of the packet to retrieve.
* @return a subclass of {@link ie.omk.smpp.message.SMPPPacket}
* corresponding to SMPP command <code>commandId</code>.
* @throws ie.omk.smpp.BadCommandIDException if the command ID is not
* recognised.
* @throws ie.omk.smpp.NotSupportedException if the Connection is currently
* using an SMPP version which does not support SMPP command
* <code>commandId</code>.
*/
public SMPPPacket newInstance(int commandId) throws BadCommandIDException, VersionException {
if (!this.interfaceVersion.isSupported(commandId))
throw new VersionException("Command is not supported in this SMPP version");
SMPPPacket response = PacketFactory.newInstance(commandId);
response.setVersion(this.interfaceVersion);
if (this.seqNumScheme != null)
response.setSequenceNum(this.seqNumScheme.nextNumber());
if (defaultAlphabet != null)
response.setAlphabet(defaultAlphabet, 0);
return (response);
}
}
| src/ie/omk/smpp/Connection.java | /*
* Java SMPP API
* Copyright (C) 1998 - 2002 by Oran Kelly
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* A copy of the LGPL can be viewed at http://www.gnu.org/copyleft/lesser.html
* Java SMPP API author: [email protected]
* Java SMPP API Homepage: http://smppapi.sourceforge.net/
* $Id$
*/
package ie.omk.smpp;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;
import ie.omk.smpp.event.ConnectionObserver;
import ie.omk.smpp.event.EventDispatcher;
import ie.omk.smpp.event.SimpleEventDispatcher;
import ie.omk.smpp.event.SMPPEvent;
import ie.omk.smpp.event.ReceiverExceptionEvent;
import ie.omk.smpp.event.ReceiverExitEvent;
import ie.omk.smpp.event.ReceiverStartEvent;
import ie.omk.smpp.message.AlertNotification;
import ie.omk.smpp.message.Bind;
import ie.omk.smpp.message.BindReceiver;
import ie.omk.smpp.message.BindReceiverResp;
import ie.omk.smpp.message.BindResp;
import ie.omk.smpp.message.BindTransceiver;
import ie.omk.smpp.message.BindTransceiverResp;
import ie.omk.smpp.message.BindTransmitter;
import ie.omk.smpp.message.BindTransmitterResp;
import ie.omk.smpp.message.CancelSM;
import ie.omk.smpp.message.CancelSMResp;
import ie.omk.smpp.message.DataSM;
import ie.omk.smpp.message.DataSMResp;
import ie.omk.smpp.message.DeliverSM;
import ie.omk.smpp.message.DeliverSMResp;
import ie.omk.smpp.message.EnquireLink;
import ie.omk.smpp.message.EnquireLinkResp;
import ie.omk.smpp.message.GenericNack;
import ie.omk.smpp.message.InvalidParameterValueException;
import ie.omk.smpp.message.ParamRetrieve;
import ie.omk.smpp.message.ParamRetrieveResp;
import ie.omk.smpp.message.QueryLastMsgs;
import ie.omk.smpp.message.QueryLastMsgsResp;
import ie.omk.smpp.message.QueryMsgDetails;
import ie.omk.smpp.message.QueryMsgDetailsResp;
import ie.omk.smpp.message.QuerySM;
import ie.omk.smpp.message.QuerySMResp;
import ie.omk.smpp.message.ReplaceSM;
import ie.omk.smpp.message.ReplaceSMResp;
import ie.omk.smpp.message.SMPPPacket;
import ie.omk.smpp.message.SMPPProtocolException;
import ie.omk.smpp.message.SMPPRequest;
import ie.omk.smpp.message.SMPPResponse;
import ie.omk.smpp.message.SubmitMulti;
import ie.omk.smpp.message.SubmitMultiResp;
import ie.omk.smpp.message.SubmitSM;
import ie.omk.smpp.message.SubmitSMResp;
import ie.omk.smpp.message.Unbind;
import ie.omk.smpp.message.UnbindResp;
import ie.omk.smpp.net.SmscLink;
import ie.omk.smpp.net.TcpLink;
import ie.omk.smpp.util.AlphabetEncoding;
import ie.omk.smpp.util.APIConfig;
import ie.omk.smpp.util.DefaultSequenceScheme;
import ie.omk.smpp.util.PacketFactory;
import ie.omk.smpp.util.PropertyNotFoundException;
import ie.omk.smpp.util.SequenceNumberScheme;
import ie.omk.smpp.util.SMPPDate;
import ie.omk.smpp.util.SMPPIO;
import ie.omk.smpp.version.SMPPVersion;
import ie.omk.smpp.version.VersionException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/** SMPP client connection (ESME). An SMPP Connection represents any kind of
* connection to the SMSC, be it a transmitter, receiver or transceiver. It also
* supports both synchronous and asynchronous modes of communication.
* Synchronous mode is only useful for very simple applications that use
* single-threading. Asynchronous mode is recommended for more complex
* applications, especially those that will be running many threads.
* <p><b>Important Note</b>: if you wish to use synchronous mode in a
* multi-threaded environment, it is the <u>application's</u> responsiblity to
* ensure there is only one thread executing a call to either or both of the
* <code>sendRequest</code> and <code>readNextPacket</code> methods. If there
* are concurrent calls to these methods executing, there is a strong
* possibility of the incorrect packet being returned in a particular thread and
* both the API and the application getting confused. These are the only methods
* that contain such a race condition.</p>
* @author Oran Kelly
* @version 1.0
*/
public class Connection
implements java.lang.Runnable
{
/** Get the logger for this Connection. */
protected Logger logger = Logger.getLogger("ie.omk.smpp.Connection");
/** SMPP Transmitter connection type. */
public static final int TRANSMITTER = 1;
/** SMPP Receiver connection type. */
public static final int RECEIVER = 2;
/** SMPP Transciever connection type. */
public static final int TRANSCEIVER = 3;
/** Connection state: not bound to the SMSC. */
public static final int UNBOUND = 0;
/** Connection state: waiting for successful acknowledgement to bind
* request.
*/
public static final int BINDING = 1;
/** Connection state: bound to the SMSC. */
public static final int BOUND = 2;
/** Connection state: waiting for successful acknowledgement to unbind
* request or waiting for application to respond to unbind request.
*/
public static final int UNBINDING = 3;
/** Type of this SMPP connection. */
private int connectionType = 0;
/** Packet listener thread for Asyncronous comms. */
private Thread rcvThread = null;
/** Queue of incoming packets to deliver to application before reading from
* the network. The queue is used only in syncrhonized mode. In the case
* where an application has sent a request to the SMSC and is blocked
* waiting a response and the SMSC initiates a request of it's own (an
* unbind request or an enquire_link), the API will cache the request packet
* and wait for the response to it's packet. Any other type of packet will
* be added to the packetQueue and subsequent calls to
* <code>readNextPacket</code> will clear this queue.
*/
private ArrayList packetQueue = null;
/** Object used to notify observers of SMPP events.
*/
private EventDispatcher eventDispatcher = null;
/** Byte buffer used in readNextPacketInternal. */
private byte[] buf = new byte[300];
/** Sequence numbering scheme to use for this connection. */
private SequenceNumberScheme seqNumScheme = new DefaultSequenceScheme();
/** The network link (virtual circuit) to the SMSC */
private SmscLink link = null;
/** SMPP protocol version number.
*/
protected SMPPVersion interfaceVersion = SMPPVersion.getDefaultVersion();
/** Current state of the SMPP connection.
* Possible states are UNBOUND, BINDING, BOUND and UNBINDING.
*/
private int state = UNBOUND;
/** Specify whether the listener thread will automatically ack
* enquire_link primitives received from the Smsc
*/
protected boolean ackQryLinks = true;
/** Automatically acknowledge incoming deliver_sm messages.
* Only valid for the Receiver
*/
protected boolean ackDeliverSm = false;
/** Is the user using synchronous are async communication?. */
protected boolean asyncComms = false;
/** The default alphabet to use for this connection.
*/
protected AlphabetEncoding defaultAlphabet = null;
/** Initialise a new SMPP connection object. This is a convenience
* constructor that will create a new {@link ie.omk.smpp.net.TcpLink} object
* using the host name and port provided. The connection created will use
* synchronous communications.
* @param host the hostname of the SMSC.
* @param port the port to connect to. If 0, use the default SMPP port
* number.
*/
public Connection(String host, int port)
throws java.net.UnknownHostException
{
this (new TcpLink(host, port), false);
}
/** Initialise a new SMPP connection object. This is a convenience
* constructor that will create a new {@link ie.omk.smpp.net.TcpLink} object
* using the host name and port provided.
* @param host the hostname of the SMSC.
* @param port the port to connect to. If 0, use the default SMPP port
* number.
* @param async true for asyncronous communication, false for synchronous.
*/
public Connection(String host, int port, boolean async) throws java.net.UnknownHostException {
this (new TcpLink(host, port), async);
}
/** Initialise a new SMPP connection object. The connection will use
* synchronous communications.
* @param link The network link object to the Smsc (cannot be null)
*/
public Connection(SmscLink link)
{
this (link, false);
}
/** Initialise a new SMPP connection object, specifying the type of
* communication desired. See the {@link Connection} class description for
* some required knowledge on using the Connection in syncrhonous mode.
* @param link The network link object to the Smsc (cannot be null)
* @param async true for asyncronous communication, false for synchronous.
*/
public Connection(SmscLink link, boolean async)
{
this.link = link;
this.asyncComms = async;
if (asyncComms) {
initAsyncComms();
} else {
initSyncComms();
}
}
private void initAsyncComms() {
String className = "";
try {
className = APIConfig.getInstance().getProperty(APIConfig.EVENT_DISPATCHER_CLASS);
if (className != null && !"".equals(className)) {
Class cl = Class.forName(className);
eventDispatcher = (EventDispatcher)cl.newInstance();
} else {
logger.info("EventDispatcher property value is empty.");
}
} catch (PropertyNotFoundException x) {
logger.debug("No event dispatcher specified in properties. Using default.");
} catch (ClassNotFoundException x) {
logger.error("Cannot locate event dispatcher class " + className, x);
} catch (Exception x) {
// Something wrong with the implementation.
StringBuffer errorMessage = new StringBuffer();
errorMessage.append("Event dispatcher implementation is ")
.append("incorrect.\n")
.append(className)
.append(" should implement ie.omk.smpp.event.EventDispatcher ")
.append("and have a default constructor.\n")
.append("Falling back to default implementation after ")
.append("receiving exception.");
logger.error(errorMessage.toString(), x);
} finally {
if (eventDispatcher == null)
eventDispatcher = new SimpleEventDispatcher();
}
// Initialise the event dispatcher
eventDispatcher.init();
// Create the receiver daemon thread.
createRecvThread();
}
private void initSyncComms() {
packetQueue = new ArrayList();
}
/** Create the receiver thread if asynchronous communications is on, does
* nothing otherwise.
*/
private void createRecvThread()
{
logger.info("Creating receiver thread");
rcvThread = new Thread(this, "ReceiverDaemon");
rcvThread.setDaemon(true);
}
/** Set the default alphabet of the SMSC this <code>Connection</code> is
* communicating with. Each SMSC has its own default alphabet it uses. When
* messages arrive and announce themselves with a data coding value of zero,
* that means the message is encoded in the SMSC's default alphabet. The
* smppapi assumes the GSM default alphabet as it's default alphabet. By
* setting the default alphabet on the <code>Connection</code> all packets
* returned by {@link #newInstance(int)} will use the Connection's default
* alphabet plus any packets read from the wire with a data coding value of
* zero will have their default alphabet initialised appropriately.
* @param alphabet the alphabet to use as the default for this connection
* (may be <code>null</code> in which case the API falls back to using its
* own internal default).
*/
public void setDefaultAlphabet(AlphabetEncoding alphabet) {
this.defaultAlphabet = alphabet;
}
/** Get the current alphabet this <code>Connection</code> is using as its
* default.
* @return the default alphabet for this <code>Connection</code>.
*/
public AlphabetEncoding getDefaultAlphabet() {
return (defaultAlphabet);
}
/** Set the state of this ESME.
* @see ie.omk.smpp.Connection#getState
*/
private synchronized void setState(int state)
{
logger.info("Setting state " + state);
this.state = state;
}
/** Set the SMPP version this connection will use. Setting the version is
* only a valid operation before the connection is bound. Any attempt to set
* the version after binding to the SMSC will result in an exception being
* thrown.
* @param version the SMPP version to use.
* @throws ie.omk.smpp.version.VersionException if an attempt is made to set
* the version of the connection after binding to the SMSC.
* @see ie.omk.smpp.version.SMPPVersion
*/
public void setVersion(SMPPVersion version) throws VersionException {
if (getState() != UNBOUND)
throw new VersionException("Cannot set SMPP version after binding");
if (version == null)
this.interfaceVersion = SMPPVersion.getDefaultVersion();
else
this.interfaceVersion = version;
}
/** Get the SMPP version in use by this connection. The version in use by
* the connection <b>may</b> be different to that specified before the bind
* operation as binding to the SMSC may result in an alternative SMPP
* version being negotiated. For instance, if the client sends a bind packet
* to the SMSC specifying that it supports SMPP version 3.4 but the SMSC
* returns a bind_resp stating it supports version 3.3, the Connection
* automatically sets it's internal version to use down to 3.3.
*/
public SMPPVersion getVersion() {
return (interfaceVersion);
}
/** Get the current state of the ESME. One of UNBOUND, BINDING, BOUND or
* UNBINDING.
*/
public synchronized int getState()
{
return (this.state);
}
/** Method to open the link to the SMSC. This method will connect the
* underlying SmscLink object if necessary and reset the sequence numbering
* scheme to the beginning.
* @throws java.io.IOException if an i/o error occurs while opening the
* connection.
*/
protected void openLink()
throws java.io.IOException
{
if (!this.link.isConnected()) {
logger.info("Opening network link.");
this.link.open();
if (this.seqNumScheme != null)
this.seqNumScheme.reset();
} else {
logger.debug("openLink called, link already open");
}
}
/** Close the underlying network link to the SMSC. This method calls the
* underlying link's <code>close</code> method to actually shutdown
* the network connection to the SMSC.
* @throws ie.omk.smpp.IllegalStateException if an attempt is made to close
* the connection while bound to the SMSC.
* @throws java.io.IOException if an I/O exception occurs while trying to
* close the link.
* @see ie.omk.smpp.net.SmscLink#close
*/
public void closeLink() throws IOException {
if (getState() != UNBOUND)
throw new IllegalStateException("Cannot close the link while bound to the SMSC");
if (this.link.isConnected()) {
logger.info("Shutting down the network link");
this.link.close();
} else {
logger.debug("closeLink called on an unopen connection");
}
}
/** Get the interface version.
* @see #setInterfaceVersion(SMPPVersion)
*/
public SMPPVersion getInterfaceVersion()
{
return (this.interfaceVersion);
}
/** Set the desired interface version for this connection. The default
* version is 3.3 (XXX soon to be 3.4). The bind operation may negotiate
* an eariler version of the protocol if the SC does not understand the
* version sent by the ESME. This API will not support any version eariler
* than SMPP v3.3. The interface version is encoded as follows:
* <table border="1" cellspacing="1" cellpadding="1">
* <tr><th>SMPP version</th><th>Version value</th></tr>
* <tr><td>v3.4</td><td>0x34</td></tr>
* <tr><td>v3.3</td><td>0x33</td></tr>
* <tr>
* <td colspan="2" align="center"><i>All other values reserved.</i></td>
* </tr>
* </table>
*/
public void setInterfaceVersion(SMPPVersion interfaceVersion)
{
logger.info("setInterfaceVersion " + interfaceVersion);
this.interfaceVersion = interfaceVersion;
}
/** Set the behaviour of automatically acking ENQUIRE_LINK's from the SMSC.
* By default, the listener thread will automatically ack an enquire_link
* message from the Smsc so as not to lose the connection. This
* can be turned off with this method.
* @param true to activate automatic acknowledgment, false to disable
*/
public void autoAckLink(boolean b)
{
this.ackQryLinks = b;
}
/** Set the behaviour of automatically acking Deliver_Sm's from the Smsc.
* By default the listener thread will <b>not</b> acknowledge a message.
* @param true to activate this function, false to deactivate.
*/
public void autoAckMessages(boolean b)
{
this.ackDeliverSm = b;
}
/** Check is this connection automatically acking Enquire link requests.
*/
public boolean isAckingLinks()
{
return (ackQryLinks);
}
/** Check is this connection automatically acking delivered messages
*/
public boolean isAckingMessages()
{
return (ackDeliverSm);
}
/** Acknowledge a DeliverSM command received from the Smsc.
* @param rq The deliver_sm request to respond to.
* @throws java.io.IOException If an I/O error occurs writing the response
* packet to the network connection.
*/
public void ackDeliverSm(DeliverSM rq)
throws java.io.IOException
{
DeliverSMResp rsp = new DeliverSMResp(rq);
sendResponse(rsp);
logger.info("deliver_sm_resp sent.");
}
/** Send an smpp request to the SMSC.
* No fields in the SMPPRequest packet will be altered except possibly the
* sequence number. The sequence number will be assigned the next number as
* defined by this Connection's sequence numbering scheme. If the sequence
* numbering scheme class is <code>null</code> for this Connection, no
* number will be assigned. By default, the
* {@link ie.omk.smpp.util.DefaultSequenceScheme} class is used to assign
* sequence numbers to packets.
* @param r The request packet to send to the SMSC
* @return The response packet returned by the SMSC, or null if
* asynchronous communication is being used.
* @throws java.lang.NullPointerException if <code>r</code> is null.
* @throws java.net.SocketTimeoutException If a socket timeout occurs while
* waiting for a response packet. (Only in synchronized mode).
* @throws java.io.IOException If an I/O error occurs while writing the
* request packet to the network connection.
* @throws ie.omk.smpp.UnsupportedOperationException If this connection
* type does not support operation <code>r</code>. For example, a receiver
* link does not support the submit_sm operation.
* @throws ie.omk.smpp.AlreadyBoundException If the request type is a bind
* packet and this connection is already bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous
* communications is in use and the incoming response packet violates the
* SMPP specification, this exception will be thrown.
* @see #setSeqNumScheme
*/
public SMPPResponse sendRequest(SMPPRequest r)
throws java.net.SocketTimeoutException, java.io.IOException, AlreadyBoundException, VersionException, SMPPProtocolException, UnsupportedOperationException
{
SMPPResponse resp = null;
int id = r.getCommandId();
if (this.state != BOUND)
throw new NotBoundException("Must be bound to the SMSC before "
+ "sending packets");
// Very few request types allowed by a receiver connection.
if (connectionType == RECEIVER) {
if (id != SMPPPacket.ENQUIRE_LINK && id != SMPPPacket.UNBIND)
throw new UnsupportedOperationException(
"Operation not permitted over receiver connection");
}
return (sendRequestInternal(r));
}
/** Send a request to the SMSC.
* XXX complete javadoc for this method.
* @throws ie.omk.smpp.version.VersionException if the version in use
* does not support the request being sent.
*/
protected SMPPResponse sendRequestInternal(SMPPRequest r)
throws java.net.SocketTimeoutException, java.io.IOException, AlreadyBoundException, VersionException, SMPPProtocolException {
SMPPResponse resp = null;
int id = r.getCommandId();
if (link == null)
throw new IOException("No SMSC connection.");
// Check the command is supported by the interface version..
if (!this.interfaceVersion.isSupported(id)) {
throw new VersionException("Command ID 0x"
+ Integer.toHexString(id)
+ " is not supported by SMPP "
+ this.interfaceVersion);
}
if (id == SMPPPacket.BIND_TRANSMITTER
|| id == SMPPPacket.BIND_RECEIVER
|| id == SMPPPacket.BIND_TRANSCEIVER) {
if (this.state != UNBOUND)
throw new AlreadyBoundException("Already bound to the SMSC");
openLink();
setState(BINDING);
if (asyncComms) {
if (rcvThread == null)
createRecvThread();
if (!rcvThread.isAlive())
rcvThread.start();
}
} else if (id == SMPPPacket.UNBIND) {
if (!asyncComms && packetQueue.size() > 0)
throw new IllegalStateException("Cannot unbind while there are incoming packets "
+ "waiting responses");
if (this.state != BOUND)
throw new IllegalStateException("Not currently bound");
setState(UNBINDING);
}
// XXX temporary...this should be removed once it's safe to assume that
// no packet can be submitted that has been constructed outside the
// confines of this connection's factory method.
if (r.getSequenceNum() == 0 && seqNumScheme != null)
r.setSequenceNum(seqNumScheme.nextNumber());
link.write(r);
if (!asyncComms)
resp = waitForResponsePacket(r);
return ((SMPPResponse)resp);
}
/** Wait for a response packet from the SMSC. A response packet with the
* same sequence number as <code>req</code> will be waited for from the
* SMSC. If an unexpected packet arrives, either a response packet with a
* different sequence number or a request packet, it will be queued for
* later retrieval by the application via <code>readNextPacket</code>.
* @param req the request packet to wait for a response to.
* @return A response packet with the same sequence number as
* <code>req</code>.
* @throws java.net.SocketTimeoutException if the read on the socket times
* out.
* @see #readNextPacket
* @see java.net.SocketTimeoutException
*/
protected SMPPResponse waitForResponsePacket(SMPPPacket req)
throws java.net.SocketTimeoutException, java.io.IOException, SMPPProtocolException {
try {
int id = -1;
SMPPPacket resp = null;
int expectedSeq = req.getSequenceNum();
while (true) {
resp = readNextPacketInternal();
id = resp.getCommandId();
if ((id & 0x80000000) != 0
&& resp.getSequenceNum() == expectedSeq) {
break;
} else {
logger.info("Queuing unexpected sequence numbered packet.");
if (logger.isDebugEnabled()) {
StringBuffer b = new StringBuffer("Expected:")
.append(Integer.toString(expectedSeq))
.append(" but got ")
.append(Integer.toString(resp.getSequenceNum()));
logger.debug(b.toString());
}
packetQueue.add(resp);
}
}
return ((SMPPResponse)resp);
} catch (java.net.SocketTimeoutException x) {
// Must set our state and re-throw the exception..
logger.error("Received a socket timeout exception", x);
throw x;
}
}
/** Determine if there are packets available for reading using
* <code>readNextPacket</code>. This method is only valid for synchronous
* communications...it will always return 0 if asynchronous mode is in
* use.
* @return 0 if there is no packet available for reading, 1 if there is data
* available but the call to <code>readNextPacket</code> may block or 2 if
* there is a full packet available.
*/
public int packetAvailable() {
int ret = 0;
if (!asyncComms) {
if (packetQueue.size() > 0)
ret = 2;
else if (link.available() > 0)
ret = 1;
}
return (ret);
}
/** Send an smpp response packet to the SMSC
* @param r The response packet to send to the SMSC
* @throws java.io.IOException If an I/O error occurs while writing the
* response packet to the output stream.
*/
public void sendResponse(SMPPResponse resp)
throws java.io.IOException
{
Integer key = null;
if (link == null)
throw new IOException("Connection to SMSC is not valid.");
try {
link.write(resp);
} catch (java.net.SocketTimeoutException x) {
logger.warn("Got a socket timeout exception", x);
setState(UNBOUND);
throw x;
}
if (resp.getCommandId() == SMPPPacket.UNBIND_RESP
&& resp.getCommandStatus() == 0)
setState(UNBOUND);
}
/** Bind this connection to the SMSC. An application must bind to an SMSC as
* one of transmitter, receiver or transceiver. Binding as transmitter
* allows general manipulation of messages at the SMSC including submitting
* messages for delivery, cancelling, replacing and querying the state of
* previously submitted messages. Binding as a receiver allows an
* application to receive all messages previously queued for delivery to
* it's address. The transceiver mode, which was added in version 3.4 of the
* SMPP protocol, combines the functionality of both transmitter and
* receiver into one connection type.
* <p>Note that it is only necessary to supply values for
* <code>type, systemID</code> and <code>password</code>. The other
* arguments may be left at null (or zero, as applicable).</p>
* @param type connection type to use, either {@link #TRANSMITTER},
* {@link #RECEIVER} or {@link #TRANSCEIVER}.
* @param systemID the system ID to identify as to the SMSC.
* @param password password to use to authenticate to the SMSC.
* @param systemType the system type to bind as.
* @return the bind response packet.
* @throws java.lang.IllegalArgumentException if a bad <code>type</code>
* value is supplied.
* @throws ie.omk.smpp.VersionException if an attempt is made
* to bind as transceiver while using SMPP version 3.3.
* @throws ie.omk.smpp.InvalidParameterValueException If any of systemID,
* password, system type or address range are outside allowed bounds or the
* TON or NPI is invalid.
* @throws java.io.IOException If an I/O error occurs while writing the bind
* packet to the output stream.
* @throws ie.omk.smpp.AlreadyBoundException If the Connection is already
* bound.
* @throws ie.omk.smpp.SMPPProtocolExcpetion if synchronous communication is
* in use and the incoming response packet violates the SMPP protocol.
*/
public BindResp bind(int type,
String systemID,
String password,
String systemType)
throws java.io.IOException, InvalidParameterValueException, IllegalArgumentException, AlreadyBoundException, VersionException, SMPPProtocolException
{
return (this.bind(type, systemID, password, systemType, 0, 0, null));
}
/** Bind this connection to the SMSC. An application must bind to an SMSC as
* one of transmitter, receiver or transceiver. Binding as transmitter
* allows general manipulation of messages at the SMSC including submitting
* messages for delivery, cancelling, replacing and querying the state of
* previously submitted messages. Binding as a receiver allows an
* application to receive all messages previously queued for delivery to
* it's address. The transceiver mode, which was added in version 3.4 of the
* SMPP protocol, combines the functionality of both transmitter and
* receiver into one connection type.
* <p>Note that it is only necessary to supply values for
* <code>type, systemID</code> and <code>password</code>. The other
* arguments may be left at null (or zero, as applicable).</p>
* @param type connection type to use, either {@link #TRANSMITTER},
* {@link #RECEIVER} or {@link #TRANSCEIVER}.
* @param systemID the system ID to identify as to the SMSC.
* @param password password to use to authenticate to the SMSC.
* @param systemType the system type to bind as.
* @param typeOfNum the TON of the address to bind as.
* @param numberPlan the NPI of the address to bind as.
* @param addrRange the address range regular expression to bind as.
* @return the bind response packet.
* @throws java.lang.IllegalArgumentException if a bad <code>type</code>
* value is supplied.
* @throws ie.omk.smpp.VersionException if an attempt is made
* to bind as transceiver while using SMPP version 3.3.
* @throws ie.omk.smpp.InvalidParameterValueException If any of systemID,
* password, system type or address range are outside allowed bounds.
* @throws java.io.IOException If an I/O error occurs while writing the bind
* packet to the output stream.
* @throws ie.omk.smpp.AlreadyBoundException If the Connection is already
* bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous comms is
* in use and the incoming bind response packet violates the SMPP
* specification, this exception is thrown.
*/
public BindResp bind(int type,
String systemID,
String password,
String systemType,
int typeOfNum,
int numberPlan,
String addrRange)
throws java.io.IOException, InvalidParameterValueException, IllegalArgumentException, AlreadyBoundException, VersionException, SMPPProtocolException
{
Bind bindReq = null;
switch (type) {
case TRANSMITTER:
bindReq = new BindTransmitter();
break;
case RECEIVER:
bindReq = new BindReceiver();
break;
case TRANSCEIVER:
if (this.interfaceVersion.isOlder(SMPPVersion.V34)) {
throw new VersionException("Cannot bind as "
+ "transceiver "
+ interfaceVersion.toString());
}
bindReq = new BindTransceiver();
break;
default:
throw new IllegalArgumentException("No such connection type.");
}
this.connectionType = type;
logger.info("Binding to the SMSC as type " + type);
bindReq.setVersion(interfaceVersion);
bindReq.setSystemId(systemID);
bindReq.setPassword(password);
bindReq.setSystemType(systemType);
bindReq.setAddressTon(typeOfNum);
bindReq.setAddressNpi(numberPlan);
bindReq.setAddressRange(addrRange);
return ((BindResp)sendRequestInternal(bindReq));
}
/** Unbind from the SMSC. This method will unbind the SMPP protocol
* connection from the SMSC. No further SMPP operations will be possible
* once unbound. If the calling application is using sync mode, it should be
* sure there are no incoming packets awaiting a response (check using
* {@link #packetAvailable}), otherwise an
* <code>IllegalStateException</code> may be thrown. Note that this method
* will <b>not</b> close the underlying network connection.
* @return The Unbind response packet, or null if asynchronous
* communication is being used.
* @throws ie.omk.smpp.NotBoundException if the connection is not yet
* bound.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous comms is
* in use and the incoming unbind_resp packet violates the SMPP
* specification, this exception is thrown.
* @throws java.io.IOException If an I/O error occurs while writing the
* unbind request or reading the unbind response.
*/
public UnbindResp unbind()
throws java.io.IOException, NotBoundException, SMPPProtocolException
{
if((state != BOUND) || !(link.isConnected()))
throw new NotBoundException();
try {
logger.info("Unbinding from the SMSC");
Unbind u = (Unbind)newInstance(SMPPPacket.UNBIND);
return ((UnbindResp)sendRequest(u));
} catch (VersionException x) {
// impossible...every version supports unbind!
throw new SMPPRuntimeException("Internal smppapi error");
} catch (BadCommandIDException x) {
// similarly impossible!
throw new SMPPRuntimeException("Internal smppapi error");
}
}
/** Unbind from the SMSC. This method is used to acknowledge an unbind
* request from the SMSC.
* @throws ie.omk.smpp.NotBoundException if the connection is not currently
* bound.
* @throws ie.omk.smpp.AlreadyBoundException if no unbind request has
* been received from the SMSC.
* @throws java.io.IOException If an I/O error occurs while writing the
* response packet to the network connection.
*/
public void unbind(UnbindResp ubr)
throws java.io.IOException, ie.omk.smpp.SMPPException
{
if (state != UNBINDING)
throw new NotBoundException("Link is not connected.");
if (!(link.isConnected()))
throw new AlreadyBoundException("No unbind request received.");
sendResponse(ubr);
}
/** Force the SMPP connection down.
* Only use this method once it's full sure that graceful unbinding and
* disconnection isn't going to work. This method cleans up it's internal
* state, forcing the network connection closed and terminating the receiver
* thread if necessary.
* <p>If you end up having to use this method to terminate a Connection, it
* is advisable not to attempt to reuse the connection at all. Create a new
* object and start from scratch. Use of this method indicates something
* seriously wrong!</p>
*/
public void force_unbind()
{
logger.warn("Attempting to force SMPP connection down.");
try {
setState(UNBOUND);
// The thread must DIE!!!!
if(rcvThread != null && rcvThread.isAlive()) {
try {
// Wait to see if the thread will terminate due to the state
// becoming UNBOUND.
Thread.sleep(1000);
} catch (InterruptedException x) {
logger.debug("Interrupted exception waiting on receiver to die", x);
}
if (rcvThread.isAlive())
logger.error("Listener thread has not died.");
rcvThread = null;
}
link.close();
} catch(IOException ix) {
logger.warn("Forced unbind caused IO exception", ix);
}
return;
}
/** Acknowledge an EnquireLink received from the Smsc
* @throws java.io.IOException If an I/O error occurs while writing to the
* network connection.
*/
public void ackEnquireLink(EnquireLink rq)
throws java.io.IOException
{
EnquireLinkResp resp = new EnquireLinkResp(rq);
sendResponse(resp);
logger.info("enquire_link_resp sent.");
}
/** Do a confidence check on the SMPP link to the SMSC.
* @return The Enquire link response packet or null if asynchronous
* communication is in use.
* @throws java.io.IOException If an I/O error occurs while writing to the
* network connection.
* @throws ie.omk.smpp.message.SMPPProtocolException If synchronous
* communications is in use and the incoming enquire_link_resp packet
* violates the SMPP specification, this exception is thrown.
*/
public EnquireLinkResp enquireLink()
throws java.io.IOException, SMPPProtocolException
{
try {
EnquireLink s = (EnquireLink)newInstance(SMPPPacket.ENQUIRE_LINK);
SMPPResponse resp = sendRequest(s);
logger.debug("enquire_link request sent.");
if (resp != null)
logger.debug("enquire_link_response received.");
return ((EnquireLinkResp)resp);
} catch (BadCommandIDException x) {
throw new SMPPRuntimeException("Internal smppapi error");
}
}
/** Get the type of this SMPP connection. The connection type is one of
* TRANSMITTER, RECEIVER or TRANSCEIVER.
*/
public int getConnectionType()
{
return (connectionType);
}
/** Report whether the connection is bound or not.
* @return true if the connection is bound.
*/
public boolean isBound()
{
return (state == BOUND);
}
/** Reset this connection's sequence numbering to the beginning. The
* underlying SequenceNumberScheme's reset method is called to start from
* that sequence's 'beginning'.
* @throws ie.omk.smpp.AlreadyBoundException if the connection is
* currently bound to the SMSC.
*/
public void reset()
throws AlreadyBoundException
{
if(state == BOUND) {
logger.warn("Attempt to reset sequence numbering on a bound connection");
throw new AlreadyBoundException("Cannot reset connection while bound");
}
if (this.seqNumScheme != null)
this.seqNumScheme.reset();
logger.info("Sequence numbering reset.");
}
/** Set the sequence numbering scheme for this connection. A sequence
* numbering scheme determines what sequence number each SMPP packet will
* have. By default, {@link ie.omk.smpp.util.DefaultSequenceScheme} is used,
* which will begin with sequence number 1 and increase the number by 1 for
* each packet thereafter.
* <p>If the application sets the <code>scheme</code> to null, it is
* responsible for maintaining and setting the sequence number for each SMPP
* request it sends to the SMSC.
* @see ie.omk.smpp.util.SequenceNumberScheme
* @see ie.omk.smpp.message.SMPPPacket#setSequenceNum
*/
public void setSeqNumScheme(SequenceNumberScheme scheme) {
this.seqNumScheme = scheme;
}
/** Get the current sequence numbering scheme object being used by this
* connection.
*/
public SequenceNumberScheme getSeqNumScheme() {
return (this.seqNumScheme);
}
/** Read in the next packet from the SMSC link.
* If asynchronous communications is in use, calling this method results in
* an SMPPException as the listener thread will be hogging the input stream
* of the socket connection.
* @return The next SMPP packet from the SMSC.
* @throws java.io.IOException If an I/O error occurs while reading from
* the network connection.
* @throws ie.omk.smpp.InvalidOperationException If asynchronous comms
* is in use.
* @throws ie.omk.smpp.message.SMPPProtocolException if the incoming data
* violates the SMPP protocol specifications.
*/
public SMPPPacket readNextPacket()
throws java.io.IOException, InvalidOperationException, SMPPProtocolException
{
if (asyncComms) {
throw new InvalidOperationException("Asynchronous comms in use.");
} else {
if (packetQueue.size() > 0)
return ((SMPPPacket)packetQueue.remove(0));
else
return (readNextPacketInternal());
}
}
/** Read the next packet from the SMSC link. Internal version...handles
* special case packets like bind responses and unbind request and
* responses.
* @return The read SMPP packet, or null if the connection timed out.
* @throws java.io.IOException If an I/O error occurs while reading from
* the network connection.
*/
private SMPPPacket readNextPacketInternal()
throws java.io.IOException, SMPPProtocolException
{
try {
SMPPPacket pak = null;
int id = -1, st = -1;
this.buf = link.read(this.buf);
id = SMPPIO.bytesToInt(this.buf, 4, 4);
pak = PacketFactory.newInstance(id);
if (pak != null) {
pak.readFrom(this.buf, 0);
if (logger.isDebugEnabled()) {
StringBuffer b = new StringBuffer("Packet Received: ");
int l = pak.getLength();
int s = pak.getCommandStatus();
int n = pak.getSequenceNum();
b.append("id:").append(Integer.toHexString(id));
b.append(" len:").append(Integer.toString(l));
b.append(" st:").append(Integer.toString(s));
b.append(" sq:").append(Integer.toString(n));
logger.debug(b.toString());
}
// Special case handling for certain packet types..
st = pak.getCommandStatus();
switch (pak.getCommandId()) {
case SMPPPacket.BIND_TRANSMITTER_RESP:
case SMPPPacket.BIND_RECEIVER_RESP:
case SMPPPacket.BIND_TRANSCEIVER_RESP:
handleBindResp((BindResp)pak);
break;
case SMPPPacket.UNBIND_RESP:
handleUnbindResp((UnbindResp)pak);
break;
case SMPPPacket.UNBIND:
handleUnbind((Unbind)pak);
break;
}
if (st == 0) {
// Fix up the alphabet for this connection type if the
// packet needs it. DCS value 0 means the alphabet is in the
// default encoding of the SMSC, which varies depending on
// implementation.
if (defaultAlphabet != null && pak.getDataCoding() == 0)
pak.setAlphabet(defaultAlphabet);
}
}
return (pak);
} catch (BadCommandIDException x) {
throw new SMPPProtocolException("Unrecognised command received", x);
}
}
/** Handle an incoming bind response packet. Method is called by a few
* methods in this class that read from the incoming connection.
*/
private void handleBindResp(BindResp resp) {
if (state == BINDING && resp.getCommandStatus() == 0)
setState(BOUND);
}
/** Handle an incoming unbind packet.
*/
private void handleUnbind(Unbind req) {
logger.info("SMSC requested unbind");
setState(UNBINDING);
}
/** Handle an incoming unbind response packet.
*/
private void handleUnbindResp(UnbindResp resp) {
if (state == UNBINDING && resp.getCommandStatus() == 0) {
logger.info("Successfully unbound");
setState(UNBOUND);
}
}
/** Set the event dispatcher for this connection object. Before using the
* new event dispatcher, this method will call
* {@link EventDispatcher#init} to initialise the dispatcher. It will then
* iterate through all the observers registered with the current event
* dispatcher and register them with the new one.
* <p>It is not a particularly good idea to set the event dispatcher after
* communications have begun. However, the observer copy is guarded against
* multi-threaded access to the current event dispatcher. During the copy,
* however, events will continue to be delievered via the current
* dispatcher. Only <b>after</b> the copy is complete will the new event
* dispatcher become the active one and events begin being delivered by
* it.</p>
* <p>The caller of this method can be sure that, once this method returns,
* all new events will be handled by the new event dispatcher. However,
* there may be events that occurred before, or during the operation of, the
* call to this method which will be delivered by the old dispatcher. Once
* the new event dispatcher is in place, the {@link EventDispatcher#destroy}
* method will be called on the old dispatcher.</p>
*/
public void setEventDispatcher(EventDispatcher eventDispatcher) {
if (eventDispatcher == null)
throw new NullPointerException("Event dispatcher cannot be null");
eventDispatcher.init();
// Copy all current observers to the new event dispatcher..
synchronized (this.eventDispatcher) {
Iterator iter = this.eventDispatcher.observerIterator();
while (iter.hasNext())
eventDispatcher.addObserver((ConnectionObserver)iter.next());
}
EventDispatcher old = this.eventDispatcher;
// ..and swap out the old dispatcher.
this.eventDispatcher = eventDispatcher;
// Clean up the old dispatcher.
old.destroy();
}
/** Add a connection observer to receive SMPP events from this connection.
* If this connection is not using asynchronous communication, this method
* call has no effect.
* @param ob the ConnectionObserver implementation to add.
*/
public void addObserver(ConnectionObserver ob) {
if (eventDispatcher != null)
eventDispatcher.addObserver(ob);
}
/** Remove a connection observer from this Connection.
*/
public void removeObserver(ConnectionObserver ob) {
if (eventDispatcher != null)
eventDispatcher.removeObserver(ob);
}
/** Listener thread method for asynchronous communication.
*/
public void run()
{
SMPPPacket pak = null;
int smppEx = 0, id = 0, st = 0;
SMPPEvent exitEvent = null;
int tooManyIOEx = 5;
logger.info("Receiver thread started");
try {
tooManyIOEx =
APIConfig.getInstance().getInt(APIConfig.TOO_MANY_IO_EXCEPTIONS);
} catch (PropertyNotFoundException x) {
// just stick with the default
logger.debug("Didn't find I/O exception config. Using default of "
+ tooManyIOEx);
}
eventDispatcher.notifyObservers(this, new ReceiverStartEvent(this));
try {
while (state != UNBOUND) {
try {
pak = readNextPacketInternal();
if (pak == null) {
// XXX Send an event to the application??
continue;
}
} catch (SocketTimeoutException x) {
// is it okay to ignore this ??
logger.info("Ignoring SocketTimeoutException");
continue;
} catch (EOFException x) {
// The network connection has disappeared! Wah!
logger.error("EOFException received in daemon thread.", x);
// Will be caught by the general handler lower in this
// method.
throw x;
} catch (IOException x) {
logger.warn("I/O Exception caught", x);
ReceiverExceptionEvent ev =
new ReceiverExceptionEvent(this, x, state);
eventDispatcher.notifyObservers(this, ev);
smppEx++;
if (smppEx > tooManyIOEx) {
logger.warn("Too many IOExceptions in receiver thread", x);
throw x;
}
continue;
}
// Reset smppEx back to zero if we reach here, as packet
// reception was successful.
smppEx = 0;
id = pak.getCommandId();
st = pak.getCommandStatus();
// Handle special case packets..
switch (id) {
case SMPPPacket.DELIVER_SM:
if (ackDeliverSm)
ackDeliverSm((DeliverSM)pak);
break;
case SMPPPacket.ENQUIRE_LINK:
if (ackQryLinks)
ackEnquireLink((EnquireLink)pak);
break;
}
// Tell all the observers about the new packet
logger.info("Notifying observers of packet received");
eventDispatcher.notifyObservers(this, pak);
} // end while
// Notify observers that the thread is exiting with no error..
exitEvent = new ReceiverExitEvent(this, null, state);
} catch (Exception x) {
logger.error("Fatal exception in receiver thread", x);
exitEvent = new ReceiverExitEvent(this, x, state);
setState(UNBOUND);
} finally {
// make sure other code doesn't try to restart the rcvThread..
rcvThread = null;
}
if (exitEvent != null)
eventDispatcher.notifyObservers(this, exitEvent);
// Clean up the event dispatcher.
eventDispatcher.destroy();
}
/**
* @deprecated #ackEnquireLink
*/
public void ackLinkQuery(EnquireLink el)
throws java.io.IOException
{
ackEnquireLink(el);
}
/** Get a new instance of an SMPP packet. The packet will be initialised so
* that it uses the same SMPP version as this connection and it's sequence
* number will be initialised to using this connection's sequence numbering
* scheme.
* @param commandId the SMPP command ID of the packet to retrieve.
* @return a subclass of {@link ie.omk.smpp.message.SMPPPacket}
* corresponding to SMPP command <code>commandId</code>.
* @throws ie.omk.smpp.BadCommandIDException if the command ID is not
* recognised.
* @throws ie.omk.smpp.NotSupportedException if the Connection is currently
* using an SMPP version which does not support SMPP command
* <code>commandId</code>.
*/
public SMPPPacket newInstance(int commandId) throws BadCommandIDException, VersionException {
if (!this.interfaceVersion.isSupported(commandId))
throw new VersionException("Command is not supported in this SMPP version");
SMPPPacket response = PacketFactory.newInstance(commandId);
response.setVersion(this.interfaceVersion);
if (this.seqNumScheme != null)
response.setSequenceNum(this.seqNumScheme.nextNumber());
if (defaultAlphabet != null)
response.setAlphabet(defaultAlphabet);
return (response);
}
}
| Set the DCS to 0 for the Connection's default alphabet
| src/ie/omk/smpp/Connection.java | Set the DCS to 0 for the Connection's default alphabet |
|
Java | mit | 2d75f86ac9b4982fb48ad1f34ba7d4ef24e26082 | 0 | DMDirc/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,DMDirc/DMDirc,greboid/DMDirc,DMDirc/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc,greboid/DMDirc | src/com/dmdirc/util/SystemInfo.java | /*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.util;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Provides static utility methods to access information about the java system environment.
*/
@Singleton
public class SystemInfo {
@Inject
public SystemInfo() {}
public String getProperty(final String key) {
return System.getProperty(key);
}
public String getProperty(final String key, final String def) {
return System.getProperty(key, def);
}
public Map<String, String> getenv() {
return System.getenv();
}
public String getenv(final String key) {
return System.getenv(key);
}
}
| Remove file that shouldn't have been committed.
| src/com/dmdirc/util/SystemInfo.java | Remove file that shouldn't have been committed. |
||
Java | bsd-3-clause | 6cb16e38c5bd85cb6ca095b06d5490b8f95e5654 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | src/gov/nih/nci/cananolab/service/particle/NanoparticleSampleSearchHibernateHelper.java | package gov.nih.nci.cananolab.service.particle;
import gov.nih.nci.cananolab.domain.common.Source;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.domain.particle.characterization.Characterization;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.Function;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.OtherFunction;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.ComposingElement;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.NanoparticleEntity;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.OtherNanoparticleEntity;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.FunctionalizingEntity;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.OtherFunctionalizingEntity;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
/**
* Hibernate helper class for local implementation of
* NanoparticleSampleSearchInterface and grid service implementation.
*
* @author pansu
*
*/
public class NanoparticleSampleSearchHibernateHelper {
public List<NanoparticleSample> findNanoparticleSamplesBy(
String[] particleSources, String[] nanoparticleEntityClassNames,
String[] otherNanoparticleTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
String[] functionClassNames, String[] otherFunctionTypes,
String[] characterizationClassNames, String[] wordList)
throws Exception {
List<NanoparticleSample> particles = new ArrayList<NanoparticleSample>();
DetachedCriteria crit = DetachedCriteria
.forClass(NanoparticleSample.class);
if (particleSources != null && particleSources.length > 0) {
crit.createAlias("source", "source",
CriteriaSpecification.LEFT_JOIN)
.add(
Restrictions.in("source.organizationName",
particleSources));
}
if (wordList != null && wordList.length > 0) {
// turn words into upper case before searching keywords
String[] upperKeywords = new String[wordList.length];
for (int i = 0; i < wordList.length; i++) {
upperKeywords[i] = wordList[i].toUpperCase();
}
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias("keywordCollection", "keyword1",
CriteriaSpecification.LEFT_JOIN);
for (String keyword : upperKeywords) {
Criterion keywordCrit1 = Restrictions.like("keyword1.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit1);
}
crit.createAlias("characterizationCollection", "chara",
CriteriaSpecification.LEFT_JOIN).createAlias(
"chara.derivedBioAssayDataCollection", "derived",
CriteriaSpecification.LEFT_JOIN).createAlias(
"derived.labFile", "charFile",
CriteriaSpecification.LEFT_JOIN).createAlias(
"charFile.keywordCollection", "keyword2",
CriteriaSpecification.LEFT_JOIN);
;
for (String keyword : upperKeywords) {
Criterion keywordCrit2 = Restrictions.like("keyword2.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit2);
}
for (String word : wordList) {
Criterion summaryCrit1 = Restrictions.ilike(
"chara.description", word, MatchMode.ANYWHERE);
Criterion summaryCrit2 = Restrictions.ilike(
"charFile.description", word, MatchMode.ANYWHERE);
Criterion summaryCrit = Restrictions.or(summaryCrit1,
summaryCrit2);
disjunction.add(summaryCrit);
}
crit.add(disjunction);
}
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanoparticleEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanoparticleEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanoparticleEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
for (Object obj : results) {
NanoparticleSample particle = (NanoparticleSample) obj;
particles.add(particle);
}
List<NanoparticleSample> functionFilteredParticles = filterByFunctions(
functionClassNames, otherFunctionTypes, particles);
List<NanoparticleSample> characterizationFilteredParticles = filterByCharacterizations(
characterizationClassNames, functionFilteredParticles);
List<NanoparticleSample> theParticles = filterByCompositions(
nanoparticleEntityClassNames, otherNanoparticleTypes,
functionalizingEntityClassNames,
otherFunctionalizingEntityTypes,
characterizationFilteredParticles);
Collections.sort(theParticles,
new CaNanoLabComparators.NanoparticleSampleComparator());
return theParticles;
}
/**
* Return all stored functionalizing entity class names. In case of
* OtherFunctionalizingEntity, store the OtherFunctionalizingEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionalizingEntityClassNames(
NanoparticleSample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
if (entity instanceof OtherFunctionalizingEntity) {
storedEntities.add(((OtherFunctionalizingEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
/**
* Return all stored function class names. In case of OtherFunction, store
* the otherFunction type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionClassNames(
NanoparticleSample particleSample) {
SortedSet<String> storedFunctions = new TreeSet<String>();
if (particleSample.getSampleComposition() != null) {
if (particleSample.getSampleComposition()
.getNanoparticleEntityCollection() != null) {
for (NanoparticleEntity entity : particleSample
.getSampleComposition()
.getNanoparticleEntityCollection()) {
for (ComposingElement element : entity
.getComposingElementCollection()) {
for (Function function : element
.getInherentFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function.getClass()
.getCanonicalName()));
}
}
}
}
}
if (particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
for (Function function : entity.getFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function.getClass()
.getCanonicalName()));
}
}
}
}
}
return storedFunctions;
}
/**
* Return all stored nanoparticle entity class names. In case of
* OtherNanoparticleEntity, store the otherNanoparticleEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredNanoparticleEntityClassNames(
NanoparticleSample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getNanoparticleEntityCollection() != null) {
for (NanoparticleEntity entity : particleSample
.getSampleComposition().getNanoparticleEntityCollection()) {
if (entity instanceof OtherNanoparticleEntity) {
storedEntities.add(((OtherNanoparticleEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
public SortedSet<String> getStoredCharacterizationClassNames(
NanoparticleSample particle) {
SortedSet<String> storedChars = new TreeSet<String>();
if (particle.getCharacterizationCollection() != null) {
for (Characterization achar : particle
.getCharacterizationCollection()) {
storedChars.add(ClassUtils.getShortClassName(achar.getClass()
.getCanonicalName()));
}
}
return storedChars;
}
private List<NanoparticleSample> filterByFunctions(
String[] functionClassNames, String[] otherFunctionTypes,
List<NanoparticleSample> particles) {
if (functionClassNames != null && functionClassNames.length > 0) {
List<NanoparticleSample> filteredSet = new ArrayList<NanoparticleSample>();
for (NanoparticleSample particle : particles) {
SortedSet<String> storedFunctions = getStoredFunctionClassNames(particle);
for (String func : functionClassNames) {
// if at least one function type matches, keep the particle
if (storedFunctions.contains(func)) {
filteredSet.add(particle);
break;
}
}
for (String other : otherFunctionTypes) {
if (storedFunctions.contains(other)) {
filteredSet.add(particle);
break;
}
}
}
return filteredSet;
} else {
return particles;
}
}
private List<NanoparticleSample> filterByCharacterizations(
String[] characterizationClassNames,
List<NanoparticleSample> particles) {
if (characterizationClassNames != null
&& characterizationClassNames.length > 0) {
List<NanoparticleSample> filteredSet = new ArrayList<NanoparticleSample>();
for (NanoparticleSample particle : particles) {
SortedSet<String> storedChars = getStoredCharacterizationClassNames(particle);
for (String func : characterizationClassNames) {
// if at least one characterization type matches, keep the
// particle
if (storedChars.contains(func)) {
filteredSet.add(particle);
break;
}
}
}
return filteredSet;
} else {
return particles;
}
}
private List<NanoparticleSample> filterByCompositions(
String[] nanoparticleEntityClassNames,
String[] otherNanoparticleEntityTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
List<NanoparticleSample> particles) {
List<NanoparticleSample> filteredSet1 = new ArrayList<NanoparticleSample>();
if (nanoparticleEntityClassNames != null
&& nanoparticleEntityClassNames.length > 0) {
for (NanoparticleSample particle : particles) {
SortedSet<String> storedEntities = getStoredNanoparticleEntityClassNames(particle);
for (String entity : nanoparticleEntityClassNames) {
// if at least one function type matches, keep the particle
if (storedEntities.contains(entity)) {
filteredSet1.add(particle);
break;
}
}
for (String other : otherNanoparticleEntityTypes) {
// if at least one function type matches, keep the particle
if (storedEntities.contains(other)) {
filteredSet1.add(particle);
break;
}
}
}
} else {
filteredSet1 = particles;
}
List<NanoparticleSample> filteredSet2 = new ArrayList<NanoparticleSample>();
if (functionalizingEntityClassNames != null
&& functionalizingEntityClassNames.length > 0) {
for (NanoparticleSample particle : particles) {
SortedSet<String> storedEntities = getStoredFunctionalizingEntityClassNames(particle);
for (String entity : functionalizingEntityClassNames) {
// if at least one function type matches, keep the particle
if (storedEntities.contains(entity)) {
filteredSet2.add(particle);
break;
}
}
for (String other : otherFunctionalizingEntityTypes) {
// if at least one function type matches, keep the particle
if (storedEntities.contains(other)) {
filteredSet2.add(particle);
break;
}
}
}
} else {
filteredSet2 = particles;
}
if (filteredSet1.size() > filteredSet2.size()) {
filteredSet1.retainAll(filteredSet2);
return filteredSet1;
} else {
filteredSet2.retainAll(filteredSet1);
return filteredSet2;
}
}
public NanoparticleSample findNanoparticleSampleById(String particleId)
throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(
NanoparticleSample.class).add(
Property.forName("id").eq(new Long(particleId)));
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanoparticleEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode("sampleComposition.labFileCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.chemicalAssociationCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementA",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementB",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("reportCollection", FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
NanoparticleSample particleSample = null;
if (!result.isEmpty()) {
particleSample = (NanoparticleSample) result.get(0);
}
return particleSample;
}
public NanoparticleSample findNanoparticleSampleByName(String particleName)
throws Exception {
NanoparticleSample particleSample = null;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(
NanoparticleSample.class).add(
Property.forName("name").eq(particleName));
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanoparticleEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode("sampleComposition.labFileCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.chemicalAssociationCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementA",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementB",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("reportCollection", FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
if (!result.isEmpty()) {
particleSample = (NanoparticleSample) result.get(0);
}
return particleSample;
}
public SortedSet<Source> findAllParticleSources() throws Exception {
SortedSet<Source> sampleSources = new TreeSet<Source>(
new CaNanoLabComparators.ParticleSourceComparator());
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.getAll(Source.class);
for (Object obj : results) {
sampleSources.add((Source) obj);
}
return sampleSources;
}
} | refactored to different name
SVN-Revision: 12435
| src/gov/nih/nci/cananolab/service/particle/NanoparticleSampleSearchHibernateHelper.java | refactored to different name |
||
Java | mit | 635bb5d24cc8bc8f53ca9a24a054c536a13ad884 | 0 | Mac-lp3/turnover,Mac-lp3/turnover,Mac-lp3/turnover | package org.mac.sim.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.junit.Test;
import org.mac.sim.domain.WorkerTask;
import junit.framework.Assert;
public class QueueManagerTest {
/**
* Test that the proper number of tasks have been added to the queue.
*/
@Test
public void runTest() {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(25);
QueueManager qm = new QueueManager(queue, 5, 5);
qm.run();
Assert.assertEquals(25, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(50);
qm = new QueueManager(queue, 5, 10);
qm.run();
Assert.assertEquals(50, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(500);
qm = new QueueManager(queue, 5, 100);
qm.run();
Assert.assertEquals(500, queue.size());
}
@Test
public void workersTest() {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(500);
QueueManager qm = new QueueManager(queue, 5, 100);
Worker w1 = new Worker(queue, 3, 3);
Worker w2 = new Worker(queue, 3, 3);
qm.start();
w1.start();
w2.start();
// few extra nanos saved by declaring variable early (I think)
long endTime;
long startTime = System.nanoTime();
while (!queue.isEmpty()) {
System.out.println(queue.size());
}
endTime = System.nanoTime();
w1.doStop();
w2.doStop();
System.out.println("Execution time ??? " + Math.floor((endTime - startTime)) / 1000000);
System.out.println("Periods in loop: " + qm.getPeriodsSpentInLoop());
System.out.println("~~~" + qm.getAddActions());
System.out.println("~~~" + w1.getTasksCompleted());
System.out.println("~~~" + w2.getTasksCompleted());
}
}
| src/test/java/org/mac/sim/thread/QueueManagerTest.java | package org.mac.sim.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.junit.Test;
import org.mac.sim.domain.WorkerTask;
import junit.framework.Assert;
public class QueueManagerTest {
/**
* Test that the proper number of tasks have been added to the queue.
*/
@Test
public void runTest() {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(25);
QueueManager qm = new QueueManager(queue, 5, 5);
qm.run();
Assert.assertEquals(25, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(50);
qm = new QueueManager(queue, 5, 10);
qm.run();
Assert.assertEquals(50, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(500);
qm = new QueueManager(queue, 5, 100);
qm.run();
Assert.assertEquals(500, queue.size());
}
@Test
public void workersTest() {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(500);
QueueManager qm = new QueueManager(queue, 5, 100);
Worker w = new Worker(queue);
qm.start();
w.start();
while (!queue.isEmpty()) {
System.out.println(queue.size());
}
w.doStop();
}
}
| added more test conditions to measure the time/periods spent in the execution phases
| src/test/java/org/mac/sim/thread/QueueManagerTest.java | added more test conditions to measure the time/periods spent in the execution phases |
|
Java | mit | 168dd45a85b0711cece7831a0748ee7336917708 | 0 | BuycraftPlugin/BuycraftX,BuycraftPlugin/BuycraftX | package net.buycraft.plugin.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import net.buycraft.plugin.data.Coupon;
import net.buycraft.plugin.data.RecentPayment;
import net.buycraft.plugin.data.responses.*;
import okhttp3.*;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
public class ProductionApiClient implements ApiClient {
private static final String API_URL = "https://plugin.buycraft.net";
private static final String API_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX";
private final Gson gson = new GsonBuilder()
.setDateFormat(API_DATE_FORMAT)
.create();
private final OkHttpClient httpClient;
private final String secret;
public ProductionApiClient(String secret) {
this(secret, new OkHttpClient());
}
public ProductionApiClient(String secret, OkHttpClient client) {
this.secret = Objects.requireNonNull(secret, "secret");
this.httpClient = Objects.requireNonNull(client, "client");
}
private Request.Builder getBuilder(String endpoint) {
return new Request.Builder()
.url(API_URL + endpoint)
.addHeader("X-Buycraft-Secret", secret)
.addHeader("Accept", "application/json")
.addHeader("User-Agent", "BuycraftX");
}
private ApiException handleError(Response response, ResponseBody body) throws IOException {
String in = body.string();
if (!Objects.equals(response.header("Content-Type"), "application/json")) {
return new ApiException("Unexpected content-type " + response.header("Content-Type"), response.request(), response, in);
}
BuycraftError error = gson.fromJson(in, BuycraftError.class);
if (error != null) {
return new ApiException(error.getErrorMessage(), response.request(), response, in);
} else {
return new ApiException("Unknown error occurred whilst deserializing error object.", response.request(), response, in);
}
}
private <T> T get(String endpoint, Type type) throws IOException, ApiException {
return get(endpoint, null, type);
}
private <T> T get(String endpoint, CacheControl control, Type type) throws IOException, ApiException {
try {
Request.Builder requestBuilder = getBuilder(endpoint).get();
if (control != null) requestBuilder.cacheControl(control);
Request request = requestBuilder.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (response.isSuccessful()) {
try {
return gson.fromJson(body.charStream(), type);
} catch (JsonSyntaxException e) {
throw new ApiException("Unable to parse response.", response.request(), response, body.string());
}
} else {
throw handleError(response, body);
}
}
} catch (Exception e) {
throw new ApiException("Unable to connect to API");
}
}
@Override
public ServerInformation getServerInformation() throws IOException, ApiException {
return get("/information", CacheControl.FORCE_NETWORK, ServerInformation.class);
}
@Override
public Listing retrieveListing() throws IOException, ApiException {
Listing listing = get("/listing", CacheControl.FORCE_NETWORK, Listing.class);
listing.order();
return listing;
}
@Override
public QueueInformation retrieveOfflineQueue() throws IOException, ApiException {
return get("/queue/offline-commands", CacheControl.FORCE_NETWORK, QueueInformation.class);
}
@Override
public DueQueueInformation retrieveDueQueue(int limit, int page) throws IOException, ApiException {
return get("/queue?limit=" + limit + "&page=" + page, CacheControl.FORCE_NETWORK, DueQueueInformation.class);
}
@Override
public QueueInformation getPlayerQueue(int id) throws IOException, ApiException {
return get("/queue/online-commands/" + id, CacheControl.FORCE_NETWORK, QueueInformation.class);
}
@Override
public void deleteCommand(List<Integer> ids) throws IOException, ApiException {
FormBody.Builder builder = new FormBody.Builder();
for (Integer id : ids) {
builder.add("ids[]", id.toString());
}
Request request = getBuilder("/queue")
.method("DELETE", builder.build())
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, body);
}
}
}
@Override
public CheckoutUrlResponse getCheckoutUri(String username, int packageId) throws IOException, ApiException {
RequestBody body = new FormBody.Builder()
.add("username", username)
.add("package_id", Integer.toString(packageId))
.build();
Request request = getBuilder("/checkout")
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
} else {
return gson.fromJson(rspBody.charStream(), CheckoutUrlResponse.class);
}
}
}
@Override
public List<RecentPayment> getRecentPayments(int limit) throws IOException, ApiException {
return get("/payments?limit=" + limit, CacheControl.FORCE_NETWORK, new TypeToken<List<RecentPayment>>() {
}.getType());
}
@Override
public List<Coupon> getAllCoupons() throws IOException, ApiException {
CouponListing listing = get("/coupons", CouponListing.class);
return listing.getData();
}
@Override
public Coupon getCoupon(int id) throws IOException, ApiException {
CouponSingleListing listing = get("/coupons/" + id, CouponSingleListing.class);
return listing.getData();
}
@Override
public void deleteCoupon(int id) throws IOException, ApiException {
Request request = getBuilder("/coupons/" + id)
.delete()
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
}
}
}
@Override
public Coupon createCoupon(Coupon coupon) throws IOException, ApiException {
FormBody.Builder build = new FormBody.Builder()
.add("code", coupon.getCode())
.add("effective_on", coupon.getEffective().getType());
switch (coupon.getEffective().getType()) {
case "packages":
for (Integer id1 : coupon.getEffective().getPackages()) {
build.add("packages[]", Integer.toString(id1));
}
break;
case "categories":
for (Integer id2 : coupon.getEffective().getCategories()) {
build.add("categories[]", Integer.toString(id2));
}
break;
}
RequestBody body = build.add("discount_type", coupon.getDiscount().getType())
.add("discount_amount", coupon.getDiscount().getValue().toPlainString())
.add("discount_percentage", coupon.getDiscount().getPercentage().toPlainString())
.add("expire_type", coupon.getExpire().getType())
.add("expire_limit", Integer.toString(coupon.getExpire().getLimit()))
.add("expire_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getExpire().getDate()))
.add("start_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getStartDate()))
.add("basket_type", coupon.getBasketType())
.add("minimum", coupon.getMinimum().toPlainString())
.add("redeem_limit", Integer.toString(coupon.getUserLimit()))
.build();
Request request = getBuilder("/coupons")
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
} else {
return gson.fromJson(rspBody.charStream(), CouponSingleListing.class).getData();
}
}
}
@Override
public boolean verifyUser(String username, String code) throws IOException, ApiException {
FormBody.Builder builder = new FormBody.Builder();
builder.add("username", username);
builder.add("code", code);
Request request = getBuilder("/verify")
.method("POST", builder.build())
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, body);
}
}
return true;
}
}
| common/src/main/java/net/buycraft/plugin/client/ProductionApiClient.java | package net.buycraft.plugin.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import net.buycraft.plugin.data.Coupon;
import net.buycraft.plugin.data.RecentPayment;
import net.buycraft.plugin.data.responses.*;
import okhttp3.*;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
public class ProductionApiClient implements ApiClient {
private static final String API_URL = "https://plugin.buycraft.net";
private static final String API_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX";
private final Gson gson = new GsonBuilder()
.setDateFormat(API_DATE_FORMAT)
.create();
private final OkHttpClient httpClient;
private final String secret;
public ProductionApiClient(String secret) {
this(secret, new OkHttpClient());
}
public ProductionApiClient(String secret, OkHttpClient client) {
this.secret = Objects.requireNonNull(secret, "secret");
this.httpClient = Objects.requireNonNull(client, "client");
}
private Request.Builder getBuilder(String endpoint) {
return new Request.Builder()
.url(API_URL + endpoint)
.addHeader("X-Buycraft-Secret", secret)
.addHeader("Accept", "application/json")
.addHeader("User-Agent", "BuycraftX");
}
private ApiException handleError(Response response, ResponseBody body) throws IOException {
String in = body.string();
if (!Objects.equals(response.header("Content-Type"), "application/json")) {
return new ApiException("Unexpected content-type " + response.header("Content-Type"), response.request(), response, in);
}
BuycraftError error = gson.fromJson(in, BuycraftError.class);
if (error != null) {
return new ApiException(error.getErrorMessage(), response.request(), response, in);
} else {
return new ApiException("Unknown error occurred whilst deserializing error object.", response.request(), response, in);
}
}
private <T> T get(String endpoint, Type type) throws IOException, ApiException {
return get(endpoint, null, type);
}
private <T> T get(String endpoint, CacheControl control, Type type) throws IOException, ApiException {
Request.Builder requestBuilder = getBuilder(endpoint).get();
if (control != null) requestBuilder.cacheControl(control);
Request request = requestBuilder.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (response.isSuccessful()) {
return gson.fromJson(body.charStream(), type);
} else {
throw handleError(response, body);
}
}
}
@Override
public ServerInformation getServerInformation() throws IOException, ApiException {
return get("/information", CacheControl.FORCE_NETWORK, ServerInformation.class);
}
@Override
public Listing retrieveListing() throws IOException, ApiException {
Listing listing = get("/listing", CacheControl.FORCE_NETWORK, Listing.class);
listing.order();
return listing;
}
@Override
public QueueInformation retrieveOfflineQueue() throws IOException, ApiException {
return get("/queue/offline-commands", CacheControl.FORCE_NETWORK, QueueInformation.class);
}
@Override
public DueQueueInformation retrieveDueQueue(int limit, int page) throws IOException, ApiException {
return get("/queue?limit=" + limit + "&page=" + page, CacheControl.FORCE_NETWORK, DueQueueInformation.class);
}
@Override
public QueueInformation getPlayerQueue(int id) throws IOException, ApiException {
return get("/queue/online-commands/" + id, CacheControl.FORCE_NETWORK, QueueInformation.class);
}
@Override
public void deleteCommand(List<Integer> ids) throws IOException, ApiException {
FormBody.Builder builder = new FormBody.Builder();
for (Integer id : ids) {
builder.add("ids[]", id.toString());
}
Request request = getBuilder("/queue")
.method("DELETE", builder.build())
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, body);
}
}
}
@Override
public CheckoutUrlResponse getCheckoutUri(String username, int packageId) throws IOException, ApiException {
RequestBody body = new FormBody.Builder()
.add("username", username)
.add("package_id", Integer.toString(packageId))
.build();
Request request = getBuilder("/checkout")
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
} else {
return gson.fromJson(rspBody.charStream(), CheckoutUrlResponse.class);
}
}
}
@Override
public List<RecentPayment> getRecentPayments(int limit) throws IOException, ApiException {
return get("/payments?limit=" + limit, CacheControl.FORCE_NETWORK, new TypeToken<List<RecentPayment>>() {
}.getType());
}
@Override
public List<Coupon> getAllCoupons() throws IOException, ApiException {
CouponListing listing = get("/coupons", CouponListing.class);
return listing.getData();
}
@Override
public Coupon getCoupon(int id) throws IOException, ApiException {
CouponSingleListing listing = get("/coupons/" + id, CouponSingleListing.class);
return listing.getData();
}
@Override
public void deleteCoupon(int id) throws IOException, ApiException {
Request request = getBuilder("/coupons/" + id)
.delete()
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
}
}
}
@Override
public Coupon createCoupon(Coupon coupon) throws IOException, ApiException {
FormBody.Builder build = new FormBody.Builder()
.add("code", coupon.getCode())
.add("effective_on", coupon.getEffective().getType());
switch (coupon.getEffective().getType()) {
case "packages":
for (Integer id1 : coupon.getEffective().getPackages()) {
build.add("packages[]", Integer.toString(id1));
}
break;
case "categories":
for (Integer id2 : coupon.getEffective().getCategories()) {
build.add("categories[]", Integer.toString(id2));
}
break;
}
RequestBody body = build.add("discount_type", coupon.getDiscount().getType())
.add("discount_amount", coupon.getDiscount().getValue().toPlainString())
.add("discount_percentage", coupon.getDiscount().getPercentage().toPlainString())
.add("expire_type", coupon.getExpire().getType())
.add("expire_limit", Integer.toString(coupon.getExpire().getLimit()))
.add("expire_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getExpire().getDate()))
.add("start_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getStartDate()))
.add("basket_type", coupon.getBasketType())
.add("minimum", coupon.getMinimum().toPlainString())
.add("redeem_limit", Integer.toString(coupon.getUserLimit()))
.build();
Request request = getBuilder("/coupons")
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody rspBody = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, rspBody);
} else {
return gson.fromJson(rspBody.charStream(), CouponSingleListing.class).getData();
}
}
}
@Override
public boolean verifyUser(String username, String code) throws IOException, ApiException {
FormBody.Builder builder = new FormBody.Builder();
builder.add("username", username);
builder.add("code", code);
Request request = getBuilder("/verify")
.method("POST", builder.build())
.build();
Response response = httpClient.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (!response.isSuccessful()) {
throw handleError(response, body);
}
}
return true;
}
}
| Additional Exception handler on get() to prevent uncaught Exceptions, try...catch on JSON parsing
| common/src/main/java/net/buycraft/plugin/client/ProductionApiClient.java | Additional Exception handler on get() to prevent uncaught Exceptions, try...catch on JSON parsing |
|
Java | mit | 87ed2f94226c43170d772b9aecdf67258bd50597 | 0 | lightblueseas/swing-components,lightblueseas/swing-components | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package de.alpharogroup.swing.table.editor;
import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import lombok.Getter;
import lombok.Setter;
/**
* The class {@link TableCellButtonEditor}.
*/
@Getter
@Setter
public class TableCellButtonEditor extends DefaultCellEditor
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The button. */
private JButton button;
/** The flag if the button was clicked. */
private boolean clicked;
/** The row index. */
private int row;
/** The value. */
private Object value;
/** The column index. */
private int column;
/**
* Instantiates a new {@link TableCellButtonEditor} object.
*
* @param checkBox
* the check box
*/
public TableCellButtonEditor(final JCheckBox checkBox)
{
super(checkBox);
setButton(new JButton());
getButton().setOpaque(true);
getButton().addActionListener(e -> {
onClick();
fireEditingStopped();
});
}
/**
* {@inheritDoc}
*/
@Override
public Object getCellEditorValue()
{
if (isClicked())
{
JOptionPane.showMessageDialog(button, "You clicked the button with the value "
+ this.value + " in row index " + row + " and in colunm index " + column + ".");
}
setClicked(false);
String text = "";
if (getValue() != null)
{
text = getValue().toString();
}
return text;
}
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected,
final int row, final int column)
{
setRow(row);
setColumn(column);
setValue(value);
if (isSelected)
{
getButton().setForeground(table.getSelectionForeground());
getButton().setBackground(table.getSelectionBackground());
}
else
{
getButton().setForeground(table.getForeground());
getButton().setBackground(table.getBackground());
}
String text = "";
if (value != null)
{
text = getValue().toString();
}
getButton().setText(text);
setClicked(true);
return getButton();
}
/**
* Callback method to interact when the button is clicked.
*/
protected void onClick()
{
}
/**
* {@inheritDoc}
*/
@Override
public boolean stopCellEditing()
{
setClicked(false);
return super.stopCellEditing();
}
} | src/main/java/de/alpharogroup/swing/table/editor/TableCellButtonEditor.java | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package de.alpharogroup.swing.table.editor;
import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import lombok.Getter;
import lombok.Setter;
/**
* The class {@link TableCellButtonEditor}.
*/
@Getter
@Setter
public class TableCellButtonEditor extends DefaultCellEditor
{
/** The button. */
private JButton button;
/** The flag if the button was clicked. */
private boolean clicked;
/** The row index. */
private int row;
/** The value. */
private Object value;
/** The column index. */
private int column;
/**
* Instantiates a new {@link TableCellButtonEditor} object.
*
* @param checkBox
* the check box
*/
public TableCellButtonEditor(JCheckBox checkBox)
{
super(checkBox);
setButton(new JButton());
getButton().setOpaque(true);
getButton().addActionListener(e -> {
onClick();
fireEditingStopped();
});
}
/**
* {@inheritDoc}
*/
@Override
public Object getCellEditorValue()
{
if (isClicked())
{
JOptionPane.showMessageDialog(button, "You clicked the button with the value "
+ this.value + " in row index " + row + " and in colunm index " + column + ".");
}
setClicked(false);
String text = "";
if (getValue() != null)
{
text = getValue().toString();
}
return text;
}
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column)
{
setRow(row);
setColumn(column);
setValue(value);
if (isSelected)
{
getButton().setForeground(table.getSelectionForeground());
getButton().setBackground(table.getSelectionBackground());
}
else
{
getButton().setForeground(table.getForeground());
getButton().setBackground(table.getBackground());
}
String text = "";
if (value != null)
{
text = getValue().toString();
}
getButton().setText(text);
setClicked(true);
return getButton();
}
/**
* Callback method to interact when the button is clicked.
*/
protected void onClick()
{
}
/**
* {@inheritDoc}
*/
@Override
public boolean stopCellEditing()
{
setClicked(false);
return super.stopCellEditing();
}
} | remove warning | src/main/java/de/alpharogroup/swing/table/editor/TableCellButtonEditor.java | remove warning |
|
Java | mit | 47f9b0764059eadde4640a37a41d8a6841756691 | 0 | javagl/Common | /*
* www.javagl.de - Common
*
* Copyright (c) 2012-2014 Marco Hutter - http://www.javagl.de
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package de.javagl.common.iteration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Utility methods related to Iterables.<br>
* <br>
* Unless otherwise noted, none of the parameters of these methods
* may be <code>null</code>.
*/
public class Iterables
{
/**
* Drains all elements that are provided by the iterator of
* the given iterable into a list
*
* @param <T> The element type
*
* @param iterable The iterable
* @return The list
*/
public static <T> List<T> toList(Iterable<T> iterable)
{
Objects.requireNonNull(iterable, "The iterable is null");
return Iterables.toCollection(iterable, new ArrayList<T>());
}
/**
* Drains all elements that are provided by the iterator of
* the given iterable into a set
*
* @param <T> The element type
*
* @param iterable The iterable
* @return The set
*/
public static <T> Set<T> toSet(Iterable<T> iterable)
{
Objects.requireNonNull(iterable, "The iterable is null");
return Iterables.toCollection(iterable, new LinkedHashSet<T>());
}
/**
* Drains all elements that are provided by the iterator of
* the given iterable into the given collection
*
* @param <T> The element type
* @param <C> The collection type
*
* @param iterable The iterable
* @param collection The target collection
* @return The given collection
*/
public static <T, C extends Collection<? super T>> C toCollection(
Iterable<T> iterable, C collection)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(collection, "The collection is null");
return Iterators.toCollection(iterable.iterator(), collection);
}
/**
* Returns an iterator that combines the iterators that are provided
* by the iterables that are provided by the iterator of the given
* iterable. Fancy stuff, he?
*
* @param <T> The element type
*
* @param iterablesIterable The iterable over the iterables. May not
* provide <code>null</code> iterables.
* @return The iterator
*/
public static <T> Iterable<T> iterableOverIterables(
final Iterable<? extends Iterable<? extends T>> iterablesIterable)
{
Objects.requireNonNull(iterablesIterable,
"The iterablesIterable is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return Iterators.iteratorOverIterables(
iterablesIterable.iterator());
}
};
}
/**
* Returns an iterable that provides iterators that are transforming
* the elements provided by the iterators of the given iterable using
* the given function
*
* @param <S> The element type
* @param <T> The value type
*
* @param iterable The delegate iterable
* @param function The function
* @return The iterator
*/
public static <S, T> Iterable<T> transformingIterable(
final Iterable<? extends S> iterable,
final Function<S, ? extends T> function)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(function, "The function is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return new TransformingIterator<S, T>(
iterable.iterator(), function);
}
};
}
/**
* Returns an iterable that provides an iterator that only returns the
* elements provided by the iterator of the given iterable to which
* the given predicate applies.
*
* @param <T> The element type
*
* @param iterable The delegate iterable
* @param predicate The predicate
* @return The iterator
*/
public static <T> Iterable<T> filteringIterable(
final Iterable<? extends T> iterable,
final Predicate<? super T> predicate)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(predicate, "The predicate is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return new FilteringIterator<T>(
iterable.iterator(), predicate);
}
};
}
/**
* Returns whether the given iterable is sorted according to the given
* comparator. Returns <code>true</code> if the sequence is empty.
*
* @param <T> The element type
*
* @param iterable The iterable
* @param comparator The comparator
* @return Whether the iterable is sorted
*/
public static <T> boolean isSorted(
Iterable<? extends T> iterable, Comparator<? super T> comparator)
{
Iterator<? extends T> iterator = iterable.iterator();
if (!iterator.hasNext())
{
return true;
}
T t0 = iterator.next();
while (iterator.hasNext())
{
T t1 = iterator.next();
if (comparator.compare(t0, t1) > 0)
{
return false;
}
t0 = t1;
}
return true;
}
/**
* Private constructor to prevent instantiation
*/
private Iterables()
{
// Private constructor to prevent instantiation
}
}
| src/main/java/de/javagl/common/iteration/Iterables.java | /*
* www.javagl.de - Common
*
* Copyright (c) 2012-2014 Marco Hutter - http://www.javagl.de
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package de.javagl.common.iteration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Utility methods related to Iterables.<br>
* <br>
* Unless otherwise noted, none of the parameters of these methods
* may be <code>null</code>.
*/
public class Iterables
{
/**
* Drains all elements that are provided by the iterator of
* the given iterable into a list
*
* @param <T> The element type
* @param iterable The iterable
* @return The list
*/
public static <T> List<T> toList(Iterable<T> iterable)
{
Objects.requireNonNull(iterable, "The iterable is null");
return Iterables.toCollection(iterable, new ArrayList<T>());
}
/**
* Drains all elements that are provided by the iterator of
* the given iterable into a set
*
* @param <T> The element type
* @param iterable The iterable
* @return The set
*/
public static <T> Set<T> toSet(Iterable<T> iterable)
{
Objects.requireNonNull(iterable, "The iterable is null");
return Iterables.toCollection(iterable, new LinkedHashSet<T>());
}
/**
* Drains all elements that are provided by the iterator of
* the given iterable into the given collection
*
* @param <T> The element type
* @param <C> The collection type
* @param iterable The iterable
* @param collection The target collection
* @return The given collection
*/
public static <T, C extends Collection<? super T>> C toCollection(
Iterable<T> iterable, C collection)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(collection, "The collection is null");
return Iterators.toCollection(iterable.iterator(), collection);
}
/**
* Returns an iterator that combines the iterators that are provided
* by the iterables that are provided by the iterator of the given
* iterable. Fancy stuff, he?
*
* @param <T> The element type
* @param iterablesIterable The iterable over the iterables. May not
* provide <code>null</code> iterables.
* @return The iterator
*/
public static <T> Iterable<T> iterableOverIterables(
final Iterable<? extends Iterable<? extends T>> iterablesIterable)
{
Objects.requireNonNull(iterablesIterable,
"The iterablesIterable is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return Iterators.iteratorOverIterables(
iterablesIterable.iterator());
}
};
}
/**
* Returns an iterable that provides iterators that are transforming
* the elements provided by the iterators of the given iterable using
* the given function
*
* @param <S> The element type
* @param <T> The value type
* @param iterable The delegate iterable
* @param function The function
* @return The iterator
*/
public static <S, T> Iterable<T> transformingIterable(
final Iterable<? extends S> iterable,
final Function<S, ? extends T> function)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(function, "The function is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return new TransformingIterator<S, T>(
iterable.iterator(), function);
}
};
}
/**
* Returns an iterable that provides an iterator that only returns the
* elements provided by the iterator of the given iterable to which
* the given predicate applies.
*
* @param <T> The element type
* @param iterable The delegate iterable
* @param predicate The predicate
* @return The iterator
*/
public static <T> Iterable<T> filteringIterable(
final Iterable<? extends T> iterable,
final Predicate<? super T> predicate)
{
Objects.requireNonNull(iterable, "The iterable is null");
Objects.requireNonNull(predicate, "The predicate is null");
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return new FilteringIterator<T>(
iterable.iterator(), predicate);
}
};
}
/**
* Returns whether the given iterable is sorted according to the given
* comparator. Returns <code>true</code> if the sequence is empty.
*
* @param iterable The iterable
* @param comparator The comparator
* @return Whether the iterable is sorted
*/
public static <T> boolean isSorted(
Iterable<? extends T> iterable, Comparator<? super T> comparator)
{
Iterator<? extends T> iterator = iterable.iterator();
if (!iterator.hasNext())
{
return true;
}
T t0 = iterator.next();
while (iterator.hasNext())
{
T t1 = iterator.next();
if (comparator.compare(t0, t1) > 0)
{
return false;
}
t0 = t1;
}
return true;
}
/**
* Private constructor to prevent instantiation
*/
private Iterables()
{
// Private constructor to prevent instantiation
}
}
| Minor JavaDoc fix and formatting
| src/main/java/de/javagl/common/iteration/Iterables.java | Minor JavaDoc fix and formatting |
|
Java | mit | 45fe9f6972fc358d6d48bab9abdda83da2986774 | 0 | ThisIsTyDell/springboot-angular-demo-app,ThisIsTyDell/springboot-angular-demo-app,ThisIsTyDell/springboot-angular-demo-app,ThisIsTyDell/springboot-angular-demo-app,ThisIsTyDell/springboot-angular-demo-app | package com.tymiller.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tymiller.dao.PhotoDao;
import com.tymiller.model.Photo;
import com.tymiller.model.User;
import com.tymiller.service.PhotoService;
@Service
public class PhotoServiceImpl implements PhotoService {
@Autowired
private PhotoDao photoDao;
public Photo save(Photo photo) {
return photoDao.save(photo);
}
public List<Photo> findAll() {
return photoDao.findAll();
}
public List<Photo> findByUser(User user) {
return photoDao.findByUser(user);
}
public Photo findByPhotoId(Long photoId) {
return photoDao.findByPhotoId(photoId);
}
}
| Photable-Backend/src/main/java/com/tymiller/service/impl/PhotoServiceImpl.java | package com.tymiller.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tymiller.model.Photo;
import com.tymiller.model.User;
import com.tymiller.service.PhotoService;
@Service
public class PhotoServiceImpl implements PhotoService {
@Autowired
private PhotoDao photoDao;
public Photo save(Photo photo) {
return photoDao.save(photo);
}
public List<Photo> findAll() {
return photoDao.findAll();
}
public List<Photo> findByUser(User user) {
return photoDao.findByUser(user);
}
public Photo findByPhotoId(Long photoId) {
return photoDao.findByPhotoId(photoId);
}
}
| import photo dao
| Photable-Backend/src/main/java/com/tymiller/service/impl/PhotoServiceImpl.java | import photo dao |
|
Java | mit | 15bb82f0b11b06c86b541fde4a07e4767bb9af0f | 0 | ltearno/hexa.tools,ltearno/hexa.tools,ltearno/hexa.tools | package fr.lteconsulting.hexa.server.qpath;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import fr.lteconsulting.hexa.client.common.HexaDate;
import fr.lteconsulting.hexa.client.common.HexaDateTime;
import fr.lteconsulting.hexa.client.common.HexaTime;
import fr.lteconsulting.hexa.client.common.text.DateTimeFormat;
import fr.lteconsulting.hexa.client.interfaces.IHasIntegerId;
import fr.lteconsulting.hexa.shared.data.IdDTO;
public class DatabaseHelper
{
private Database db;
private static final DateTimeFormat dateFormatter = DateTimeFormat.getFormat( "yyyy/MM/dd HH:mm:ss" );
HashMap<String, ArrayList<String>> cacheFields;
public DatabaseHelper( Database db )
{
this.db = db;
}
public void term()
{
db = null;
}
public boolean hasField( String table, String field )
{
DBResults res = db.sql( "SELECT * FROM " + table + " WHERE 1=0" );
if( res == null )
return false;
int idx = res.getColumnIndex( field );
return idx >= 0;
}
public ArrayList<String> getTableFields( String table )
{
if( cacheFields == null )
cacheFields = new HashMap<String, ArrayList<String>>();
ArrayList<String> list = cacheFields.get( table );
if( list != null )
return list;
list = new ArrayList<String>();
cacheFields.put( table, list );
DBResults res = db.sql( "SELECT * FROM " + table + " WHERE 1=0" );
if( res == null )
return list;
int n = res.getColumnCount();
for( int i = 0; i < n; i++ )
list.add( res.getColumnName( i ) );
return list;
}
public ArrayList<String> getTables()
{
ArrayList<String> list = new ArrayList<String>();
try
{
DBResults res = new DBResults( db.getDatabaseMetaData().getTables( db.getCurrentDatabase(), null, null, new String[] { "TABLE" } ), null );
int idx = res.getColumnIndex( "TABLE_NAME" );
while( res.next() )
list.add( res.getString( idx ) );
}
catch( SQLException e )
{
e.printStackTrace();
}
return list;
}
// TODO : this one works only on MySQL server
public boolean hasTrigger( String triggerName )
{
DBResults res = db.sql( "SELECT * FROM information_schema.TRIGGERS WHERE TRIGGER_NAME='$triggerName' AND TRIGGER_SCHEMA='" + db.getCurrentDatabase() + "'" );
if( res.getRowCount() == 0 )
return false;
return true;
}
public static class FieldsMap
{
HashMap<String, Object> map = new HashMap<String, Object>();
public static FieldsMap create()
{
return new FieldsMap();
}
public FieldsMap p( String name, Object value )
{
if( value != null && value.getClass().isEnum() )
{
map.put( name, value.toString() );
return this;
}
map.put( name, value );
return this;
}
}
public <T extends IdDTO> T insert( String table, Class<T> clazz, T item )
{
return insert( table, clazz, item, null );
}
private String getStringForObject( Object o )
{
if( o == null )
return "NULL";
if( o.getClass().isEnum() )
return "'" + o.toString() + "'";
if( o instanceof Date )
return "'" + dateFormatter.format( (Date) o ) + "'";
if( o instanceof HexaDateTime )
return "'" + ((HexaDateTime) o).getString() + "'";
if( o instanceof HexaDate )
return "'" + ((HexaDate) o).getString() + "'";
if( o instanceof HexaTime )
return "'" + ((HexaTime) o).getString() + "'";
return "'" + o.toString().replaceAll( "'" , "''" ) + "'";
}
// TODO : return the T item. for this have to prepare for the clazz some
// data, to be optimized a bit
public <T extends IdDTO> T insert( String table, Class<T> clazz, T item, FieldsMap toAppendFieldsMap )
{
try
{
FieldsMap fields = FieldsMap.create();
Field[] classFields = clazz.getFields();
for( int i = 0; i < classFields.length; i++ )
{
Field classField = classFields[i];
if( classField.getName().equals( "id" ) )
continue;
fields.p( JavaDBNames.javaToDBName( classFields[i].getName() ), classField.get( item ) );
}
if( toAppendFieldsMap != null )
{
for( Entry<String, Object> e : toAppendFieldsMap.map.entrySet() )
{
fields.map.put( e.getKey(), e.getValue() );
// TODO sets the item's field also
}
}
int insertedId = insert( table, fields );
item.setId( insertedId );
return item;
}
catch( IllegalAccessException e )
{
return null;
}
}
public int insert( String table, FieldsMap fields )
{
return insert( table, fields.map );
}
public int insert( String table, HashMap<String, ?> fields )
{
String sql;
if( fields == null )
{
sql = "INSERT INTO " + table + " () VALUES ()";
}
else
{
StringBuilder fieldsSb = new StringBuilder();
StringBuilder valuesSb = new StringBuilder();
boolean fFirst = true;
for( Entry<String, ?> entry : fields.entrySet() )
{
if( fFirst )
{
fFirst = false;
}
else
{
fieldsSb.append( ", " );
valuesSb.append( ", " );
}
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
fieldsSb.append( "`" + fieldName + "`" );
valuesSb.append( getStringForObject( fieldValue ) );
}
sql = "INSERT INTO " + table + " (" + fieldsSb.toString() + ") VALUES (" + valuesSb.toString() + ")";
}
return db.sqlInsert( sql );
}
public int delete( String table, String condition )
{
return db.sqlDelete( "DELETE FROM " + table + " WHERE " + condition );
}
public int update( String table, String condition, FieldsMap fields )
{
return update( table, condition, fields.map );
}
public <T extends IHasIntegerId> T update( String table, Class<T> clazz, T item )
{
return update( table, clazz, item, null );
}
public <T extends IHasIntegerId> T update( String table, Class<T> clazz, T item, FieldsMap toAppendFieldsMap )
{
try
{
FieldsMap fields = FieldsMap.create();
Field[] classFields = clazz.getFields();
for( int i = 0; i < classFields.length; i++ )
{
Field classField = classFields[i];
if( classField.getName().equals( "id" ) )
continue;
fields.p( JavaDBNames.javaToDBName( classFields[i].getName() ), classField.get( item ) );
}
if( toAppendFieldsMap != null )
{
for( Entry<String, Object> e : toAppendFieldsMap.map.entrySet() )
{
fields.map.put( e.getKey(), e.getValue() );
// TODO sets the item's field also
}
}
int res = update( table, "id="+item.getId(), fields.map );
if( res < 0 )
return null;
return item;
}
catch( IllegalAccessException e )
{
return null;
}
}
public int update( String table, String condition, HashMap<String, ?> data )
{
if( data == null || data.size() == 0 )
return 0;
StringBuilder updateSb = new StringBuilder();
boolean fFirst = true;
for( Entry<String, ?> entry : data.entrySet() )
{
if( fFirst )
fFirst = false;
else
updateSb.append( ", " );
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
updateSb.append( "`" + fieldName + "`=" );
if( fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equalsIgnoreCase( "null" )) )
updateSb.append( "NULL" );
else
updateSb.append( "'" + fieldValue.toString() + "'" );
}
String sql = "UPDATE " + table + " SET " + updateSb.toString() + " WHERE " + condition;
return db.sqlUpdate( sql );
}
}
| hexa.core/src/main/java/fr/lteconsulting/hexa/server/qpath/DatabaseHelper.java | package fr.lteconsulting.hexa.server.qpath;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import fr.lteconsulting.hexa.client.common.HexaDate;
import fr.lteconsulting.hexa.client.common.HexaDateTime;
import fr.lteconsulting.hexa.client.common.HexaTime;
import fr.lteconsulting.hexa.client.common.text.DateTimeFormat;
import fr.lteconsulting.hexa.client.interfaces.IHasIntegerId;
import fr.lteconsulting.hexa.shared.data.IdDTO;
public class DatabaseHelper
{
private Database db;
private static final DateTimeFormat dateFormatter = DateTimeFormat.getFormat( "yyyy/MM/dd HH:mm:ss" );
HashMap<String, ArrayList<String>> cacheFields;
public DatabaseHelper( Database db )
{
this.db = db;
}
public void term()
{
db = null;
}
public boolean hasField( String table, String field )
{
DBResults res = db.sql( "SELECT * FROM " + table + " WHERE 1=0" );
if( res == null )
return false;
int idx = res.getColumnIndex( field );
return idx >= 0;
}
public ArrayList<String> getTableFields( String table )
{
if( cacheFields == null )
cacheFields = new HashMap<String, ArrayList<String>>();
ArrayList<String> list = cacheFields.get( table );
if( list != null )
return list;
list = new ArrayList<String>();
cacheFields.put( table, list );
DBResults res = db.sql( "SELECT * FROM " + table + " WHERE 1=0" );
if( res == null )
return list;
int n = res.getColumnCount();
for( int i = 0; i < n; i++ )
list.add( res.getColumnName( i ) );
return list;
}
public ArrayList<String> getTables()
{
ArrayList<String> list = new ArrayList<String>();
try
{
DBResults res = new DBResults( db.getDatabaseMetaData().getTables( db.getCurrentDatabase(), null, null, new String[] { "TABLE" } ), null );
int idx = res.getColumnIndex( "TABLE_NAME" );
while( res.next() )
list.add( res.getString( idx ) );
}
catch( SQLException e )
{
e.printStackTrace();
}
return list;
}
// TODO : this one works only on MySQL server
public boolean hasTrigger( String triggerName )
{
DBResults res = db.sql( "SELECT * FROM information_schema.TRIGGERS WHERE TRIGGER_NAME='$triggerName' AND TRIGGER_SCHEMA='" + db.getCurrentDatabase() + "'" );
if( res.getRowCount() == 0 )
return false;
return true;
}
public static class FieldsMap
{
HashMap<String, Object> map = new HashMap<String, Object>();
public static FieldsMap create()
{
return new FieldsMap();
}
public FieldsMap p( String name, Object value )
{
if( value != null && value.getClass().isEnum() )
{
map.put( name, value.toString() );
return this;
}
map.put( name, value );
return this;
}
}
public <T extends IdDTO> T insert( String table, Class<T> clazz, T item )
{
return insert( table, clazz, item, null );
}
private String getStringForObject( Object o )
{
if( o == null )
return "NULL";
if( o.getClass().isEnum() )
return "'" + o.toString() + "'";
if( o instanceof Date )
return "'" + dateFormatter.format( (Date) o ) + "'";
if( o instanceof HexaDateTime )
return "'" + ((HexaDateTime) o).getString() + "'";
if( o instanceof HexaDate )
return "'" + ((HexaDate) o).getString() + "'";
if( o instanceof HexaTime )
return "'" + ((HexaTime) o).getString() + "'";
return "'" + o.toString() + "'";
}
// TODO : return the T item. for this have to prepare for the clazz some
// data, to be optimized a bit
public <T extends IdDTO> T insert( String table, Class<T> clazz, T item, FieldsMap toAppendFieldsMap )
{
try
{
FieldsMap fields = FieldsMap.create();
Field[] classFields = clazz.getFields();
for( int i = 0; i < classFields.length; i++ )
{
Field classField = classFields[i];
if( classField.getName().equals( "id" ) )
continue;
fields.p( JavaDBNames.javaToDBName( classFields[i].getName() ), classField.get( item ) );
}
if( toAppendFieldsMap != null )
{
for( Entry<String, Object> e : toAppendFieldsMap.map.entrySet() )
{
fields.map.put( e.getKey(), e.getValue() );
// TODO sets the item's field also
}
}
int insertedId = insert( table, fields );
item.setId( insertedId );
return item;
}
catch( IllegalAccessException e )
{
return null;
}
}
public int insert( String table, FieldsMap fields )
{
return insert( table, fields.map );
}
public int insert( String table, HashMap<String, ?> fields )
{
String sql;
if( fields == null )
{
sql = "INSERT INTO " + table + " () VALUES ()";
}
else
{
StringBuilder fieldsSb = new StringBuilder();
StringBuilder valuesSb = new StringBuilder();
boolean fFirst = true;
for( Entry<String, ?> entry : fields.entrySet() )
{
if( fFirst )
{
fFirst = false;
}
else
{
fieldsSb.append( ", " );
valuesSb.append( ", " );
}
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
fieldsSb.append( "`" + fieldName + "`" );
valuesSb.append( getStringForObject( fieldValue ) );
}
sql = "INSERT INTO " + table + " (" + fieldsSb.toString() + ") VALUES (" + valuesSb.toString() + ")";
}
return db.sqlInsert( sql );
}
public int delete( String table, String condition )
{
return db.sqlDelete( "DELETE FROM " + table + " WHERE " + condition );
}
public int update( String table, String condition, FieldsMap fields )
{
return update( table, condition, fields.map );
}
public <T extends IHasIntegerId> T update( String table, Class<T> clazz, T item )
{
return update( table, clazz, item, null );
}
public <T extends IHasIntegerId> T update( String table, Class<T> clazz, T item, FieldsMap toAppendFieldsMap )
{
try
{
FieldsMap fields = FieldsMap.create();
Field[] classFields = clazz.getFields();
for( int i = 0; i < classFields.length; i++ )
{
Field classField = classFields[i];
if( classField.getName().equals( "id" ) )
continue;
fields.p( JavaDBNames.javaToDBName( classFields[i].getName() ), classField.get( item ) );
}
if( toAppendFieldsMap != null )
{
for( Entry<String, Object> e : toAppendFieldsMap.map.entrySet() )
{
fields.map.put( e.getKey(), e.getValue() );
// TODO sets the item's field also
}
}
int res = update( table, "id="+item.getId(), fields.map );
if( res < 0 )
return null;
return item;
}
catch( IllegalAccessException e )
{
return null;
}
}
public int update( String table, String condition, HashMap<String, ?> data )
{
if( data == null || data.size() == 0 )
return 0;
StringBuilder updateSb = new StringBuilder();
boolean fFirst = true;
for( Entry<String, ?> entry : data.entrySet() )
{
if( fFirst )
fFirst = false;
else
updateSb.append( ", " );
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
updateSb.append( "`" + fieldName + "`=" );
if( fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equalsIgnoreCase( "null" )) )
updateSb.append( "NULL" );
else
updateSb.append( "'" + fieldValue.toString() + "'" );
}
String sql = "UPDATE " + table + " SET " + updateSb.toString() + " WHERE " + condition;
return db.sqlUpdate( sql );
}
}
| Database : poor man's way of quoting sql parameters
| hexa.core/src/main/java/fr/lteconsulting/hexa/server/qpath/DatabaseHelper.java | Database : poor man's way of quoting sql parameters |
|
Java | mit | 7cbc8cb75f183c9228d18e737f5e6951f93dfaa1 | 0 | Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial | package br.com.redesocial.modelo.dao;
import br.com.redesocial.modelo.dto.PostagemPalavraChave;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lara
*/
public class PostagemPalavraChaveDAO extends DAOBase {
/**
* Método responsável por selecionar uma postagem a partir de suas palavras chaves
* @author Lara Caroline
* @param palavraChave e postagem, da postagem a ser selecionada
* @return a postagem selecionada a partir da palavra chave
* @throws Exception possíveis exceções que podem acontecer
*/
public PostagemPalavraChave selecionar(int palavraChave, int postagem) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from postagens_palavras_chave where palavra_chave = ? and postagem = ?");
pstmt.setInt(1, palavraChave);
pstmt.setInt(2, postagem);
ResultSet rs;
rs = pstmt.executeQuery();
if(rs.next()){
PostagemPalavraChave ppc = new PostagemPalavraChave();
PostagemDAO postagemDAO = new PostagemDAO();
PalavraChaveDAO palavraChaveDAO = new PalavraChaveDAO();
/*ppc.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
ppc.setPalavraChave(palavraChaveDAO.selecionar(rs.getInt("palavra_chave")));*/
return ppc;
}else{
return null;
}
}
public void inserir(PostagemPalavraChave dto) throws Exception {
}
/**
* Método responsável por alterar uma postagem a partir de suas palavras chaves
* @author José Gilvan
* @param palavraChave da postagem a ser alterada
* @return a postagem alterada a partir da palavra chave
* @throws Exception possíveis exceções que podem acontecer
*/
public void alterar(PostagemPalavraChave dto) throws Exception {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("update postagens set postagem = ?, palavra_chave = ? where id = ? ");
/*pstmt.setInt(1, dto.getPostagem());
pstmt.setInt(2, dto.getPalavraChave());*/
pstmt.executeUpdate();
}
public List listar() throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("Select * from postagens order by data desc");
ResultSet rs;
rs = pstmt.executeQuery();
PostagemDAO postagemDAO = new PostagemDAO();
PalavraChaveDAO palavrachaveDAO = new PalavraChaveDAO();
List lista;
lista = new ArrayList();
while(rs.next()){
PostagemPalavraChave ppc = new PostagemPalavraChave();
/*ppc.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
ppc.setPalavraChave(palavrachaveDAO.selecionar(rs.getInt("palavra_chave")));*/
}
return lista;
}
public void excluir(int palavraChave, int postagem) throws Exception {
}
}
| codigo/RedeSocial/src/br/com/redesocial/modelo/dao/PostagemPalavraChaveDAO.java | package br.com.redesocial.modelo.dao;
import br.com.redesocial.modelo.dto.PostagemPalavraChave;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lara
*/
public class PostagemPalavraChaveDAO extends DAOBase {
/**
* Método responsável por selecionar uma postagem a partir de suas palavras chaves
* @author Lara Caroline
* @param palavraChave da postagem a ser selecionada
* @return a postagem selecionada a partir da palavra chave
* @throws Exception possíveis exceções que podem acontecer
*/
public PostagemPalavraChave selecionar(int palavraChave, int postagem) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from postagens_palavras_chave where palavra_chave = ?");
pstmt.setInt(1, palavraChave);
ResultSet rs;
rs = pstmt.executeQuery();
if(rs.next()){
PostagemPalavraChave ppc = new PostagemPalavraChave();
PostagemDAO postagemDAO = new PostagemDAO();
PalavraChaveDAO palavraChaveDAO = new PalavraChaveDAO();
/*ppc.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
ppc.setPalavraChave(palavraChaveDAO.selecionar(rs.getInt("palavra_chave")));*/
return ppc;
}else{
return null;
}
}
public void inserir(PostagemPalavraChave dto) throws Exception {
}
/**
* Método responsável por alterar uma postagem a partir de suas palavras chaves
* @author José Gilvan
* @param palavraChave da postagem a ser alterada
* @return a postagem alterada a partir da palavra chave
* @throws Exception possíveis exceções que podem acontecer
*/
public void alterar(PostagemPalavraChave dto) throws Exception {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("update postagens set postagem = ?, palavra_chave = ? where id = ? ");
/*pstmt.setInt(1, dto.getPostagem());
pstmt.setInt(2, dto.getPalavraChave());*/
pstmt.executeUpdate();
}
public List listar() throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("Select * from postagens order by data desc");
ResultSet rs;
rs = pstmt.executeQuery();
PostagemDAO postagemDAO = new PostagemDAO();
PalavraChaveDAO palavrachaveDAO = new PalavraChaveDAO();
List lista;
lista = new ArrayList();
while(rs.next()){
PostagemPalavraChave ppc = new PostagemPalavraChave();
/*ppc.setPostagem(postagemDAO.selecionar(rs.getInt("postagem")));
ppc.setPalavraChave(palavrachaveDAO.selecionar(rs.getInt("palavra_chave")));*/
}
return lista;
}
public void excluir(int palavraChave, int postagem) throws Exception {
}
}
| correção selecionar PostagemPalavraChaveDAO
| codigo/RedeSocial/src/br/com/redesocial/modelo/dao/PostagemPalavraChaveDAO.java | correção selecionar PostagemPalavraChaveDAO |
|
Java | agpl-3.0 | d49b7ee32ed7dc4ae2c20a83d04f2ca448f90cdd | 0 | OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment | package org.openlmis.fulfillment.service;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.hasProperty;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_PERMISSION_MISSING;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_TRANSFER;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_EDIT;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_VIEW;
import static org.openlmis.fulfillment.service.PermissionService.PODS_MANAGE;
import static org.openlmis.fulfillment.service.PermissionService.SYSTEM_SETTINGS_MANAGE;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.openlmis.fulfillment.domain.Order;
import org.openlmis.fulfillment.domain.ProofOfDelivery;
import org.openlmis.fulfillment.service.referencedata.RightDto;
import org.openlmis.fulfillment.service.referencedata.UserDto;
import org.openlmis.fulfillment.service.referencedata.UserReferenceDataService;
import org.openlmis.fulfillment.util.AuthenticationHelper;
import org.openlmis.fulfillment.web.MissingPermissionException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import java.util.UUID;
@SuppressWarnings("PMD.TooManyMethods")
@RunWith(MockitoJUnitRunner.class)
public class PermissionServiceTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Mock
private UserReferenceDataService userReferenceDataService;
@Mock
private AuthenticationHelper authenticationHelper;
@InjectMocks
private PermissionService permissionService;
@Mock
private UserDto user;
@Mock
private RightDto fulfillmentOrdersEditRight;
@Mock
private RightDto fulfillmentTransferOrderRight;
@Mock
private RightDto fulfillmentManagePodRight;
@Mock
private RightDto fulfillmentOrdersViewRight;
@Mock
private RightDto systemSettingsManageRight;
private UUID userId = UUID.randomUUID();
private UUID fulfillmentTransferOrderRightId = UUID.randomUUID();
private UUID fulfillmentManagePodRightId = UUID.randomUUID();
private UUID fulfillmentOrdersViewRightId = UUID.randomUUID();
private UUID fulfillmentOrdersEditRightId = UUID.randomUUID();
private UUID systemSettingsManageRightId = UUID.randomUUID();
private UUID programId = UUID.randomUUID();
private UUID facilityId = UUID.randomUUID();
private Order order = new Order();
private ProofOfDelivery proofOfDelivery;
private SecurityContext securityContext;
private OAuth2Authentication userClient;
private OAuth2Authentication trustedClient;
@Before
public void setUp() {
securityContext = mock(SecurityContext.class);
SecurityContextHolder.setContext(securityContext);
userClient = new OAuth2Authentication(mock(OAuth2Request.class), mock(Authentication.class));
trustedClient = new OAuth2Authentication(mock(OAuth2Request.class), null);
order.setCreatedById(userId);
order.setProgramId(programId);
order.setSupplyingFacilityId(facilityId);
order.setOrderLineItems(Lists.newArrayList());
proofOfDelivery = new ProofOfDelivery(order);
when(user.getId()).thenReturn(userId);
when(fulfillmentTransferOrderRight.getId()).thenReturn(fulfillmentTransferOrderRightId);
when(fulfillmentManagePodRight.getId()).thenReturn(fulfillmentManagePodRightId);
when(fulfillmentOrdersViewRight.getId()).thenReturn(fulfillmentOrdersViewRightId);
when(fulfillmentOrdersEditRight.getId()).thenReturn(fulfillmentOrdersEditRightId);
when(systemSettingsManageRight.getId()).thenReturn(systemSettingsManageRightId);
when(authenticationHelper.getCurrentUser()).thenReturn(user);
when(authenticationHelper.getRight(ORDERS_TRANSFER)).thenReturn(
fulfillmentTransferOrderRight);
when(authenticationHelper.getRight(PODS_MANAGE)).thenReturn(
fulfillmentManagePodRight);
when(authenticationHelper.getRight(ORDERS_VIEW)).thenReturn(
fulfillmentOrdersViewRight);
when(authenticationHelper.getRight(ORDERS_EDIT)).thenReturn(
fulfillmentOrdersEditRight);
when(authenticationHelper.getRight(SYSTEM_SETTINGS_MANAGE)).thenReturn(
systemSettingsManageRight);
}
@Test
public void canTransferOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId);
permissionService.canTransferOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId);
}
@Test
public void cannotTransferOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_TRANSFER);
permissionService.canTransferOrder(order);
}
@Test
public void canManageSystemSettingsByServiceToken() {
when(securityContext.getAuthentication()).thenReturn(trustedClient);
/*If endpoint does not allow for service level token authorization, method will throw Exception.
When using service level token PermissionService does not use AuthenticationHelper nor
UserReferenceDataService.*/
permissionService.canManageSystemSettings();
}
@Test
public void canManageSystemSettingsByUserToken() {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(systemSettingsManageRightId, true, null);
permissionService.canManageSystemSettings();
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null);
}
@Test
public void cannotManageSystemSettingsByUserToken() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(SYSTEM_SETTINGS_MANAGE);
permissionService.canManageSystemSettings();
}
@Test
public void canManagePod() throws Exception {
mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId);
when(securityContext.getAuthentication()).thenReturn(userClient);
permissionService.canManagePod(proofOfDelivery);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId);
}
@Test
public void cannotManagePod() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(PODS_MANAGE);
permissionService.canManagePod(proofOfDelivery);
}
@Test
public void canViewOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId);
permissionService.canViewOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId);
}
@Test
public void cannotViewOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_VIEW);
permissionService.canViewOrder(order);
}
@Test
public void canEditOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId);
permissionService.canEditOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId);
}
@Test
public void cannotEditOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_EDIT);
permissionService.canEditOrder(order);
}
private void mockFulfillmentHasRight(UUID rightId, boolean assign, UUID facility) {
ResultDto<Boolean> resultDto = new ResultDto<>(assign);
when(userReferenceDataService
.hasRight(userId, rightId, null, null, facility)
).thenReturn(resultDto);
}
private void expectException(String rightName) {
exception.expect(MissingPermissionException.class);
exception.expect(hasProperty("params", arrayContaining(rightName)));
exception.expectMessage(ERROR_PERMISSION_MISSING);
}
private void verifyFulfillmentRight(InOrder order, String rightName, UUID rightId,
UUID facility) {
order.verify(authenticationHelper).getCurrentUser();
order.verify(authenticationHelper).getRight(rightName);
order.verify(userReferenceDataService).hasRight(userId, rightId, null, null, facility);
}
}
| src/test/java/org/openlmis/fulfillment/service/PermissionServiceTest.java | package org.openlmis.fulfillment.service;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.hasProperty;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_PERMISSION_MISSING;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_TRANSFER;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_EDIT;
import static org.openlmis.fulfillment.service.PermissionService.ORDERS_VIEW;
import static org.openlmis.fulfillment.service.PermissionService.PODS_MANAGE;
import static org.openlmis.fulfillment.service.PermissionService.SYSTEM_SETTINGS_MANAGE;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.openlmis.fulfillment.domain.Order;
import org.openlmis.fulfillment.domain.ProofOfDelivery;
import org.openlmis.fulfillment.service.referencedata.RightDto;
import org.openlmis.fulfillment.service.referencedata.UserDto;
import org.openlmis.fulfillment.service.referencedata.UserReferenceDataService;
import org.openlmis.fulfillment.util.AuthenticationHelper;
import org.openlmis.fulfillment.web.MissingPermissionException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import java.util.UUID;
@SuppressWarnings("PMD.TooManyMethods")
@RunWith(MockitoJUnitRunner.class)
public class PermissionServiceTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Mock
private UserReferenceDataService userReferenceDataService;
@Mock
private AuthenticationHelper authenticationHelper;
@InjectMocks
private PermissionService permissionService;
@Mock
private UserDto user;
@Mock
private RightDto fulfillmentOrdersEditRight;
@Mock
private RightDto fulfillmentTransferOrderRight;
@Mock
private RightDto fulfillmentManagePodRight;
@Mock
private RightDto fulfillmentOrdersViewRight;
@Mock
private RightDto systemSettingsManageRight;
private UUID userId = UUID.randomUUID();
private UUID fulfillmentTransferOrderRightId = UUID.randomUUID();
private UUID fulfillmentManagePodRightId = UUID.randomUUID();
private UUID fulfillmentOrdersViewRightId = UUID.randomUUID();
private UUID fulfillmentOrdersEditRightId = UUID.randomUUID();
private UUID systemSettingsManageRightId = UUID.randomUUID();
private UUID programId = UUID.randomUUID();
private UUID facilityId = UUID.randomUUID();
private Order order = new Order();
private ProofOfDelivery proofOfDelivery;
private SecurityContext securityContext;
private OAuth2Authentication userClient;
private OAuth2Authentication trustedClient;
@Before
public void setUp() {
securityContext = mock(SecurityContext.class);
SecurityContextHolder.setContext(securityContext);
userClient = new OAuth2Authentication(mock(OAuth2Request.class), mock(Authentication.class));
trustedClient = new OAuth2Authentication(mock(OAuth2Request.class), null);
order.setCreatedById(userId);
order.setProgramId(programId);
order.setSupplyingFacilityId(facilityId);
order.setOrderLineItems(Lists.newArrayList());
proofOfDelivery = new ProofOfDelivery(order);
when(user.getId()).thenReturn(userId);
when(fulfillmentTransferOrderRight.getId()).thenReturn(fulfillmentTransferOrderRightId);
when(fulfillmentManagePodRight.getId()).thenReturn(fulfillmentManagePodRightId);
when(fulfillmentOrdersViewRight.getId()).thenReturn(fulfillmentOrdersViewRightId);
when(fulfillmentOrdersEditRight.getId()).thenReturn(fulfillmentOrdersEditRightId);
when(systemSettingsManageRight.getId()).thenReturn(systemSettingsManageRightId);
when(authenticationHelper.getCurrentUser()).thenReturn(user);
when(authenticationHelper.getRight(ORDERS_TRANSFER)).thenReturn(
fulfillmentTransferOrderRight);
when(authenticationHelper.getRight(PODS_MANAGE)).thenReturn(
fulfillmentManagePodRight);
when(authenticationHelper.getRight(ORDERS_VIEW)).thenReturn(
fulfillmentOrdersViewRight);
when(authenticationHelper.getRight(ORDERS_EDIT)).thenReturn(
fulfillmentOrdersEditRight);
when(authenticationHelper.getRight(SYSTEM_SETTINGS_MANAGE)).thenReturn(
systemSettingsManageRight);
}
@Test
public void canTransferOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId);
permissionService.canTransferOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId);
}
@Test
public void cannotTransferOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_TRANSFER);
permissionService.canTransferOrder(order);
}
@Test
public void canManageSystemSettingsByServiceToken() {
when(securityContext.getAuthentication()).thenReturn(trustedClient);
permissionService.canManageSystemSettings();
}
@Test
public void canManageSystemSettingsByUserToken() {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(systemSettingsManageRightId, true, null);
permissionService.canManageSystemSettings();
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null);
}
@Test
public void cannotManageSystemSettingsByUserToken() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(SYSTEM_SETTINGS_MANAGE);
permissionService.canManageSystemSettings();
}
@Test
public void canManagePod() throws Exception {
mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId);
when(securityContext.getAuthentication()).thenReturn(userClient);
permissionService.canManagePod(proofOfDelivery);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId);
}
@Test
public void cannotManagePod() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(PODS_MANAGE);
permissionService.canManagePod(proofOfDelivery);
}
@Test
public void canViewOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId);
permissionService.canViewOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId);
}
@Test
public void cannotViewOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_VIEW);
permissionService.canViewOrder(order);
}
@Test
public void canEditOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId);
permissionService.canEditOrder(order);
InOrder order = inOrder(authenticationHelper, userReferenceDataService);
verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId);
}
@Test
public void cannotEditOrder() throws Exception {
when(securityContext.getAuthentication()).thenReturn(userClient);
expectException(ORDERS_EDIT);
permissionService.canEditOrder(order);
}
private void mockFulfillmentHasRight(UUID rightId, boolean assign, UUID facility) {
ResultDto<Boolean> resultDto = new ResultDto<>(assign);
when(userReferenceDataService
.hasRight(userId, rightId, null, null, facility)
).thenReturn(resultDto);
}
private void expectException(String rightName) {
exception.expect(MissingPermissionException.class);
exception.expect(hasProperty("params", arrayContaining(rightName)));
exception.expectMessage(ERROR_PERMISSION_MISSING);
}
private void verifyFulfillmentRight(InOrder order, String rightName, UUID rightId,
UUID facility) {
order.verify(authenticationHelper).getCurrentUser();
order.verify(authenticationHelper).getRight(rightName);
order.verify(userReferenceDataService).hasRight(userId, rightId, null, null, facility);
}
}
| OLMIS-1662 Added comment in unit test about using service level tokens.
| src/test/java/org/openlmis/fulfillment/service/PermissionServiceTest.java | OLMIS-1662 Added comment in unit test about using service level tokens. |
|
Java | agpl-3.0 | 38253d81c6af1c8217aad405b30dd25f41e64435 | 0 | kaltura/playkit-android,kaltura/playkit-android,kaltura/playkit-android,kaltura/playkit-android | /*
* ============================================================================
* Copyright (C) 2018 Kaltura Inc.
*
* Licensed under the AGPLv3 license, unless a different license for a
* particular library is specified in the applicable library path.
*
* You may obtain a copy of the License at
* https://www.gnu.org/licenses/agpl-3.0.html
* ============================================================================
*/
package com.kaltura.playkit.player;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.kaltura.android.exoplayer2.text.CaptionStyleCompat;
public class SubtitleStyleSettings {
public enum SubtitleStyleEdgeType {
EDGE_TYPE_NONE, EDGE_TYPE_OUTLINE, EDGE_TYPE_DROP_SHADOW, EDGE_TYPE_RAISED, EDGE_TYPE_DEPRESSED
}
public enum SubtitleTextSizeFraction {
SUBTITLE_FRACTION_50, SUBTITLE_FRACTION_75, SUBTITLE_FRACTION_100, SUBTITLE_FRACTION_125, SUBTITLE_FRACTION_150, SUBTITLE_FRACTION_200
}
public enum SubtitleStyleTypeface {
DEFAULT, DEFAULT_BOLD, MONOSPACE, SERIF, SANS_SERIF
}
public enum SubtitleTypefaceStyle {
NORMAL, BOLD, ITALIC, BOLD_ITALIC
}
private static final float fraction50 = 0.50f;
private static final float fraction75 = 0.75f;
private static final float fraction100 = 1.0f;
private static final float fraction125 = 1.25f;
private static final float fraction150 = 1.50f;
private static final float fraction200 = 2.0f;
private int subtitleTextColor = Color.WHITE;
private int subtitleBackgroundColor = Color.BLACK;
// Recommended fraction values is 1f < subtitleTextSizeFraction < 2.5f with 0.25f Multiplier
// Subtitle TextSize fraction, Default is 1.0f ; {@link com.kaltura.android.exoplayer2.ui.SubtitleView}
private float subtitleTextSizeFraction = fraction100;
private int subtitleWindowColor = Color.TRANSPARENT;
private int subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_NONE;
private int subtitleEdgeColor = Color.WHITE;
private Typeface subtitleTypeface = Typeface.DEFAULT;
private String subtitleStyleName;
private PKSubtitlePosition subtitlePosition;
public SubtitleStyleSettings(String subtitleStyleName) {
if (!TextUtils.isEmpty(subtitleStyleName)) {
this.subtitleStyleName = subtitleStyleName;
} else {
this.subtitleStyleName = "Unknown"; // Application does not provide any subtitle name or it is set to null
}
}
public int getTextColor() {
return subtitleTextColor;
}
public int getBackgroundColor() {
return subtitleBackgroundColor;
}
public float getTextSizeFraction() {
return subtitleTextSizeFraction;
}
public int getWindowColor() {
return subtitleWindowColor;
}
public int getEdgeType() {
return subtitleEdgeType;
}
public int getEdgeColor() {
return subtitleEdgeColor;
}
public Typeface getTypeface() {
return subtitleTypeface;
}
public String getStyleName() {
return subtitleStyleName;
}
public PKSubtitlePosition getSubtitlePosition() {
return subtitlePosition;
}
public SubtitleStyleSettings setTextColor(int subtitleTextColor) {
this.subtitleTextColor = subtitleTextColor;
return this;
}
public SubtitleStyleSettings setBackgroundColor(int subtitleBackgroundColor) {
this.subtitleBackgroundColor = subtitleBackgroundColor;
return this;
}
public SubtitleStyleSettings setEdgeColor(int subtitleEdgeColor) {
this.subtitleEdgeColor = subtitleEdgeColor;
return this;
}
public SubtitleStyleSettings setWindowColor(int subtitleWindowColor) {
this.subtitleWindowColor = subtitleWindowColor;
return this;
}
public SubtitleStyleSettings setEdgeType(@NonNull SubtitleStyleEdgeType subtitleEdgeType) {
switch (subtitleEdgeType) {
case EDGE_TYPE_OUTLINE:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE;
break;
case EDGE_TYPE_DROP_SHADOW:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW;
break;
case EDGE_TYPE_RAISED:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_RAISED;
break;
case EDGE_TYPE_DEPRESSED:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_DEPRESSED;
break;
default:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_NONE;
break;
}
return this;
}
public SubtitleStyleSettings setTextSizeFraction(@NonNull SubtitleTextSizeFraction subtitleTextSizeFraction) {
switch (subtitleTextSizeFraction) {
case SUBTITLE_FRACTION_50:
this.subtitleTextSizeFraction = fraction50;
break;
case SUBTITLE_FRACTION_75:
this.subtitleTextSizeFraction = fraction75;
break;
case SUBTITLE_FRACTION_125:
this.subtitleTextSizeFraction = fraction125;
break;
case SUBTITLE_FRACTION_150:
this.subtitleTextSizeFraction = fraction150;
break;
case SUBTITLE_FRACTION_200:
this.subtitleTextSizeFraction = fraction200;
break;
default:
this.subtitleTextSizeFraction = fraction100;
break;
}
return this;
}
public SubtitleStyleSettings setTypeface(@NonNull SubtitleStyleTypeface subtitleStyleTypeface) {
switch (subtitleStyleTypeface) {
case DEFAULT_BOLD:
subtitleTypeface = Typeface.DEFAULT_BOLD;
break;
case MONOSPACE:
subtitleTypeface = Typeface.MONOSPACE;
break;
case SERIF:
subtitleTypeface = Typeface.SERIF;
break;
case SANS_SERIF:
subtitleTypeface = Typeface.SANS_SERIF;
break;
case DEFAULT:
default:
subtitleTypeface = Typeface.DEFAULT;
break;
}
return this;
}
public SubtitleStyleSettings setSystemTypeface(String fontFamilyName, SubtitleTypefaceStyle style) {
if (fontFamilyName == null || style == null) {
subtitleTypeface = Typeface.DEFAULT;
} else {
subtitleTypeface = Typeface.create(fontFamilyName, style.ordinal());
}
return this;
}
public SubtitleStyleSettings setAssetTypeface(Typeface asstTypeface) {
if (asstTypeface == null) {
subtitleTypeface = Typeface.DEFAULT;
} else {
subtitleTypeface = asstTypeface;
}
return this;
}
public SubtitleStyleSettings setSubtitlePosition(PKSubtitlePosition subtitlePosition) {
this.subtitlePosition = subtitlePosition;
return this;
}
public CaptionStyleCompat toCaptionStyle() {
return new CaptionStyleCompat(getTextColor(),
getBackgroundColor(),
getWindowColor(),
getEdgeType(),
getEdgeColor(),
getTypeface());
}
}
| playkit/src/main/java/com/kaltura/playkit/player/SubtitleStyleSettings.java | /*
* ============================================================================
* Copyright (C) 2018 Kaltura Inc.
*
* Licensed under the AGPLv3 license, unless a different license for a
* particular library is specified in the applicable library path.
*
* You may obtain a copy of the License at
* https://www.gnu.org/licenses/agpl-3.0.html
* ============================================================================
*/
package com.kaltura.playkit.player;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.kaltura.android.exoplayer2.text.CaptionStyleCompat;
public class SubtitleStyleSettings {
public enum SubtitleStyleEdgeType {
EDGE_TYPE_NONE, EDGE_TYPE_OUTLINE, EDGE_TYPE_DROP_SHADOW, EDGE_TYPE_RAISED, EDGE_TYPE_DEPRESSED
}
public enum SubtitleTextSizeFraction {
SUBTITLE_FRACTION_50, SUBTITLE_FRACTION_75, SUBTITLE_FRACTION_100, SUBTITLE_FRACTION_125, SUBTITLE_FRACTION_150, SUBTITLE_FRACTION_200
}
public enum SubtitleStyleTypeface {
DEFAULT, DEFAULT_BOLD, MONOSPACE, SERIF, SANS_SERIF
}
private static final float fraction50 = 0.50f;
private static final float fraction75 = 0.75f;
private static final float fraction100 = 1.0f;
private static final float fraction125 = 1.25f;
private static final float fraction150 = 1.50f;
private static final float fraction200 = 2.0f;
private int subtitleTextColor = Color.WHITE;
private int subtitleBackgroundColor = Color.BLACK;
// Recommended fraction values is 1f < subtitleTextSizeFraction < 2.5f with 0.25f Multiplier
// Subtitle TextSize fraction, Default is 1.0f ; {@link com.kaltura.android.exoplayer2.ui.SubtitleView}
private float subtitleTextSizeFraction = fraction100;
private int subtitleWindowColor = Color.TRANSPARENT;
private int subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_NONE;
private int subtitleEdgeColor = Color.WHITE;
private Typeface subtitleTypeface = Typeface.DEFAULT;
private String subtitleStyleName;
private PKSubtitlePosition subtitlePosition;
public SubtitleStyleSettings(String subtitleStyleName) {
if (!TextUtils.isEmpty(subtitleStyleName)) {
this.subtitleStyleName = subtitleStyleName;
} else {
this.subtitleStyleName = "Unknown"; // Application does not provide any subtitle name or it is set to null
}
}
public int getTextColor() {
return subtitleTextColor;
}
public int getBackgroundColor() {
return subtitleBackgroundColor;
}
public float getTextSizeFraction() {
return subtitleTextSizeFraction;
}
public int getWindowColor() {
return subtitleWindowColor;
}
public int getEdgeType() {
return subtitleEdgeType;
}
public int getEdgeColor() {
return subtitleEdgeColor;
}
public Typeface getTypeface() {
return subtitleTypeface;
}
public String getStyleName() {
return subtitleStyleName;
}
public PKSubtitlePosition getSubtitlePosition() {
return subtitlePosition;
}
public SubtitleStyleSettings setTextColor(int subtitleTextColor) {
this.subtitleTextColor = subtitleTextColor;
return this;
}
public SubtitleStyleSettings setBackgroundColor(int subtitleBackgroundColor) {
this.subtitleBackgroundColor = subtitleBackgroundColor;
return this;
}
public SubtitleStyleSettings setEdgeColor(int subtitleEdgeColor) {
this.subtitleEdgeColor = subtitleEdgeColor;
return this;
}
public SubtitleStyleSettings setWindowColor(int subtitleWindowColor) {
this.subtitleWindowColor = subtitleWindowColor;
return this;
}
public SubtitleStyleSettings setEdgeType(@NonNull SubtitleStyleEdgeType subtitleEdgeType) {
switch (subtitleEdgeType) {
case EDGE_TYPE_OUTLINE:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE;
break;
case EDGE_TYPE_DROP_SHADOW:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW;
break;
case EDGE_TYPE_RAISED:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_RAISED;
break;
case EDGE_TYPE_DEPRESSED:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_DEPRESSED;
break;
default:
this.subtitleEdgeType = CaptionStyleCompat.EDGE_TYPE_NONE;
break;
}
return this;
}
public SubtitleStyleSettings setTextSizeFraction(@NonNull SubtitleTextSizeFraction subtitleTextSizeFraction) {
switch (subtitleTextSizeFraction) {
case SUBTITLE_FRACTION_50:
this.subtitleTextSizeFraction = fraction50;
break;
case SUBTITLE_FRACTION_75:
this.subtitleTextSizeFraction = fraction75;
break;
case SUBTITLE_FRACTION_125:
this.subtitleTextSizeFraction = fraction125;
break;
case SUBTITLE_FRACTION_150:
this.subtitleTextSizeFraction = fraction150;
break;
case SUBTITLE_FRACTION_200:
this.subtitleTextSizeFraction = fraction200;
break;
default:
this.subtitleTextSizeFraction = fraction100;
break;
}
return this;
}
public SubtitleStyleSettings setTypeface(@NonNull SubtitleStyleTypeface subtitleStyleTypeface) {
switch (subtitleStyleTypeface) {
case DEFAULT_BOLD:
subtitleTypeface = Typeface.DEFAULT_BOLD;
break;
case MONOSPACE:
subtitleTypeface = Typeface.MONOSPACE;
break;
case SERIF:
subtitleTypeface = Typeface.SERIF;
break;
case SANS_SERIF:
subtitleTypeface = Typeface.SANS_SERIF;
break;
case DEFAULT:
default:
subtitleTypeface = Typeface.DEFAULT;
break;
}
return this;
}
public SubtitleStyleSettings setSubtitlePosition(PKSubtitlePosition subtitlePosition) {
this.subtitlePosition = subtitlePosition;
return this;
}
public CaptionStyleCompat toCaptionStyle() {
return new CaptionStyleCompat(getTextColor(),
getBackgroundColor(),
getWindowColor(),
getEdgeType(),
getEdgeColor(),
getTypeface());
}
}
| FEC-11064 Expose generic subtitles font update api (#690)
* Expose generic subtitles font update api
public SubtitleStyleSettings setSystemTypeface(String fontFamilyName, SubtitleTypefaceStyle style ) {
if (fontFamilyName == null) {
subtitleTypeface = Typeface.DEFAULT;
} else {
subtitleTypeface = Typeface.create(fontFamilyName, style.ordinal());
}
return this;
}
public SubtitleStyleSettings setAssetTypeface(Typeface asstTypeface) {
if (asstTypeface == null) {
subtitleTypeface = Typeface.DEFAULT;
} else {
subtitleTypeface = asstTypeface;
}
return this;
}
| playkit/src/main/java/com/kaltura/playkit/player/SubtitleStyleSettings.java | FEC-11064 Expose generic subtitles font update api (#690) |
|
Java | lgpl-2.1 | e11866735c6177f41f1203bb502b0fd0139b01c3 | 0 | allati/eclipse-rbe | /*
* Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
*
* This file is part of Essiembre ResourceBundle Editor.
*
* Essiembre ResourceBundle Editor 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.
*
* Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package com.essiembre.eclipse.rbe.ui.editor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
import com.essiembre.eclipse.rbe.ui.editor.i18n.I18nPageEditor;
/**
* Manages the installation/deinstallation of global actions for multi-page
* editors. Responsible for the redirection of global actions to the active
* editor.
* Multi-page contributor replaces the contributors for the individual editors
* in the multi-page editor.
*/
public class ResourceBundleEditorContributor extends MultiPageEditorActionBarContributor {
private IEditorPart activeEditorPart;
/**
* Creates a multi-page contributor.
*/
public ResourceBundleEditorContributor() {
super();
createActions();
}
/**
* Returns the action registed with the given text editor.
* @param editor eclipse text editor
* @param actionID action id
* @return IAction or null if editor is null.
*/
protected IAction getAction(ITextEditor editor, String actionID) {
return (editor == null ? null : editor.getAction(actionID));
}
@Override
public void dispose() {
activeEditorPart = null;
}
/**
* @see MultiPageEditorActionBarContributor
* #setActivePage(org.eclipse.ui.IEditorPart)
*/
public void setActivePage(IEditorPart part) {
if (activeEditorPart == part)
return;
activeEditorPart = part;
IActionBars actionBars = getActionBars();
if (actionBars != null) {
ITextEditor editor = (part instanceof ITextEditor)
? (ITextEditor) part : null;
if(editor instanceof I18nPageEditor) {
actionBars.clearGlobalActionHandlers();
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
((I18nPageEditor)editor).getFindReplaceAction());
actionBars.setGlobalActionHandler(
IWorkbenchActionDefinitionIds.FIND_NEXT,
((I18nPageEditor)editor).getFindNextAction());
actionBars.setGlobalActionHandler(
IWorkbenchActionDefinitionIds.FIND_PREVIOUS,
((I18nPageEditor)editor).getFindPreviousAction());
actionBars.updateActionBars();
return;
}
actionBars.setGlobalActionHandler(
ActionFactory.DELETE.getId(),
getAction(editor, ITextEditorActionConstants.DELETE));
actionBars.setGlobalActionHandler(
ActionFactory.UNDO.getId(),
getAction(editor, ITextEditorActionConstants.UNDO));
actionBars.setGlobalActionHandler(
ActionFactory.REDO.getId(),
getAction(editor, ITextEditorActionConstants.REDO));
actionBars.setGlobalActionHandler(
ActionFactory.CUT.getId(),
getAction(editor, ITextEditorActionConstants.CUT));
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
getAction(editor, ITextEditorActionConstants.COPY));
actionBars.setGlobalActionHandler(
ActionFactory.PASTE.getId(),
getAction(editor, ITextEditorActionConstants.PASTE));
actionBars.setGlobalActionHandler(
ActionFactory.SELECT_ALL.getId(),
getAction(editor, ITextEditorActionConstants.SELECT_ALL));
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
getAction(editor, ITextEditorActionConstants.FIND));
actionBars.setGlobalActionHandler(
IDEActionFactory.BOOKMARK.getId(),
getAction(editor, IDEActionFactory.BOOKMARK.getId()));
actionBars.updateActionBars();
}
}
private void createActions() {
// sampleAction = new Action() {
// public void run() {
// MessageDialog.openInformation(null,
// "ResourceBundle Editor Plug-in", "Sample Action Executed");
// }
// };
// sampleAction.setText("Sample Action");
// sampleAction.setToolTipText("Sample Action tool tip");
// sampleAction.setImageDescriptor(
// PlatformUI.getWorkbench().getSharedImages().
// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
}
/**
* @see org.eclipse.ui.part.EditorActionBarContributor
* #contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
public void contributeToMenu(IMenuManager manager) {
// IMenuManager menu = new MenuManager("Editor &Menu");
// manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu);
// menu.add(sampleAction);
}
/**
* @see org.eclipse.ui.part.EditorActionBarContributor
* #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
*/
public void contributeToToolBar(IToolBarManager manager) {
// manager.add(new Separator());
// manager.add(sampleAction);
}
}
| src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditorContributor.java | /*
* Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
*
* This file is part of Essiembre ResourceBundle Editor.
*
* Essiembre ResourceBundle Editor 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.
*
* Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package com.essiembre.eclipse.rbe.ui.editor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
import com.essiembre.eclipse.rbe.ui.editor.i18n.I18nPageEditor;
/**
* Manages the installation/deinstallation of global actions for multi-page
* editors. Responsible for the redirection of global actions to the active
* editor.
* Multi-page contributor replaces the contributors for the individual editors
* in the multi-page editor.
*/
public class ResourceBundleEditorContributor extends MultiPageEditorActionBarContributor {
private IEditorPart activeEditorPart;
/**
* Creates a multi-page contributor.
*/
public ResourceBundleEditorContributor() {
super();
createActions();
}
/**
* Returns the action registed with the given text editor.
* @param editor eclipse text editor
* @param actionID action id
* @return IAction or null if editor is null.
*/
protected IAction getAction(ITextEditor editor, String actionID) {
return (editor == null ? null : editor.getAction(actionID));
}
@Override
public void dispose() {
activeEditorPart = null;
}
/**
* @see MultiPageEditorActionBarContributor
* #setActivePage(org.eclipse.ui.IEditorPart)
*/
public void setActivePage(IEditorPart part) {
if (activeEditorPart == part)
return;
activeEditorPart = part;
IActionBars actionBars = getActionBars();
if (actionBars != null) {
ITextEditor editor = (part instanceof ITextEditor)
? (ITextEditor) part : null;
if(editor instanceof I18nPageEditor) {
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
((I18nPageEditor)editor).getFindReplaceAction());
actionBars.setGlobalActionHandler(
IWorkbenchActionDefinitionIds.FIND_NEXT,
((I18nPageEditor)editor).getFindNextAction());
actionBars.setGlobalActionHandler(
IWorkbenchActionDefinitionIds.FIND_PREVIOUS,
((I18nPageEditor)editor).getFindPreviousAction());
return;
}
actionBars.setGlobalActionHandler(
ActionFactory.DELETE.getId(),
getAction(editor, ITextEditorActionConstants.DELETE));
actionBars.setGlobalActionHandler(
ActionFactory.UNDO.getId(),
getAction(editor, ITextEditorActionConstants.UNDO));
actionBars.setGlobalActionHandler(
ActionFactory.REDO.getId(),
getAction(editor, ITextEditorActionConstants.REDO));
actionBars.setGlobalActionHandler(
ActionFactory.CUT.getId(),
getAction(editor, ITextEditorActionConstants.CUT));
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
getAction(editor, ITextEditorActionConstants.COPY));
actionBars.setGlobalActionHandler(
ActionFactory.PASTE.getId(),
getAction(editor, ITextEditorActionConstants.PASTE));
actionBars.setGlobalActionHandler(
ActionFactory.SELECT_ALL.getId(),
getAction(editor, ITextEditorActionConstants.SELECT_ALL));
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
getAction(editor, ITextEditorActionConstants.FIND));
actionBars.setGlobalActionHandler(
IDEActionFactory.BOOKMARK.getId(),
getAction(editor, IDEActionFactory.BOOKMARK.getId()));
actionBars.updateActionBars();
}
}
private void createActions() {
// sampleAction = new Action() {
// public void run() {
// MessageDialog.openInformation(null,
// "ResourceBundle Editor Plug-in", "Sample Action Executed");
// }
// };
// sampleAction.setText("Sample Action");
// sampleAction.setToolTipText("Sample Action tool tip");
// sampleAction.setImageDescriptor(
// PlatformUI.getWorkbench().getSharedImages().
// getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
}
/**
* @see org.eclipse.ui.part.EditorActionBarContributor
* #contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
public void contributeToMenu(IMenuManager manager) {
// IMenuManager menu = new MenuManager("Editor &Menu");
// manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu);
// menu.add(sampleAction);
}
/**
* @see org.eclipse.ui.part.EditorActionBarContributor
* #contributeToToolBar(org.eclipse.jface.action.IToolBarManager)
*/
public void contributeToToolBar(IToolBarManager manager) {
// manager.add(new Separator());
// manager.add(sampleAction);
}
}
| Regression bugfix: copy & paste actions didn't work in BundleEntryComposites, since they were overridden by editor actions
| src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditorContributor.java | Regression bugfix: copy & paste actions didn't work in BundleEntryComposites, since they were overridden by editor actions |
|
Java | unlicense | f51acb0ee7868cf721fa0ec48d0e4fedf1fb9a68 | 0 | eduardog3000/EnderIO,D-Inc/EnderIO,eduardog3000/EnderIO,mmelvin0/EnderIO,MrNuggelz/EnderIO,SleepyTrousers/EnderIO,Joccob/EnderIO,MatthiasMann/EnderIO,HenryLoenwind/EnderIO,Quantum64/EnderIO,torteropaid/EnderIO,Joccob/EnderIO,Samernieve/EnderIO,mezz/EnderIO | package crazypants.enderio.machine.spawner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.BlockMobSpawner;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.MobSpawnerBaseLogic;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.EnderIO;
import crazypants.enderio.GuiHandler;
import crazypants.enderio.Log;
import crazypants.enderio.ModObject;
import crazypants.enderio.config.Config;
import crazypants.enderio.gui.IAdvancedTooltipProvider;
import crazypants.enderio.gui.TooltipAddera;
import crazypants.enderio.machine.AbstractMachineBlock;
import crazypants.enderio.machine.MachineRecipeRegistry;
import crazypants.enderio.network.PacketHandler;
import crazypants.enderio.waila.IWailaInfoProvider;
import crazypants.util.Lang;
import crazypants.util.Util;
public class BlockPoweredSpawner extends AbstractMachineBlock<TilePoweredSpawner> implements IAdvancedTooltipProvider {
public static void writeMobTypeToNBT(NBTTagCompound nbt, String type) {
if(nbt == null) {
return;
}
if(type == null) {
nbt.removeTag("mobType");
} else {
nbt.setString("mobType", type);
}
}
public static String readMobTypeFromNBT(NBTTagCompound nbt) {
if(nbt == null) {
return null;
}
if(!nbt.hasKey("mobType")) {
return null;
}
return nbt.getString("mobType");
}
public static String getSpawnerTypeFromItemStack(ItemStack stack) {
if(stack == null || stack.getItem() != Item.getItemFromBlock(EnderIO.blockPoweredSpawner)) {
return null;
}
return readMobTypeFromNBT(stack.stackTagCompound);
}
public static final String KEY_SPAWNED_BY_POWERED_SPAWNER = "spawnedByPoweredSpawner";
public static BlockPoweredSpawner create() {
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPoweredSpawner.unlocalisedName, new DummyRecipe());
PacketHandler.INSTANCE.registerMessage(PacketMode.class, PacketMode.class, PacketHandler.nextID(), Side.SERVER);
//Ensure costs are loaded at startup
PoweredSpawnerConfig.getInstance();
BlockPoweredSpawner res = new BlockPoweredSpawner();
MinecraftForge.EVENT_BUS.register(res);
FMLCommonHandler.instance().bus().register(res);
res.init();
return res;
}
private final List<DropInfo> dropQueue = new ArrayList<BlockPoweredSpawner.DropInfo>();
private final List<UniqueIdentifier> toolBlackList = new ArrayList<UniqueIdentifier>();
private Field fieldpersistenceRequired;
protected BlockPoweredSpawner() {
super(ModObject.blockPoweredSpawner, TilePoweredSpawner.class);
String[] blackListNames = Config.brokenSpawnerToolBlacklist;
for (String name : blackListNames) {
toolBlackList.add(new UniqueIdentifier(name));
}
try {
fieldpersistenceRequired = ReflectionHelper.findField(EntityLiving.class, "field_82179_bU", "persistenceRequired");
} catch (Exception e) {
Log.error("BlockPoweredSpawner: Could not find field: persistenceRequired");
}
}
@SubscribeEvent
public void onBreakEvent(BlockEvent.BreakEvent evt) {
if(evt.block instanceof BlockMobSpawner) {
if(evt.getPlayer() != null && !evt.getPlayer().capabilities.isCreativeMode && !evt.getPlayer().worldObj.isRemote && !evt.isCanceled()) {
TileEntity tile = evt.getPlayer().worldObj.getTileEntity(evt.x, evt.y, evt.z);
if(tile instanceof TileEntityMobSpawner) {
if(Math.random() > Config.brokenSpawnerDropChance) {
return;
}
ItemStack equipped = evt.getPlayer().getCurrentEquippedItem();
if(equipped != null) {
for (UniqueIdentifier uid : toolBlackList) {
Item blackListItem = GameRegistry.findItem(uid.modId, uid.name);
if(blackListItem == equipped.getItem()) {
return;
}
}
}
TileEntityMobSpawner spawner = (TileEntityMobSpawner) tile;
MobSpawnerBaseLogic logic = spawner.func_145881_a();
if(logic != null) {
String name = logic.getEntityNameToSpawn();
if(name != null && !isBlackListed(name)) {
ItemStack drop = ItemBrokenSpawner.createStackForMobType(name);
dropQueue.add(new DropInfo(evt, drop));
for (int i = (int) (Math.random() * 7); i > 0; i--) {
logic.spawnDelay = 0;
logic.updateSpawner();
}
}
}
}
}
}
}
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent event) {
if(event.phase != TickEvent.Phase.END) {
return;
}
for (DropInfo action : dropQueue) {
action.doDrop();
}
dropQueue.clear();
}
@SubscribeEvent
public void handleAnvilEvent(AnvilUpdateEvent evt) {
if(evt.left == null || evt.left.stackSize != 1 || evt.left.getItem() != Item.getItemFromBlock(EnderIO.blockPoweredSpawner) ||
evt.right == null || ItemBrokenSpawner.getMobTypeFromStack(evt.right) == null) {
return;
}
String spawnerType = ItemBrokenSpawner.getMobTypeFromStack(evt.right);
if(isBlackListed(spawnerType)) {
return;
}
evt.cost = Config.powerSpawnerAddSpawnerCost;
evt.output = evt.left.copy();
if(evt.output.stackTagCompound == null) {
evt.output.stackTagCompound = new NBTTagCompound();
}
evt.output.stackTagCompound.setBoolean("eio.abstractMachine", true);
writeMobTypeToNBT(evt.output.stackTagCompound, spawnerType);
}
@SubscribeEvent
public void onLivingUpdate(LivingUpdateEvent livingUpdate) {
Entity ent = livingUpdate.entityLiving;
if(!ent.getEntityData().hasKey(KEY_SPAWNED_BY_POWERED_SPAWNER)) {
return;
}
if(fieldpersistenceRequired == null) {
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
return;
}
long spawnTime = ent.getEntityData().getLong(KEY_SPAWNED_BY_POWERED_SPAWNER);
long livedFor = livingUpdate.entity.worldObj.getTotalWorldTime() - spawnTime;
if(livedFor > Config.poweredSpawnerDespawnTimeSeconds*20) {
try {
fieldpersistenceRequired.setBoolean(livingUpdate.entityLiving, false);
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
} catch (Exception e) {
Log.warn("BlockPoweredSpawner.onLivingUpdate: Error occured allowing entity to despawn: " + e);
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
}
}
}
public boolean isBlackListed(String entityId) {
return PoweredSpawnerConfig.getInstance().isBlackListed(entityId);
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TilePoweredSpawner) {
return new ContainerPoweredSpawner(player.inventory, (TilePoweredSpawner) te);
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TilePoweredSpawner) {
return new GuiPoweredSpawner(player.inventory, (TilePoweredSpawner) te);
}
return null;
}
@Override
protected int getGuiId() {
return GuiHandler.GUI_ID_POWERED_SPAWNER;
}
@Override
protected String getMachineFrontIconKey(boolean active) {
if(active) {
return "enderio:poweredSpawnerFrontActive";
}
return "enderio:poweredSpawnerFront";
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
String type = getSpawnerTypeFromItemStack(itemstack);
if(type != null) {
list.add(StatCollector.translateToLocal("entity." + type + ".name"));
} else {
list.add(Lang.localize("tile.blockPoweredSpawner.tooltip.empty", false));
}
}
@Override
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
}
@Override
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
String type = getSpawnerTypeFromItemStack(itemstack);
if(type == null) {
TooltipAddera.addDetailedTooltipFromResources(list, "tile.blockPoweredSpawner.empty");
} else {
TooltipAddera.addDetailedTooltipFromResources(list, "tile.blockPoweredSpawner");
}
}
@Override
public void getWailaInfo(List<String> tooltip, EntityPlayer player, World world, int x, int y, int z) {
TilePoweredSpawner te = (TilePoweredSpawner) world.getTileEntity(x, y, z);
tooltip.add(te.getEntityName());
}
@Override
public int getDefaultDisplayMask(World world, int x, int y, int z) {
return IWailaInfoProvider.BIT_DETAILED;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
super.getSubBlocks(item, tab, list);
list.add(createItemStackForMob("Enderman"));
list.add(createItemStackForMob("Chicken"));
}
protected ItemStack createItemStackForMob(String mob) {
ItemStack stack = new ItemStack(this);
stack.stackTagCompound = new NBTTagCompound();
stack.stackTagCompound.setBoolean("eio.abstractMachine", true);
writeMobTypeToNBT(stack.stackTagCompound, mob);
return stack;
}
private static class DropInfo {
BlockEvent.BreakEvent evt;
ItemStack drop;
DropInfo(BreakEvent evt, ItemStack stack) {
super();
this.evt = evt;
drop = stack;
}
void doDrop() {
if(evt.isCanceled()) {
return;
}
Util.dropItems(evt.getPlayer().worldObj, drop, evt.x, evt.y, evt.z, true);
}
}
}
| src/main/java/crazypants/enderio/machine/spawner/BlockPoweredSpawner.java | package crazypants.enderio.machine.spawner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.BlockMobSpawner;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.MobSpawnerBaseLogic;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.EnderIO;
import crazypants.enderio.GuiHandler;
import crazypants.enderio.Log;
import crazypants.enderio.ModObject;
import crazypants.enderio.config.Config;
import crazypants.enderio.gui.IAdvancedTooltipProvider;
import crazypants.enderio.gui.TooltipAddera;
import crazypants.enderio.machine.AbstractMachineBlock;
import crazypants.enderio.machine.MachineRecipeRegistry;
import crazypants.enderio.network.PacketHandler;
import crazypants.enderio.waila.IWailaInfoProvider;
import crazypants.util.Lang;
import crazypants.util.Util;
public class BlockPoweredSpawner extends AbstractMachineBlock<TilePoweredSpawner> implements IAdvancedTooltipProvider {
public static void writeMobTypeToNBT(NBTTagCompound nbt, String type) {
if(nbt == null) {
return;
}
if(type == null) {
nbt.removeTag("mobType");
} else {
nbt.setString("mobType", type);
}
}
public static String readMobTypeFromNBT(NBTTagCompound nbt) {
if(nbt == null) {
return null;
}
if(!nbt.hasKey("mobType")) {
return null;
}
return nbt.getString("mobType");
}
public static String getSpawnerTypeFromItemStack(ItemStack stack) {
if(stack == null || stack.getItem() != Item.getItemFromBlock(EnderIO.blockPoweredSpawner)) {
return null;
}
return readMobTypeFromNBT(stack.stackTagCompound);
}
public static final String KEY_SPAWNED_BY_POWERED_SPAWNER = "spawnedByPoweredSpawner";
public static BlockPoweredSpawner create() {
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPoweredSpawner.unlocalisedName, new DummyRecipe());
PacketHandler.INSTANCE.registerMessage(PacketMode.class, PacketMode.class, PacketHandler.nextID(), Side.SERVER);
//Ensure costs are loaded at startup
PoweredSpawnerConfig.getInstance();
BlockPoweredSpawner res = new BlockPoweredSpawner();
MinecraftForge.EVENT_BUS.register(res);
FMLCommonHandler.instance().bus().register(res);
res.init();
return res;
}
private final List<DropInfo> dropQueue = new ArrayList<BlockPoweredSpawner.DropInfo>();
private final List<UniqueIdentifier> toolBlackList = new ArrayList<UniqueIdentifier>();
private Field fieldpersistenceRequired;
protected BlockPoweredSpawner() {
super(ModObject.blockPoweredSpawner, TilePoweredSpawner.class);
String[] blackListNames = Config.brokenSpawnerToolBlacklist;
for (String name : blackListNames) {
toolBlackList.add(new UniqueIdentifier(name));
}
try {
fieldpersistenceRequired = ReflectionHelper.findField(EntityLiving.class, "field_82179_bU", "persistenceRequired");
} catch (Exception e) {
Log.error("BlockPoweredSpawner: Could not find field: persistenceRequired");
}
}
@SubscribeEvent
public void onBreakEvent(BlockEvent.BreakEvent evt) {
if(evt.block instanceof BlockMobSpawner) {
if(evt.getPlayer() != null && !evt.getPlayer().capabilities.isCreativeMode && !evt.getPlayer().worldObj.isRemote && !evt.isCanceled()) {
TileEntity tile = evt.getPlayer().worldObj.getTileEntity(evt.x, evt.y, evt.z);
if(tile instanceof TileEntityMobSpawner) {
if(Math.random() > Config.brokenSpawnerDropChance) {
return;
}
ItemStack equipped = evt.getPlayer().getCurrentEquippedItem();
if(equipped != null) {
for (UniqueIdentifier uid : toolBlackList) {
Item blackListItem = GameRegistry.findItem(uid.modId, uid.name);
if(blackListItem == equipped.getItem()) {
return;
}
}
}
TileEntityMobSpawner spawner = (TileEntityMobSpawner) tile;
MobSpawnerBaseLogic logic = spawner.func_145881_a();
if(logic != null) {
String name = logic.getEntityNameToSpawn();
if(name != null && !isBlackListed(name)) {
ItemStack drop = ItemBrokenSpawner.createStackForMobType(name);
dropQueue.add(new DropInfo(evt, drop));
}
}
}
}
}
}
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent event) {
if(event.phase != TickEvent.Phase.END) {
return;
}
for (DropInfo action : dropQueue) {
action.doDrop();
}
dropQueue.clear();
}
@SubscribeEvent
public void handleAnvilEvent(AnvilUpdateEvent evt) {
if(evt.left == null || evt.left.stackSize != 1 || evt.left.getItem() != Item.getItemFromBlock(EnderIO.blockPoweredSpawner) ||
evt.right == null || ItemBrokenSpawner.getMobTypeFromStack(evt.right) == null) {
return;
}
String spawnerType = ItemBrokenSpawner.getMobTypeFromStack(evt.right);
if(isBlackListed(spawnerType)) {
return;
}
evt.cost = Config.powerSpawnerAddSpawnerCost;
evt.output = evt.left.copy();
if(evt.output.stackTagCompound == null) {
evt.output.stackTagCompound = new NBTTagCompound();
}
evt.output.stackTagCompound.setBoolean("eio.abstractMachine", true);
writeMobTypeToNBT(evt.output.stackTagCompound, spawnerType);
}
@SubscribeEvent
public void onLivingUpdate(LivingUpdateEvent livingUpdate) {
Entity ent = livingUpdate.entityLiving;
if(!ent.getEntityData().hasKey(KEY_SPAWNED_BY_POWERED_SPAWNER)) {
return;
}
if(fieldpersistenceRequired == null) {
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
return;
}
long spawnTime = ent.getEntityData().getLong(KEY_SPAWNED_BY_POWERED_SPAWNER);
long livedFor = livingUpdate.entity.worldObj.getTotalWorldTime() - spawnTime;
if(livedFor > Config.poweredSpawnerDespawnTimeSeconds*20) {
try {
fieldpersistenceRequired.setBoolean(livingUpdate.entityLiving, false);
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
} catch (Exception e) {
Log.warn("BlockPoweredSpawner.onLivingUpdate: Error occured allowing entity to despawn: " + e);
ent.getEntityData().removeTag(KEY_SPAWNED_BY_POWERED_SPAWNER);
}
}
}
public boolean isBlackListed(String entityId) {
return PoweredSpawnerConfig.getInstance().isBlackListed(entityId);
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TilePoweredSpawner) {
return new ContainerPoweredSpawner(player.inventory, (TilePoweredSpawner) te);
}
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TilePoweredSpawner) {
return new GuiPoweredSpawner(player.inventory, (TilePoweredSpawner) te);
}
return null;
}
@Override
protected int getGuiId() {
return GuiHandler.GUI_ID_POWERED_SPAWNER;
}
@Override
protected String getMachineFrontIconKey(boolean active) {
if(active) {
return "enderio:poweredSpawnerFrontActive";
}
return "enderio:poweredSpawnerFront";
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
String type = getSpawnerTypeFromItemStack(itemstack);
if(type != null) {
list.add(StatCollector.translateToLocal("entity." + type + ".name"));
} else {
list.add(Lang.localize("tile.blockPoweredSpawner.tooltip.empty", false));
}
}
@Override
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
}
@Override
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
String type = getSpawnerTypeFromItemStack(itemstack);
if(type == null) {
TooltipAddera.addDetailedTooltipFromResources(list, "tile.blockPoweredSpawner.empty");
} else {
TooltipAddera.addDetailedTooltipFromResources(list, "tile.blockPoweredSpawner");
}
}
@Override
public void getWailaInfo(List<String> tooltip, EntityPlayer player, World world, int x, int y, int z) {
TilePoweredSpawner te = (TilePoweredSpawner) world.getTileEntity(x, y, z);
tooltip.add(te.getEntityName());
}
@Override
public int getDefaultDisplayMask(World world, int x, int y, int z) {
return IWailaInfoProvider.BIT_DETAILED;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
super.getSubBlocks(item, tab, list);
list.add(createItemStackForMob("Enderman"));
list.add(createItemStackForMob("Chicken"));
}
protected ItemStack createItemStackForMob(String mob) {
ItemStack stack = new ItemStack(this);
stack.stackTagCompound = new NBTTagCompound();
stack.stackTagCompound.setBoolean("eio.abstractMachine", true);
writeMobTypeToNBT(stack.stackTagCompound, mob);
return stack;
}
private static class DropInfo {
BlockEvent.BreakEvent evt;
ItemStack drop;
DropInfo(BreakEvent evt, ItemStack stack) {
super();
this.evt = evt;
drop = stack;
}
void doDrop() {
if(evt.isCanceled()) {
return;
}
Util.dropItems(evt.getPlayer().worldObj, drop, evt.x, evt.y, evt.z, true);
}
}
}
| Spawners get nasty when broken
At least a little bit
| src/main/java/crazypants/enderio/machine/spawner/BlockPoweredSpawner.java | Spawners get nasty when broken |
|
Java | apache-2.0 | b47e4be5c79a74ada84ad516471b6442596621d2 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.utils;
import org.javarosa.core.util.DataUtil;
import org.junit.Test;
import java.util.Vector;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Phillip Mates ([email protected])
*/
public class AndroidUtilTest {
@Test
public void intersectionTest() {
DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda();
Vector<String> setOne = new Vector<>();
setOne.add("one");
setOne.add("two");
Vector<String> setTwo = new Vector<>();
setTwo.add("one");
setTwo.add("three");
Vector<String> intersectSet = intersectionLambda.intersection(setOne, setTwo);
// for safety, we want to return a whole new vector
assertFalse(intersectSet == setOne);
assertFalse(intersectSet == setTwo);
// for safety, don't modify ingoing vector arguments
assertTrue(setOne.contains("one"));
assertTrue(setOne.contains("two"));
assertTrue(setTwo.contains("one"));
assertTrue(setTwo.contains("three"));
// make sure proper intersection is computed
assertTrue(intersectSet.contains("one"));
assertFalse(intersectSet.contains("two"));
assertFalse(intersectSet.contains("three"));
}
}
| unit-tests/src/org/commcare/utils/AndroidUtilTest.java | package org.commcare.utils;
import org.javarosa.core.util.DataUtil;
import org.junit.Test;
import java.util.Vector;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Phillip Mates ([email protected])
*/
public class AndroidUtilTest {
@Test
public void intersectionTest() {
DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda();
Vector<String> setOne = new Vector<>();
setOne.add("one");
setOne.add("two");
Vector<String> setTwo = new Vector<>();
setTwo.add("one");
setTwo.add("three");
Vector<String> unionSet = intersectionLambda.intersection(setOne, setTwo);
// for safety, we want to return a whole new vector
assertFalse(unionSet == setOne);
assertFalse(unionSet == setTwo);
// for safety, don't modify ingoing vector arguments
assertTrue(setOne.contains("one"));
assertTrue(setOne.contains("two"));
assertTrue(setTwo.contains("one"));
assertTrue(setTwo.contains("three"));
// make sure proper intersection is computed
assertTrue(unionSet.contains("one"));
assertFalse(unionSet.contains("two"));
assertFalse(unionSet.contains("three"));
}
}
| Give test var proper name
| unit-tests/src/org/commcare/utils/AndroidUtilTest.java | Give test var proper name |
|
Java | apache-2.0 | a2288c73aa5bc2db1758f66a0e32136cea3ae8a1 | 0 | hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly | package com.firefly.server.http2;
import com.firefly.codec.http2.decode.HttpParser;
import com.firefly.codec.http2.decode.HttpParser.RequestHandler;
import com.firefly.codec.http2.decode.HttpParser.ResponseHandler;
import com.firefly.codec.http2.decode.SettingsBodyParser;
import com.firefly.codec.http2.encode.HttpGenerator;
import com.firefly.codec.http2.frame.HeadersFrame;
import com.firefly.codec.http2.frame.PrefaceFrame;
import com.firefly.codec.http2.frame.SettingsFrame;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.stream.*;
import com.firefly.net.SecureSession;
import com.firefly.net.Session;
import com.firefly.utils.Assert;
import com.firefly.utils.codec.Base64Utils;
import com.firefly.utils.concurrent.Callback;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.lang.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.CONTINUE_100_BYTES;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.H2C_BYTES;
public class HTTP1ServerConnection extends AbstractHTTP1Connection implements HTTPServerConnection {
protected static final Logger log = LoggerFactory.getLogger("firefly-system");
private final ServerSessionListener serverSessionListener;
private final HTTP1ServerRequestHandler serverRequestHandler;
AtomicBoolean upgradeHTTP2Complete = new AtomicBoolean(false);
Promise<HTTPTunnelConnection> tunnelConnectionPromise;
HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession,
HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) {
super(config, secureSession, tcpSession, requestHandler, null);
requestHandler.connection = this;
this.serverSessionListener = serverSessionListener;
this.serverRequestHandler = requestHandler;
}
@Override
protected HttpParser initHttpParser(HTTP2Configuration config, RequestHandler requestHandler, ResponseHandler responseHandler) {
return new HttpParser(requestHandler, config.getMaxRequestHeadLength());
}
HttpParser getParser() {
return parser;
}
SecureSession getSecureSession() {
return secureSession;
}
Session getTcpSession() {
return tcpSession;
}
HTTP2Configuration getHTTP2Configuration() {
return config;
}
public MetaData.Request getRequest() {
return serverRequestHandler.request;
}
public MetaData.Response getResponse() {
return serverRequestHandler.response;
}
void response100Continue() {
serverRequestHandler.outputStream.response100Continue();
}
private void responseH2c() {
serverRequestHandler.outputStream.responseH2c();
}
@Override
public void upgradeHTTPTunnel(Promise<HTTPTunnelConnection> tunnelConnectionPromise) {
this.tunnelConnectionPromise = tunnelConnectionPromise;
}
@Override
public CompletableFuture<HTTPTunnelConnection> upgradeHTTPTunnel() {
Promise.Completable<HTTPTunnelConnection> c = new Promise.Completable<>();
tunnelConnectionPromise = c;
return c;
}
HTTP1ServerTunnelConnection createHTTPTunnel() {
if (tunnelConnectionPromise != null) {
HTTP1ServerTunnelConnection tunnelConnection = new HTTP1ServerTunnelConnection(secureSession, tcpSession, httpVersion);
tunnelConnectionPromise.succeeded(tunnelConnection);
tcpSession.attachObject(tunnelConnection);
return tunnelConnection;
} else {
return null;
}
}
static class HTTP1ServerResponseOutputStream extends AbstractHTTP1OutputStream {
private final HTTP1ServerConnection connection;
private final HttpGenerator httpGenerator;
HTTP1ServerResponseOutputStream(MetaData.Response response, HTTP1ServerConnection connection) {
super(response, false);
this.connection = connection;
httpGenerator = new HttpGenerator(true, true);
}
HTTP1ServerConnection getHTTP1ServerConnection() {
return connection;
}
void responseH2c() {
getSession().encode(ByteBuffer.wrap(H2C_BYTES));
}
void response100Continue() {
getSession().encode(ByteBuffer.wrap(CONTINUE_100_BYTES));
}
@Override
protected void generateHTTPMessageSuccessfully() {
log.debug("server session {} generates the HTTP message completely", connection.getSessionId());
final MetaData.Response response = connection.getResponse();
final MetaData.Request request = connection.getRequest();
String requestConnectionValue = request.getFields().get(HttpHeader.CONNECTION);
String responseConnectionValue = response.getFields().get(HttpHeader.CONNECTION);
switch (request.getHttpVersion()) {
case HTTP_1_0:
if ("keep-alive".equalsIgnoreCase(requestConnectionValue)
&& "keep-alive".equalsIgnoreCase(responseConnectionValue)) {
log.debug("the server {} connection {} is persistent", response.getHttpVersion(), connection.getSessionId());
} else {
connection.close();
}
break;
case HTTP_1_1: // the persistent connection is default in HTTP 1.1
if ("close".equalsIgnoreCase(requestConnectionValue)
|| "close".equalsIgnoreCase(responseConnectionValue)) {
connection.close();
} else {
log.debug("the server {} connection {} is persistent", response.getHttpVersion(),
connection.getSessionId());
}
break;
default:
throw new IllegalStateException("server response does not support the http version " + connection.getHttpVersion());
}
}
@Override
protected void generateHTTPMessageExceptionally(HttpGenerator.Result actualResult,
HttpGenerator.State actualState,
HttpGenerator.Result expectedResult,
HttpGenerator.State expectedState) {
log.error("http1 generator error, actual: [{}, {}], expected: [{}, {}]", actualResult, actualState, expectedResult, expectedState);
throw new IllegalStateException("server generates http message exception.");
}
@Override
protected ByteBuffer getHeaderByteBuffer() {
return BufferUtils.allocate(connection.getHTTP2Configuration().getMaxResponseHeadLength());
}
@Override
protected ByteBuffer getTrailerByteBuffer() {
return BufferUtils.allocate(connection.getHTTP2Configuration().getMaxResponseTrailerLength());
}
@Override
protected Session getSession() {
return connection.getTcpSession();
}
@Override
protected HttpGenerator getHttpGenerator() {
return httpGenerator;
}
}
boolean directUpgradeHTTP2(MetaData.Request request) {
if (HttpMethod.PRI.is(request.getMethod())) {
HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config, tcpSession, secureSession,
serverSessionListener);
tcpSession.attachObject(http2ServerConnection);
http2ServerConnection.getParser().directUpgrade();
upgradeHTTP2Complete.compareAndSet(false, true);
return true;
} else {
return false;
}
}
boolean upgradeProtocol(MetaData.Request request, MetaData.Response response) {
switch (Protocol.from(request)) {
case H2: {
HttpField settingsField = request.getFields().getField(HttpHeader.HTTP2_SETTINGS);
Assert.notNull(settingsField, "The http2 setting field must be not null.");
final byte[] settings = Base64Utils.decodeFromUrlSafeString(settingsField.getValue());
if (log.isDebugEnabled()) {
log.debug("the server received settings {}", TypeUtils.toHexString(settings));
}
SettingsFrame settingsFrame = SettingsBodyParser.parseBody(BufferUtils.toBuffer(settings));
if (settingsFrame == null) {
throw new BadMessageException("settings frame parsing error");
} else {
responseH2c();
HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config,
tcpSession, secureSession, serverSessionListener);
tcpSession.attachObject(http2ServerConnection);
http2ServerConnection.getParser().standardUpgrade();
serverSessionListener.onAccept(http2ServerConnection.getHttp2Session());
SessionSPI sessionSPI = http2ServerConnection.getSessionSPI();
sessionSPI.onFrame(new PrefaceFrame());
sessionSPI.onFrame(settingsFrame);
sessionSPI.onFrame(new HeadersFrame(1, request, null, true));
}
upgradeHTTP2Complete.compareAndSet(false, true);
return true;
}
case WEB_SOCKET: {
// TODO
return false;
}
default:
return false;
}
}
}
| firefly/src/main/java/com/firefly/server/http2/HTTP1ServerConnection.java | package com.firefly.server.http2;
import com.firefly.codec.http2.decode.HttpParser;
import com.firefly.codec.http2.decode.HttpParser.RequestHandler;
import com.firefly.codec.http2.decode.HttpParser.ResponseHandler;
import com.firefly.codec.http2.decode.SettingsBodyParser;
import com.firefly.codec.http2.encode.HttpGenerator;
import com.firefly.codec.http2.frame.HeadersFrame;
import com.firefly.codec.http2.frame.PrefaceFrame;
import com.firefly.codec.http2.frame.SettingsFrame;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.stream.*;
import com.firefly.net.SecureSession;
import com.firefly.net.Session;
import com.firefly.utils.Assert;
import com.firefly.utils.codec.Base64Utils;
import com.firefly.utils.concurrent.Callback;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.lang.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.CONTINUE_100_BYTES;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.H2C_BYTES;
public class HTTP1ServerConnection extends AbstractHTTP1Connection implements HTTPServerConnection {
protected static final Logger log = LoggerFactory.getLogger("firefly-system");
private final ServerSessionListener serverSessionListener;
private final HTTP1ServerRequestHandler serverRequestHandler;
AtomicBoolean upgradeHTTP2Complete = new AtomicBoolean(false);
Promise<HTTPTunnelConnection> tunnelConnectionPromise;
HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession,
HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) {
super(config, secureSession, tcpSession, requestHandler, null);
requestHandler.connection = this;
this.serverSessionListener = serverSessionListener;
this.serverRequestHandler = requestHandler;
}
@Override
protected HttpParser initHttpParser(HTTP2Configuration config, RequestHandler requestHandler, ResponseHandler responseHandler) {
return new HttpParser(requestHandler, config.getMaxRequestHeadLength());
}
HttpParser getParser() {
return parser;
}
SecureSession getSecureSession() {
return secureSession;
}
Session getTcpSession() {
return tcpSession;
}
HTTP2Configuration getHTTP2Configuration() {
return config;
}
public MetaData.Request getRequest() {
return serverRequestHandler.request;
}
public MetaData.Response getResponse() {
return serverRequestHandler.response;
}
void response100Continue() {
serverRequestHandler.outputStream.response100Continue();
}
private void responseH2c() {
serverRequestHandler.outputStream.responseH2c();
}
@Override
public void upgradeHTTPTunnel(Promise<HTTPTunnelConnection> tunnelConnectionPromise) {
this.tunnelConnectionPromise = tunnelConnectionPromise;
}
@Override
public CompletableFuture<HTTPTunnelConnection> upgradeHTTPTunnel() {
Promise.Completable<HTTPTunnelConnection> c = new Promise.Completable<>();
tunnelConnectionPromise = c;
return c;
}
HTTP1ServerTunnelConnection createHTTPTunnel() {
if (tunnelConnectionPromise != null) {
HTTP1ServerTunnelConnection tunnelConnection = new HTTP1ServerTunnelConnection(secureSession, tcpSession, httpVersion);
tunnelConnectionPromise.succeeded(tunnelConnection);
tcpSession.attachObject(tunnelConnection);
return tunnelConnection;
} else {
return null;
}
}
static class HTTP1ServerResponseOutputStream extends AbstractHTTP1OutputStream {
private final HTTP1ServerConnection connection;
private final HttpGenerator httpGenerator;
HTTP1ServerResponseOutputStream(MetaData.Response response, HTTP1ServerConnection connection) {
super(response, false);
this.connection = connection;
httpGenerator = new HttpGenerator(true, true);
}
HTTP1ServerConnection getHTTP1ServerConnection() {
return connection;
}
void responseH2c() {
// getSession().encode(ByteBuffer.wrap(H2C_BYTES));
CompletableFuture<Boolean> future = new CompletableFuture<>();
getSession().write(ByteBuffer.wrap(H2C_BYTES), new Callback() {
@Override
public void succeeded() {
future.complete(true);
}
@Override
public void failed(Throwable x) {
future.completeExceptionally(x);
}
});
try {
future.get(2, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Write h2c response exception", e);
}
}
void response100Continue() {
getSession().encode(ByteBuffer.wrap(CONTINUE_100_BYTES));
}
@Override
protected void generateHTTPMessageSuccessfully() {
log.debug("server session {} generates the HTTP message completely", connection.getSessionId());
final MetaData.Response response = connection.getResponse();
final MetaData.Request request = connection.getRequest();
String requestConnectionValue = request.getFields().get(HttpHeader.CONNECTION);
String responseConnectionValue = response.getFields().get(HttpHeader.CONNECTION);
switch (request.getHttpVersion()) {
case HTTP_1_0:
if ("keep-alive".equalsIgnoreCase(requestConnectionValue)
&& "keep-alive".equalsIgnoreCase(responseConnectionValue)) {
log.debug("the server {} connection {} is persistent", response.getHttpVersion(), connection.getSessionId());
} else {
connection.close();
}
break;
case HTTP_1_1: // the persistent connection is default in HTTP 1.1
if ("close".equalsIgnoreCase(requestConnectionValue)
|| "close".equalsIgnoreCase(responseConnectionValue)) {
connection.close();
} else {
log.debug("the server {} connection {} is persistent", response.getHttpVersion(),
connection.getSessionId());
}
break;
default:
throw new IllegalStateException("server response does not support the http version " + connection.getHttpVersion());
}
}
@Override
protected void generateHTTPMessageExceptionally(HttpGenerator.Result actualResult,
HttpGenerator.State actualState,
HttpGenerator.Result expectedResult,
HttpGenerator.State expectedState) {
log.error("http1 generator error, actual: [{}, {}], expected: [{}, {}]", actualResult, actualState, expectedResult, expectedState);
throw new IllegalStateException("server generates http message exception.");
}
@Override
protected ByteBuffer getHeaderByteBuffer() {
return BufferUtils.allocate(connection.getHTTP2Configuration().getMaxResponseHeadLength());
}
@Override
protected ByteBuffer getTrailerByteBuffer() {
return BufferUtils.allocate(connection.getHTTP2Configuration().getMaxResponseTrailerLength());
}
@Override
protected Session getSession() {
return connection.getTcpSession();
}
@Override
protected HttpGenerator getHttpGenerator() {
return httpGenerator;
}
}
boolean directUpgradeHTTP2(MetaData.Request request) {
if (HttpMethod.PRI.is(request.getMethod())) {
HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config, tcpSession, secureSession,
serverSessionListener);
tcpSession.attachObject(http2ServerConnection);
http2ServerConnection.getParser().directUpgrade();
upgradeHTTP2Complete.compareAndSet(false, true);
return true;
} else {
return false;
}
}
boolean upgradeProtocol(MetaData.Request request, MetaData.Response response) {
switch (Protocol.from(request)) {
case H2: {
HttpField settingsField = request.getFields().getField(HttpHeader.HTTP2_SETTINGS);
Assert.notNull(settingsField, "The http2 setting field must be not null.");
final byte[] settings = Base64Utils.decodeFromUrlSafeString(settingsField.getValue());
if (log.isDebugEnabled()) {
log.debug("the server received settings {}", TypeUtils.toHexString(settings));
}
SettingsFrame settingsFrame = SettingsBodyParser.parseBody(BufferUtils.toBuffer(settings));
if (settingsFrame == null) {
throw new BadMessageException("settings frame parsing error");
} else {
responseH2c();
HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config,
tcpSession, secureSession, serverSessionListener);
tcpSession.attachObject(http2ServerConnection);
http2ServerConnection.getParser().standardUpgrade();
serverSessionListener.onAccept(http2ServerConnection.getHttp2Session());
SessionSPI sessionSPI = http2ServerConnection.getSessionSPI();
sessionSPI.onFrame(new PrefaceFrame());
sessionSPI.onFrame(settingsFrame);
sessionSPI.onFrame(new HeadersFrame(1, request, null, true));
}
upgradeHTTP2Complete.compareAndSet(false, true);
return true;
}
case WEB_SOCKET: {
// TODO
return false;
}
default:
return false;
}
}
}
| [test]: test h2c
| firefly/src/main/java/com/firefly/server/http2/HTTP1ServerConnection.java | [test]: test h2c |
|
Java | apache-2.0 | 8da2835989f2a5f1c58558c1131f69bba8e63670 | 0 | ekux44/LampShade,ekux44/HueMore | package com.kuxhausen.huemore.persistence;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import android.util.Pair;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.api.BulbState;
public class HueUrlEncoder {
/** zero indexed **/
public final static Integer PROTOCOL_VERSION_NUMBER = 4;
public static String encode(Mood mood)
{
return encode(mood, null, null);
}
public static String encode(Mood m, Integer[] bulbsAffected, Integer brightness){
Mood mood = m.clone();
if (mood == null)
return "";
ManagedBitSet mBitSet = new ManagedBitSet();
// Set 3 bit protocol version
mBitSet.addNumber(PROTOCOL_VERSION_NUMBER,3);
//Flag if optional bulblist included
mBitSet.incrementingSet(bulbsAffected!=null);
//50 bit optional bulb inclusion flags
if(bulbsAffected!=null){
boolean[] bulbs = new boolean[50];
for(Integer i: bulbsAffected){
if(i!=null)
bulbs[i-1]=true;
}
for(int i = 0; i<bulbs.length; i++)
mBitSet.incrementingSet(bulbs[i]);
}
/** optional total brightness added in Protocol_Version_Number==3 **/
{
/**
* The brightness value to set the light to. Brightness is a scale from 0
* (the minimum the light is capable of) to 255 (the maximum). Note: a
* brightness of 0 is not off.
*/
//Flag if optional brightness included
mBitSet.incrementingSet(brightness!=null);
//If optional brightness included, write it's 8 bits
if(brightness!=null)
mBitSet.addNumber(brightness, 8);
}
// Set 6 bit number of channels
mBitSet.addNumber(mood.getNumChannels(),6);
addTimingRepeatPolicy(mBitSet, mood);
ArrayList<Integer> timeArray = generateTimesArray(mood);
// Set 6 bit number of timestamps
mBitSet.addNumber(timeArray.size(),6);
// Set variable size list of 20 bit timestamps
for(Integer i : timeArray)
mBitSet.addNumber(i,20);
ArrayList<BulbState> stateArray = generateStatesArray(mood);
// Set 12 bit number of states
mBitSet.addNumber(stateArray.size(),12);
for(BulbState state : stateArray)
addState(mBitSet, state);
// Set 12 bit number of events
mBitSet.addNumber(mood.events.length,12);
addListOfEvents(mBitSet, mood, timeArray, stateArray);
// Set 20 bit timestamps representing the loopIterationTimeLength
mBitSet.addNumber(mood.loopIterationTimeLength,20);
return mBitSet.getBase64Encoding();
}
/** Set 8 bit timing repeat policy **/
private static void addTimingRepeatPolicy(ManagedBitSet mBitSet, Mood mood){
//1 bit timing addressing reference mode
mBitSet.incrementingSet(mood.timeAddressingRepeatPolicy);
//7 bit timing repeat number (max value specialcased to infinity)
mBitSet.addNumber(mood.getNumLoops(),7);
}
/** Set variable length state **/
private static void addState(ManagedBitSet mBitSet, BulbState bs){
/** Put 9 bit properties flags **/
{
// On/OFF flag always include in v1 implementation 1
mBitSet.incrementingSet(bs.on != null);
// Put bri flag
mBitSet.incrementingSet(bs.bri != null);
// Put hue flag
mBitSet.incrementingSet(bs.hue != null);
// Put sat flag
mBitSet.incrementingSet(bs.sat != null);
// Put xy flag
mBitSet.incrementingSet(bs.xy != null);
// Put ct flag
mBitSet.incrementingSet(bs.ct != null);
// Put alert flag
mBitSet.incrementingSet(bs.alert != null);
// Put effect flag
mBitSet.incrementingSet(bs.effect != null);
// Put transitiontime flag
mBitSet.incrementingSet(bs.transitiontime != null);
}
/** Put on bit **/
if (bs.on != null) {
mBitSet.incrementingSet(bs.on);
}
/** Put 8 bit bri **/
if (bs.bri != null) {
mBitSet.addNumber(bs.bri,8);
}
/** Put 16 bit hue **/
if (bs.hue != null) {
mBitSet.addNumber(bs.hue,16);
}
/** Put 8 bit sat **/
if (bs.sat != null) {
mBitSet.addNumber(bs.sat,8);
}
/** Put 64 bit xy **/
if (bs.xy != null) {
int x = Float
.floatToIntBits(bs.xy[0]);
mBitSet.addNumber(x,32);
int y = Float
.floatToIntBits(bs.xy[1]);
mBitSet.addNumber(y,32);
}
/** Put 9 bit ct **/
if (bs.ct != null) {
mBitSet.addNumber(bs.ct,9);
}
/** Put 2 bit alert **/
if (bs.alert != null) {
int value = 0;
if (bs.alert.equals("none"))
value = 0;
else if (bs.alert.equals("select"))
value = 1;
else if (bs.alert.equals("lselect"))
value = 2;
mBitSet.addNumber(value,2);
}
/** Put 4 bit effect **/
// three more bits than needed, reserved for future API
// functionality
if (bs.effect != null) {
int value = 0;
if (bs.effect.equals("none"))
value = 0;
else if (bs.effect.equals("colorloop"))
value = 1;
mBitSet.addNumber(value,4);
}
/** Put 16 bit transitiontime **/
if (bs.transitiontime != null) {
mBitSet.addNumber(bs.transitiontime,16);
}
}
/** Set variable length list of variable length events **/
private static void addListOfEvents(ManagedBitSet mBitSet, Mood mood, ArrayList<Integer> timeArray, ArrayList<BulbState> stateArray){
String[] bulbStateToStringArray = new String[stateArray.size()];
for(int i = 0; i< stateArray.size(); i++){
bulbStateToStringArray[i] = stateArray.get(i).toString();
}
ArrayList<String> bulbStateToStringList = new ArrayList<String>(Arrays.asList(bulbStateToStringArray));
for(Event e: mood.events){
// add channel number
mBitSet.addNumber(e.channel, getBitLength(mood.getNumChannels()));
//add timestamp lookup number
mBitSet.addNumber(timeArray.indexOf(e.time), getBitLength(timeArray.size()));
//add mood lookup number
mBitSet.addNumber(bulbStateToStringList.indexOf(e.state.toString()), getBitLength(stateArray.size()));
}
}
/** calulate number of bits needed to address this many addresses **/
private static int getBitLength(int addresses){
int length=0;
while(addresses!=0){
addresses = addresses>>>1;
length++;
}
return length;
}
private static ArrayList<Integer> generateTimesArray(Mood mood){
HashSet<Integer> timeset = new HashSet<Integer>();
for(Event e : mood.events){
timeset.add(e.time);
}
ArrayList<Integer> timesArray = new ArrayList<Integer>();
timesArray.addAll(timeset);
return timesArray;
}
private static ArrayList<BulbState> generateStatesArray(Mood mood){
HashMap<String, BulbState> statemap = new HashMap<String, BulbState>();
for(Event e : mood.events){
statemap.put(e.state.toString(), e.state);
}
ArrayList<BulbState> statesArray = new ArrayList<BulbState>();
statesArray.addAll(statemap.values());
return statesArray;
}
private static BulbState extractState(ManagedBitSet mBitSet){
BulbState bs = new BulbState();
/**
* On, Bri, Hue, Sat, XY, CT, Alert, Effect, Transitiontime
*/
boolean[] propertiesFlags = new boolean[9];
/** Get 9 bit properties flags **/
for (int j = 0; j < 9; j++) {
propertiesFlags[j] = mBitSet.incrementingGet();
}
/** Get on bit **/
if (propertiesFlags[0]) {
bs.on = mBitSet.incrementingGet();
}
/** Get 8 bit bri **/
if (propertiesFlags[1]) {
bs.bri = mBitSet.extractNumber(8);
}
/** Get 16 bit hue **/
if (propertiesFlags[2]) {
bs.hue = mBitSet.extractNumber(16);
}
/** Get 8 bit sat **/
if (propertiesFlags[3]) {
bs.sat = (short) mBitSet.extractNumber(8);
}
/** Get 64 bit xy **/
if (propertiesFlags[4]) {
Float x = Float.intBitsToFloat(mBitSet.extractNumber(32));
Float y = Float.intBitsToFloat(mBitSet.extractNumber(32));
bs.xy = new Float[] { x, y };
}
/** Get 9 bit ct **/
if (propertiesFlags[5]) {
bs.ct = mBitSet.extractNumber(9);
}
/** Get 2 bit alert **/
if (propertiesFlags[6]) {
int value = mBitSet.extractNumber(2);
switch (value) {
case 0:
bs.alert = "none";
break;
case 1:
bs.alert = "select";
break;
case 2:
bs.alert = "lselect";
break;
}
}
/** Get 4 bit effect **/
// three more bits than needed, reserved for future API
// functionality
if (propertiesFlags[7]) {
int value = mBitSet.extractNumber(4);
switch (value) {
case 0:
bs.effect = "none";
break;
case 1:
bs.effect = "colorloop";
break;
}
}
/** Get 16 bit transitiontime **/
if (propertiesFlags[8]) {
int value = mBitSet.extractNumber(16);
bs.transitiontime = value;
}
return bs;
}
public static Pair<Integer[], Pair<Mood,Integer>> decode(String code) throws InvalidEncodingException, FutureEncodingException{
try {
Mood mood = new Mood();
ArrayList<Integer> bList = new ArrayList<Integer>();
Integer brightness = null;
ManagedBitSet mBitSet = new ManagedBitSet(code);
//3 bit encoding version
int encodingVersion = mBitSet.extractNumber(3);
//1 bit optional bulb inclusion flags flag
boolean hasBulbs = mBitSet.incrementingGet();
if(hasBulbs){
//50 bits of optional bulb inclusion flags
for (int i = 0; i < 50; i++)
if (mBitSet.incrementingGet())
bList.add(i + 1);
}
if(encodingVersion == 1||encodingVersion==2 ||encodingVersion == 3){
boolean hasBrightness = false;
if(encodingVersion>=3){
//1 bit optional brightness inclusion flag
hasBrightness = mBitSet.incrementingGet();
if(hasBrightness)
//8 bit optional global brightness
brightness = mBitSet.extractNumber(8);
}
int numChannels = mBitSet.extractNumber(6);
mood.setNumChannels(numChannels);
//1 bit timing addressing reference mode
mood.timeAddressingRepeatPolicy = mBitSet.incrementingGet();
//7 bit timing repeat number
mood.setNumLoops(mBitSet.extractNumber(7));
//flag infinite looping if max numLoops
mood.setInfiniteLooping(mood.getNumLoops() == 127);
//6 bit number of timestamps
int numTimestamps = mBitSet.extractNumber(6);
int[] timeArray = new int[numTimestamps];
for(int i = 0; i<numTimestamps; i++){
//20 bit timestamp
timeArray[i]= mBitSet.extractNumber(20);
}
mood.usesTiming = !(timeArray.length==0||(timeArray.length==1&&timeArray[0]==0));
int numStates;
if(encodingVersion>=4){
//12 bit number of states
numStates = mBitSet.extractNumber(12);
}else{
//6 bit number of states
numStates = mBitSet.extractNumber(6);
}
BulbState[] stateArray = new BulbState[numStates];
for(int i = 0; i<numStates; i++){
//decode each state
stateArray[i] = extractState(mBitSet);
if(encodingVersion<3){
//convert from old brightness stuffing to new relative brightness + total brightness system
if(stateArray[i].bri!=null){
brightness = stateArray[i].bri;
stateArray[i].bri = null;
}
}
}
// number of events, 8 bits for encodings 1 & 2, 12 bits for 3+
int numEvents;
if(encodingVersion <=2)
numEvents = mBitSet.extractNumber(8);
else
numEvents = mBitSet.extractNumber(12);
Event[] eList = new Event[numEvents];
for(int i =0; i<numEvents; i++){
Event e = new Event();
e.channel = mBitSet.extractNumber(getBitLength(mood.getNumChannels()));
e.time = timeArray[mBitSet.extractNumber(getBitLength(numTimestamps))];
e.state = stateArray[mBitSet.extractNumber(getBitLength(numStates))];
eList[i] = e;
}
mood.events=eList;
// 20 bit loopIterationTimeLength is only difference between encodingVersion=1 & =2
if(encodingVersion>=2)
mood.loopIterationTimeLength = mBitSet.extractNumber(20);
} else if(encodingVersion==0){
mBitSet.useLittleEndianEncoding(true);
//7 bit number of states
int numStates = mBitSet.extractNumber(7);
Event[] eventArray = new Event[numStates];
/** Decode each state **/
for(int i = 0; i<numStates; i++){
Event e = new Event();
//decode each state
e.state = extractState(mBitSet);
//convert from old brightness stuffing to new relative brightness + total brightness system
if(e.state.bri!=null){
brightness = e.state.bri;
e.state.bri = null;
}
e.channel = i;
e.time = 0;
eventArray[i] = e;
}
mood.events = eventArray;
mood.setNumChannels(numStates);
mood.timeAddressingRepeatPolicy = false;
mood.usesTiming = false;
}
else{
throw new FutureEncodingException();
}
Integer[] bulbs=null;
if(hasBulbs){
bulbs = new Integer[bList.size()];
for(int i = 0; i<bList.size(); i++)
bulbs[i]=bList.get(i);
}
return new Pair<Integer[], Pair<Mood,Integer>>(bulbs, new Pair<Mood, Integer>(mood, brightness));
} catch(FutureEncodingException e){
throw new FutureEncodingException();
}catch(Exception e){
throw new InvalidEncodingException();
}
}
}
| app/src/com/kuxhausen/huemore/persistence/HueUrlEncoder.java | package com.kuxhausen.huemore.persistence;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import android.util.Pair;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.api.BulbState;
public class HueUrlEncoder {
/** zero indexed **/
public final static Integer PROTOCOL_VERSION_NUMBER = 3;
public static String encode(Mood mood)
{
return encode(mood, null, null);
}
public static String encode(Mood m, Integer[] bulbsAffected, Integer brightness){
Mood mood = m.clone();
if (mood == null)
return "";
ManagedBitSet mBitSet = new ManagedBitSet();
// Set 3 bit protocol version
mBitSet.addNumber(PROTOCOL_VERSION_NUMBER,3);
//Flag if optional bulblist included
mBitSet.incrementingSet(bulbsAffected!=null);
//50 bit optional bulb inclusion flags
if(bulbsAffected!=null){
boolean[] bulbs = new boolean[50];
for(Integer i: bulbsAffected){
if(i!=null)
bulbs[i-1]=true;
}
for(int i = 0; i<bulbs.length; i++)
mBitSet.incrementingSet(bulbs[i]);
}
/** optional total brightness added in Protocol_Version_Number==3 **/
{
/**
* The brightness value to set the light to. Brightness is a scale from 0
* (the minimum the light is capable of) to 255 (the maximum). Note: a
* brightness of 0 is not off.
*/
//Flag if optional brightness included
mBitSet.incrementingSet(brightness!=null);
//If optional brightness included, write it's 8 bits
if(brightness!=null)
mBitSet.addNumber(brightness, 8);
}
// Set 6 bit number of channels
mBitSet.addNumber(mood.getNumChannels(),6);
addTimingRepeatPolicy(mBitSet, mood);
ArrayList<Integer> timeArray = generateTimesArray(mood);
// Set 6 bit number of timestamps
mBitSet.addNumber(timeArray.size(),6);
// Set variable size list of 20 bit timestamps
for(Integer i : timeArray)
mBitSet.addNumber(i,20);
ArrayList<BulbState> stateArray = generateStatesArray(mood);
// Set 6 bit number of states
mBitSet.addNumber(stateArray.size(),6);
for(BulbState state : stateArray)
addState(mBitSet, state);
// Set 12 bit number of events
mBitSet.addNumber(mood.events.length,12);
addListOfEvents(mBitSet, mood, timeArray, stateArray);
// Set 20 bit timestamps representing the loopIterationTimeLength
mBitSet.addNumber(mood.loopIterationTimeLength,20);
return mBitSet.getBase64Encoding();
}
/** Set 8 bit timing repeat policy **/
private static void addTimingRepeatPolicy(ManagedBitSet mBitSet, Mood mood){
//1 bit timing addressing reference mode
mBitSet.incrementingSet(mood.timeAddressingRepeatPolicy);
//7 bit timing repeat number (max value specialcased to infinity)
mBitSet.addNumber(mood.getNumLoops(),7);
}
/** Set variable length state **/
private static void addState(ManagedBitSet mBitSet, BulbState bs){
/** Put 9 bit properties flags **/
{
// On/OFF flag always include in v1 implementation 1
mBitSet.incrementingSet(bs.on != null);
// Put bri flag
mBitSet.incrementingSet(bs.bri != null);
// Put hue flag
mBitSet.incrementingSet(bs.hue != null);
// Put sat flag
mBitSet.incrementingSet(bs.sat != null);
// Put xy flag
mBitSet.incrementingSet(bs.xy != null);
// Put ct flag
mBitSet.incrementingSet(bs.ct != null);
// Put alert flag
mBitSet.incrementingSet(bs.alert != null);
// Put effect flag
mBitSet.incrementingSet(bs.effect != null);
// Put transitiontime flag
mBitSet.incrementingSet(bs.transitiontime != null);
}
/** Put on bit **/
if (bs.on != null) {
mBitSet.incrementingSet(bs.on);
}
/** Put 8 bit bri **/
if (bs.bri != null) {
mBitSet.addNumber(bs.bri,8);
}
/** Put 16 bit hue **/
if (bs.hue != null) {
mBitSet.addNumber(bs.hue,16);
}
/** Put 8 bit sat **/
if (bs.sat != null) {
mBitSet.addNumber(bs.sat,8);
}
/** Put 64 bit xy **/
if (bs.xy != null) {
int x = Float
.floatToIntBits(bs.xy[0]);
mBitSet.addNumber(x,32);
int y = Float
.floatToIntBits(bs.xy[1]);
mBitSet.addNumber(y,32);
}
/** Put 9 bit ct **/
if (bs.ct != null) {
mBitSet.addNumber(bs.ct,9);
}
/** Put 2 bit alert **/
if (bs.alert != null) {
int value = 0;
if (bs.alert.equals("none"))
value = 0;
else if (bs.alert.equals("select"))
value = 1;
else if (bs.alert.equals("lselect"))
value = 2;
mBitSet.addNumber(value,2);
}
/** Put 4 bit effect **/
// three more bits than needed, reserved for future API
// functionality
if (bs.effect != null) {
int value = 0;
if (bs.effect.equals("none"))
value = 0;
else if (bs.effect.equals("colorloop"))
value = 1;
mBitSet.addNumber(value,4);
}
/** Put 16 bit transitiontime **/
if (bs.transitiontime != null) {
mBitSet.addNumber(bs.transitiontime,16);
}
}
/** Set variable length list of variable length events **/
private static void addListOfEvents(ManagedBitSet mBitSet, Mood mood, ArrayList<Integer> timeArray, ArrayList<BulbState> stateArray){
String[] bulbStateToStringArray = new String[stateArray.size()];
for(int i = 0; i< stateArray.size(); i++){
bulbStateToStringArray[i] = stateArray.get(i).toString();
}
ArrayList<String> bulbStateToStringList = new ArrayList<String>(Arrays.asList(bulbStateToStringArray));
for(Event e: mood.events){
// add channel number
mBitSet.addNumber(e.channel, getBitLength(mood.getNumChannels()));
//add timestamp lookup number
mBitSet.addNumber(timeArray.indexOf(e.time), getBitLength(timeArray.size()));
//add mood lookup number
mBitSet.addNumber(bulbStateToStringList.indexOf(e.state.toString()), getBitLength(stateArray.size()));
}
}
/** calulate number of bits needed to address this many addresses **/
private static int getBitLength(int addresses){
int length=0;
while(addresses!=0){
addresses = addresses>>>1;
length++;
}
return length;
}
private static ArrayList<Integer> generateTimesArray(Mood mood){
HashSet<Integer> timeset = new HashSet<Integer>();
for(Event e : mood.events){
timeset.add(e.time);
}
ArrayList<Integer> timesArray = new ArrayList<Integer>();
timesArray.addAll(timeset);
return timesArray;
}
private static ArrayList<BulbState> generateStatesArray(Mood mood){
HashMap<String, BulbState> statemap = new HashMap<String, BulbState>();
for(Event e : mood.events){
statemap.put(e.state.toString(), e.state);
}
ArrayList<BulbState> statesArray = new ArrayList<BulbState>();
statesArray.addAll(statemap.values());
return statesArray;
}
private static BulbState extractState(ManagedBitSet mBitSet){
BulbState bs = new BulbState();
/**
* On, Bri, Hue, Sat, XY, CT, Alert, Effect, Transitiontime
*/
boolean[] propertiesFlags = new boolean[9];
/** Get 9 bit properties flags **/
for (int j = 0; j < 9; j++) {
propertiesFlags[j] = mBitSet.incrementingGet();
}
/** Get on bit **/
if (propertiesFlags[0]) {
bs.on = mBitSet.incrementingGet();
}
/** Get 8 bit bri **/
if (propertiesFlags[1]) {
bs.bri = mBitSet.extractNumber(8);
}
/** Get 16 bit hue **/
if (propertiesFlags[2]) {
bs.hue = mBitSet.extractNumber(16);
}
/** Get 8 bit sat **/
if (propertiesFlags[3]) {
bs.sat = (short) mBitSet.extractNumber(8);
}
/** Get 64 bit xy **/
if (propertiesFlags[4]) {
Float x = Float.intBitsToFloat(mBitSet.extractNumber(32));
Float y = Float.intBitsToFloat(mBitSet.extractNumber(32));
bs.xy = new Float[] { x, y };
}
/** Get 9 bit ct **/
if (propertiesFlags[5]) {
bs.ct = mBitSet.extractNumber(9);
}
/** Get 2 bit alert **/
if (propertiesFlags[6]) {
int value = mBitSet.extractNumber(2);
switch (value) {
case 0:
bs.alert = "none";
break;
case 1:
bs.alert = "select";
break;
case 2:
bs.alert = "lselect";
break;
}
}
/** Get 4 bit effect **/
// three more bits than needed, reserved for future API
// functionality
if (propertiesFlags[7]) {
int value = mBitSet.extractNumber(4);
switch (value) {
case 0:
bs.effect = "none";
break;
case 1:
bs.effect = "colorloop";
break;
}
}
/** Get 16 bit transitiontime **/
if (propertiesFlags[8]) {
int value = mBitSet.extractNumber(16);
bs.transitiontime = value;
}
return bs;
}
public static Pair<Integer[], Pair<Mood,Integer>> decode(String code) throws InvalidEncodingException, FutureEncodingException{
try {
Mood mood = new Mood();
ArrayList<Integer> bList = new ArrayList<Integer>();
Integer brightness = null;
ManagedBitSet mBitSet = new ManagedBitSet(code);
//3 bit encoding version
int encodingVersion = mBitSet.extractNumber(3);
//1 bit optional bulb inclusion flags flag
boolean hasBulbs = mBitSet.incrementingGet();
if(hasBulbs){
//50 bits of optional bulb inclusion flags
for (int i = 0; i < 50; i++)
if (mBitSet.incrementingGet())
bList.add(i + 1);
}
if(encodingVersion == 1||encodingVersion==2 ||encodingVersion == 3){
boolean hasBrightness = false;
if(encodingVersion>=3){
//1 bit optional brightness inclusion flag
hasBrightness = mBitSet.incrementingGet();
if(hasBrightness)
//8 bit optional global brightness
brightness = mBitSet.extractNumber(8);
}
int numChannels = mBitSet.extractNumber(6);
mood.setNumChannels(numChannels);
//1 bit timing addressing reference mode
mood.timeAddressingRepeatPolicy = mBitSet.incrementingGet();
//7 bit timing repeat number
mood.setNumLoops(mBitSet.extractNumber(7));
//flag infinite looping if max numLoops
mood.setInfiniteLooping(mood.getNumLoops() == 127);
//6 bit number of timestamps
int numTimestamps = mBitSet.extractNumber(6);
int[] timeArray = new int[numTimestamps];
for(int i = 0; i<numTimestamps; i++){
//20 bit timestamp
timeArray[i]= mBitSet.extractNumber(20);
}
mood.usesTiming = !(timeArray.length==0||(timeArray.length==1&&timeArray[0]==0));
//6 bit number of states
int numStates = mBitSet.extractNumber(6);
BulbState[] stateArray = new BulbState[numStates];
for(int i = 0; i<numStates; i++){
//decode each state
stateArray[i] = extractState(mBitSet);
if(encodingVersion<3){
//convert from old brightness stuffing to new relative brightness + total brightness system
if(stateArray[i].bri!=null){
brightness = stateArray[i].bri;
stateArray[i].bri = null;
}
}
}
// number of events, 8 bits for encodings 1 & 2, 12 bits for 3+
int numEvents;
if(encodingVersion <=2)
numEvents = mBitSet.extractNumber(8);
else
numEvents = mBitSet.extractNumber(12);
Event[] eList = new Event[numEvents];
for(int i =0; i<numEvents; i++){
Event e = new Event();
e.channel = mBitSet.extractNumber(getBitLength(mood.getNumChannels()));
e.time = timeArray[mBitSet.extractNumber(getBitLength(numTimestamps))];
e.state = stateArray[mBitSet.extractNumber(getBitLength(numStates))];
eList[i] = e;
}
mood.events=eList;
// 20 bit loopIterationTimeLength is only difference between encodingVersion=1 & =2
if(encodingVersion>=2)
mood.loopIterationTimeLength = mBitSet.extractNumber(20);
} else if(encodingVersion==0){
mBitSet.useLittleEndianEncoding(true);
//7 bit number of states
int numStates = mBitSet.extractNumber(7);
Event[] eventArray = new Event[numStates];
/** Decode each state **/
for(int i = 0; i<numStates; i++){
Event e = new Event();
//decode each state
e.state = extractState(mBitSet);
//convert from old brightness stuffing to new relative brightness + total brightness system
if(e.state.bri!=null){
brightness = e.state.bri;
e.state.bri = null;
}
e.channel = i;
e.time = 0;
eventArray[i] = e;
}
mood.events = eventArray;
mood.setNumChannels(numStates);
mood.timeAddressingRepeatPolicy = false;
mood.usesTiming = false;
}
else{
throw new FutureEncodingException();
}
Integer[] bulbs=null;
if(hasBulbs){
bulbs = new Integer[bList.size()];
for(int i = 0; i<bList.size(); i++)
bulbs[i]=bList.get(i);
}
return new Pair<Integer[], Pair<Mood,Integer>>(bulbs, new Pair<Mood, Integer>(mood, brightness));
} catch(FutureEncodingException e){
throw new FutureEncodingException();
}catch(Exception e){
throw new InvalidEncodingException();
}
}
}
| Created HueUrlEncoder versionNumber=4 (5th iteration)
Increased max num states to 4096 to match max num events (since it is
impractical to enforce max state number < max event number in the UI)
| app/src/com/kuxhausen/huemore/persistence/HueUrlEncoder.java | Created HueUrlEncoder versionNumber=4 (5th iteration) |
|
Java | apache-2.0 | 9ed3f41884d2044c8d4ae0a86d7f3f541f777f27 | 0 | MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab | /**
*
* @author GroG & Mats (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab 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 (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* 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.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.List;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.Mapper;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.NameProvider;
import org.myrobotlab.service.interfaces.PinListener;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.motor.MotorConfig;
import org.myrobotlab.motor.MotorConfigDualPwm;
import org.myrobotlab.motor.MotorConfigPulse;
import org.myrobotlab.motor.MotorConfigSimpleH;
import org.myrobotlab.sensor.Encoder;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* @author Grog & Mats
*
* Servos have both input and output. Input is usually of the range of
* integers between 0 - 180, and output can relay those values directly
* to the servo's firmware (Arduino ServoLib, I2C controller, etc)
*
* However there can be the occasion that the input comes from a system
* which does not have the same range. Such that input can vary from 0.0
* to 1.0. For example, OpenCV coordinates are often returned in this
* range. When a mapping is needed Servo.map can be used. For this
* mapping Servo.map(0.0, 1.0, 0, 180) might be desired. Reversing input
* would be done with Servo.map(180, 0, 0, 180)
*
* outputY - is the values sent to the firmware, and should not
* necessarily be confused with the inputX which is the input values
* sent to the servo
*
* This service is to be used if you have a motor without feedback and
* you want to use it as a Servo. So you connect the motor as a Motor
* and use an Aduino, Ads1115 or some other input source that can give
* an analog input from a potentiometer or other device that can give
* analog feedback.
*/
public class DiyServo extends Service implements ServoControl, MotorControl, PinListener {
/**
* Sweeper
*
*/
public class Sweeper extends Thread {
/*
* int min; int max; int delay; // depending on type - this is 2
* different things COMPUTER // its ms delay - CONTROLLER its modulus
* loop count int step; boolean sweepOneWay;
*/
public Sweeper(String name) {
super(String.format("%s.sweeper", name));
}
@Override
public void run() {
if (targetPos == null) {
targetPos = sweepMin;
}
try {
while (isSweeping) {
// increment position that we should go to.
if (targetPos < sweepMax && sweepStep >= 0) {
targetPos += sweepStep;
} else if (targetPos > sweepMin && sweepStep < 0) {
targetPos += sweepStep;
}
// switch directions or exit if we are sweeping 1 way
if ((targetPos <= sweepMin && sweepStep < 0) || (targetPos >= sweepMax && sweepStep > 0)) {
if (sweepOneWay) {
isSweeping = false;
break;
}
sweepStep = sweepStep * -1;
}
moveTo(targetPos.intValue());
Thread.sleep(sweepDelay);
}
} catch (Exception e) {
isSweeping = false;
if (e instanceof InterruptedException) {
info("shutting down sweeper");
} else {
logException(e);
}
}
}
}
/**
* MotorUpdater The control loop to update the motor service with new values
* based on the PID calculations
*
*/
public class MotorUpdater extends Thread {
double lastOutput = 0;
DiyServo mc;
public MotorUpdater(DiyServo mc) {
super(String.format("%s.MotorUpdater", mc.getName()));
this.mc = mc;
}
@Override
public void run() {
try {
while (true) {
if (controller != null) {
// Calculate the new value for the motor
if (pid.compute(pidKey)) {
double setPoint = pid.getSetpoint(pidKey);
double output = pid.getOutput(pidKey);
mc.setPowerLevel(output);
log.debug(String.format("setPoint(%s), processVariable(%s), output(%s)", setPoint,
processVariable, output));
if (output != lastOutput) {
// controller.move(output);
controller.motorMove((MotorControl) mc);
lastOutput = output;
}
}
Thread.sleep(1000 / sampleTime);
}
}
} catch (Exception e) {
if (e instanceof InterruptedException) {
info("Shutting down MotorUpdater");
} else {
logException(e);
}
}
}
}
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(DiyServo.class);
// MotorController
transient MotorController controller;
public String controllerName = null;
MotorConfig config;
// Reference to the Analog input service
public List<String> pinArrayControls; // List
// of
// available
// services
// for
// analog
// inpt
transient PinArrayControl pinArrayControl; // Handle
// to
// the
// selected
// analog
// input
// service
public String pinControlName; // Name
// of
// the
// selected
// analog
// input
// service
public List<Integer> pinList = new ArrayList<Integer>();
public Integer pin;
Mapper mapper = new Mapper(0, 180, 0, 180);
Integer rest = 90;
long lastActivityTime = 0;
/**
* the requested INPUT position of the servo
*/
Integer targetPos;
/**
* the calculated output for the servo
*/
Integer targetOutput;
/**
* list of names of possible controllers
*/
public List<String> controllers;
/**
* current speed of the servo
*/
Double speed = 1.0;
// FIXME - currently is only computer control - needs to be either
// microcontroller or computer
boolean isSweeping = false;
int sweepMin = 0;
int sweepMax = 180;
int sweepDelay = 1;
int sweepStep = 1;
boolean sweepOneWay = false;
// sweep types
// TODO - computer implemented speed control (non-sweep)
boolean speedControlOnUC = false;
transient Thread sweeper = null;
/**
* feedback of both incremental position and stops. would allow blocking
* moveTo if desired
*/
boolean isEventsEnabled = false;
private int maxVelocity = 425;
private boolean isAttached = false;
private boolean isControllerSet = false;
private boolean isPinArrayControlSet = false;
// Initial parameters for PID.
static final public int MODE_AUTOMATIC = 1;
static final public int MODE_MANUAL = 0;
public int mode = MODE_MANUAL;
public Pid pid;
private String pidKey;
private double kp = 0.020;
private double ki = 0.001; // 0.020;
private double kd = 0.0; // 0.020;
public double setPoint = 90; // Intial
// setpoint
// corresponding
// to
// a
// centered
// servo
// The
// pinListener
// value
// depends
// on
// the
// hardwawe
// behind
// it,
// so
// the
// value
// from
// the
int resolution = 1024; // AD
// converter
// needs
// to
// be
// remapped
// to
// 0
// -
// 180.
// D1024
// is
// the
// default
// for
// the
// Arduino
int sampleTime = 20; // Sample
// time
// 20
// ms
// =
// 50
// Hz
public double processVariable = 0; // Initial
// process
// variable
transient MotorUpdater motorUpdater;
double powerLevel = 0;
double maxPower = 1.0;
double minPower = -1.0;
Mapper powerMap = new Mapper(-1.0, 1.0, -255.0, 255.0);
/**
* Constructor
*
* @param n
* name of the service
*/
public DiyServo(String n) {
super(n);
refreshControllers();
refreshPinArrayControls();
initPid();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
lastActivityTime = System.currentTimeMillis();
}
/**
* Update the list of MotorControllers and PinArrayControls
*
* @param s
*/
public void onRegistered(ServiceInterface s) {
refreshControllers();
refreshPinArrayControls();
broadcastState();
}
/**
* Initiate the PID controller
*/
void initPid() {
pid = (Pid) createPeer("Pid");
pidKey = this.getName();
pid.setPID(pidKey, kp, ki, kd); // Create a PID with the name of this
// service instance
pid.setMode(pidKey, MODE_AUTOMATIC); // Initial mode is manual
pid.setOutputRange(pidKey, -1.0, 1.0); // Set the Output range to match
// the
// Motor input
pid.setSampleTime(pidKey, sampleTime); // Sets the sample time
pid.setSetpoint(pidKey, setPoint);
pid.startService();
}
/**
* @param service
*/
public void addServoEventListener(NameProvider service) {
addListener("publishServoEvent", service.getName(), "onServoEvent");
}
/**
* Re-attach to servo's current pin. The pin must have be set previously.
* Equivalent to Arduino's Servo.attach(currentPin) In this service it stops
* the motor and PID is set to manual mode
*/
@Override
public void attach() {
attach(pin);
broadcastState();
}
/**
* Equivalent to Arduino's Servo.attach(pin). It energizes the servo sending
* pulses to maintain its current position.
*/
@Override
public void attach(int pin) {
// TODO Activate the motor and PID
lastActivityTime = System.currentTimeMillis();
isAttached = true;
broadcastState();
}
/**
* Equivalent to Arduino's Servo.detach() it de-energizes the servo
*/
@Override
// TODO DeActivate the motor and PID
public void detach() {
controller.motorStop((MotorControl) this);
isAttached = false;
broadcastState();
}
/////// config start ////////////////////////
public void setPwmPins(int leftPin, int rightPin) {
config = new MotorConfigDualPwm(leftPin, rightPin);
broadcastState();
}
public void setPwrDirPins(int pwrPin, int dirPin){
config = new MotorConfigSimpleH(pwrPin, dirPin);
broadcastState();
}
public MotorConfig getConfig() {
return config;
}
/**
* Method to check if events are enabled or not
*
* @param b
* @return
*/
public boolean eventsEnabled(boolean b) {
isEventsEnabled = b;
broadcastState();
return b;
}
public long getLastActivityTime() {
return lastActivityTime;
}
public Double getMax() {
return mapper.getMaxY();
}
public Double getMaxInput() {
return mapper.getMaxX();
}
public Double getMaxOutput() {
return mapper.getMaxOutput();
}
public Double getMin() {
return mapper.getMinY();
}
public Double getMinInput() {
return mapper.getMinX();
}
public Double getMinOutput() {
return mapper.getMinOutput();
}
public Integer getPos() {
return targetPos;
}
public int getRest() {
return rest;
}
public boolean isAttached() {
return isAttached;
}
public boolean isControllerSet() {
return isControllerSet;
}
public boolean isPinArrayControlSet() {
return isPinArrayControlSet;
}
public boolean isInverted() {
return mapper.isInverted();
}
public void map(double minX, double maxX, double minY, double maxY) {
mapper = new Mapper(minX, maxX, minY, maxY);
broadcastState();
}
/**
* The most important method, that tells the servo what position it should
* move to
*/
public void moveTo(int pos) {
if (controller == null) {
error(String.format("%s's controller is not set", getName()));
return;
}
if (motorUpdater == null) {
motorUpdater = new MotorUpdater(this);
motorUpdater.run();
}
targetPos = pos;
targetOutput = mapper.calcInt(targetPos);
pid.setSetpoint(pidKey, targetOutput);
lastActivityTime = System.currentTimeMillis();
if (isEventsEnabled) {
// update others of our position change
invoke("publishServoEvent", targetOutput);
}
}
/**
* basic move command of the servo - usually is 0 - 180 valid range but can
* be adjusted and / or re-mapped with min / max and map commands
*
* TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION"
* response
*/
// uber good
public Integer publishServoEvent(Integer position) {
return position;
}
/**
* FIXME - Hmmm good canidate for Microcontroller Peripheral
*
* @return
*/
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(MotorController.class);
return controllers;
}
public List<String> refreshPinArrayControls() {
pinArrayControls = Runtime.getServiceNamesFromInterface(PinArrayControl.class);
return pinArrayControls;
}
@Override
public void releaseService() {
detach();
super.releaseService();
}
public void rest() {
moveTo(rest);
}
@Override
public void setController(DeviceController controller) {
if (controller == null) {
info("setting controller to null");
this.controllerName = null;
this.controller = null;
return;
}
log.info(String.format("%s setController %s", getName(), controller.getName()));
this.controller = (MotorController) controller;
this.controllerName = controller.getName();
broadcastState();
}
/*
* (non-Javadoc)
*
* @see org.myrobotlab.service.interfaces.ServoControl#setPin(int)
*/
/*
* @Override public boolean setPin(int pin) { log.info(String.format(
* "setting %s pin to %d", getName(), pin)); if (isAttached()) { warn(
* "%s can not set pin %d when servo is attached", getName(), pin); return
* false; } this.pin = pin; broadcastState(); return true; }
*/
public void setInverted(boolean invert) {
mapper.setInverted(invert);
}
@Override
public void setMinMax(int min, int max) {
mapper.setMin(min);
mapper.setMax(max);
broadcastState();
}
public void setRest(int rest) {
this.rest = rest;
}
public void setSpeed(double speed) {
this.speed = speed;
// TODO Replace with PID / Motor logic
// getController().servoSetSpeed(this);
}
// choose to handle sweep on arduino or in MRL on host computer thread.
public void setSpeedControlOnUC(boolean b) {
speedControlOnUC = b;
}
public void setSweepDelay(int delay) {
sweepDelay = delay;
}
/*
* (non-Javadoc)
*
* @see org.myrobotlab.service.interfaces.ServoControl#stopServo()
*/
@Override
public void stop() {
isSweeping = false;
sweeper = null;
// TODO Replace with internal logic for motor and PID
// getController().servoSweepStop(this);
broadcastState();
}
public void sweep() {
int min = mapper.getMinX().intValue();
int max = mapper.getMaxX().intValue();
sweep(min, max, 1, 1);
}
public void sweep(int min, int max) {
sweep(min, max, 1, 1);
}
// FIXME - is it really speed control - you don't currently thread for
// fractional speed values
public void sweep(int min, int max, int delay, int step) {
sweep(min, max, delay, step, false);
}
public void sweep(int min, int max, int delay, int step, boolean oneWay) {
this.sweepMin = min;
this.sweepMax = max;
this.sweepDelay = delay;
this.sweepStep = step;
this.sweepOneWay = oneWay;
// FIXME - CONTROLLER TYPE SWITCH
// In case PID is implemented in Arduino, this could happen
if (speedControlOnUC) {
// getController().servoSweepStart(this); // delay &
// step
// implemented
} else {
if (isSweeping) {
stop();
}
sweeper = new Sweeper(getName());
sweeper.start();
}
isSweeping = true;
broadcastState();
}
/**
* Writes a value in microseconds (uS) to the servo, controlling the shaft
* accordingly. On a standard servo, this will set the angle of the shaft.
* On standard servos a parameter value of 1000 is fully counter-clockwise,
* 2000 is fully clockwise, and 1500 is in the middle.
*
* Note that some manufactures do not follow this standard very closely so
* that servos often respond to values between 700 and 2300. Feel free to
* increase these endpoints until the servo no longer continues to increase
* its range. Note however that attempting to drive a servo past its
* endpoints (often indicated by a growling sound) is a high-current state,
* and should be avoided.
*
* Continuous-rotation servos will respond to the writeMicrosecond function
* in an analogous manner to the write function.
*
* @param pos
*/
public void writeMicroseconds(Integer uS) {
log.info("writeMicroseconds({})", uS);
// TODO. This need to be remapped to Motor and PID internal to this
// Service
// getController().servoWriteMicroseconds(this, uS);
lastActivityTime = System.currentTimeMillis();
broadcastState();
}
/*
* @Override public void setPin(int pin) { this.pin = pin; }
*/
@Override
public Integer getPin() {
return this.pin;
}
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
// Runtime.start("webgui", "WebGui");
Runtime.start("gui", "GUIService");
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
arduino.connect("COM3");
Ads1115 ads = (Ads1115) Runtime.start("Ads1115", "Ads1115");
ads.setController(arduino, "1", "0x48");
DiyServo dyiServo = (DiyServo) Runtime.start("DiyServo", "DiyServo");
dyiServo.attach(arduino);
dyiServo.attach((PinArrayControl) ads, 0); // PIN 14 = A0
// Servo Servo = (Servo) Runtime.start("Servo", "Servo");
dyiServo.moveTo(90);
dyiServo.setRest(30);
dyiServo.moveTo(10);
dyiServo.moveTo(90);
dyiServo.moveTo(180);
dyiServo.rest();
dyiServo.setMinMax(30, 160);
dyiServo.moveTo(40);
dyiServo.moveTo(140);
dyiServo.moveTo(180);
dyiServo.setSpeed(0.5);
dyiServo.moveTo(31);
dyiServo.setSpeed(0.2);
dyiServo.moveTo(90);
dyiServo.moveTo(180);
// servo.test();
} catch (Exception e) {
Logging.logError(e);
}
}
@Override
public int getSweepMin() {
return sweepMin;
}
@Override
public int getSweepMax() {
return sweepMax;
}
@Override
public int getSweepStep() {
return sweepStep;
}
@Override
public Integer getTargetOutput() {
return targetOutput;
}
@Override
public double getSpeed() {
return speed;
}
public void attach(String controllerName) throws Exception {
attach((MotorController) Runtime.getService(controllerName));
}
public void attach(MotorController controller) throws Exception {
this.controller = controller;
if (controller != null) {
controllerName = controller.getName();
isControllerSet = true;
}
broadcastState();
}
@Override
public void detach(String controllerName) {
ServiceInterface si = Runtime.getService(controllerName);
if (si instanceof MotorController) {
detach((MotorController) Runtime.getService(controllerName));
}
if (si instanceof PinArrayControl) {
detach((PinArrayControl) Runtime.getService(controllerName));
}
}
public void detach(MotorController controller) {
if (this.controller == controller) {
this.controller = null;
isAttached = false;
isControllerSet = false;
broadcastState();
}
}
public void detach(PinArrayControl pinArrayControl) {
if (this.pinArrayControl == pinArrayControl) {
this.pinArrayControl = null;
isPinArrayControlSet = false;
broadcastState();
}
}
public void setMaxVelocity(int velocity) {
this.maxVelocity = velocity;
}
@Override
public int getMaxVelocity() {
return maxVelocity;
}
@Override
public void onPin(PinData pindata) {
int inputValue = pindata.getValue();
processVariable = 180 * inputValue / resolution;
// log.info(String.format("onPin received value %s converted to %s",
// inputValue, processVariable));
pid.setInput(pidKey, processVariable);
}
@Override
public DeviceController getController() {
return (DeviceController) controller;
}
public void attach(String pinArrayControlName, Integer pin) throws Exception {
attach(pinArrayControlName, (int) pin);
}
@Override
public void attach(String pinArrayControlName, int pin) throws Exception {
attach((PinArrayControl) Runtime.getService(pinArrayControlName), pin);
}
public void attach(PinArrayControl pinArrayControl, int pin) throws Exception {
this.pinArrayControl = pinArrayControl;
if (pinArrayControl != null) {
pinControlName = pinArrayControl.getName();
isPinArrayControlSet = true;
this.pin = pin;
}
// TODO The resolution is a property of the AD converter and should be
// fetched thru a method call like controller.getADResolution()
if (pinArrayControl instanceof Arduino) {
resolution = 1024;
}
if (pinArrayControl instanceof Ads1115) {
resolution = 65536;
}
int rate = 1000 / sampleTime;
pinArrayControl.attach(this, pin);
pinArrayControl.enablePin(pin, rate);
broadcastState();
}
//
// A bunch of unused methods from ServoControl. Perhaps I should create a
// new
// DiyServoControl interface.
// I was hoping to be able to avoid that, but might be a better solution
@Override
public void attach(ServoController controller, int pin, Integer pos) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void detach(ServoController controller) {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin) throws Exception {
// TODO Auto-generated method stub
}
@Override
public int getVelocity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void attach(String controllerName, int pin, Integer pos) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin, Integer pos, Integer velocity) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(String controllerName, int pin, Integer pos, Integer velocity) throws Exception {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(DiyServo.class.getCanonicalName());
meta.addDescription("Controls a motor so that it can be used as a Servo");
meta.addCategory("motor", "control");
meta.addPeer("Motor", "Motor", "Servo motor");
meta.addPeer("Pid", "Pid", "PID service");
return meta;
}
@Override
public double getPowerLevel() {
return powerLevel;
}
@Override
public void setPowerLevel(double power) {
this.powerLevel = power;
}
@Override
public double getPowerOutput() {
return powerMap.calc(powerLevel);
}
@Override
public int getTargetPos() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void lock() {
// TODO Auto-generated method stub
}
@Override
public void move(double power) {
// TODO Auto-generated method stub
}
@Override
public void moveTo(int newPos, Double power) {
// TODO Auto-generated method stub
}
@Override
public void setEncoder(Encoder encoder) {
// TODO Auto-generated method stub
}
@Override
public void stopAndLock() {
// TODO Auto-generated method stub
}
@Override
public void unlock() {
// TODO Auto-generated method stub
}
} | src/org/myrobotlab/service/DiyServo.java | /**
*
* @author GroG & Mats (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab 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 (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* 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.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.List;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.Mapper;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.NameProvider;
import org.myrobotlab.service.interfaces.PinListener;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.motor.MotorConfig;
import org.myrobotlab.motor.MotorConfigDualPwm;
import org.myrobotlab.motor.MotorConfigPulse;
import org.myrobotlab.motor.MotorConfigSimpleH;
import org.myrobotlab.sensor.Encoder;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* @author Grog & Mats
*
* Servos have both input and output. Input is usually of the range of
* integers between 0 - 180, and output can relay those values directly
* to the servo's firmware (Arduino ServoLib, I2C controller, etc)
*
* However there can be the occasion that the input comes from a system
* which does not have the same range. Such that input can vary from 0.0
* to 1.0. For example, OpenCV coordinates are often returned in this
* range. When a mapping is needed Servo.map can be used. For this
* mapping Servo.map(0.0, 1.0, 0, 180) might be desired. Reversing input
* would be done with Servo.map(180, 0, 0, 180)
*
* outputY - is the values sent to the firmware, and should not
* necessarily be confused with the inputX which is the input values
* sent to the servo
*
* This service is to be used if you have a motor without feedback and
* you want to use it as a Servo. So you connect the motor as a Motor
* and use an Aduino, Ads1115 or some other input source that can give
* an analog input from a potentiometer or other device that can give
* analog feedback.
*/
public class DiyServo extends Service implements ServoControl, MotorControl, PinListener {
/**
* Sweeper
*
*/
public class Sweeper extends Thread {
/*
* int min; int max; int delay; // depending on type - this is 2
* different things COMPUTER // its ms delay - CONTROLLER its modulus
* loop count int step; boolean sweepOneWay;
*/
public Sweeper(String name) {
super(String.format("%s.sweeper", name));
}
@Override
public void run() {
if (targetPos == null) {
targetPos = sweepMin;
}
try {
while (isSweeping) {
// increment position that we should go to.
if (targetPos < sweepMax && sweepStep >= 0) {
targetPos += sweepStep;
} else if (targetPos > sweepMin && sweepStep < 0) {
targetPos += sweepStep;
}
// switch directions or exit if we are sweeping 1 way
if ((targetPos <= sweepMin && sweepStep < 0) || (targetPos >= sweepMax && sweepStep > 0)) {
if (sweepOneWay) {
isSweeping = false;
break;
}
sweepStep = sweepStep * -1;
}
moveTo(targetPos.intValue());
Thread.sleep(sweepDelay);
}
} catch (Exception e) {
isSweeping = false;
if (e instanceof InterruptedException) {
info("shutting down sweeper");
} else {
logException(e);
}
}
}
}
/**
* MotorUpdater The control loop to update the motor service with new values
* based on the PID calculations
*
*/
public class MotorUpdater extends Thread {
double lastOutput = 0;
MotorControl mc;
public MotorUpdater(MotorControl mc) {
super(String.format("%s.MotorUpdater", mc.getName()));
this.mc = mc;
}
@Override
public void run() {
try {
while (true) {
if (controller != null) {
// Calculate the new value for the motor
if (pid.compute(pidKey)) {
double setPoint = pid.getSetpoint(pidKey);
double output = pid.getOutput(pidKey);
log.debug(String.format("setPoint(%s), processVariable(%s), output(%s)", setPoint,
processVariable, output));
if (output != lastOutput) {
// controller.move(output);
controller.motorMove(mc);
lastOutput = output;
}
}
Thread.sleep(1000 / sampleTime);
}
}
} catch (Exception e) {
if (e instanceof InterruptedException) {
info("Shutting down MotorUpdater");
} else {
logException(e);
}
}
}
}
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(DiyServo.class);
// MotorController
transient MotorController controller;
public String controllerName = null;
MotorConfig config;
// Reference to the Analog input service
public List<String> pinArrayControls; // List
// of
// available
// services
// for
// analog
// inpt
transient PinArrayControl pinArrayControl; // Handle
// to
// the
// selected
// analog
// input
// service
public String pinControlName; // Name
// of
// the
// selected
// analog
// input
// service
public List<Integer> pinList = new ArrayList<Integer>();
public Integer pin;
Mapper mapper = new Mapper(0, 180, 0, 180);
Integer rest = 90;
long lastActivityTime = 0;
/**
* the requested INPUT position of the servo
*/
Integer targetPos;
/**
* the calculated output for the servo
*/
Integer targetOutput;
/**
* list of names of possible controllers
*/
public List<String> controllers;
/**
* current speed of the servo
*/
Double speed = 1.0;
// FIXME - currently is only computer control - needs to be either
// microcontroller or computer
boolean isSweeping = false;
int sweepMin = 0;
int sweepMax = 180;
int sweepDelay = 1;
int sweepStep = 1;
boolean sweepOneWay = false;
// sweep types
// TODO - computer implemented speed control (non-sweep)
boolean speedControlOnUC = false;
transient Thread sweeper = null;
/**
* feedback of both incremental position and stops. would allow blocking
* moveTo if desired
*/
boolean isEventsEnabled = false;
private int maxVelocity = 425;
private boolean isAttached = false;
private boolean isControllerSet = false;
private boolean isPinArrayControlSet = false;
// Initial parameters for PID.
static final public int MODE_AUTOMATIC = 1;
static final public int MODE_MANUAL = 0;
public int mode = MODE_MANUAL;
public Pid pid;
private String pidKey;
private double kp = 0.020;
private double ki = 0.001; // 0.020;
private double kd = 0.0; // 0.020;
public double setPoint = 90; // Intial
// setpoint
// corresponding
// to
// a
// centered
// servo
// The
// pinListener
// value
// depends
// on
// the
// hardwawe
// behind
// it,
// so
// the
// value
// from
// the
int resolution = 1024; // AD
// converter
// needs
// to
// be
// remapped
// to
// 0
// -
// 180.
// D1024
// is
// the
// default
// for
// the
// Arduino
int sampleTime = 20; // Sample
// time
// 20
// ms
// =
// 50
// Hz
public double processVariable = 0; // Initial
// process
// variable
transient MotorUpdater motorUpdater;
/**
* Constructor
*
* @param n
* name of the service
*/
public DiyServo(String n) {
super(n);
refreshControllers();
refreshPinArrayControls();
initPid();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
lastActivityTime = System.currentTimeMillis();
}
/**
* Update the list of MotorControllers and PinArrayControls
*
* @param s
*/
public void onRegistered(ServiceInterface s) {
refreshControllers();
refreshPinArrayControls();
broadcastState();
}
/**
* Initiate the PID controller
*/
void initPid() {
pid = (Pid) createPeer("Pid");
pidKey = this.getName();
pid.setPID(pidKey, kp, ki, kd); // Create a PID with the name of this
// service instance
pid.setMode(pidKey, MODE_AUTOMATIC); // Initial mode is manual
pid.setOutputRange(pidKey, -1.0, 1.0); // Set the Output range to match
// the
// Motor input
pid.setSampleTime(pidKey, sampleTime); // Sets the sample time
pid.setSetpoint(pidKey, setPoint);
pid.startService();
}
/**
* @param service
*/
public void addServoEventListener(NameProvider service) {
addListener("publishServoEvent", service.getName(), "onServoEvent");
}
/**
* Re-attach to servo's current pin. The pin must have be set previously.
* Equivalent to Arduino's Servo.attach(currentPin) In this service it stops
* the motor and PID is set to manual mode
*/
@Override
public void attach() {
attach(pin);
broadcastState();
}
/**
* Equivalent to Arduino's Servo.attach(pin). It energizes the servo sending
* pulses to maintain its current position.
*/
@Override
public void attach(int pin) {
// TODO Activate the motor and PID
lastActivityTime = System.currentTimeMillis();
isAttached = true;
broadcastState();
}
/**
* Equivalent to Arduino's Servo.detach() it de-energizes the servo
*/
@Override
// TODO DeActivate the motor and PID
public void detach() {
controller.motorStop((MotorControl) this);
isAttached = false;
broadcastState();
}
/////// config start ////////////////////////
public void setPwmPins(int leftPin, int rightPin) {
config = new MotorConfigDualPwm(leftPin, rightPin);
broadcastState();
}
public void setPwrDirPins(int pwrPin, int dirPin){
config = new MotorConfigSimpleH(pwrPin, dirPin);
broadcastState();
}
public MotorConfig getConfig() {
return config;
}
/**
* Method to check if events are enabled or not
*
* @param b
* @return
*/
public boolean eventsEnabled(boolean b) {
isEventsEnabled = b;
broadcastState();
return b;
}
public long getLastActivityTime() {
return lastActivityTime;
}
public Double getMax() {
return mapper.getMaxY();
}
public Double getMaxInput() {
return mapper.getMaxX();
}
public Double getMaxOutput() {
return mapper.getMaxOutput();
}
public Double getMin() {
return mapper.getMinY();
}
public Double getMinInput() {
return mapper.getMinX();
}
public Double getMinOutput() {
return mapper.getMinOutput();
}
public Integer getPos() {
return targetPos;
}
public int getRest() {
return rest;
}
public boolean isAttached() {
return isAttached;
}
public boolean isControllerSet() {
return isControllerSet;
}
public boolean isPinArrayControlSet() {
return isPinArrayControlSet;
}
public boolean isInverted() {
return mapper.isInverted();
}
public void map(double minX, double maxX, double minY, double maxY) {
mapper = new Mapper(minX, maxX, minY, maxY);
broadcastState();
}
/**
* The most important method, that tells the servo what position it should
* move to
*/
public void moveTo(int pos) {
if (controller == null) {
error(String.format("%s's controller is not set", getName()));
return;
}
if (motorUpdater == null) {
motorUpdater = new MotorUpdater(this);
motorUpdater.run();
}
targetPos = pos;
targetOutput = mapper.calcInt(targetPos);
pid.setSetpoint(pidKey, targetOutput);
lastActivityTime = System.currentTimeMillis();
if (isEventsEnabled) {
// update others of our position change
invoke("publishServoEvent", targetOutput);
}
}
/**
* basic move command of the servo - usually is 0 - 180 valid range but can
* be adjusted and / or re-mapped with min / max and map commands
*
* TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION"
* response
*/
// uber good
public Integer publishServoEvent(Integer position) {
return position;
}
/**
* FIXME - Hmmm good canidate for Microcontroller Peripheral
*
* @return
*/
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(MotorController.class);
return controllers;
}
public List<String> refreshPinArrayControls() {
pinArrayControls = Runtime.getServiceNamesFromInterface(PinArrayControl.class);
return pinArrayControls;
}
@Override
public void releaseService() {
detach();
super.releaseService();
}
public void rest() {
moveTo(rest);
}
@Override
public void setController(DeviceController controller) {
if (controller == null) {
info("setting controller to null");
this.controllerName = null;
this.controller = null;
return;
}
log.info(String.format("%s setController %s", getName(), controller.getName()));
this.controller = (MotorController) controller;
this.controllerName = controller.getName();
broadcastState();
}
/*
* (non-Javadoc)
*
* @see org.myrobotlab.service.interfaces.ServoControl#setPin(int)
*/
/*
* @Override public boolean setPin(int pin) { log.info(String.format(
* "setting %s pin to %d", getName(), pin)); if (isAttached()) { warn(
* "%s can not set pin %d when servo is attached", getName(), pin); return
* false; } this.pin = pin; broadcastState(); return true; }
*/
public void setInverted(boolean invert) {
mapper.setInverted(invert);
}
@Override
public void setMinMax(int min, int max) {
mapper.setMin(min);
mapper.setMax(max);
broadcastState();
}
public void setRest(int rest) {
this.rest = rest;
}
public void setSpeed(double speed) {
this.speed = speed;
// TODO Replace with PID / Motor logic
// getController().servoSetSpeed(this);
}
// choose to handle sweep on arduino or in MRL on host computer thread.
public void setSpeedControlOnUC(boolean b) {
speedControlOnUC = b;
}
public void setSweepDelay(int delay) {
sweepDelay = delay;
}
/*
* (non-Javadoc)
*
* @see org.myrobotlab.service.interfaces.ServoControl#stopServo()
*/
@Override
public void stop() {
isSweeping = false;
sweeper = null;
// TODO Replace with internal logic for motor and PID
// getController().servoSweepStop(this);
broadcastState();
}
public void sweep() {
int min = mapper.getMinX().intValue();
int max = mapper.getMaxX().intValue();
sweep(min, max, 1, 1);
}
public void sweep(int min, int max) {
sweep(min, max, 1, 1);
}
// FIXME - is it really speed control - you don't currently thread for
// fractional speed values
public void sweep(int min, int max, int delay, int step) {
sweep(min, max, delay, step, false);
}
public void sweep(int min, int max, int delay, int step, boolean oneWay) {
this.sweepMin = min;
this.sweepMax = max;
this.sweepDelay = delay;
this.sweepStep = step;
this.sweepOneWay = oneWay;
// FIXME - CONTROLLER TYPE SWITCH
// In case PID is implemented in Arduino, this could happen
if (speedControlOnUC) {
// getController().servoSweepStart(this); // delay &
// step
// implemented
} else {
if (isSweeping) {
stop();
}
sweeper = new Sweeper(getName());
sweeper.start();
}
isSweeping = true;
broadcastState();
}
/**
* Writes a value in microseconds (uS) to the servo, controlling the shaft
* accordingly. On a standard servo, this will set the angle of the shaft.
* On standard servos a parameter value of 1000 is fully counter-clockwise,
* 2000 is fully clockwise, and 1500 is in the middle.
*
* Note that some manufactures do not follow this standard very closely so
* that servos often respond to values between 700 and 2300. Feel free to
* increase these endpoints until the servo no longer continues to increase
* its range. Note however that attempting to drive a servo past its
* endpoints (often indicated by a growling sound) is a high-current state,
* and should be avoided.
*
* Continuous-rotation servos will respond to the writeMicrosecond function
* in an analogous manner to the write function.
*
* @param pos
*/
public void writeMicroseconds(Integer uS) {
log.info("writeMicroseconds({})", uS);
// TODO. This need to be remapped to Motor and PID internal to this
// Service
// getController().servoWriteMicroseconds(this, uS);
lastActivityTime = System.currentTimeMillis();
broadcastState();
}
/*
* @Override public void setPin(int pin) { this.pin = pin; }
*/
@Override
public Integer getPin() {
return this.pin;
}
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
// Runtime.start("webgui", "WebGui");
Runtime.start("gui", "GUIService");
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
arduino.connect("COM3");
Ads1115 ads = (Ads1115) Runtime.start("Ads1115", "Ads1115");
ads.setController(arduino, "1", "0x48");
DiyServo dyiServo = (DiyServo) Runtime.start("DiyServo", "DiyServo");
dyiServo.attach(arduino);
dyiServo.attach((PinArrayControl) ads, 0); // PIN 14 = A0
// Servo Servo = (Servo) Runtime.start("Servo", "Servo");
dyiServo.moveTo(90);
dyiServo.setRest(30);
dyiServo.moveTo(10);
dyiServo.moveTo(90);
dyiServo.moveTo(180);
dyiServo.rest();
dyiServo.setMinMax(30, 160);
dyiServo.moveTo(40);
dyiServo.moveTo(140);
dyiServo.moveTo(180);
dyiServo.setSpeed(0.5);
dyiServo.moveTo(31);
dyiServo.setSpeed(0.2);
dyiServo.moveTo(90);
dyiServo.moveTo(180);
// servo.test();
} catch (Exception e) {
Logging.logError(e);
}
}
@Override
public int getSweepMin() {
return sweepMin;
}
@Override
public int getSweepMax() {
return sweepMax;
}
@Override
public int getSweepStep() {
return sweepStep;
}
@Override
public Integer getTargetOutput() {
return targetOutput;
}
@Override
public double getSpeed() {
return speed;
}
public void attach(String controllerName) throws Exception {
attach((MotorController) Runtime.getService(controllerName));
}
public void attach(MotorController controller) throws Exception {
this.controller = controller;
if (controller != null) {
controllerName = controller.getName();
isControllerSet = true;
}
broadcastState();
}
@Override
public void detach(String controllerName) {
ServiceInterface si = Runtime.getService(controllerName);
if (si instanceof MotorController) {
detach((MotorController) Runtime.getService(controllerName));
}
if (si instanceof PinArrayControl) {
detach((PinArrayControl) Runtime.getService(controllerName));
}
}
public void detach(MotorController controller) {
if (this.controller == controller) {
this.controller = null;
isAttached = false;
isControllerSet = false;
broadcastState();
}
}
public void detach(PinArrayControl pinArrayControl) {
if (this.pinArrayControl == pinArrayControl) {
this.pinArrayControl = null;
isPinArrayControlSet = false;
broadcastState();
}
}
public void setMaxVelocity(int velocity) {
this.maxVelocity = velocity;
}
@Override
public int getMaxVelocity() {
return maxVelocity;
}
@Override
public void onPin(PinData pindata) {
int inputValue = pindata.getValue();
processVariable = 180 * inputValue / resolution;
// log.info(String.format("onPin received value %s converted to %s",
// inputValue, processVariable));
pid.setInput(pidKey, processVariable);
}
@Override
public DeviceController getController() {
return (DeviceController) controller;
}
public void attach(String pinArrayControlName, Integer pin) throws Exception {
attach(pinArrayControlName, (int) pin);
}
@Override
public void attach(String pinArrayControlName, int pin) throws Exception {
attach((PinArrayControl) Runtime.getService(pinArrayControlName), pin);
}
public void attach(PinArrayControl pinArrayControl, int pin) throws Exception {
this.pinArrayControl = pinArrayControl;
if (pinArrayControl != null) {
pinControlName = pinArrayControl.getName();
isPinArrayControlSet = true;
this.pin = pin;
}
// TODO The resolution is a property of the AD converter and should be
// fetched thru a method call like controller.getADResolution()
if (pinArrayControl instanceof Arduino) {
resolution = 1024;
}
if (pinArrayControl instanceof Ads1115) {
resolution = 65536;
}
int rate = 1000 / sampleTime;
pinArrayControl.attach(this, pin);
pinArrayControl.enablePin(pin, rate);
broadcastState();
}
//
// A bunch of unused methods from ServoControl. Perhaps I should create a
// new
// DiyServoControl interface.
// I was hoping to be able to avoid that, but might be a better solution
@Override
public void attach(ServoController controller, int pin, Integer pos) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void detach(ServoController controller) {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin) throws Exception {
// TODO Auto-generated method stub
}
@Override
public int getVelocity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void attach(String controllerName, int pin, Integer pos) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin, Integer pos, Integer velocity) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(String controllerName, int pin, Integer pos, Integer velocity) throws Exception {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(DiyServo.class.getCanonicalName());
meta.addDescription("Controls a motor so that it can be used as a Servo");
meta.addCategory("motor", "control");
meta.addPeer("Motor", "Motor", "Servo motor");
meta.addPeer("Pid", "Pid", "PID service");
return meta;
}
@Override
public double getPowerLevel() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setPowerLevel(double power) {
// TODO Auto-generated method stub
}
@Override
public double getPowerOutput() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getTargetPos() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void lock() {
// TODO Auto-generated method stub
}
@Override
public void move(double power) {
// TODO Auto-generated method stub
}
@Override
public void moveTo(int newPos, Double power) {
// TODO Auto-generated method stub
}
@Override
public void setEncoder(Encoder encoder) {
// TODO Auto-generated method stub
}
@Override
public void stopAndLock() {
// TODO Auto-generated method stub
}
@Override
public void unlock() {
// TODO Auto-generated method stub
}
} | DiyServo. Implemented more methods from MotorControl. | src/org/myrobotlab/service/DiyServo.java | DiyServo. Implemented more methods from MotorControl. |
|
Java | apache-2.0 | f0fa1376589c533b2f3e5cec4c89ff2525883916 | 0 | reportportal/commons-dao | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.commons.querygen;
import com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant;
import com.epam.ta.reportportal.commons.querygen.query.JoinEntity;
import com.epam.ta.reportportal.commons.querygen.query.QuerySupplier;
import com.epam.ta.reportportal.entity.activity.Activity;
import com.epam.ta.reportportal.entity.dashboard.Dashboard;
import com.epam.ta.reportportal.entity.enums.LogLevel;
import com.epam.ta.reportportal.entity.filter.UserFilter;
import com.epam.ta.reportportal.entity.integration.Integration;
import com.epam.ta.reportportal.entity.item.TestItem;
import com.epam.ta.reportportal.entity.launch.Launch;
import com.epam.ta.reportportal.entity.log.Log;
import com.epam.ta.reportportal.entity.project.Project;
import com.epam.ta.reportportal.entity.project.ProjectInfo;
import com.epam.ta.reportportal.entity.user.User;
import com.epam.ta.reportportal.entity.widget.Widget;
import com.epam.ta.reportportal.jooq.enums.JIntegrationGroupEnum;
import com.epam.ta.reportportal.jooq.enums.JLaunchModeEnum;
import com.epam.ta.reportportal.jooq.enums.JStatusEnum;
import com.epam.ta.reportportal.jooq.enums.JTestItemTypeEnum;
import com.google.common.collect.Lists;
import org.jooq.*;
import org.jooq.impl.DSL;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.epam.ta.reportportal.commons.querygen.QueryBuilder.STATISTICS_KEY;
import static com.epam.ta.reportportal.commons.querygen.constant.ActivityCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.IntegrationCriteriaConstant.CRITERIA_INTEGRATION_TYPE;
import static com.epam.ta.reportportal.commons.querygen.constant.IssueCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.ItemAttributeConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.LaunchCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.LogCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.ProjectCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_TYPE;
import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.*;
import static com.epam.ta.reportportal.entity.project.ProjectInfo.*;
import static com.epam.ta.reportportal.jooq.Tables.*;
import static org.jooq.impl.DSL.choose;
import static org.jooq.impl.DSL.field;
public enum FilterTarget {
PROJECT_TARGET(Project.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, PROJECT.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ALLOCATED_STORAGE, PROJECT.ALLOCATED_STORAGE, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ORGANIZATION, PROJECT.ORGANIZATION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_TYPE, PROJECT.PROJECT_TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ATTRIBUTE_NAME, ATTRIBUTE.NAME, String.class, Lists.newArrayList(
JoinEntity.of(PROJECT_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_ATTRIBUTE.PROJECT_ID)),
JoinEntity.of(ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT_ATTRIBUTE.ATTRIBUTE_ID.eq(ATTRIBUTE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(USERS_QUANTITY,
USERS_QUANTITY,
Long.class,
Lists.newArrayList(JoinEntity.of(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID)))
).withAggregateCriteria(DSL.countDistinct(PROJECT_USER.USER_ID).toString()).get(),
new CriteriaHolderBuilder().newBuilder(LAUNCHES_QUANTITY,
LAUNCHES_QUANTITY,
Long.class,
Lists.newArrayList(JoinEntity.of(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID)))
)
.withAggregateCriteria(DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT)
.and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)), LAUNCH.ID)).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(PROJECT.ID,
PROJECT.NAME,
PROJECT.ORGANIZATION,
PROJECT.PROJECT_TYPE,
PROJECT.CREATION_DATE,
PROJECT.METADATA,
PROJECT_ATTRIBUTE.VALUE,
ATTRIBUTE.NAME,
PROJECT_USER.PROJECT_ID,
PROJECT_USER.PROJECT_ROLE,
PROJECT_USER.USER_ID,
USERS.LOGIN
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(PROJECT);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID));
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, PROJECT_USER.USER_ID.eq(USERS.ID));
query.addJoin(PROJECT_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_ATTRIBUTE.PROJECT_ID));
query.addJoin(ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT_ATTRIBUTE.ATTRIBUTE_ID.eq(ATTRIBUTE.ID));
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return PROJECT.ID;
}
},
PROJECT_INFO(ProjectInfo.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, PROJECT.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_TYPE, PROJECT.PROJECT_TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ORGANIZATION, PROJECT.ORGANIZATION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_CREATION_DATE, PROJECT.CREATION_DATE, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(USERS_QUANTITY, USERS_QUANTITY, Long.class)
.withAggregateCriteria(DSL.countDistinct(PROJECT_USER.USER_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(LAST_RUN, LAST_RUN, Timestamp.class)
.withAggregateCriteria(DSL.max(LAUNCH.START_TIME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(LAUNCHES_QUANTITY, LAUNCHES_QUANTITY, Long.class)
.withAggregateCriteria(DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT)
.and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)), LAUNCH.ID)).toString())
.get()
)) {
@Override
public QuerySupplier getQuery() {
SelectQuery<? extends Record> query = DSL.select(selectFields()).getQuery();
addFrom(query);
query.addGroupBy(PROJECT.ID, PROJECT.CREATION_DATE, PROJECT.NAME, PROJECT.PROJECT_TYPE);
QuerySupplier querySupplier = new QuerySupplier(query);
joinTables(querySupplier);
return querySupplier;
}
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(DSL.countDistinct(PROJECT_USER.USER_ID).as(USERS_QUANTITY),
DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT).and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)),
LAUNCH.ID
))
.as(LAUNCHES_QUANTITY),
DSL.max(LAUNCH.START_TIME).as(LAST_RUN),
PROJECT.ID,
PROJECT.CREATION_DATE,
PROJECT.NAME,
PROJECT.PROJECT_TYPE,
PROJECT.ORGANIZATION
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(PROJECT);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID));
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID));
}
@Override
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query) {
throw new UnsupportedOperationException("Doesn't supported for Project Info query");
}
@Override
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query, String... excluding) {
throw new UnsupportedOperationException("Doesn't supported for Project Info query");
}
@Override
protected Field<Long> idField() {
return PROJECT.ID;
}
},
USER_TARGET(User.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, USERS.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER, USERS.LOGIN, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_EMAIL, USERS.EMAIL, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_FULL_NAME, USERS.FULL_NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ROLE, USERS.ROLE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TYPE, USERS.TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_EXPIRED, USERS.EXPIRED, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, PROJECT_USER.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT, PROJECT.NAME, List.class)
.withAggregateCriteria(DSL.arrayAgg(PROJECT.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_LOGIN,
"(" + USERS.METADATA + "-> 'metadata' ->> 'last_login')::DOUBLE PRECISION ",
Long.class
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SYNCHRONIZATION_DATE,
"(" + USERS.METADATA.getQualifiedName().toString() + "-> 'metadata' ->> 'synchronizationDate')::DOUBLE PRECISION ",
Long.class
).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(USERS.ID,
USERS.LOGIN,
USERS.FULL_NAME,
USERS.TYPE,
USERS.ATTACHMENT,
USERS.ATTACHMENT_THUMBNAIL,
USERS.EMAIL,
USERS.EXPIRED,
USERS.PASSWORD,
USERS.ROLE,
USERS.METADATA,
PROJECT.NAME,
PROJECT.PROJECT_TYPE,
PROJECT_USER.PROJECT_ID,
PROJECT_USER.PROJECT_ROLE,
PROJECT_USER.USER_ID
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(USERS);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, USERS.ID.eq(PROJECT_USER.USER_ID));
query.addJoin(PROJECT, JoinType.LEFT_OUTER_JOIN, PROJECT_USER.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return USERS.ID;
}
},
LAUNCH_TARGET(Launch.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, LAUNCH.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, LAUNCH.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, LAUNCH.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_UUID, LAUNCH.UUID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_START_TIME, LAUNCH.START_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_END_TIME, LAUNCH.END_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, LAUNCH.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER_ID, LAUNCH.USER_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_NUMBER, LAUNCH.NUMBER, Integer.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, LAUNCH.LAST_MODIFIED, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_MODE, LAUNCH.MODE, JLaunchModeEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_STATUS, LAUNCH.STATUS, JStatusEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_RETRIES, LAUNCH.HAS_RETRIES, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_KEY,
ITEM_ATTRIBUTE.KEY,
String.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID)))
).withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.KEY).filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false)).toString()).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_VALUE,
ITEM_ATTRIBUTE.VALUE,
String.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID)))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.VALUE)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_COMPOSITE_ATTRIBUTE,
ITEM_ATTRIBUTE.KEY,
List.class,
Lists.newArrayList(JoinEntity.of(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID)))
)
.withAggregateCriteria(DSL.arrayAgg(DSL.concat(DSL.coalesce(LAUNCH_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
LAUNCH_ATTRIBUTE.VALUE
))
.filterWhere(LAUNCH_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER,
USERS.LOGIN,
String.class,
Lists.newArrayList(JoinEntity.of(USERS, JoinType.LEFT_OUTER_JOIN, LAUNCH.USER_ID.eq(USERS.ID)))
).withAggregateCriteria(DSL.max(USERS.LOGIN).toString()).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(LAUNCH.ID,
LAUNCH.UUID,
LAUNCH.NAME,
LAUNCH.DESCRIPTION,
LAUNCH.START_TIME,
LAUNCH.END_TIME,
LAUNCH.PROJECT_ID,
LAUNCH.USER_ID,
LAUNCH.NUMBER,
LAUNCH.LAST_MODIFIED,
LAUNCH.MODE,
LAUNCH.STATUS,
LAUNCH.HAS_RETRIES,
LAUNCH.RERUN,
LAUNCH.APPROXIMATE_DURATION,
ITEM_ATTRIBUTE.KEY,
ITEM_ATTRIBUTE.VALUE,
ITEM_ATTRIBUTE.SYSTEM,
STATISTICS.S_COUNTER,
STATISTICS_FIELD.NAME,
USERS.ID,
USERS.LOGIN
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(LAUNCH);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID));
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, LAUNCH.USER_ID.eq(USERS.ID));
query.addJoin(STATISTICS, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(STATISTICS.LAUNCH_ID));
query.addJoin(STATISTICS_FIELD, JoinType.LEFT_OUTER_JOIN, STATISTICS.STATISTICS_FIELD_ID.eq(STATISTICS_FIELD.SF_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return LAUNCH.ID;
}
},
TEST_ITEM_TARGET(TestItem.class,
Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, LAUNCH.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, TEST_ITEM.ITEM_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, TEST_ITEM.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(TestItemCriteriaConstant.CRITERIA_TYPE, TEST_ITEM.TYPE, JTestItemTypeEnum.class)
.withAggregateCriteria(DSL.max(TEST_ITEM.TYPE).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_START_TIME, TEST_ITEM.START_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, TEST_ITEM.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, TEST_ITEM.LAST_MODIFIED, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATH, TEST_ITEM.PATH, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_UNIQUE_ID, TEST_ITEM.UNIQUE_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_UUID, TEST_ITEM.UUID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_CASE_ID, TEST_ITEM.TEST_CASE_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_CASE_HASH, TEST_ITEM.TEST_CASE_HASH, Integer.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARENT_ID, TEST_ITEM.PARENT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_CHILDREN, TEST_ITEM.HAS_CHILDREN, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_RETRIES, TEST_ITEM.HAS_RETRIES, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_STATS, TEST_ITEM.HAS_STATS, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_STATUS,
TEST_ITEM_RESULTS.STATUS,
JStatusEnum.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
)
.withAggregateCriteria(DSL.max(TEST_ITEM_RESULTS.STATUS).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_END_TIME,
TEST_ITEM_RESULTS.END_TIME,
Timestamp.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DURATION,
TEST_ITEM_RESULTS.DURATION,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARAMETER_KEY,
PARAMETER.KEY,
String.class,
Lists.newArrayList(JoinEntity.of(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARAMETER_VALUE,
PARAMETER.VALUE,
String.class,
Lists.newArrayList(JoinEntity.of(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_ID, ISSUE.ISSUE_ID, Long.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_TYPE, ISSUE_TYPE.LOCATOR, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_AUTO_ANALYZED,
ISSUE.AUTO_ANALYZED,
Boolean.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_IGNORE_ANALYZER,
ISSUE.IGNORE_ANALYZER,
Boolean.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_COMMENT,
ISSUE.ISSUE_DESCRIPTION,
String.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_LOCATOR, ISSUE_TYPE.LOCATOR, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_GROUP_ID,
ISSUE_TYPE.ISSUE_GROUP_ID,
Short.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_ID, TEST_ITEM.LAUNCH_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_MODE, LAUNCH.MODE, JLaunchModeEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARENT_ID, TEST_ITEM.PARENT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_ID, TEST_ITEM.RETRY_OF, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_KEY,
ITEM_ATTRIBUTE.KEY,
List.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)
))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.KEY)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_VALUE,
ITEM_ATTRIBUTE.VALUE,
List.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)
))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.VALUE)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_COMPOSITE_ATTRIBUTE, ITEM_ATTRIBUTE.KEY, List.class, Lists.newArrayList(
JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)),
JoinEntity.of(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID))
))
.withAggregateCriteria(DSL.field("array_cat({0}, {1})::varchar[]",
DSL.arrayAgg(DSL.concat(DSL.coalesce(ITEM_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
ITEM_ATTRIBUTE.VALUE
))
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false)),
DSL.arrayAgg(DSL.concat(DSL.coalesce(LAUNCH_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
LAUNCH_ATTRIBUTE.VALUE
))
.filterWhere(LAUNCH_ATTRIBUTE.SYSTEM.eq(false))
).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATTERN_TEMPLATE_NAME,
PATTERN_TEMPLATE.NAME,
List.class,
Lists.newArrayList(
JoinEntity.of(PATTERN_TEMPLATE_TEST_ITEM,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(PATTERN_TEMPLATE_TEST_ITEM.ITEM_ID)
),
JoinEntity.of(PATTERN_TEMPLATE,
JoinType.LEFT_OUTER_JOIN,
PATTERN_TEMPLATE_TEST_ITEM.PATTERN_ID.eq(PATTERN_TEMPLATE.ID)
)
)
).withAggregateCriteria(DSL.arrayAggDistinct(PATTERN_TEMPLATE.NAME).toString()).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TICKET_ID, TICKET.TICKET_ID, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_ID.eq(ISSUE_TICKET.ISSUE_ID)),
JoinEntity.of(TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE_TICKET.TICKET_ID.eq(TICKET.ID))
)).withAggregateCriteria(DSL.arrayAggDistinct(TICKET.TICKET_ID).toString()).get()
)
) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(TEST_ITEM.ITEM_ID,
TEST_ITEM.NAME,
TEST_ITEM.CODE_REF,
TEST_ITEM.TYPE,
TEST_ITEM.START_TIME,
TEST_ITEM.DESCRIPTION,
TEST_ITEM.LAST_MODIFIED,
TEST_ITEM.PATH,
TEST_ITEM.UNIQUE_ID,
TEST_ITEM.UUID,
TEST_ITEM.TEST_CASE_ID,
TEST_ITEM.TEST_CASE_HASH,
TEST_ITEM.PARENT_ID,
TEST_ITEM.RETRY_OF,
TEST_ITEM.HAS_CHILDREN,
TEST_ITEM.HAS_STATS,
TEST_ITEM.HAS_RETRIES,
TEST_ITEM.LAUNCH_ID,
TEST_ITEM_RESULTS.STATUS,
TEST_ITEM_RESULTS.END_TIME,
TEST_ITEM_RESULTS.DURATION,
ITEM_ATTRIBUTE.KEY,
ITEM_ATTRIBUTE.VALUE,
ITEM_ATTRIBUTE.SYSTEM,
PARAMETER.ITEM_ID,
PARAMETER.KEY,
PARAMETER.VALUE,
STATISTICS_FIELD.NAME,
STATISTICS.S_COUNTER,
ISSUE.ISSUE_ID,
ISSUE.AUTO_ANALYZED,
ISSUE.IGNORE_ANALYZER,
ISSUE.ISSUE_DESCRIPTION,
ISSUE_TYPE.LOCATOR,
ISSUE_TYPE.ABBREVIATION,
ISSUE_TYPE.HEX_COLOR,
ISSUE_TYPE.ISSUE_NAME,
ISSUE_GROUP.ISSUE_GROUP_,
TICKET.ID,
TICKET.BTS_PROJECT,
TICKET.BTS_URL,
TICKET.TICKET_ID,
TICKET.URL,
PATTERN_TEMPLATE.ID,
PATTERN_TEMPLATE.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(TEST_ITEM);
}
@Override
protected Field<Long> idField() {
return TEST_ITEM.ITEM_ID;
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.LAUNCH_ID.eq(LAUNCH.ID));
query.addJoin(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID));
query.addJoin(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID));
query.addJoin(STATISTICS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(STATISTICS.ITEM_ID));
query.addJoin(STATISTICS_FIELD, JoinType.LEFT_OUTER_JOIN, STATISTICS.STATISTICS_FIELD_ID.eq(STATISTICS_FIELD.SF_ID));
query.addJoin(PATTERN_TEMPLATE_TEST_ITEM, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PATTERN_TEMPLATE_TEST_ITEM.ITEM_ID));
query.addJoin(PATTERN_TEMPLATE, JoinType.LEFT_OUTER_JOIN, PATTERN_TEMPLATE_TEST_ITEM.PATTERN_ID.eq(PATTERN_TEMPLATE.ID));
query.addJoin(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID));
query.addJoin(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID));
query.addJoin(ISSUE_GROUP, JoinType.LEFT_OUTER_JOIN, ISSUE_TYPE.ISSUE_GROUP_ID.eq(ISSUE_GROUP.ISSUE_GROUP_ID));
query.addJoin(ISSUE_TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_ID.eq(ISSUE_TICKET.ISSUE_ID));
query.addJoin(TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE_TICKET.TICKET_ID.eq(TICKET.ID));
query.addJoin(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID));
query.addJoin(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.LAUNCH_ID.eq(LAUNCH.ID));
}
},
LOG_TARGET(Log.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, LOG.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_ID, LOG.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_TIME, LOG.LOG_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, LOG.LAST_MODIFIED, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_LEVEL, LOG.LOG_LEVEL, LogLevel.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_MESSAGE, LOG.LOG_MESSAGE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_ITEM_ID, LOG.ITEM_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_LAUNCH_ID, LOG.LAUNCH_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_BINARY_CONTENT,
ATTACHMENT.FILE_ID,
String.class,
Lists.newArrayList(JoinEntity.of(ATTACHMENT, JoinType.LEFT_OUTER_JOIN, LOG.ATTACHMENT_ID.eq(ATTACHMENT.ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_LAUNCH_ID,
TEST_ITEM.LAUNCH_ID,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_ID,
TEST_ITEM.RETRY_OF,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_LAUNCH_ID,
TEST_ITEM.as(RETRY_PARENT).LAUNCH_ID,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)), JoinEntity.of(
TEST_ITEM.as(RETRY_PARENT),
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.RETRY_OF.eq(TEST_ITEM.as(RETRY_PARENT).ITEM_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATH,
TEST_ITEM.PATH,
String.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_STATUS, TEST_ITEM_RESULTS.STATUS, JStatusEnum.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)),
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_AUTO_ANALYZED, ISSUE.AUTO_ANALYZED, Boolean.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)),
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(LOG.ID,
LOG.LOG_TIME,
LOG.LOG_MESSAGE,
LOG.LAST_MODIFIED,
LOG.LOG_LEVEL,
LOG.ITEM_ID,
LOG.LAUNCH_ID,
LOG.ATTACHMENT_ID,
ATTACHMENT.ID,
ATTACHMENT.FILE_ID,
ATTACHMENT.THUMBNAIL_ID,
ATTACHMENT.CONTENT_TYPE,
ATTACHMENT.FILE_SIZE,
ATTACHMENT.PROJECT_ID,
ATTACHMENT.LAUNCH_ID,
ATTACHMENT.ITEM_ID
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(LOG);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID));
query.addJoin(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID));
query.addJoin(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID));
query.addJoin(ATTACHMENT, JoinType.LEFT_OUTER_JOIN, LOG.ATTACHMENT_ID.eq(ATTACHMENT.ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return LOG.ID;
}
},
ACTIVITY_TARGET(Activity.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, ACTIVITY.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, ACTIVITY.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, Long.class)
.withAggregateCriteria(DSL.max(PROJECT.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER_ID, ACTIVITY.USER_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ENTITY, ACTIVITY.ENTITY, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ACTION, ACTIVITY.ACTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOGIN, ACTIVITY.USERNAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_CREATION_DATE, ACTIVITY.CREATION_DATE, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OBJECT_ID, ACTIVITY.OBJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER, USERS.LOGIN, String.class)
.withAggregateCriteria(DSL.max(USERS.LOGIN).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OBJECT_NAME, ACTIVITY.DETAILS + " ->> 'objectName'", String.class).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(ACTIVITY.ID,
ACTIVITY.PROJECT_ID,
ACTIVITY.USERNAME,
ACTIVITY.USER_ID,
ACTIVITY.ENTITY,
ACTIVITY.ACTION,
ACTIVITY.CREATION_DATE,
ACTIVITY.DETAILS,
ACTIVITY.OBJECT_ID,
USERS.LOGIN,
PROJECT.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(ACTIVITY);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, ACTIVITY.USER_ID.eq(USERS.ID));
query.addJoin(PROJECT, JoinType.JOIN, ACTIVITY.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return ACTIVITY.ID;
}
},
INTEGRATION_TARGET(Integration.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, INTEGRATION.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, INTEGRATION.PROJECT_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_INTEGRATION_TYPE, INTEGRATION_TYPE.GROUP_TYPE, JIntegrationGroupEnum.class)
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, INTEGRATION_TYPE.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(INTEGRATION.ID,
INTEGRATION.NAME,
INTEGRATION.PROJECT_ID,
INTEGRATION.TYPE,
INTEGRATION.PARAMS,
INTEGRATION.CREATOR,
INTEGRATION.CREATION_DATE,
INTEGRATION_TYPE.NAME,
INTEGRATION_TYPE.GROUP_TYPE,
PROJECT.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(INTEGRATION);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(INTEGRATION_TYPE, JoinType.JOIN, INTEGRATION.TYPE.eq(INTEGRATION_TYPE.ID));
query.addJoin(PROJECT, JoinType.JOIN, INTEGRATION.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return DSL.cast(INTEGRATION.ID, Long.class);
}
},
DASHBOARD_TARGET(Dashboard.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, DASHBOARD.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, DASHBOARD.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.PROJECT_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(DASHBOARD.ID,
DASHBOARD.NAME,
DASHBOARD.DESCRIPTION,
DASHBOARD.CREATION_DATE,
DASHBOARD_WIDGET.WIDGET_OWNER,
DASHBOARD_WIDGET.IS_CREATED_ON,
DASHBOARD_WIDGET.WIDGET_ID,
DASHBOARD_WIDGET.WIDGET_NAME,
DASHBOARD_WIDGET.WIDGET_TYPE,
DASHBOARD_WIDGET.WIDGET_HEIGHT,
DASHBOARD_WIDGET.WIDGET_WIDTH,
DASHBOARD_WIDGET.WIDGET_POSITION_X,
DASHBOARD_WIDGET.WIDGET_POSITION_Y,
DASHBOARD_WIDGET.SHARE,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(DASHBOARD);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(DASHBOARD_WIDGET, JoinType.LEFT_OUTER_JOIN, DASHBOARD.ID.eq(DASHBOARD_WIDGET.DASHBOARD_ID));
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, DASHBOARD.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, DASHBOARD.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return DASHBOARD.ID.cast(Long.class);
}
},
WIDGET_TARGET(Widget.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, WIDGET.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, WIDGET.NAME, String.class)
.withAggregateCriteria(DSL.max(WIDGET.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, WIDGET.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(WIDGET.ID,
WIDGET.NAME,
WIDGET.WIDGET_TYPE,
WIDGET.DESCRIPTION,
WIDGET.ITEMS_COUNT,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(WIDGET);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, WIDGET.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, WIDGET.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return WIDGET.ID;
}
},
USER_FILTER_TARGET(UserFilter.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, FILTER.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, FILTER.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.PROJECT_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(FILTER.ID,
FILTER.NAME,
FILTER.TARGET,
FILTER.DESCRIPTION,
FILTER_CONDITION.SEARCH_CRITERIA,
FILTER_CONDITION.CONDITION,
FILTER_CONDITION.VALUE,
FILTER_CONDITION.NEGATIVE,
FILTER_SORT.FIELD,
FILTER_SORT.DIRECTION,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(FILTER);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, FILTER.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(FILTER_CONDITION, JoinType.LEFT_OUTER_JOIN, FILTER.ID.eq(FILTER_CONDITION.FILTER_ID));
query.addJoin(FILTER_SORT, JoinType.LEFT_OUTER_JOIN, FILTER.ID.eq(FILTER_SORT.FILTER_ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, FILTER.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return FILTER.ID;
}
};
public static final String FILTERED_QUERY = "filtered";
public static final String FILTERED_ID = "id";
private Class<?> clazz;
private List<CriteriaHolder> criteriaHolders;
FilterTarget(Class<?> clazz, List<CriteriaHolder> criteriaHolders) {
this.clazz = clazz;
this.criteriaHolders = criteriaHolders;
}
public QuerySupplier getQuery() {
SelectQuery<? extends Record> query = DSL.select(idField().as(FILTERED_ID)).getQuery();
addFrom(query);
query.addGroupBy(idField());
QuerySupplier querySupplier = new QuerySupplier(query);
joinTablesForFilter(querySupplier);
return querySupplier;
}
protected abstract Collection<? extends SelectField> selectFields();
protected abstract void addFrom(SelectQuery<? extends Record> query);
protected abstract void joinTables(QuerySupplier query);
protected void joinTablesForFilter(QuerySupplier query) {
joinTables(query);
}
protected abstract Field<Long> idField();
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query) {
SelectQuery<Record> wrappedQuery = DSL.with(FILTERED_QUERY).as(query).select(selectFields()).getQuery();
addFrom(wrappedQuery);
QuerySupplier querySupplier = new QuerySupplier(wrappedQuery);
querySupplier.addJoin(DSL.table(DSL.name(FILTERED_QUERY)),
JoinType.JOIN,
idField().eq(field(DSL.name(FILTERED_QUERY, FILTERED_ID), Long.class))
);
joinTables(querySupplier);
return querySupplier;
}
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query, String... excluding) {
List<String> excludingFields = Lists.newArrayList(excluding);
List<? extends SelectField> fields = selectFields().stream()
.filter(it -> !excludingFields.contains(it.getName()))
.collect(Collectors.toList());
SelectQuery<Record> wrappedQuery = DSL.with(FILTERED_QUERY).as(query).select(fields).getQuery();
addFrom(wrappedQuery);
QuerySupplier querySupplier = new QuerySupplier(wrappedQuery);
querySupplier.addJoin(DSL.table(DSL.name(FILTERED_QUERY)),
JoinType.JOIN,
idField().eq(field(DSL.name(FILTERED_QUERY, FILTERED_ID), Long.class))
);
joinTables(querySupplier);
return querySupplier;
}
public Class<?> getClazz() {
return clazz;
}
public List<CriteriaHolder> getCriteriaHolders() {
return criteriaHolders;
}
public Optional<CriteriaHolder> getCriteriaByFilter(String filterCriteria) {
/*
creates criteria holder for statistics search criteria cause there
can be custom statistics so we can't know it till this moment
*/
if (filterCriteria != null && filterCriteria.startsWith(STATISTICS_KEY)) {
return Optional.of(new CriteriaHolderBuilder().newBuilder(filterCriteria,
DSL.coalesce(DSL.max(STATISTICS.S_COUNTER).filterWhere(STATISTICS_FIELD.NAME.eq(filterCriteria)), 0).toString(),
Long.class
).get());
}
return criteriaHolders.stream().filter(holder -> holder.getFilterCriteria().equals(filterCriteria)).findAny();
}
public static FilterTarget findByClass(Class<?> clazz) {
return Arrays.stream(values())
.filter(val -> val.clazz.equals(clazz))
.findAny()
.orElseThrow(() -> new IllegalArgumentException(String.format("No target query builder for clazz %s", clazz)));
}
}
| src/main/java/com/epam/ta/reportportal/commons/querygen/FilterTarget.java | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.commons.querygen;
import com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant;
import com.epam.ta.reportportal.commons.querygen.query.JoinEntity;
import com.epam.ta.reportportal.commons.querygen.query.QuerySupplier;
import com.epam.ta.reportportal.entity.activity.Activity;
import com.epam.ta.reportportal.entity.dashboard.Dashboard;
import com.epam.ta.reportportal.entity.enums.LogLevel;
import com.epam.ta.reportportal.entity.filter.UserFilter;
import com.epam.ta.reportportal.entity.integration.Integration;
import com.epam.ta.reportportal.entity.item.TestItem;
import com.epam.ta.reportportal.entity.launch.Launch;
import com.epam.ta.reportportal.entity.log.Log;
import com.epam.ta.reportportal.entity.project.Project;
import com.epam.ta.reportportal.entity.project.ProjectInfo;
import com.epam.ta.reportportal.entity.user.User;
import com.epam.ta.reportportal.entity.widget.Widget;
import com.epam.ta.reportportal.jooq.enums.JIntegrationGroupEnum;
import com.epam.ta.reportportal.jooq.enums.JLaunchModeEnum;
import com.epam.ta.reportportal.jooq.enums.JStatusEnum;
import com.epam.ta.reportportal.jooq.enums.JTestItemTypeEnum;
import com.google.common.collect.Lists;
import org.jooq.*;
import org.jooq.impl.DSL;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.epam.ta.reportportal.commons.querygen.QueryBuilder.STATISTICS_KEY;
import static com.epam.ta.reportportal.commons.querygen.constant.ActivityCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.IntegrationCriteriaConstant.CRITERIA_INTEGRATION_TYPE;
import static com.epam.ta.reportportal.commons.querygen.constant.IssueCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.ItemAttributeConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.LaunchCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.LogCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.ProjectCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.*;
import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_TYPE;
import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.*;
import static com.epam.ta.reportportal.entity.project.ProjectInfo.*;
import static com.epam.ta.reportportal.jooq.Tables.*;
import static org.jooq.impl.DSL.choose;
import static org.jooq.impl.DSL.field;
public enum FilterTarget {
PROJECT_TARGET(Project.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, PROJECT.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ALLOCATED_STORAGE, PROJECT.ALLOCATED_STORAGE, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ORGANIZATION, PROJECT.ORGANIZATION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_TYPE, PROJECT.PROJECT_TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ATTRIBUTE_NAME, ATTRIBUTE.NAME, String.class, Lists.newArrayList(
JoinEntity.of(PROJECT_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_ATTRIBUTE.PROJECT_ID)),
JoinEntity.of(ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT_ATTRIBUTE.ATTRIBUTE_ID.eq(ATTRIBUTE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(USERS_QUANTITY,
USERS_QUANTITY,
Long.class,
Lists.newArrayList(JoinEntity.of(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID)))
)
.withAggregateCriteria(DSL.countDistinct(PROJECT_USER.USER_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(LAUNCHES_QUANTITY,
LAUNCHES_QUANTITY,
Long.class,
Lists.newArrayList(JoinEntity.of(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID)))
)
.withAggregateCriteria(DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT)
.and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)), LAUNCH.ID)).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(PROJECT.ID,
PROJECT.NAME,
PROJECT.ORGANIZATION,
PROJECT.PROJECT_TYPE,
PROJECT.CREATION_DATE,
PROJECT.METADATA,
PROJECT_ATTRIBUTE.VALUE,
ATTRIBUTE.NAME,
PROJECT_USER.PROJECT_ID,
PROJECT_USER.PROJECT_ROLE,
PROJECT_USER.USER_ID,
USERS.LOGIN
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(PROJECT);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID));
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, PROJECT_USER.USER_ID.eq(USERS.ID));
query.addJoin(PROJECT_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_ATTRIBUTE.PROJECT_ID));
query.addJoin(ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, PROJECT_ATTRIBUTE.ATTRIBUTE_ID.eq(ATTRIBUTE.ID));
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return PROJECT.ID;
}
},
PROJECT_INFO(ProjectInfo.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, PROJECT.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_TYPE, PROJECT.PROJECT_TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ORGANIZATION, PROJECT.ORGANIZATION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_CREATION_DATE, PROJECT.CREATION_DATE, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(USERS_QUANTITY, USERS_QUANTITY, Long.class)
.withAggregateCriteria(DSL.countDistinct(PROJECT_USER.USER_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(LAST_RUN, LAST_RUN, Timestamp.class)
.withAggregateCriteria(DSL.max(LAUNCH.START_TIME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(LAUNCHES_QUANTITY, LAUNCHES_QUANTITY, Long.class)
.withAggregateCriteria(DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT)
.and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)), LAUNCH.ID)).toString())
.get()
)) {
@Override
public QuerySupplier getQuery() {
SelectQuery<? extends Record> query = DSL.select(selectFields()).getQuery();
addFrom(query);
query.addGroupBy(PROJECT.ID, PROJECT.CREATION_DATE, PROJECT.NAME, PROJECT.PROJECT_TYPE);
QuerySupplier querySupplier = new QuerySupplier(query);
joinTables(querySupplier);
return querySupplier;
}
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(DSL.countDistinct(PROJECT_USER.USER_ID).as(USERS_QUANTITY),
DSL.countDistinct(choose().when(LAUNCH.MODE.eq(JLaunchModeEnum.DEFAULT).and(LAUNCH.STATUS.ne(JStatusEnum.IN_PROGRESS)),
LAUNCH.ID
))
.as(LAUNCHES_QUANTITY),
DSL.max(LAUNCH.START_TIME).as(LAST_RUN),
PROJECT.ID,
PROJECT.CREATION_DATE,
PROJECT.NAME,
PROJECT.PROJECT_TYPE,
PROJECT.ORGANIZATION
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(PROJECT);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(PROJECT_USER.PROJECT_ID));
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, PROJECT.ID.eq(LAUNCH.PROJECT_ID));
}
@Override
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query) {
throw new UnsupportedOperationException("Doesn't supported for Project Info query");
}
@Override
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query, String... excluding) {
throw new UnsupportedOperationException("Doesn't supported for Project Info query");
}
@Override
protected Field<Long> idField() {
return PROJECT.ID;
}
},
USER_TARGET(User.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, USERS.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER, USERS.LOGIN, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_EMAIL, USERS.EMAIL, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_FULL_NAME, USERS.FULL_NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ROLE, USERS.ROLE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TYPE, USERS.TYPE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_EXPIRED, USERS.EXPIRED, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, PROJECT_USER.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT, PROJECT.NAME, List.class)
.withAggregateCriteria(DSL.arrayAgg(PROJECT.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_LOGIN,
"(" + USERS.METADATA + "-> 'metadata' ->> 'last_login')::DOUBLE PRECISION ",
Long.class
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SYNCHRONIZATION_DATE,
"(" + USERS.METADATA.getQualifiedName().toString() + "-> 'metadata' ->> 'synchronizationDate')::DOUBLE PRECISION ",
Long.class
).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(USERS.ID,
USERS.LOGIN,
USERS.FULL_NAME,
USERS.TYPE,
USERS.ATTACHMENT,
USERS.ATTACHMENT_THUMBNAIL,
USERS.EMAIL,
USERS.EXPIRED,
USERS.PASSWORD,
USERS.ROLE,
USERS.METADATA,
PROJECT.NAME,
PROJECT.PROJECT_TYPE,
PROJECT_USER.PROJECT_ID,
PROJECT_USER.PROJECT_ROLE,
PROJECT_USER.USER_ID
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(USERS);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(PROJECT_USER, JoinType.LEFT_OUTER_JOIN, USERS.ID.eq(PROJECT_USER.USER_ID));
query.addJoin(PROJECT, JoinType.LEFT_OUTER_JOIN, PROJECT_USER.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return USERS.ID;
}
},
LAUNCH_TARGET(Launch.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, LAUNCH.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, LAUNCH.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, LAUNCH.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_UUID, LAUNCH.UUID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_START_TIME, LAUNCH.START_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_END_TIME, LAUNCH.END_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, LAUNCH.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER_ID, LAUNCH.USER_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_NUMBER, LAUNCH.NUMBER, Integer.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, LAUNCH.LAST_MODIFIED, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_MODE, LAUNCH.MODE, JLaunchModeEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_STATUS, LAUNCH.STATUS, JStatusEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_RETRIES, LAUNCH.HAS_RETRIES, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_KEY,
ITEM_ATTRIBUTE.KEY,
String.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID)))
).withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.KEY).filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false)).toString()).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_VALUE,
ITEM_ATTRIBUTE.VALUE,
String.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID)))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.VALUE)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_COMPOSITE_ATTRIBUTE,
ITEM_ATTRIBUTE.KEY,
List.class,
Lists.newArrayList(JoinEntity.of(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID)))
)
.withAggregateCriteria(DSL.field("array_cat({0}, {1})::varchar[]",
DSL.arrayAgg(DSL.concat(DSL.coalesce(ITEM_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
ITEM_ATTRIBUTE.VALUE
))
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false)),
DSL.arrayAgg(DSL.concat(DSL.coalesce(LAUNCH_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
LAUNCH_ATTRIBUTE.VALUE
))
.filterWhere(LAUNCH_ATTRIBUTE.SYSTEM.eq(false))
).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER,
USERS.LOGIN,
String.class,
Lists.newArrayList(JoinEntity.of(USERS, JoinType.LEFT_OUTER_JOIN, LAUNCH.USER_ID.eq(USERS.ID)))
).withAggregateCriteria(DSL.max(USERS.LOGIN).toString()).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(LAUNCH.ID,
LAUNCH.UUID,
LAUNCH.NAME,
LAUNCH.DESCRIPTION,
LAUNCH.START_TIME,
LAUNCH.END_TIME,
LAUNCH.PROJECT_ID,
LAUNCH.USER_ID,
LAUNCH.NUMBER,
LAUNCH.LAST_MODIFIED,
LAUNCH.MODE,
LAUNCH.STATUS,
LAUNCH.HAS_RETRIES,
LAUNCH.RERUN,
LAUNCH.APPROXIMATE_DURATION,
ITEM_ATTRIBUTE.KEY,
ITEM_ATTRIBUTE.VALUE,
ITEM_ATTRIBUTE.SYSTEM,
STATISTICS.S_COUNTER,
STATISTICS_FIELD.NAME,
USERS.ID,
USERS.LOGIN
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(LAUNCH);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(ITEM_ATTRIBUTE.LAUNCH_ID));
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, LAUNCH.USER_ID.eq(USERS.ID));
query.addJoin(STATISTICS, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(STATISTICS.LAUNCH_ID));
query.addJoin(STATISTICS_FIELD, JoinType.LEFT_OUTER_JOIN, STATISTICS.STATISTICS_FIELD_ID.eq(STATISTICS_FIELD.SF_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return LAUNCH.ID;
}
},
TEST_ITEM_TARGET(TestItem.class,
Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, LAUNCH.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, TEST_ITEM.ITEM_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, TEST_ITEM.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(TestItemCriteriaConstant.CRITERIA_TYPE, TEST_ITEM.TYPE, JTestItemTypeEnum.class)
.withAggregateCriteria(DSL.max(TEST_ITEM.TYPE).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_START_TIME, TEST_ITEM.START_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, TEST_ITEM.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, TEST_ITEM.LAST_MODIFIED, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATH, TEST_ITEM.PATH, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_UNIQUE_ID, TEST_ITEM.UNIQUE_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_UUID, TEST_ITEM.UUID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_CASE_ID, TEST_ITEM.TEST_CASE_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_CASE_HASH, TEST_ITEM.TEST_CASE_HASH, Integer.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARENT_ID, TEST_ITEM.PARENT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_CHILDREN, TEST_ITEM.HAS_CHILDREN, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_RETRIES, TEST_ITEM.HAS_RETRIES, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_HAS_STATS, TEST_ITEM.HAS_STATS, Boolean.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_STATUS,
TEST_ITEM_RESULTS.STATUS,
JStatusEnum.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
)
.withAggregateCriteria(DSL.max(TEST_ITEM_RESULTS.STATUS).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_END_TIME,
TEST_ITEM_RESULTS.END_TIME,
Timestamp.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DURATION,
TEST_ITEM_RESULTS.DURATION,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARAMETER_KEY,
PARAMETER.KEY,
String.class,
Lists.newArrayList(JoinEntity.of(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARAMETER_VALUE,
PARAMETER.VALUE,
String.class,
Lists.newArrayList(JoinEntity.of(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_ID, ISSUE.ISSUE_ID, Long.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_TYPE, ISSUE_TYPE.LOCATOR, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_AUTO_ANALYZED,
ISSUE.AUTO_ANALYZED,
Boolean.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_IGNORE_ANALYZER,
ISSUE.IGNORE_ANALYZER,
Boolean.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_COMMENT,
ISSUE.ISSUE_DESCRIPTION,
String.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_LOCATOR, ISSUE_TYPE.LOCATOR, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_GROUP_ID,
ISSUE_TYPE.ISSUE_GROUP_ID,
Short.class,
Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)
),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID))
)
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_ID, TEST_ITEM.LAUNCH_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAUNCH_MODE, LAUNCH.MODE, JLaunchModeEnum.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PARENT_ID, TEST_ITEM.PARENT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_ID, TEST_ITEM.RETRY_OF, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_KEY,
ITEM_ATTRIBUTE.KEY,
List.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)
))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.KEY)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_ATTRIBUTE_VALUE,
ITEM_ATTRIBUTE.VALUE,
List.class,
Lists.newArrayList(JoinEntity.of(ITEM_ATTRIBUTE,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)
))
)
.withAggregateCriteria(DSL.arrayAggDistinct(ITEM_ATTRIBUTE.VALUE)
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false))
.toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_COMPOSITE_ATTRIBUTE, ITEM_ATTRIBUTE.KEY, List.class, Lists.newArrayList(
JoinEntity.of(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID)),
JoinEntity.of(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID))
))
.withAggregateCriteria(DSL.field("array_cat({0}, {1})::varchar[]",
DSL.arrayAgg(DSL.concat(DSL.coalesce(ITEM_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
ITEM_ATTRIBUTE.VALUE
))
.filterWhere(ITEM_ATTRIBUTE.SYSTEM.eq(false)),
DSL.arrayAgg(DSL.concat(DSL.coalesce(LAUNCH_ATTRIBUTE.KEY, ""),
DSL.val(KEY_VALUE_SEPARATOR),
LAUNCH_ATTRIBUTE.VALUE
))
.filterWhere(LAUNCH_ATTRIBUTE.SYSTEM.eq(false))
).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATTERN_TEMPLATE_NAME,
PATTERN_TEMPLATE.NAME,
List.class,
Lists.newArrayList(JoinEntity.of(PATTERN_TEMPLATE_TEST_ITEM,
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.ITEM_ID.eq(PATTERN_TEMPLATE_TEST_ITEM.ITEM_ID)
), JoinEntity.of(PATTERN_TEMPLATE,
JoinType.LEFT_OUTER_JOIN,
PATTERN_TEMPLATE_TEST_ITEM.PATTERN_ID.eq(PATTERN_TEMPLATE.ID)
))
).withAggregateCriteria(DSL.arrayAggDistinct(PATTERN_TEMPLATE.NAME).toString()).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TICKET_ID, TICKET.TICKET_ID, String.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID)),
JoinEntity.of(ISSUE_TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_ID.eq(ISSUE_TICKET.ISSUE_ID)),
JoinEntity.of(TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE_TICKET.TICKET_ID.eq(TICKET.ID))
)).withAggregateCriteria(DSL.arrayAggDistinct(TICKET.TICKET_ID).toString()).get()
)
) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(TEST_ITEM.ITEM_ID,
TEST_ITEM.NAME,
TEST_ITEM.CODE_REF,
TEST_ITEM.TYPE,
TEST_ITEM.START_TIME,
TEST_ITEM.DESCRIPTION,
TEST_ITEM.LAST_MODIFIED,
TEST_ITEM.PATH,
TEST_ITEM.UNIQUE_ID,
TEST_ITEM.UUID,
TEST_ITEM.TEST_CASE_ID,
TEST_ITEM.TEST_CASE_HASH,
TEST_ITEM.PARENT_ID,
TEST_ITEM.RETRY_OF,
TEST_ITEM.HAS_CHILDREN,
TEST_ITEM.HAS_STATS,
TEST_ITEM.HAS_RETRIES,
TEST_ITEM.LAUNCH_ID,
TEST_ITEM_RESULTS.STATUS,
TEST_ITEM_RESULTS.END_TIME,
TEST_ITEM_RESULTS.DURATION,
ITEM_ATTRIBUTE.KEY,
ITEM_ATTRIBUTE.VALUE,
ITEM_ATTRIBUTE.SYSTEM,
PARAMETER.ITEM_ID,
PARAMETER.KEY,
PARAMETER.VALUE,
STATISTICS_FIELD.NAME,
STATISTICS.S_COUNTER,
ISSUE.ISSUE_ID,
ISSUE.AUTO_ANALYZED,
ISSUE.IGNORE_ANALYZER,
ISSUE.ISSUE_DESCRIPTION,
ISSUE_TYPE.LOCATOR,
ISSUE_TYPE.ABBREVIATION,
ISSUE_TYPE.HEX_COLOR,
ISSUE_TYPE.ISSUE_NAME,
ISSUE_GROUP.ISSUE_GROUP_,
TICKET.ID,
TICKET.BTS_PROJECT,
TICKET.BTS_URL,
TICKET.TICKET_ID,
TICKET.URL,
PATTERN_TEMPLATE.ID,
PATTERN_TEMPLATE.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(TEST_ITEM);
}
@Override
protected Field<Long> idField() {
return TEST_ITEM.ITEM_ID;
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.LAUNCH_ID.eq(LAUNCH.ID));
query.addJoin(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID));
query.addJoin(ITEM_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(ITEM_ATTRIBUTE.ITEM_ID));
query.addJoin(STATISTICS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(STATISTICS.ITEM_ID));
query.addJoin(STATISTICS_FIELD, JoinType.LEFT_OUTER_JOIN, STATISTICS.STATISTICS_FIELD_ID.eq(STATISTICS_FIELD.SF_ID));
query.addJoin(PATTERN_TEMPLATE_TEST_ITEM, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PATTERN_TEMPLATE_TEST_ITEM.ITEM_ID));
query.addJoin(PATTERN_TEMPLATE, JoinType.LEFT_OUTER_JOIN, PATTERN_TEMPLATE_TEST_ITEM.PATTERN_ID.eq(PATTERN_TEMPLATE.ID));
query.addJoin(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID));
query.addJoin(ISSUE_TYPE, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_TYPE.eq(ISSUE_TYPE.ID));
query.addJoin(ISSUE_GROUP, JoinType.LEFT_OUTER_JOIN, ISSUE_TYPE.ISSUE_GROUP_ID.eq(ISSUE_GROUP.ISSUE_GROUP_ID));
query.addJoin(ISSUE_TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE.ISSUE_ID.eq(ISSUE_TICKET.ISSUE_ID));
query.addJoin(TICKET, JoinType.LEFT_OUTER_JOIN, ISSUE_TICKET.TICKET_ID.eq(TICKET.ID));
query.addJoin(PARAMETER, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(PARAMETER.ITEM_ID));
query.addJoin(LAUNCH_ATTRIBUTE, JoinType.LEFT_OUTER_JOIN, LAUNCH.ID.eq(LAUNCH_ATTRIBUTE.LAUNCH_ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
query.addJoin(LAUNCH, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.LAUNCH_ID.eq(LAUNCH.ID));
}
},
LOG_TARGET(Log.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, LOG.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_ID, LOG.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_TIME, LOG.LOG_TIME, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LAST_MODIFIED, LOG.LAST_MODIFIED, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_LEVEL, LOG.LOG_LEVEL, LogLevel.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_MESSAGE, LOG.LOG_MESSAGE, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_TEST_ITEM_ID, LOG.ITEM_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_LAUNCH_ID, LOG.LAUNCH_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOG_BINARY_CONTENT,
ATTACHMENT.FILE_ID,
String.class,
Lists.newArrayList(JoinEntity.of(ATTACHMENT, JoinType.LEFT_OUTER_JOIN, LOG.ATTACHMENT_ID.eq(ATTACHMENT.ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ITEM_LAUNCH_ID,
TEST_ITEM.LAUNCH_ID,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_ID,
TEST_ITEM.RETRY_OF,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_RETRY_PARENT_LAUNCH_ID,
TEST_ITEM.as(RETRY_PARENT).LAUNCH_ID,
Long.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)), JoinEntity.of(
TEST_ITEM.as(RETRY_PARENT),
JoinType.LEFT_OUTER_JOIN,
TEST_ITEM.RETRY_OF.eq(TEST_ITEM.as(RETRY_PARENT).ITEM_ID)
))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PATH,
TEST_ITEM.PATH,
String.class,
Lists.newArrayList(JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)))
).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_STATUS, TEST_ITEM_RESULTS.STATUS, JStatusEnum.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)),
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID))
)).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ISSUE_AUTO_ANALYZED, ISSUE.AUTO_ANALYZED, Boolean.class, Lists.newArrayList(
JoinEntity.of(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID)),
JoinEntity.of(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID)),
JoinEntity.of(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID))
)).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(LOG.ID,
LOG.LOG_TIME,
LOG.LOG_MESSAGE,
LOG.LAST_MODIFIED,
LOG.LOG_LEVEL,
LOG.ITEM_ID,
LOG.LAUNCH_ID,
LOG.ATTACHMENT_ID,
ATTACHMENT.ID,
ATTACHMENT.FILE_ID,
ATTACHMENT.THUMBNAIL_ID,
ATTACHMENT.CONTENT_TYPE,
ATTACHMENT.FILE_SIZE,
ATTACHMENT.PROJECT_ID,
ATTACHMENT.LAUNCH_ID,
ATTACHMENT.ITEM_ID
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(LOG);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(TEST_ITEM, JoinType.LEFT_OUTER_JOIN, LOG.ITEM_ID.eq(TEST_ITEM.ITEM_ID));
query.addJoin(TEST_ITEM_RESULTS, JoinType.LEFT_OUTER_JOIN, TEST_ITEM.ITEM_ID.eq(TEST_ITEM_RESULTS.RESULT_ID));
query.addJoin(ISSUE, JoinType.LEFT_OUTER_JOIN, TEST_ITEM_RESULTS.RESULT_ID.eq(ISSUE.ISSUE_ID));
query.addJoin(ATTACHMENT, JoinType.LEFT_OUTER_JOIN, LOG.ATTACHMENT_ID.eq(ATTACHMENT.ID));
}
@Override
protected void joinTablesForFilter(QuerySupplier query) {
}
@Override
protected Field<Long> idField() {
return LOG.ID;
}
},
ACTIVITY_TARGET(Activity.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, ACTIVITY.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, ACTIVITY.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, Long.class)
.withAggregateCriteria(DSL.max(PROJECT.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER_ID, ACTIVITY.USER_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ENTITY, ACTIVITY.ENTITY, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_ACTION, ACTIVITY.ACTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_LOGIN, ACTIVITY.USERNAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_CREATION_DATE, ACTIVITY.CREATION_DATE, Timestamp.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OBJECT_ID, ACTIVITY.OBJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_USER, USERS.LOGIN, String.class)
.withAggregateCriteria(DSL.max(USERS.LOGIN).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OBJECT_NAME, ACTIVITY.DETAILS + " ->> 'objectName'", String.class).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(ACTIVITY.ID,
ACTIVITY.PROJECT_ID,
ACTIVITY.USERNAME,
ACTIVITY.USER_ID,
ACTIVITY.ENTITY,
ACTIVITY.ACTION,
ACTIVITY.CREATION_DATE,
ACTIVITY.DETAILS,
ACTIVITY.OBJECT_ID,
USERS.LOGIN,
PROJECT.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(ACTIVITY);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(USERS, JoinType.LEFT_OUTER_JOIN, ACTIVITY.USER_ID.eq(USERS.ID));
query.addJoin(PROJECT, JoinType.JOIN, ACTIVITY.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return ACTIVITY.ID;
}
},
INTEGRATION_TARGET(Integration.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, INTEGRATION.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, INTEGRATION.PROJECT_ID, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_INTEGRATION_TYPE, INTEGRATION_TYPE.GROUP_TYPE, JIntegrationGroupEnum.class)
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, INTEGRATION_TYPE.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_NAME, PROJECT.NAME, String.class).get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(INTEGRATION.ID,
INTEGRATION.NAME,
INTEGRATION.PROJECT_ID,
INTEGRATION.TYPE,
INTEGRATION.PARAMS,
INTEGRATION.CREATOR,
INTEGRATION.CREATION_DATE,
INTEGRATION_TYPE.NAME,
INTEGRATION_TYPE.GROUP_TYPE,
PROJECT.NAME
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(INTEGRATION);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(INTEGRATION_TYPE, JoinType.JOIN, INTEGRATION.TYPE.eq(INTEGRATION_TYPE.ID));
query.addJoin(PROJECT, JoinType.JOIN, INTEGRATION.PROJECT_ID.eq(PROJECT.ID));
}
@Override
protected Field<Long> idField() {
return DSL.cast(INTEGRATION.ID, Long.class);
}
},
DASHBOARD_TARGET(Dashboard.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, DASHBOARD.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, DASHBOARD.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.PROJECT_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(DASHBOARD.ID,
DASHBOARD.NAME,
DASHBOARD.DESCRIPTION,
DASHBOARD.CREATION_DATE,
DASHBOARD_WIDGET.WIDGET_OWNER,
DASHBOARD_WIDGET.IS_CREATED_ON,
DASHBOARD_WIDGET.WIDGET_ID,
DASHBOARD_WIDGET.WIDGET_NAME,
DASHBOARD_WIDGET.WIDGET_TYPE,
DASHBOARD_WIDGET.WIDGET_HEIGHT,
DASHBOARD_WIDGET.WIDGET_WIDTH,
DASHBOARD_WIDGET.WIDGET_POSITION_X,
DASHBOARD_WIDGET.WIDGET_POSITION_Y,
DASHBOARD_WIDGET.SHARE,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(DASHBOARD);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(DASHBOARD_WIDGET, JoinType.LEFT_OUTER_JOIN, DASHBOARD.ID.eq(DASHBOARD_WIDGET.DASHBOARD_ID));
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, DASHBOARD.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, DASHBOARD.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return DASHBOARD.ID.cast(Long.class);
}
},
WIDGET_TARGET(Widget.class, Arrays.asList(
new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, WIDGET.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, WIDGET.NAME, String.class)
.withAggregateCriteria(DSL.max(WIDGET.NAME).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_DESCRIPTION, WIDGET.DESCRIPTION, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(WIDGET.ID,
WIDGET.NAME,
WIDGET.WIDGET_TYPE,
WIDGET.DESCRIPTION,
WIDGET.ITEMS_COUNT,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(WIDGET);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, WIDGET.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, WIDGET.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return WIDGET.ID;
}
},
USER_FILTER_TARGET(UserFilter.class, Arrays.asList(new CriteriaHolderBuilder().newBuilder(CRITERIA_ID, FILTER.ID, Long.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_NAME, FILTER.NAME, String.class).get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_SHARED, SHAREABLE_ENTITY.SHARED, Boolean.class)
.withAggregateCriteria(DSL.boolAnd(SHAREABLE_ENTITY.SHARED).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_PROJECT_ID, SHAREABLE_ENTITY.PROJECT_ID, Long.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.PROJECT_ID).toString())
.get(),
new CriteriaHolderBuilder().newBuilder(CRITERIA_OWNER, SHAREABLE_ENTITY.OWNER, String.class)
.withAggregateCriteria(DSL.max(SHAREABLE_ENTITY.OWNER).toString())
.get()
)) {
@Override
protected Collection<? extends SelectField> selectFields() {
return Lists.newArrayList(FILTER.ID,
FILTER.NAME,
FILTER.TARGET,
FILTER.DESCRIPTION,
FILTER_CONDITION.SEARCH_CRITERIA,
FILTER_CONDITION.CONDITION,
FILTER_CONDITION.VALUE,
FILTER_CONDITION.NEGATIVE,
FILTER_SORT.FIELD,
FILTER_SORT.DIRECTION,
SHAREABLE_ENTITY.SHARED,
SHAREABLE_ENTITY.PROJECT_ID,
SHAREABLE_ENTITY.OWNER
);
}
@Override
protected void addFrom(SelectQuery<? extends Record> query) {
query.addFrom(FILTER);
}
@Override
protected void joinTables(QuerySupplier query) {
query.addJoin(SHAREABLE_ENTITY, JoinType.JOIN, FILTER.ID.eq(SHAREABLE_ENTITY.ID));
query.addJoin(FILTER_CONDITION, JoinType.LEFT_OUTER_JOIN, FILTER.ID.eq(FILTER_CONDITION.FILTER_ID));
query.addJoin(FILTER_SORT, JoinType.LEFT_OUTER_JOIN, FILTER.ID.eq(FILTER_SORT.FILTER_ID));
query.addJoin(ACL_OBJECT_IDENTITY, JoinType.JOIN, FILTER.ID.cast(String.class).eq(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY));
query.addJoin(ACL_CLASS, JoinType.JOIN, ACL_CLASS.ID.eq(ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS));
query.addJoin(ACL_ENTRY, JoinType.JOIN, ACL_ENTRY.ACL_OBJECT_IDENTITY.eq(ACL_OBJECT_IDENTITY.ID));
}
@Override
protected Field<Long> idField() {
return FILTER.ID;
}
};
public static final String FILTERED_QUERY = "filtered";
public static final String FILTERED_ID = "id";
private Class<?> clazz;
private List<CriteriaHolder> criteriaHolders;
FilterTarget(Class<?> clazz, List<CriteriaHolder> criteriaHolders) {
this.clazz = clazz;
this.criteriaHolders = criteriaHolders;
}
public QuerySupplier getQuery() {
SelectQuery<? extends Record> query = DSL.select(idField().as(FILTERED_ID)).getQuery();
addFrom(query);
query.addGroupBy(idField());
QuerySupplier querySupplier = new QuerySupplier(query);
joinTablesForFilter(querySupplier);
return querySupplier;
}
protected abstract Collection<? extends SelectField> selectFields();
protected abstract void addFrom(SelectQuery<? extends Record> query);
protected abstract void joinTables(QuerySupplier query);
protected void joinTablesForFilter(QuerySupplier query) {
joinTables(query);
}
protected abstract Field<Long> idField();
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query) {
SelectQuery<Record> wrappedQuery = DSL.with(FILTERED_QUERY).as(query).select(selectFields()).getQuery();
addFrom(wrappedQuery);
QuerySupplier querySupplier = new QuerySupplier(wrappedQuery);
querySupplier.addJoin(DSL.table(DSL.name(FILTERED_QUERY)),
JoinType.JOIN,
idField().eq(field(DSL.name(FILTERED_QUERY, FILTERED_ID), Long.class))
);
joinTables(querySupplier);
return querySupplier;
}
public QuerySupplier wrapQuery(SelectQuery<? extends Record> query, String... excluding) {
List<String> excludingFields = Lists.newArrayList(excluding);
List<? extends SelectField> fields = selectFields().stream()
.filter(it -> !excludingFields.contains(it.getName()))
.collect(Collectors.toList());
SelectQuery<Record> wrappedQuery = DSL.with(FILTERED_QUERY).as(query).select(fields).getQuery();
addFrom(wrappedQuery);
QuerySupplier querySupplier = new QuerySupplier(wrappedQuery);
querySupplier.addJoin(DSL.table(DSL.name(FILTERED_QUERY)),
JoinType.JOIN,
idField().eq(field(DSL.name(FILTERED_QUERY, FILTERED_ID), Long.class))
);
joinTables(querySupplier);
return querySupplier;
}
public Class<?> getClazz() {
return clazz;
}
public List<CriteriaHolder> getCriteriaHolders() {
return criteriaHolders;
}
public Optional<CriteriaHolder> getCriteriaByFilter(String filterCriteria) {
/*
creates criteria holder for statistics search criteria cause there
can be custom statistics so we can't know it till this moment
*/
if (filterCriteria != null && filterCriteria.startsWith(STATISTICS_KEY)) {
return Optional.of(new CriteriaHolderBuilder().newBuilder(filterCriteria,
DSL.coalesce(DSL.max(STATISTICS.S_COUNTER).filterWhere(STATISTICS_FIELD.NAME.eq(filterCriteria)), 0).toString(),
Long.class
).get());
}
return criteriaHolders.stream().filter(holder -> holder.getFilterCriteria().equals(filterCriteria)).findAny();
}
public static FilterTarget findByClass(Class<?> clazz) {
return Arrays.stream(values())
.filter(val -> val.clazz.equals(clazz))
.findAny()
.orElseThrow(() -> new IllegalArgumentException(String.format("No target query builder for clazz %s", clazz)));
}
}
| Add composite attribute to the launch query builder
| src/main/java/com/epam/ta/reportportal/commons/querygen/FilterTarget.java | Add composite attribute to the launch query builder |
|
Java | apache-2.0 | d216e321c8c89f23c8c7853a04af599edd139085 | 0 | liyang1025/netty,shuangqiuan/netty,wangyikai/netty,AnselQiao/netty,carl-mastrangelo/netty,LuminateWireless/netty,sameira/netty,chinayin/netty,sverkera/netty,yonglehou/netty-1,yipen9/netty,mway08/netty,zzcclp/netty,junjiemars/netty,jongyeol/netty,duqiao/netty,kvr000/netty,andsel/netty,golovnin/netty,exinguu/netty,eincs/netty,smayoorans/netty,Alwayswithme/netty,eincs/netty,zhujingling/netty,rovarga/netty,zxhfirefox/netty,mx657649013/netty,Scottmitch/netty,carlbai/netty,mx657649013/netty,junjiemars/netty,yawkat/netty,CodingFabian/netty,altihou/netty,sja/netty,hyangtack/netty,lightsocks/netty,afredlyj/learn-netty,CodingFabian/netty,liuciuse/netty,ninja-/netty,zer0se7en/netty,BrunoColin/netty,s-gheldd/netty,SinaTadayon/netty,silvaran/netty,yonglehou/netty-1,timboudreau/netty,sunbeansoft/netty,maliqq/netty,tempbottle/netty,fantayeneh/netty,sja/netty,moyiguket/netty,zxhfirefox/netty,NiteshKant/netty,blucas/netty,johnou/netty,bob329/netty,Mounika-Chirukuri/netty,jovezhougang/netty,NiteshKant/netty,satishsaley/netty,altihou/netty,AchinthaReemal/netty,timboudreau/netty,yawkat/netty,jenskordowski/netty,skyao/netty,qingsong-xu/netty,louiscryan/netty,silvaran/netty,ichaki5748/netty,hgl888/netty,nayato/netty,chinayin/netty,caoyanwei/netty,gigold/netty,DolphinZhao/netty,liuciuse/netty,hgl888/netty,silvaran/netty,slandelle/netty,bob329/netty,xiexingguang/netty,huuthang1993/netty,imangry/netty-zh,afds/netty,doom369/netty,ejona86/netty,firebase/netty,shelsonjava/netty,phlizik/netty,seetharamireddy540/netty,fantayeneh/netty,fengshao0907/netty,smayoorans/netty,johnou/netty,mikkokar/netty,Mounika-Chirukuri/netty,djchen/netty,mcobrien/netty,jongyeol/netty,ichaki5748/netty,balaprasanna/netty,chinayin/netty,SinaTadayon/netty,windie/netty,louxiu/netty,olupotd/netty,ijuma/netty,f7753/netty,carl-mastrangelo/netty,x1957/netty,shism/netty,windie/netty,caoyanwei/netty,wuyinxian124/netty,gerdriesselmann/netty,exinguu/netty,ninja-/netty,Apache9/netty,joansmith/netty,yawkat/netty,mosoft521/netty,liyang1025/netty,blademainer/netty,Apache9/netty,serioussam/netty,afredlyj/learn-netty,daschl/netty,alkemist/netty,x1957/netty,chanakaudaya/netty,gigold/netty,huanyi0723/netty,mcanthony/netty,smayoorans/netty,jovezhougang/netty,carl-mastrangelo/netty,gerdriesselmann/netty,woshilaiceshide/netty,hgl888/netty,xiongzheng/netty,unei66/netty,jongyeol/netty,KeyNexus/netty,doom369/netty,carl-mastrangelo/netty,lukehutch/netty,shism/netty,fenik17/netty,lukehutch/netty,Mounika-Chirukuri/netty,nmittler/netty,mway08/netty,niuxinghua/netty,afds/netty,WangJunTYTL/netty,JungMinu/netty,liyang1025/netty,DolphinZhao/netty,yipen9/netty,drowning/netty,Kalvar/netty,windie/netty,junjiemars/netty,WangJunTYTL/netty,carl-mastrangelo/netty,doom369/netty,liyang1025/netty,artgon/netty,seetharamireddy540/netty,andsel/netty,buchgr/netty,mosoft521/netty,danny200309/netty,jovezhougang/netty,altihou/netty,orika/netty,shelsonjava/netty,serioussam/netty,MediumOne/netty,djchen/netty,duqiao/netty,luyiisme/netty,f7753/netty,IBYoung/netty,Apache9/netty,clebertsuconic/netty,ngocdaothanh/netty,menacher/netty,lukw00/netty,tbrooks8/netty,Alwayswithme/netty,jenskordowski/netty,imangry/netty-zh,seetharamireddy540/netty,CodingFabian/netty,mcanthony/netty,zxhfirefox/netty,jroper/netty,lukehutch/netty,chrisprobst/netty,maliqq/netty,pengzj/netty,Squarespace/netty,ajaysarda/netty,andsel/netty,purplefox/netty-4.0.2.8-hacked,sunbeansoft/netty,bigheary/netty,orika/netty,mosoft521/netty,Alwayswithme/netty,codevelop/netty,gigold/netty,shuangqiuan/netty,danny200309/netty,luyiisme/netty,slandelle/netty,xiexingguang/netty,jovezhougang/netty,ijuma/netty,dongjiaqiang/netty,ninja-/netty,djchen/netty,Alwayswithme/netty,ichaki5748/netty,joansmith/netty,ngocdaothanh/netty,smayoorans/netty,eincs/netty,serioussam/netty,Spikhalskiy/netty,sammychen105/netty,sverkera/netty,shelsonjava/netty,louxiu/netty,orika/netty,x1957/netty,AnselQiao/netty,buchgr/netty,jenskordowski/netty,lightsocks/netty,aperepel/netty,johnou/netty,normanmaurer/netty,zzcclp/netty,DolphinZhao/netty,bob329/netty,Squarespace/netty,yawkat/netty,Kingson4Wu/netty,SinaTadayon/netty,lznhust/netty,skyao/netty,huanyi0723/netty,sverkera/netty,ioanbsu/netty,xingguang2013/netty,f7753/netty,chanakaudaya/netty,eonezhang/netty,purplefox/netty-4.0.2.8-hacked,djchen/netty,gigold/netty,yrcourage/netty,ijuma/netty,AchinthaReemal/netty,bryce-anderson/netty,xingguang2013/netty,unei66/netty,Apache9/netty,nkhuyu/netty,mubarak/netty,moyiguket/netty,bryce-anderson/netty,idelpivnitskiy/netty,joansmith/netty,idelpivnitskiy/netty,youprofit/netty,ejona86/netty,nat2013/netty,mosoft521/netty,eonezhang/netty,yawkat/netty,louiscryan/netty,blucas/netty,lukw00/netty,wuxiaowei907/netty,sammychen105/netty,louiscryan/netty,nadeeshaan/netty,artgon/netty,LuminateWireless/netty,KatsuraKKKK/netty,maliqq/netty,louxiu/netty,windie/netty,slandelle/netty,danny200309/netty,lugt/netty,firebase/netty,mubarak/netty,niuxinghua/netty,blucas/netty,ngocdaothanh/netty,balaprasanna/netty,imangry/netty-zh,silvaran/netty,windie/netty,caoyanwei/netty,huuthang1993/netty,shism/netty,ajaysarda/netty,jchambers/netty,idelpivnitskiy/netty,brennangaunce/netty,huuthang1993/netty,eonezhang/netty,louxiu/netty,JungMinu/netty,SinaTadayon/netty,fenik17/netty,normanmaurer/netty,ijuma/netty,nkhuyu/netty,lznhust/netty,jdivy/netty,niuxinghua/netty,lukw00/netty,wuxiaowei907/netty,yipen9/netty,xiongzheng/netty,danny200309/netty,woshilaiceshide/netty,BrunoColin/netty,golovnin/netty,Techcable/netty,Mounika-Chirukuri/netty,fenik17/netty,tempbottle/netty,huanyi0723/netty,tbrooks8/netty,develar/netty,afds/netty,ichaki5748/netty,mcanthony/netty,sja/netty,caoyanwei/netty,zhoffice/netty,ifesdjeen/netty,zhujingling/netty,slandelle/netty,joansmith/netty,MediumOne/netty,balaprasanna/netty,ajaysarda/netty,JungMinu/netty,nadeeshaan/netty,alkemist/netty,Scottmitch/netty,fengjiachun/netty,kjniemi/netty,kvr000/netty,danbev/netty,dongjiaqiang/netty,jovezhougang/netty,Kalvar/netty,normanmaurer/netty,Techcable/netty,wangyikai/netty,duqiao/netty,bryce-anderson/netty,luyiisme/netty,shenguoquan/netty,lightsocks/netty,sameira/netty,niuxinghua/netty,ejona86/netty,wangyikai/netty,Kingson4Wu/netty,kiril-me/netty,zxhfirefox/netty,nadeeshaan/netty,KatsuraKKKK/netty,SinaTadayon/netty,silvaran/netty,hepin1989/netty,sunbeansoft/netty,f7753/netty,phlizik/netty,lznhust/netty,cnoldtree/netty,WangJunTYTL/netty,carlbai/netty,mway08/netty,artgon/netty,drowning/netty,duqiao/netty,nkhuyu/netty,sverkera/netty,LuminateWireless/netty,mubarak/netty,jenskordowski/netty,netty/netty,carlbai/netty,exinguu/netty,shenguoquan/netty,purplefox/netty-4.0.2.8-hacked,yipen9/netty,cnoldtree/netty,fenik17/netty,hyangtack/netty,s-gheldd/netty,fantayeneh/netty,Spikhalskiy/netty,ajaysarda/netty,fengjiachun/netty,lugt/netty,shism/netty,DavidAlphaFox/netty,zxhfirefox/netty,DolphinZhao/netty,netty/netty,youprofit/netty,yrcourage/netty,danbev/netty,ninja-/netty,louiscryan/netty,zhoffice/netty,fengjiachun/netty,NiteshKant/netty,AchinthaReemal/netty,zhujingling/netty,gerdriesselmann/netty,bigheary/netty,djchen/netty,moyiguket/netty,shuangqiuan/netty,ifesdjeen/netty,carlbai/netty,castomer/netty,IBYoung/netty,nayato/netty,blucas/netty,tempbottle/netty,hyangtack/netty,brennangaunce/netty,lznhust/netty,maliqq/netty,jchambers/netty,joansmith/netty,kjniemi/netty,wuyinxian124/netty,jdivy/netty,MediumOne/netty,kiril-me/netty,brennangaunce/netty,jdivy/netty,nmittler/netty,bigheary/netty,ichaki5748/netty,NiteshKant/netty,x1957/netty,clebertsuconic/netty,sameira/netty,kyle-liu/netty4study,sameira/netty,Kalvar/netty,balaprasanna/netty,buchgr/netty,firebase/netty,fengshao0907/netty,bigheary/netty,zer0se7en/netty,MediumOne/netty,louxiu/netty,afds/netty,danbev/netty,kiril-me/netty,carlbai/netty,eonezhang/netty,johnou/netty,bigheary/netty,sunbeansoft/netty,lugt/netty,shenguoquan/netty,pengzj/netty,drowning/netty,andsel/netty,LuminateWireless/netty,mx657649013/netty,AchinthaReemal/netty,olupotd/netty,kjniemi/netty,develar/netty,unei66/netty,fengjiachun/netty,castomer/netty,blucas/netty,AnselQiao/netty,unei66/netty,woshilaiceshide/netty,kjniemi/netty,junjiemars/netty,hepin1989/netty,timboudreau/netty,fengjiachun/netty,Techcable/netty,normanmaurer/netty,olupotd/netty,yrcourage/netty,gigold/netty,shelsonjava/netty,AnselQiao/netty,castomer/netty,s-gheldd/netty,luyiisme/netty,firebase/netty,jchambers/netty,blademainer/netty,CodingFabian/netty,huanyi0723/netty,gerdriesselmann/netty,castomer/netty,xiexingguang/netty,AnselQiao/netty,wangyikai/netty,kiril-me/netty,louiscryan/netty,LuminateWireless/netty,hyangtack/netty,nat2013/netty,nkhuyu/netty,exinguu/netty,jenskordowski/netty,wuxiaowei907/netty,s-gheldd/netty,sameira/netty,KatsuraKKKK/netty,Squarespace/netty,AchinthaReemal/netty,clebertsuconic/netty,kvr000/netty,nmittler/netty,bryce-anderson/netty,woshilaiceshide/netty,doom369/netty,satishsaley/netty,DavidAlphaFox/netty,yrcourage/netty,sverkera/netty,nayato/netty,sunbeansoft/netty,yonglehou/netty-1,eonezhang/netty,rovarga/netty,lukw00/netty,BrunoColin/netty,dongjiaqiang/netty,CodingFabian/netty,KeyNexus/netty,cnoldtree/netty,orika/netty,huuthang1993/netty,nayato/netty,buchgr/netty,exinguu/netty,wuyinxian124/netty,netty/netty,kvr000/netty,hepin1989/netty,Alwayswithme/netty,liuciuse/netty,jdivy/netty,ioanbsu/netty,mikkokar/netty,MediumOne/netty,Kalvar/netty,IBYoung/netty,duqiao/netty,gerdriesselmann/netty,fengshao0907/netty,idelpivnitskiy/netty,doom369/netty,shelsonjava/netty,shism/netty,phlizik/netty,cnoldtree/netty,golovnin/netty,blademainer/netty,ijuma/netty,hgl888/netty,caoyanwei/netty,fantayeneh/netty,lukehutch/netty,timboudreau/netty,Kingson4Wu/netty,shenguoquan/netty,mikkokar/netty,xingguang2013/netty,yrcourage/netty,zer0se7en/netty,hepin1989/netty,danbev/netty,WangJunTYTL/netty,zzcclp/netty,maliqq/netty,kjniemi/netty,Squarespace/netty,shuangqiuan/netty,ejona86/netty,normanmaurer/netty,blademainer/netty,artgon/netty,Kalvar/netty,hgl888/netty,johnou/netty,xiongzheng/netty,moyiguket/netty,alkemist/netty,luyiisme/netty,CliffYuan/netty,mosoft521/netty,mcobrien/netty,NiteshKant/netty,f7753/netty,huuthang1993/netty,chinayin/netty,Kingson4Wu/netty,serioussam/netty,Scottmitch/netty,nat2013/netty,moyiguket/netty,qingsong-xu/netty,IBYoung/netty,lukehutch/netty,idelpivnitskiy/netty,bob329/netty,jdivy/netty,DavidAlphaFox/netty,niuxinghua/netty,zhoffice/netty,smayoorans/netty,blademainer/netty,lznhust/netty,nayato/netty,olupotd/netty,altihou/netty,xiexingguang/netty,zhujingling/netty,eincs/netty,tbrooks8/netty,Spikhalskiy/netty,chrisprobst/netty,chinayin/netty,wuxiaowei907/netty,nadeeshaan/netty,imangry/netty-zh,timboudreau/netty,jchambers/netty,DavidAlphaFox/netty,dongjiaqiang/netty,chrisprobst/netty,qingsong-xu/netty,mcobrien/netty,shenguoquan/netty,xingguang2013/netty,mx657649013/netty,Techcable/netty,imangry/netty-zh,serioussam/netty,zer0se7en/netty,chrisprobst/netty,youprofit/netty,mcanthony/netty,mway08/netty,mubarak/netty,seetharamireddy540/netty,nkhuyu/netty,pengzj/netty,netty/netty,s-gheldd/netty,liuciuse/netty,KatsuraKKKK/netty,huanyi0723/netty,tbrooks8/netty,Scottmitch/netty,mubarak/netty,youprofit/netty,balaprasanna/netty,IBYoung/netty,xiexingguang/netty,castomer/netty,clebertsuconic/netty,qingsong-xu/netty,woshilaiceshide/netty,liuciuse/netty,alkemist/netty,andsel/netty,ngocdaothanh/netty,xiongzheng/netty,bryce-anderson/netty,nadeeshaan/netty,olupotd/netty,danbev/netty,CliffYuan/netty,mikkokar/netty,kvr000/netty,chrisprobst/netty,codevelop/netty,chanakaudaya/netty,skyao/netty,kiril-me/netty,mway08/netty,mx657649013/netty,sammychen105/netty,ioanbsu/netty,wuyinxian124/netty,alkemist/netty,ngocdaothanh/netty,daschl/netty,chanakaudaya/netty,ioanbsu/netty,brennangaunce/netty,shuangqiuan/netty,tempbottle/netty,BrunoColin/netty,yonglehou/netty-1,satishsaley/netty,zer0se7en/netty,wuxiaowei907/netty,Kingson4Wu/netty,Spikhalskiy/netty,rovarga/netty,Spikhalskiy/netty,youprofit/netty,satishsaley/netty,altihou/netty,ioanbsu/netty,wangyikai/netty,pengzj/netty,yonglehou/netty-1,menacher/netty,golovnin/netty,rovarga/netty,lugt/netty,DolphinZhao/netty,zhoffice/netty,kyle-liu/netty4study,Mounika-Chirukuri/netty,zzcclp/netty,codevelop/netty,jongyeol/netty,netty/netty,daschl/netty,unei66/netty,xingguang2013/netty,qingsong-xu/netty,zzcclp/netty,jongyeol/netty,ajaysarda/netty,lugt/netty,fenik17/netty,xiongzheng/netty,Techcable/netty,fantayeneh/netty,eincs/netty,junjiemars/netty,skyao/netty,zhujingling/netty,afds/netty,BrunoColin/netty,golovnin/netty,phlizik/netty,zhoffice/netty,chanakaudaya/netty,seetharamireddy540/netty,tempbottle/netty,liyang1025/netty,JungMinu/netty,satishsaley/netty,Apache9/netty,skyao/netty,tbrooks8/netty,artgon/netty,drowning/netty,Squarespace/netty,orika/netty,mcobrien/netty,KatsuraKKKK/netty,jchambers/netty,sja/netty,codevelop/netty,danny200309/netty,WangJunTYTL/netty,afredlyj/learn-netty,purplefox/netty-4.0.2.8-hacked,mcobrien/netty,bob329/netty,sja/netty,mikkokar/netty,clebertsuconic/netty,lightsocks/netty,brennangaunce/netty,mcanthony/netty,dongjiaqiang/netty,lightsocks/netty,lukw00/netty,cnoldtree/netty,ejona86/netty,ninja-/netty,Scottmitch/netty,x1957/netty | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat 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.jboss.netty.handler.codec.http;
import static org.jboss.netty.handler.codec.http.HttpCodecUtil.*;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Encodes an {@link HttpResponse} or an {@link HttpChunk} into
* a {@link ChannelBuffer}.
*
* @author The Netty Project ([email protected])
* @author Andy Taylor ([email protected])
* @author Trustin Lee ([email protected])
* @version $Rev$, $Date$
*/
public class HttpResponseEncoder extends HttpMessageEncoder {
/**
* Creates a new instance.
*/
public HttpResponseEncoder() {
super();
}
@Override
protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) throws Exception {
HttpResponse response = (HttpResponse) message;
buf.writeBytes(response.getProtocolVersion().toString().getBytes("ASCII"));
buf.writeByte(SP);
buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes("ASCII"));
buf.writeByte(SP);
buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII"));
buf.writeBytes(CRLF);
}
}
| src/main/java/org/jboss/netty/handler/codec/http/HttpResponseEncoder.java | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat 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.jboss.netty.handler.codec.http;
import static org.jboss.netty.handler.codec.http.HttpCodecUtil.*;
import java.io.UnsupportedEncodingException;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Encodes an {@link HttpResponse} or an {@link HttpChunk} into
* a {@link ChannelBuffer}.
*
* @author The Netty Project ([email protected])
* @author Andy Taylor ([email protected])
* @author Trustin Lee ([email protected])
* @version $Rev$, $Date$
*/
public class HttpResponseEncoder extends HttpMessageEncoder {
/**
* Creates a new instance.
*/
public HttpResponseEncoder() {
super();
}
@Override
protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) {
HttpResponse response = (HttpResponse) message;
try {
buf.writeBytes(response.getProtocolVersion().toString().getBytes("ASCII"));
buf.writeByte(SP);
buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes("ASCII"));
buf.writeByte(SP);
buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII"));
buf.writeBytes(CRLF);
} catch (UnsupportedEncodingException e) {
throw (Error) new Error().initCause(e);
}
}
}
| Relax throws clause restriction
| src/main/java/org/jboss/netty/handler/codec/http/HttpResponseEncoder.java | Relax throws clause restriction |
|
Java | apache-2.0 | 62ffb70685166cb6e6241937ca129245c34f0793 | 0 | uds-lsv/platon-gui,uds-lsv/platon-gui | package de.uds.lsv.platon.gui.tts;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sound.sampled.AudioInputStream;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
@Singleton
public class MaryTTS implements TTS {
private final MaryInterface marytts;
public MaryTTS() throws MaryConfigurationException {
marytts = new LocalMaryInterface();
Set<String> voices = marytts.getAvailableVoices();
if (voices.isEmpty()) {
throw new RuntimeException("No TTS voices found!");
}
marytts.setVoice(voices.iterator().next());
}
@Override
public void say(String text) {
try {
AudioInputStream audio = marytts.generateAudio(text);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
}
catch (InterruptedException e) {
}
catch (SynthesisException e) {
throw new RuntimeException(e);
}
}
}
| src/main/groovy/de/uds/lsv/platon/gui/tts/MaryTTS.java | package de.uds.lsv.platon.gui.tts;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sound.sampled.AudioInputStream;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
@Singleton
public class MaryTTS implements TTS {
private final MaryInterface marytts;
@Inject
public MaryTTS() throws MaryConfigurationException {
marytts = new LocalMaryInterface();
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
}
@Override
public void say(String text) {
try {
AudioInputStream audio = marytts.generateAudio(text);
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
}
catch (InterruptedException e) {
}
catch (SynthesisException e) {
throw new RuntimeException(e);
}
}
}
| added error message if no voices are found
| src/main/groovy/de/uds/lsv/platon/gui/tts/MaryTTS.java | added error message if no voices are found |
|
Java | apache-2.0 | d732e838361acde59993e3be37d2e780778fd206 | 0 | jvasileff/ceylon-spec,ceylon/ceylon-spec,ceylon/ceylon-spec,ceylon/ceylon-spec,jvasileff/ceylon-spec,jvasileff/ceylon-spec,lucaswerkmeister/ceylon-spec | package com.redhat.ceylon.compiler.typechecker.analyzer;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.*;
import java.util.ArrayList;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassAlias;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.ControlBlock;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Element;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.InterfaceAlias;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
* First phase of type analysis.
* Scan a compilation unit searching for declarations,
* and builds up the model objects. At this point, all
* we know is the name of the declaration and what
* kind of declaration it is. The model objects do not
* contain type information.
*
* @author Gavin King
*
*/
public class DeclarationVisitor extends Visitor {
private final Package pkg;
private final String filename;
private Scope scope;
private Unit unit;
private ParameterList parameterList;
private Declaration declaration;
public DeclarationVisitor(Package pkg, String filename) {
scope = pkg;
this.pkg = pkg;
this.filename = filename;
}
public Unit getCompilationUnit() {
return unit;
}
private Scope enterScope(Scope innerScope) {
Scope outerScope = scope;
scope = innerScope;
return outerScope;
}
private void exitScope(Scope outerScope) {
scope = outerScope;
}
private Declaration beginDeclaration(Declaration innerDec) {
Declaration outerDec = declaration;
declaration = innerDec;
return outerDec;
}
private void endDeclaration(Declaration outerDec) {
declaration = outerDec;
}
private void visitDeclaration(Tree.Declaration that, Declaration model) {
visitElement(that, model);
Tree.Identifier id = that.getIdentifier();
if ( setModelName(that, model, id) ) {
checkForDuplicateDeclaration(that, model);
}
//that.setDeclarationModel(model);
unit.getDeclarations().add(model);
scope.getMembers().add(model);
}
private void visitArgument(Tree.NamedArgument that, Declaration model) {
Tree.Identifier id = that.getIdentifier();
setModelName(that, model, id);
visitElement(that, model);
//that.setDeclarationModel(model);
unit.getDeclarations().add(model);
}
private boolean setModelName(Node that, Declaration model,
Tree.Identifier id) {
if (id==null || id.getText().startsWith("<missing")) {
that.addError("missing declaration name");
return false;
}
else {
//model.setName(internalName(that, model, id));
model.setName(id.getText());
return true;
//TODO: check for dupe arg name
}
}
/*private String internalName(Node that, Declaration model,
Tree.Identifier id) {
String n = id.getText();
if ((that instanceof Tree.ObjectDefinition||that instanceof Tree.ObjectArgument)
&& model instanceof Class) {
n = "#" + n;
}
return n;
}*/
private void checkForDuplicateDeclaration(Tree.Declaration that,
Declaration model) {
if (model.getName()!=null) {
if (model instanceof Setter) {
//a setter must have a matching getter
Declaration member = scope.getDirectMember( model.getName() );
if (member==null) {
that.addError("setter with no matching getter: " + model.getName());
}
else if (!(member instanceof Getter)) {
that.addError("setter name does not resolve to matching getter: " + model.getName());
}
else {
Getter getter = (Getter) member;
((Setter) model).setGetter(getter);
if (getter.isVariable()) {
that.addError("duplicate setter for getter: " + model.getName());
}
else {
getter.setVariable(true);
}
}
}
else if ((model instanceof Getter || model instanceof Value)
&& model.isClassMember()) {
//a getter or simple attribute is allowed to have the
//same name as a class initialization parameter
Declaration member = scope.getDirectMember( model.getName() );
if (member!=null) {
that.addError("duplicate declaration: " + model.getName());
}
}
else {
Declaration member = scope.getDirectMemberOrParameter( model.getName() );
if (member!=null) {
that.addError("duplicate declaration: " + model.getName());
}
}
}
}
private void visitElement(Node that, Element model) {
model.setUnit(unit);
model.setContainer(scope);
}
@Override
public void visitAny(Node that) {
that.setScope(scope);
that.setUnit(unit);
super.visitAny(that);
}
@Override
public void visit(Tree.CompilationUnit that) {
unit = new Unit();
//that.setModelNode(unit);
unit.setPackage(pkg);
unit.setFilename(filename);
super.visit(that);
}
@Override
public void visit(Tree.TypeDeclaration that) {
super.visit(that);
TypeDeclaration d = that.getDeclarationModel();
if (d==null) {
//TODO: this case is temporary until we have type constraints!
}
else {
d.setTypeParameters(getTypeParameters(that.getTypeParameterList()));
}
}
@Override
public void visit(Tree.ClassOrInterface that) {
super.visit(that);
if ( that.getCaseTypes()!=null ) {
that.addWarning("types with enumerated cases not yet supported");
}
}
@Override
public void visit(Tree.AnyClass that) {
Class c = that instanceof Tree.ClassDefinition ?
new Class() : new ClassAlias();
that.setDeclarationModel(c);
visitDeclaration(that, c);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
if (that.getParameterList()==null) {
that.addError("missing parameter list in class declaration: " +
name(that.getIdentifier()) );
}
}
@Override
public void visit(Tree.AnyInterface that) {
Interface i = that instanceof Tree.InterfaceDefinition ?
new Interface() : new InterfaceAlias();
that.setDeclarationModel(i);
visitDeclaration(that, i);
Scope o = enterScope(i);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.InterfaceDefinition that) {
super.visit(that);
if (that.getAdaptedTypes()!=null) {
that.addWarning("introductions are not yet supported");
}
}
@Override
public void visit(Tree.TypeParameterDeclaration that) {
TypeParameter p = new TypeParameter();
p.setDeclaration(declaration);
if (that.getTypeVariance()!=null) {
String v = that.getTypeVariance().getText();
p.setCovariant("out".equals(v));
p.setContravariant("in".equals(v));
}
that.setDeclarationModel(p);
visitDeclaration(that, p);
super.visit(that);
}
@Override
public void visit(Tree.AnyMethod that) {
Method m = new Method();
that.setDeclarationModel(m);
visitDeclaration(that, m);
Scope o = enterScope(m);
super.visit(that);
exitScope(o);
checkMethodParameters(that);
that.getDeclarationModel().setTypeParameters(getTypeParameters(that.getTypeParameterList()));
if (that.getType() instanceof Tree.ValueModifier) {
that.getType().addError("methods may not be declared using the keyword value");
}
}
@Override
public void visit(Tree.AnyAttribute that) {
super.visit(that);
if (that.getType() instanceof Tree.FunctionModifier) {
that.getType().addError("attributes may not be declared using the keyword function");
}
}
@Override
public void visit(Tree.MethodArgument that) {
Method m = new Method();
that.setDeclarationModel(m);
visitArgument(that, m);
Scope o = enterScope(m);
super.visit(that);
exitScope(o);
checkMethodArgumentParameters(that);
}
private void checkMethodParameters(Tree.AnyMethod that) {
if (that.getParameterLists().isEmpty()) {
that.addError("missing parameter list in method declaration: " +
name(that.getIdentifier()) );
}
if ( that.getParameterLists().size()>1 ) {
that.addWarning("higher-order methods are not yet supported");
}
}
private void checkMethodArgumentParameters(Tree.MethodArgument that) {
if (that.getParameterLists().isEmpty()) {
that.addError("missing parameter list in named argument declaration: " +
name(that.getIdentifier()) );
}
if ( that.getParameterLists().size()>1 ) {
that.addWarning("higher-order methods are not yet supported");
}
}
@Override
public void visit(Tree.ObjectDefinition that) {
if (that.getClassBody()==null) {
that.addError("missing object body");
}
Class c = new Class();
visitDeclaration(that, c);
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
that.getType().setTypeModel(c.getType());
v.setType(c.getType());
}
@Override
public void visit(Tree.ObjectArgument that) {
if (that.getClassBody()==null) {
that.addError("missing named argument body");
}
Class c = new Class();
visitArgument(that, c);
Value v = new Value();
that.setDeclarationModel(v);
visitArgument(that, v);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
that.getType().setTypeModel(c.getType());
v.setType(c.getType());
}
@Override
public void visit(Tree.AttributeDeclaration that) {
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
super.visit(that);
if ( v.isInterfaceMember() && !v.isFormal()) {
that.addError("interfaces may not have simple attributes");
}
if ( v.isFormal() && that.getSpecifierOrInitializerExpression()!=null ) {
that.addError("formal attributes may not have a value");
}
}
@Override
public void visit(Tree.MethodDeclaration that) {
super.visit(that);
if ( that.getSpecifierExpression()!=null ) {
that.addWarning("method definition by reference is not yet supported");
}
}
@Override
public void visit(Tree.AttributeGetterDefinition that) {
Getter g = new Getter();
that.setDeclarationModel(g);
visitDeclaration(that, g);
Scope o = enterScope(g);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.AttributeArgument that) {
Getter g = new Getter();
that.setDeclarationModel(g);
visitArgument(that, g);
Scope o = enterScope(g);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.AttributeSetterDefinition that) {
Setter s = new Setter();
that.setDeclarationModel(s);
visitDeclaration(that, s);
Scope o = enterScope(s);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.ValueParameterDeclaration that) {
ValueParameter p = new ValueParameter();
p.setDeclaration(declaration);
p.setDefaulted(that.getSpecifierExpression()!=null);
p.setSequenced(that.getType() instanceof Tree.SequencedType);
that.setDeclarationModel(p);
visitDeclaration(that, p);
super.visit(that);
parameterList.getParameters().add(p);
}
@Override
public void visit(Tree.FunctionalParameterDeclaration that) {
FunctionalParameter p = new FunctionalParameter();
p.setDeclaration(declaration);
p.setDefaulted(that.getSpecifierExpression()!=null);
that.setDeclarationModel(p);
visitDeclaration(that, p);
Scope o = enterScope(p);
super.visit(that);
exitScope(o);
parameterList.getParameters().add(p);
that.addWarning("higher order methods are not yet supported");
}
@Override
public void visit(Tree.ParameterList that) {
ParameterList pl = parameterList;
parameterList = new ParameterList();
super.visit(that);
Functional f = (Functional) scope;
if ( f instanceof Class &&
!f.getParameterLists().isEmpty() ) {
that.addError("classes may have only one parameter list");
}
else {
f.addParameterList(parameterList);
}
parameterList = pl;
}
@Override
public void visit(Tree.ControlClause that) {
ControlBlock c = new ControlBlock();
visitElement(that, c);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.Variable that) {
if (that.getSpecifierExpression()!=null) {
Scope s = scope;
scope = scope.getContainer();
that.getSpecifierExpression().visit(this);
scope = s;
}
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
if (that.getType()!=null) {
that.getType().visit(this);
}
if (that.getIdentifier()!=null) {
that.getIdentifier().visit(this);
}
if (that.getAnnotationList()!=null) {
that.getAnnotationList().visit(this);
}
//TODO: parameters of callable variables?!
/*if (that.getParameterLists().size()==0) {
if (that.getType() instanceof Tree.FunctionModifier) {
that.getType().addError("variables with no parameters may not be declared using the keyword function");
}
}
else {
if (that.getType() instanceof Tree.ValueModifier) {
that.getType().addError("variables with parameters may not be declared using the keyword value");
}
}*/
that.setScope(scope);
that.setUnit(unit);
}
private List<TypeParameter> getTypeParameters(Tree.TypeParameterList tpl) {
List<TypeParameter> typeParameters = new ArrayList<TypeParameter>();
if (tpl!=null) {
for (Tree.TypeParameterDeclaration tp: tpl.getTypeParameterDeclarations()) {
typeParameters.add(tp.getDeclarationModel());
}
}
return typeParameters;
}
private boolean hasAnnotation(Tree.AnnotationList al, String name) {
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Tree.BaseMemberExpression p = (Tree.BaseMemberExpression) a.getPrimary();
if (p!=null) {
if ( p.getIdentifier().getText().equals(name)) {
return true;
}
}
}
}
return false;
}
@Override public void visit(Tree.Declaration that) {
Declaration model = that.getDeclarationModel();
Declaration d = beginDeclaration(model);
if (declaration!=null) {
Tree.AnnotationList al = that.getAnnotationList();
if (hasAnnotation(al, "shared")) {
model.setShared(true);
}
if (hasAnnotation(al, "default")) {
model.setDefault(true);
if (that instanceof Tree.ObjectDefinition) {
that.addError("object declarations may not be default");
}
}
if (hasAnnotation(al, "formal")) {
model.setFormal(true);
if (that instanceof Tree.ObjectDefinition) {
that.addError("object declarations may not be formal");
}
}
if (hasAnnotation(al, "actual")) {
model.setActual(true);
}
if (hasAnnotation(al, "abstract")) {
if (model instanceof Class) {
((Class) declaration).setAbstract(true);
}
else {
that.addError("declaration is not a class, and may not be abstract");
}
}
if (hasAnnotation(al, "variable")) {
if (model instanceof Value) {
((Value) model).setVariable(true);
}
else if (model instanceof ValueParameter) {
that.addError("parameter may not be variable: " + model.getName());
}
else {
that.addError("declaration is not a value, and may not be variable");
}
}
buildAnnotations(al);
}
super.visit(that);
endDeclaration(d);
if (model!=null) {
checkFormalMember(that, model);
}
}
private void checkFormalMember(Tree.Declaration that, Declaration d) {
if ( d.isFormal() &&
( !(d.getContainer() instanceof ClassOrInterface) ||
!( (ClassOrInterface) d.getContainer() ).isAbstract()) ) {
that.addError("formal member does not belong to an interface or abstract class");
}
if ( d.isFormal() &&
!(that instanceof Tree.AttributeDeclaration) &&
!(that instanceof Tree.MethodDeclaration) &&
!(that instanceof Tree.ClassDefinition)) {
that.addError("formal member may not have a body");
}
if ( !d.isFormal() &&
d.getContainer() instanceof Interface &&
!(that instanceof Tree.ClassDeclaration) &&
!(that instanceof Tree.InterfaceDeclaration)) {
that.addWarning("concrete members of interfaces not yet supported");
}
}
private void buildAnnotations(Tree.AnnotationList al) {
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Annotation ann = new Annotation();
String name = ( (Tree.BaseMemberExpression) a.getPrimary() ).getIdentifier().getText();
ann.setName(name);
if (a.getNamedArgumentList()!=null) {
for ( Tree.NamedArgument na: a.getNamedArgumentList().getNamedArguments() ) {
if (na instanceof Tree.SpecifiedArgument) {
Tree.Term t = ((Tree.SpecifiedArgument) na).getSpecifierExpression().getExpression().getTerm();
String param = ((Tree.SpecifiedArgument) na).getIdentifier().getText();
if (t instanceof Tree.Literal) {
ann.addNamedArgument( param, ( (Tree.Literal) t ).getText() );
}
else if (t instanceof Tree.BaseTypeExpression) {
ann.addNamedArgument( param, ( (Tree.BaseTypeExpression) t ).getIdentifier().getText() );
}
}
}
}
if (a.getPositionalArgumentList()!=null) {
for ( Tree.PositionalArgument pa: a.getPositionalArgumentList().getPositionalArguments() ) {
Tree.Term t = pa.getExpression().getTerm();
if (t instanceof Tree.Literal) {
ann.addPositionalArgment( ( (Tree.Literal) t ).getText() );
}
else if (t instanceof Tree.BaseTypeExpression) {
ann.addPositionalArgment( ( (Tree.BaseTypeExpression) t ).getIdentifier().getText() );
}
}
}
declaration.getAnnotations().add(ann);
}
}
}
@Override public void visit(Tree.TypedArgument that) {
Declaration d = beginDeclaration(that.getDeclarationModel());
super.visit(that);
endDeclaration(d);
}
@Override
public void visit(Tree.TypeConstraint that) {
TypeParameter p = (TypeParameter) scope.getMemberOrParameter(unit, that.getIdentifier().getText());
that.setDeclarationModel(p);
if (p==null ) {
that.addError("no matching type parameter for constraint: " +
name(that.getIdentifier()));
super.visit(that);
}
else {
Scope o = enterScope(p);
super.visit(that);
exitScope(o);
}
if ( that.getAbstractedType()!=null ) {
that.addWarning("lower bound type constraints are not yet supported");
}
if ( that.getCaseTypes()!=null ) {
that.addWarning("enumerated type constraints are not yet supported");
}
if ( that.getParameterList()!=null ) {
that.addWarning("initialization parameter specifications are not yet supported");
}
}
@Override
public void visit(Tree.TryCatchStatement that) {
super.visit(that);
that.addWarning("try statements are not yet supported");
}
@Override
public void visit(Tree.SwitchStatement that) {
super.visit(that);
that.addWarning("switch statements are not yet supported");
}
@Override
public void visit(Tree.SatisfiesCondition that) {
super.visit(that);
that.addWarning("satisfies conditions are not yet supported");
}
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
that.addWarning("of clause not yet supported");
}
}
| src/com/redhat/ceylon/compiler/typechecker/analyzer/DeclarationVisitor.java | package com.redhat.ceylon.compiler.typechecker.analyzer;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.*;
import java.util.ArrayList;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassAlias;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.ControlBlock;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Element;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.InterfaceAlias;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
* First phase of type analysis.
* Scan a compilation unit searching for declarations,
* and builds up the model objects. At this point, all
* we know is the name of the declaration and what
* kind of declaration it is. The model objects do not
* contain type information.
*
* @author Gavin King
*
*/
public class DeclarationVisitor extends Visitor {
private final Package pkg;
private final String filename;
private Scope scope;
private Unit unit;
private ParameterList parameterList;
private Declaration declaration;
public DeclarationVisitor(Package pkg, String filename) {
scope = pkg;
this.pkg = pkg;
this.filename = filename;
}
public Unit getCompilationUnit() {
return unit;
}
private Scope enterScope(Scope innerScope) {
Scope outerScope = scope;
scope = innerScope;
return outerScope;
}
private void exitScope(Scope outerScope) {
scope = outerScope;
}
private Declaration beginDeclaration(Declaration innerDec) {
Declaration outerDec = declaration;
declaration = innerDec;
return outerDec;
}
private void endDeclaration(Declaration outerDec) {
declaration = outerDec;
}
private void visitDeclaration(Tree.Declaration that, Declaration model) {
visitElement(that, model);
Tree.Identifier id = that.getIdentifier();
if ( setModelName(that, model, id) ) {
checkForDuplicateDeclaration(that, model);
}
//that.setDeclarationModel(model);
unit.getDeclarations().add(model);
scope.getMembers().add(model);
}
private void visitArgument(Tree.NamedArgument that, Declaration model) {
Tree.Identifier id = that.getIdentifier();
setModelName(that, model, id);
visitElement(that, model);
//that.setDeclarationModel(model);
unit.getDeclarations().add(model);
}
private boolean setModelName(Node that, Declaration model,
Tree.Identifier id) {
if (id==null || id.getText().startsWith("<missing")) {
that.addError("missing declaration name");
return false;
}
else {
//model.setName(internalName(that, model, id));
model.setName(id.getText());
return true;
//TODO: check for dupe arg name
}
}
/*private String internalName(Node that, Declaration model,
Tree.Identifier id) {
String n = id.getText();
if ((that instanceof Tree.ObjectDefinition||that instanceof Tree.ObjectArgument)
&& model instanceof Class) {
n = "#" + n;
}
return n;
}*/
private void checkForDuplicateDeclaration(Tree.Declaration that,
Declaration model) {
if (model.getName()!=null) {
if (model instanceof Setter) {
//a setter must have a matching getter
Declaration member = scope.getDirectMember( model.getName() );
if (member==null) {
that.addError("setter with no matching getter: " + model.getName());
}
else if (!(member instanceof Getter)) {
that.addError("setter name does not resolve to matching getter: " + model.getName());
}
else {
Getter getter = (Getter) member;
((Setter) model).setGetter(getter);
if (getter.isVariable()) {
that.addError("duplicate setter for getter: " + model.getName());
}
else {
getter.setVariable(true);
}
}
}
else if ((model instanceof Getter || model instanceof Value)
&& model.isClassMember()) {
//a getter or simple attribute is allowed to have the
//same name as a class initialization parameter
Declaration member = scope.getDirectMember( model.getName() );
if (member!=null) {
that.addError("duplicate declaration: " + model.getName());
}
}
else {
Declaration member = scope.getDirectMemberOrParameter( model.getName() );
if (member!=null) {
that.addError("duplicate declaration: " + model.getName());
}
}
}
}
private void visitElement(Node that, Element model) {
model.setUnit(unit);
model.setContainer(scope);
}
@Override
public void visitAny(Node that) {
that.setScope(scope);
that.setUnit(unit);
super.visitAny(that);
}
@Override
public void visit(Tree.CompilationUnit that) {
unit = new Unit();
//that.setModelNode(unit);
unit.setPackage(pkg);
unit.setFilename(filename);
super.visit(that);
}
@Override
public void visit(Tree.TypeDeclaration that) {
super.visit(that);
TypeDeclaration d = that.getDeclarationModel();
if (d==null) {
//TODO: this case is temporary until we have type constraints!
}
else {
d.setTypeParameters(getTypeParameters(that.getTypeParameterList()));
}
}
@Override
public void visit(Tree.ClassOrInterface that) {
super.visit(that);
if ( that.getCaseTypes()!=null ) {
that.addWarning("types with enumerated cases not yet supported");
}
}
@Override
public void visit(Tree.AnyClass that) {
Class c = that instanceof Tree.ClassDefinition ?
new Class() : new ClassAlias();
that.setDeclarationModel(c);
visitDeclaration(that, c);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
if (that.getParameterList()==null) {
that.addError("missing parameter list in class declaration: " +
name(that.getIdentifier()) );
}
}
@Override
public void visit(Tree.AnyInterface that) {
Interface i = that instanceof Tree.InterfaceDefinition ?
new Interface() : new InterfaceAlias();
that.setDeclarationModel(i);
visitDeclaration(that, i);
Scope o = enterScope(i);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.InterfaceDefinition that) {
super.visit(that);
if (that.getAdaptedTypes()!=null) {
that.addWarning("introductions are not yet supported");
}
}
@Override
public void visit(Tree.TypeParameterDeclaration that) {
TypeParameter p = new TypeParameter();
p.setDeclaration(declaration);
if (that.getTypeVariance()!=null) {
String v = that.getTypeVariance().getText();
p.setCovariant("out".equals(v));
p.setContravariant("in".equals(v));
}
that.setDeclarationModel(p);
visitDeclaration(that, p);
super.visit(that);
}
@Override
public void visit(Tree.AnyMethod that) {
Method m = new Method();
that.setDeclarationModel(m);
visitDeclaration(that, m);
Scope o = enterScope(m);
super.visit(that);
exitScope(o);
checkMethodParameters(that);
that.getDeclarationModel().setTypeParameters(getTypeParameters(that.getTypeParameterList()));
if (that.getType() instanceof Tree.ValueModifier) {
that.getType().addError("methods may not be declared using the keyword value");
}
}
@Override
public void visit(Tree.AnyAttribute that) {
super.visit(that);
if (that.getType() instanceof Tree.FunctionModifier) {
that.getType().addError("attributes may not be declared using the keyword function");
}
}
@Override
public void visit(Tree.MethodArgument that) {
Method m = new Method();
that.setDeclarationModel(m);
visitArgument(that, m);
Scope o = enterScope(m);
super.visit(that);
exitScope(o);
checkMethodArgumentParameters(that);
}
private void checkMethodParameters(Tree.AnyMethod that) {
if (that.getParameterLists().isEmpty()) {
that.addError("missing parameter list in method declaration: " +
name(that.getIdentifier()) );
}
if ( that.getParameterLists().size()>1 ) {
that.addWarning("higher-order methods are not yet supported");
}
}
private void checkMethodArgumentParameters(Tree.MethodArgument that) {
if (that.getParameterLists().isEmpty()) {
that.addError("missing parameter list in named argument declaration: " +
name(that.getIdentifier()) );
}
if ( that.getParameterLists().size()>1 ) {
that.addWarning("higher-order methods are not yet supported");
}
}
@Override
public void visit(Tree.ObjectDefinition that) {
if (that.getClassBody()==null) {
that.addError("missing object body");
}
Class c = new Class();
visitDeclaration(that, c);
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
that.getType().setTypeModel(c.getType());
v.setType(c.getType());
}
@Override
public void visit(Tree.ObjectArgument that) {
if (that.getClassBody()==null) {
that.addError("missing named argument body");
}
Class c = new Class();
visitArgument(that, c);
Value v = new Value();
that.setDeclarationModel(v);
visitArgument(that, v);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
that.getType().setTypeModel(c.getType());
v.setType(c.getType());
}
@Override
public void visit(Tree.AttributeDeclaration that) {
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
super.visit(that);
if ( v.isInterfaceMember() && !v.isFormal()) {
that.addError("interfaces may not have simple attributes");
}
if ( v.isFormal() && that.getSpecifierOrInitializerExpression()!=null ) {
that.addError("formal attributes may not have a value");
}
}
@Override
public void visit(Tree.MethodDeclaration that) {
super.visit(that);
if ( that.getSpecifierExpression()!=null ) {
that.addWarning("method definition by reference is not yet supported");
}
}
@Override
public void visit(Tree.AttributeGetterDefinition that) {
Getter g = new Getter();
that.setDeclarationModel(g);
visitDeclaration(that, g);
Scope o = enterScope(g);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.AttributeArgument that) {
Getter g = new Getter();
that.setDeclarationModel(g);
visitArgument(that, g);
Scope o = enterScope(g);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.AttributeSetterDefinition that) {
Setter s = new Setter();
that.setDeclarationModel(s);
visitDeclaration(that, s);
Scope o = enterScope(s);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.ValueParameterDeclaration that) {
ValueParameter p = new ValueParameter();
p.setDeclaration(declaration);
p.setDefaulted(that.getSpecifierExpression()!=null);
p.setSequenced(that.getType() instanceof Tree.SequencedType);
that.setDeclarationModel(p);
visitDeclaration(that, p);
super.visit(that);
parameterList.getParameters().add(p);
}
@Override
public void visit(Tree.FunctionalParameterDeclaration that) {
FunctionalParameter p = new FunctionalParameter();
p.setDeclaration(declaration);
p.setDefaulted(that.getSpecifierExpression()!=null);
that.setDeclarationModel(p);
visitDeclaration(that, p);
Scope o = enterScope(p);
super.visit(that);
exitScope(o);
parameterList.getParameters().add(p);
that.addWarning("higher order methods are not yet supported");
}
@Override
public void visit(Tree.ParameterList that) {
ParameterList pl = parameterList;
parameterList = new ParameterList();
super.visit(that);
Functional f = (Functional) scope;
if ( f instanceof Class &&
!f.getParameterLists().isEmpty() ) {
that.addError("classes may have only one parameter list");
}
else {
f.addParameterList(parameterList);
}
parameterList = pl;
}
@Override
public void visit(Tree.ControlClause that) {
ControlBlock c = new ControlBlock();
visitElement(that, c);
Scope o = enterScope(c);
super.visit(that);
exitScope(o);
}
@Override
public void visit(Tree.Variable that) {
if (that.getSpecifierExpression()!=null) {
Scope s = scope;
scope = scope.getContainer();
that.getSpecifierExpression().visit(this);
scope = s;
}
Value v = new Value();
that.setDeclarationModel(v);
visitDeclaration(that, v);
if (that.getType()!=null) {
that.getType().visit(this);
}
if (that.getIdentifier()!=null) {
that.getIdentifier().visit(this);
}
if (that.getAnnotationList()!=null) {
that.getAnnotationList().visit(this);
}
//TODO: parameters of callable variables?!
/*if (that.getParameterLists().size()==0) {
if (that.getType() instanceof Tree.FunctionModifier) {
that.getType().addError("variables with no parameters may not be declared using the keyword function");
}
}
else {
if (that.getType() instanceof Tree.ValueModifier) {
that.getType().addError("variables with parameters may not be declared using the keyword value");
}
}*/
that.setScope(scope);
that.setUnit(unit);
}
private List<TypeParameter> getTypeParameters(Tree.TypeParameterList tpl) {
List<TypeParameter> typeParameters = new ArrayList<TypeParameter>();
if (tpl!=null) {
for (Tree.TypeParameterDeclaration tp: tpl.getTypeParameterDeclarations()) {
typeParameters.add(tp.getDeclarationModel());
}
}
return typeParameters;
}
private boolean hasAnnotation(Tree.AnnotationList al, String name) {
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Tree.BaseMemberExpression p = (Tree.BaseMemberExpression) a.getPrimary();
if (p!=null) {
if ( p.getIdentifier().getText().equals(name)) {
return true;
}
}
}
}
return false;
}
@Override public void visit(Tree.Declaration that) {
Declaration model = that.getDeclarationModel();
Declaration d = beginDeclaration(model);
if (declaration!=null) {
Tree.AnnotationList al = that.getAnnotationList();
if (hasAnnotation(al, "shared")) {
model.setShared(true);
}
if (hasAnnotation(al, "default")) {
model.setDefault(true);
if (that instanceof Tree.ObjectDefinition) {
that.addError("object declarations may not be default");
}
}
if (hasAnnotation(al, "formal")) {
model.setFormal(true);
if (that instanceof Tree.ObjectDefinition) {
that.addError("object declarations may not be formal");
}
}
if (hasAnnotation(al, "actual")) {
model.setActual(true);
}
if (hasAnnotation(al, "abstract")) {
if (model instanceof Class) {
((Class) declaration).setAbstract(true);
}
else {
that.addError("declaration is not a class, and may not be abstract");
}
}
if (hasAnnotation(al, "variable")) {
if (model instanceof Value) {
((Value) model).setVariable(true);
}
else {
that.addError("declaration is not a value, and may not be variable");
}
}
buildAnnotations(al);
}
super.visit(that);
endDeclaration(d);
if (model!=null) {
checkFormalMember(that, model);
}
}
private void checkFormalMember(Tree.Declaration that, Declaration d) {
if ( d.isFormal() &&
( !(d.getContainer() instanceof ClassOrInterface) ||
!( (ClassOrInterface) d.getContainer() ).isAbstract()) ) {
that.addError("formal member does not belong to an interface or abstract class");
}
if ( d.isFormal() &&
!(that instanceof Tree.AttributeDeclaration) &&
!(that instanceof Tree.MethodDeclaration) &&
!(that instanceof Tree.ClassDefinition)) {
that.addError("formal member may not have a body");
}
if ( !d.isFormal() &&
d.getContainer() instanceof Interface &&
!(that instanceof Tree.ClassDeclaration) &&
!(that instanceof Tree.InterfaceDeclaration)) {
that.addWarning("concrete members of interfaces not yet supported");
}
}
private void buildAnnotations(Tree.AnnotationList al) {
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Annotation ann = new Annotation();
String name = ( (Tree.BaseMemberExpression) a.getPrimary() ).getIdentifier().getText();
ann.setName(name);
if (a.getNamedArgumentList()!=null) {
for ( Tree.NamedArgument na: a.getNamedArgumentList().getNamedArguments() ) {
if (na instanceof Tree.SpecifiedArgument) {
Tree.Term t = ((Tree.SpecifiedArgument) na).getSpecifierExpression().getExpression().getTerm();
String param = ((Tree.SpecifiedArgument) na).getIdentifier().getText();
if (t instanceof Tree.Literal) {
ann.addNamedArgument( param, ( (Tree.Literal) t ).getText() );
}
else if (t instanceof Tree.BaseTypeExpression) {
ann.addNamedArgument( param, ( (Tree.BaseTypeExpression) t ).getIdentifier().getText() );
}
}
}
}
if (a.getPositionalArgumentList()!=null) {
for ( Tree.PositionalArgument pa: a.getPositionalArgumentList().getPositionalArguments() ) {
Tree.Term t = pa.getExpression().getTerm();
if (t instanceof Tree.Literal) {
ann.addPositionalArgment( ( (Tree.Literal) t ).getText() );
}
else if (t instanceof Tree.BaseTypeExpression) {
ann.addPositionalArgment( ( (Tree.BaseTypeExpression) t ).getIdentifier().getText() );
}
}
}
declaration.getAnnotations().add(ann);
}
}
}
@Override public void visit(Tree.TypedArgument that) {
Declaration d = beginDeclaration(that.getDeclarationModel());
super.visit(that);
endDeclaration(d);
}
@Override
public void visit(Tree.TypeConstraint that) {
TypeParameter p = (TypeParameter) scope.getMemberOrParameter(unit, that.getIdentifier().getText());
that.setDeclarationModel(p);
if (p==null ) {
that.addError("no matching type parameter for constraint: " +
name(that.getIdentifier()));
super.visit(that);
}
else {
Scope o = enterScope(p);
super.visit(that);
exitScope(o);
}
if ( that.getAbstractedType()!=null ) {
that.addWarning("lower bound type constraints are not yet supported");
}
if ( that.getCaseTypes()!=null ) {
that.addWarning("enumerated type constraints are not yet supported");
}
if ( that.getParameterList()!=null ) {
that.addWarning("initialization parameter specifications are not yet supported");
}
}
@Override
public void visit(Tree.TryCatchStatement that) {
super.visit(that);
that.addWarning("try statements are not yet supported");
}
@Override
public void visit(Tree.SwitchStatement that) {
super.visit(that);
that.addWarning("switch statements are not yet supported");
}
@Override
public void visit(Tree.SatisfiesCondition that) {
super.visit(that);
that.addWarning("satisfies conditions are not yet supported");
}
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
that.addWarning("of clause not yet supported");
}
}
| better msg for special case | src/com/redhat/ceylon/compiler/typechecker/analyzer/DeclarationVisitor.java | better msg for special case |
|
Java | apache-2.0 | 8e704d27414339a9236b53262298a58d89dc9da8 | 0 | andgau/client,andgau/client,andgau/client | package es.sinjava.basico;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import es.sinjava.rest.model.Alps;
import es.sinjava.rest.model.Category;
import es.sinjava.rest.model.Descriptor;
import es.sinjava.rest.model.DinamicBean;
import es.sinjava.rest.model.HateoasRoot;
import es.sinjava.rest.model.Item;
import es.sinjava.rest.model.ModelHateoas;
public class App {
public static void main(String... args) throws ClientHandlerException,
UniformInterfaceException, IOException {
String destiny = "http://localhost:8888/";
if (args != null && args.length > 1 && args[0] != null) {
System.out.println("Capturada la url");
destiny = args[0];
}
Client client = Client.create();
WebResource webResource = client.resource(destiny);
ObjectMapper om = new ObjectMapper();
ClientResponse response2 = webResource.accept("application/json").get(
ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response2.getStatus());
}
HateoasRoot hateoas = om.readValue(response2.getEntity(String.class),
HateoasRoot.class);
System.out.println(" Recibidos " + hateoas.get_links().size());
for (Entry<String, Item> item : hateoas.get_links().entrySet()) {
System.out.println("-> " + item.getKey() + " - "
+ item.getValue().getHref());
}
// REcuperamos los descriptores del profile:
URL profileURL = hateoas.get_links().get("profile").getHref();
WebResource webResource2 = client.resource(profileURL.toString());
ClientResponse profileResponse = webResource2
.accept("application/json").get(ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
HateoasRoot profiles = om.readValue(
profileResponse.getEntity(String.class), HateoasRoot.class);
System.out.println(profiles.get_links().size());
profiles.get_links().remove("self");
System.out.println(profiles.get_links().size());
Map<String, Alps> mapaModels = new HashMap<>();
for (Entry<String, Item> hateoasEntitys : profiles.get_links()
.entrySet()) {
webResource2 = client.resource(hateoasEntitys.getValue().getHref()
.toString());
profileResponse = webResource2.accept("application/json").get(
ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
ModelHateoas model = om
.readValue(profileResponse.getEntity(String.class),
ModelHateoas.class);
mapaModels.put(hateoasEntitys.getKey(), model.getAlps());
}
List<DinamicBean> dinamicBeanList = new ArrayList<>();
for (String fieldSelected : mapaModels.keySet()) {
for (Descriptor item : mapaModels.get(fieldSelected)
.getDescriptors()) {
if (item.getType() == null && item.getDescriptors() != null) {
System.out.println(item);
DinamicBean dinamicBean = dinamicBeanForDescriptor(
fieldSelected, hateoas.get_links(), item);
dinamicBeanList.add(dinamicBean);
}
}
}
System.out.println("Sacabao" + dinamicBeanList.size());
}
private static DinamicBean dinamicBeanForDescriptor(String fieldSelected,
Map<String, Item> urls, Descriptor desc) {
DinamicBean db = new DinamicBean();
db.setName(fieldSelected);
db.setUrl(urls.get(fieldSelected).getHref());
db.setProperty(new HashMap<>());
for (Descriptor property : desc.getDescriptors()) {
if (property.getDoc() == null) {
db.getProperty().put(property.getName(), Category.STRING);
} else if (property.getDoc() != null) {
db.getProperty().put(property.getName(), Category.ENUMERATED);
}
}
return db;
}
}
| basico/src/main/java/es/sinjava/basico/App.java | package es.sinjava.basico;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import es.sinjava.rest.model.Alps;
import es.sinjava.rest.model.Category;
import es.sinjava.rest.model.Descriptor;
import es.sinjava.rest.model.DinamicBean;
import es.sinjava.rest.model.HateoasRoot;
import es.sinjava.rest.model.Item;
import es.sinjava.rest.model.ModelHateoas;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) throws ClientHandlerException,
UniformInterfaceException, IOException {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8888/");
ObjectMapper om = new ObjectMapper();
ClientResponse response2 = webResource.accept("application/json").get(
ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response2.getStatus());
}
HateoasRoot hateoas = om.readValue(response2.getEntity(String.class),
HateoasRoot.class);
System.out.println(" Recibidos " + hateoas.get_links().size());
for (Entry<String, Item> item : hateoas.get_links().entrySet()) {
System.out.println("-> " + item.getKey() + " - "
+ item.getValue().getHref());
}
// REcuperamos los descriptores del profile:
URL profileURL = hateoas.get_links().get("profile").getHref();
WebResource webResource2 = client.resource(profileURL.toString());
ClientResponse profileResponse = webResource2
.accept("application/json").get(ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
HateoasRoot profiles = om.readValue(
profileResponse.getEntity(String.class), HateoasRoot.class);
System.out.println(profiles.get_links().size());
profiles.get_links().remove("self");
System.out.println(profiles.get_links().size());
Map<String, Alps> mapaModels = new HashMap<>();
for (Entry<String, Item> hateoasEntitys : profiles.get_links()
.entrySet()) {
webResource2 = client.resource(hateoasEntitys.getValue().getHref()
.toString());
profileResponse = webResource2.accept("application/json").get(
ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
ModelHateoas model = om
.readValue(profileResponse.getEntity(String.class),
ModelHateoas.class);
mapaModels.put(hateoasEntitys.getKey(), model.getAlps());
}
List<DinamicBean> dinamicBeanList = new ArrayList<>();
for (String fieldSelected : mapaModels.keySet()) {
for (Descriptor item : mapaModels.get(fieldSelected)
.getDescriptors()) {
if (item.getType() == null && item.getDescriptors() != null) {
System.out.println(item);
DinamicBean dinamicBean = dinamicBeanForDescriptor(
fieldSelected, hateoas.get_links(), item);
dinamicBeanList.add(dinamicBean);
}
}
}
System.out.println("Sacabao" + dinamicBeanList.size());
}
private static DinamicBean dinamicBeanForDescriptor(String fieldSelected,
Map<String, Item> urls, Descriptor desc) {
DinamicBean db = new DinamicBean();
db.setName(fieldSelected);
db.setUrl(urls.get(fieldSelected).getHref());
db.setProperty(new HashMap<>());
for (Descriptor property : desc.getDescriptors()) {
if (property.getDoc() == null) {
db.getProperty().put(property.getName(), Category.STRING);
} else if (property.getDoc() != null) {
db.getProperty().put(property.getName(), Category.ENUMERATED);
}
}
return db;
}
}
| Entrada por consola | basico/src/main/java/es/sinjava/basico/App.java | Entrada por consola |
|
Java | apache-2.0 | dbe54e685adebbe7f6e4a2ca1c77226ac0849f82 | 0 | TNG/ArchUnit,TNG/ArchUnit | package com.tngtech.archunit.core.domain;
import java.io.File;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.function.Predicate;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.packageexamples.annotated.PackageLevelAnnotation;
import com.tngtech.archunit.core.domain.packageexamples.first.First1;
import com.tngtech.archunit.core.domain.packageexamples.first.First2;
import com.tngtech.archunit.core.domain.packageexamples.second.ClassDependingOnOtherSecondClass;
import com.tngtech.archunit.core.domain.packageexamples.second.Second1;
import com.tngtech.archunit.core.domain.packageexamples.second.sub.SecondSub1;
import com.tngtech.archunit.core.domain.packageexamples.third.sub.ThirdSub1;
import com.tngtech.archunit.core.domain.packageexamples.unrelated.AnyClass;
import com.tngtech.archunit.core.domain.properties.HasName;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysFalse;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue;
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_SIMPLE_NAME;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_CLASSES;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_RELATIVE_NAME;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_SUB_PACKAGES;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
import static com.tngtech.archunit.testutil.Assertions.assertThatDependencies;
import static com.tngtech.archunit.testutil.Assertions.assertThatPackages;
import static com.tngtech.archunit.testutil.Assertions.assertThatType;
import static com.tngtech.archunit.testutil.Assertions.assertThatTypes;
import static java.util.regex.Pattern.quote;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class JavaPackageTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void creates_default_package() {
JavaPackage defaultPackage = importDefaultPackage();
assertThat(defaultPackage.getName()).isEmpty();
assertThat(defaultPackage.getRelativeName()).isEmpty();
assertThat(defaultPackage.containsPackage("any")).isFalse();
assertThat(defaultPackage.containsClass(Object.class)).isFalse();
assertThat(defaultPackage.containsClassWithFullyQualifiedName("some.SomeClass")).isFalse();
assertThat(defaultPackage.containsClassWithSimpleName("SomeClass")).isFalse();
}
@Test
public void rejects_retrieving_non_existing_subpackages() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage("some.pkg");
importDefaultPackage().getPackage("some.pkg");
}
@Test
public void rejects_retrieving_non_existing_classes_by_class_object() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getName());
importDefaultPackage().getClass(Object.class);
}
@Test
public void rejects_retrieving_non_existing_classes_by_fully_qualified_name() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getName());
importDefaultPackage().getClassWithFullyQualifiedName(Object.class.getName());
}
@Test
public void rejects_retrieving_non_existing_classes_by_simple_name() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getSimpleName());
importDefaultPackage().getClassWithSimpleName(Object.class.getSimpleName());
}
@Test
public void creates_single_package() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class);
assertThat(defaultPackage.containsPackage("java.lang"))
.as("default package contains 'java.lang'").isTrue();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.getName()).isEqualTo("java.lang");
assertThat(javaPackage.getDescription()).isEqualTo("Package <java.lang>");
assertThat(javaPackage.getRelativeName()).isEqualTo("lang");
assertThatTypes(javaPackage.getClasses()).contain(Object.class, String.class);
}
@Test
public void keeps_packages_unique() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
assertThat(javaLang).isSameAs(javaLang.getClass(Object.class).getPackage());
}
@Test
public void retrieves_JavaClasses() {
JavaClasses classes = new ClassFileImporter().importClasses(Object.class, String.class);
JavaPackage defaultPackage = classes.getDefaultPackage();
JavaClass javaLangObject = classes.get(Object.class);
assertThat(defaultPackage.getPackage("java").containsClass(javaLangObject))
.as("package 'java' contains " + javaLangObject.getName()).isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClass(javaLangObject))
.as(javaLangObject.getName() + " is contained").isTrue();
assertThat(javaPackage.getClass(Object.class))
.as(javaLangObject.getName() + "is returned").isEqualTo(javaLangObject);
}
@Test
public void retrieves_class_by_class_object() {
Class<?> javaLangObject = Object.class;
JavaPackage defaultPackage = importDefaultPackage(javaLangObject, String.class);
assertThat(defaultPackage.getPackage("java").containsClass(javaLangObject))
.as("package 'java' contains " + javaLangObject.getName()).isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClass(javaLangObject))
.as(javaLangObject + " is reported contained by class object").isTrue();
assertThat(javaPackage.getClass(javaLangObject).isEquivalentTo(javaLangObject))
.as(javaLangObject + " is returned by class object").isTrue();
}
@Test
public void retrieves_class_by_fully_qualified_name() {
Class<Object> javaLangObject = Object.class;
JavaPackage defaultPackage = importDefaultPackage(javaLangObject, String.class);
assertThat(defaultPackage.getPackage("java").containsClassWithFullyQualifiedName(javaLangObject.getName()))
.as("package 'java' contains " + javaLangObject.getName()).isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClassWithFullyQualifiedName(javaLangObject.getName()))
.as(javaLangObject.getName() + " is reported contained by fully qualified name").isTrue();
assertThat(javaPackage.getClassWithFullyQualifiedName(javaLangObject.getName()).isEquivalentTo(javaLangObject))
.as(javaLangObject.getName() + " is returned by fully qualified name").isTrue();
}
@Test
public void retrieves_class_by_simple_class_name() {
Class<Object> javaLangObject = Object.class;
JavaPackage defaultPackage = importDefaultPackage(javaLangObject, String.class);
assertThat(defaultPackage.getPackage("java").containsClassWithSimpleName(javaLangObject.getSimpleName()))
.as("package 'java' contains " + javaLangObject.getName()).isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClassWithSimpleName(javaLangObject.getSimpleName()))
.as(javaLangObject + " is reported contained by simple name").isTrue();
assertThat(javaPackage.getClassWithSimpleName(javaLangObject.getSimpleName()).isEquivalentTo(javaLangObject))
.as(javaLangObject + " is returned by simple name").isTrue();
}
@Test
public void creates_empty_middle_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
assertThat(defaultPackage.containsPackage("java")).as("default package contains 'java'").isTrue();
JavaPackage java = defaultPackage.getPackage("java");
assertThat(java.containsPackage("lang")).isTrue();
assertThat(java.getPackage("lang").getName()).isEqualTo("java.lang");
}
@Test
public void creates_parent_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
assertThat(defaultPackage.getParent()).as("parent of default package").isEmpty();
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
JavaPackage java = javaLang.getParent().get();
assertThat(java.getName()).isEqualTo("java");
assertThat(java.containsPackage("lang")).as("package 'java' contains 'lang'").isTrue();
}
@Test
public void iterates_sub_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Collection.class, File.class, Security.class);
JavaPackage java = defaultPackage.getPackage("java");
assertThatPackages(java.getSubpackages()).containRelativeNames("lang", "util", "io", "security");
assertThatPackages(java.getSubpackages()).containNames("java.lang", "java.util", "java.io", "java.security");
}
@Test
public void iterates_all_classes() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, Annotation.class, Field.class, Security.class);
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
assertThatTypes(javaLang.getAllClasses()).contain(Object.class, String.class, Annotation.class, Field.class);
}
@Test
public void iterates_all_sub_packages() {
JavaPackage defaultPackage = importDefaultPackage(
Object.class, Annotation.class, Collection.class, BlockingQueue.class, Security.class, getClass());
JavaPackage java = defaultPackage.getPackage("java");
assertThatPackages(java.getAllSubpackages()).containPackagesOf(
Object.class, Annotation.class, Collection.class, BlockingQueue.class, Security.class);
}
@Test
public void visits_classes() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, File.class, Serializable.class, Security.class);
final List<JavaClass> visitedClasses = new ArrayList<>();
defaultPackage.accept(startsWith("S"), visitedClasses::add);
assertThatTypes(visitedClasses).contain(String.class, Serializable.class, Security.class);
for (JavaClass visitedClass : visitedClasses) {
assertThat(visitedClass.getSimpleName()).startsWith("S");
}
}
@Test
public void visits_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Annotation.class, File.class, Security.class);
final List<JavaPackage> visitedPackages = new ArrayList<>();
defaultPackage.accept(nameContains(".lang"), visitedPackages::add);
assertThatPackages(visitedPackages).containPackagesOf(Object.class, Annotation.class);
for (JavaPackage visitedPackage : visitedPackages) {
assertThat(visitedPackage.getName()).contains(".lang");
}
}
@Test
public void has_class_dependencies_to_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesFromSelf())
.contain(Second1.class, First2.class)
.contain(SecondSub1.class, ThirdSub1.class)
.contain(SecondSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("third").getClassDependenciesFromSelf())
.contain(ThirdSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesFromSelf())
.doesNotContain(ClassDependingOnOtherSecondClass.class, Second1.class);
assertThatDependencies(examplePackage.getPackage("unrelated").getClassDependenciesFromSelf())
.containOnly(AnyClass.class, Object.class);
}
@Test
public void has_class_dependencies_from_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThatDependencies(examplePackage.getPackage("first").getClassDependenciesToSelf())
.contain(Second1.class, First2.class)
.contain(ThirdSub1.class, First1.class)
.contain(SecondSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("third").getClassDependenciesToSelf())
.contain(SecondSub1.class, ThirdSub1.class);
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesToSelf())
.doesNotContain(ClassDependingOnOtherSecondClass.class, Second1.class);
assertThatDependencies(examplePackage.getPackage("unrelated").getClassDependenciesToSelf())
.isEmpty();
}
@Test
public void has_package_dependencies_to_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThat(examplePackage.getPackage("second").getPackageDependenciesFromSelf())
.containsOnly(
getRoot(examplePackage).getPackage("java.lang"),
examplePackage.getPackage("first"),
examplePackage.getPackage("third.sub"));
assertThat(examplePackage.getPackage("third").getPackageDependenciesFromSelf())
.containsOnly(examplePackage.getPackage("first"));
assertThatPackages(examplePackage.getPackage("unrelated").getPackageDependenciesFromSelf())
.containOnlyNames("java.lang");
}
@Test
public void has_package_dependencies_from_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThat(examplePackage.getPackage("first").getPackageDependenciesToSelf())
.containsOnly(
examplePackage.getPackage("second"),
examplePackage.getPackage("second.sub"),
examplePackage.getPackage("third.sub"));
assertThat(examplePackage.getPackage("third").getPackageDependenciesToSelf())
.containsOnly(examplePackage.getPackage("second.sub"));
assertThat(examplePackage.getPackage("second").getPackageDependenciesToSelf())
.doesNotContain(examplePackage.getPackage("second"));
assertThat(examplePackage.getPackage("unrelated").getPackageDependenciesToSelf())
.isEmpty();
}
@Test
public void test_getPackageInfo() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.getPackageInfo()).isNotNull();
assertThatThrownBy(nonAnnotatedPackage::getPackageInfo)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " does not contain a package-info.java");
}
@Test
public void test_tryGetPackageInfo() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetPackageInfo()).isPresent();
assertThat(nonAnnotatedPackage.tryGetPackageInfo()).isEmpty();
}
@Test
public void test_getAnnotations() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
JavaAnnotation<JavaPackage> annotation = getOnlyElement(annotatedPackage.getAnnotations());
assertThatType(annotation.getRawType()).matches(PackageLevelAnnotation.class);
assertThat(annotation.getOwner()).isEqualTo(annotatedPackage);
assertThat(nonAnnotatedPackage.getAnnotations()).isEmpty();
}
@Test
public void test_getAnnotationOfType_type() {
final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class)).isInstanceOf(PackageLevelAnnotation.class);
assertThatThrownBy(() -> annotatedPackage.getAnnotationOfType(Deprecated.class)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());
assertThatThrownBy(() -> nonAnnotatedPackage.getAnnotationOfType(Deprecated.class)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());
}
@Test
public void test_getAnnotationOfType_typeName() {
final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThatType(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class.getName())
.getRawType()).matches(PackageLevelAnnotation.class);
assertThatThrownBy(() -> annotatedPackage.getAnnotationOfType("not.There")).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @not.There");
assertThatThrownBy(() -> nonAnnotatedPackage.getAnnotationOfType("not.There")).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @not.There");
}
@Test
public void test_tryGetAnnotationOfType_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetAnnotationOfType(PackageLevelAnnotation.class)).isPresent();
assertThat(annotatedPackage.tryGetAnnotationOfType(Deprecated.class)).isEmpty();
assertThat(nonAnnotatedPackage.tryGetAnnotationOfType(Deprecated.class)).isEmpty();
}
@Test
public void test_tryGetAnnotationOfType_typeName() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetAnnotationOfType(PackageLevelAnnotation.class.getName())).isPresent();
assertThat(annotatedPackage.tryGetAnnotationOfType(Deprecated.class.getName())).isEmpty();
assertThat(nonAnnotatedPackage.tryGetAnnotationOfType(Deprecated.class.getName())).isEmpty();
}
@Test
public void test_isAnnotatedWith_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class)).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
}
@Test
public void test_isAnnotatedWith_typeName() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class.getName())).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(Deprecated.class.getName())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(Deprecated.class.getName())).isFalse();
}
@Test
public void test_isAnnotatedWith_predicate() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(alwaysTrue())).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(alwaysFalse())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(alwaysTrue())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(alwaysFalse())).isFalse();
}
@Test
public void function_GET_RELATIVE_NAME() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
String name = GET_RELATIVE_NAME.apply(defaultPackage.getPackage("java.lang"));
assertThat(name).isEqualTo("lang");
}
@Test
public void function_GET_CLASSES() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, Collection.class);
Iterable<JavaClass> classes = GET_CLASSES.apply(defaultPackage.getPackage("java.lang"));
assertThatTypes(classes).contain(Object.class, String.class);
for (JavaClass javaClass : classes) {
assertThat(javaClass.getPackageName()).startsWith("java.lang");
}
}
@Test
public void function_GET_SUB_PACKAGES() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Annotation.class, Field.class, Collection.class);
Iterable<JavaPackage> packages = GET_SUB_PACKAGES.apply(defaultPackage.getPackage("java.lang"));
assertThatPackages(packages).containPackagesOf(Annotation.class, Field.class);
}
private JavaPackage getRoot(JavaPackage javaPackage) {
JavaPackage result = javaPackage;
while (result.getParent().isPresent()) {
result = result.getParent().get();
}
return result;
}
private Predicate<? super JavaPackage> nameContains(String infix) {
return HasName.Predicates.nameMatching(".*" + quote(infix) + ".*");
}
private DescribedPredicate<JavaClass> startsWith(final String prefix) {
return GET_SIMPLE_NAME.is(new DescribedPredicate<String>("starts with '%s'", prefix) {
@Override
public boolean test(String input) {
return input.startsWith(prefix);
}
});
}
private JavaPackage importDefaultPackage(Class<?>... classes) {
return new ClassFileImporter().importClasses(classes).getDefaultPackage();
}
private JavaPackage importPackage(String subpackageName) {
String packageName = getClass().getPackage().getName() + "." + subpackageName;
JavaClasses classes = new ClassFileImporter().importPackages(packageName);
return classes.getPackage(packageName);
}
}
| archunit/src/test/java/com/tngtech/archunit/core/domain/JavaPackageTest.java | package com.tngtech.archunit.core.domain;
import java.io.File;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.function.Predicate;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.packageexamples.annotated.PackageLevelAnnotation;
import com.tngtech.archunit.core.domain.packageexamples.first.First1;
import com.tngtech.archunit.core.domain.packageexamples.first.First2;
import com.tngtech.archunit.core.domain.packageexamples.second.ClassDependingOnOtherSecondClass;
import com.tngtech.archunit.core.domain.packageexamples.second.Second1;
import com.tngtech.archunit.core.domain.packageexamples.second.sub.SecondSub1;
import com.tngtech.archunit.core.domain.packageexamples.third.sub.ThirdSub1;
import com.tngtech.archunit.core.domain.packageexamples.unrelated.AnyClass;
import com.tngtech.archunit.core.domain.properties.HasName;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysFalse;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue;
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_SIMPLE_NAME;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_CLASSES;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_RELATIVE_NAME;
import static com.tngtech.archunit.core.domain.JavaPackage.Functions.GET_SUB_PACKAGES;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
import static com.tngtech.archunit.testutil.Assertions.assertThatDependencies;
import static com.tngtech.archunit.testutil.Assertions.assertThatPackages;
import static com.tngtech.archunit.testutil.Assertions.assertThatType;
import static com.tngtech.archunit.testutil.Assertions.assertThatTypes;
import static java.util.regex.Pattern.quote;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class JavaPackageTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void creates_default_package() {
JavaPackage defaultPackage = importDefaultPackage();
assertThat(defaultPackage.getName()).isEmpty();
assertThat(defaultPackage.getRelativeName()).isEmpty();
assertThat(defaultPackage.containsPackage("any")).isFalse();
assertThat(defaultPackage.containsClass(Object.class)).isFalse();
assertThat(defaultPackage.containsClassWithFullyQualifiedName("some.SomeClass")).isFalse();
assertThat(defaultPackage.containsClassWithSimpleName("SomeClass")).isFalse();
}
@Test
public void rejects_retrieving_non_existing_subpackages() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage("some.pkg");
importDefaultPackage().getPackage("some.pkg");
}
@Test
public void rejects_retrieving_non_existing_classes_by_class_object() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getName());
importDefaultPackage().getClass(Object.class);
}
@Test
public void rejects_retrieving_non_existing_classes_by_fully_qualified_name() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getName());
importDefaultPackage().getClassWithFullyQualifiedName(Object.class.getName());
}
@Test
public void rejects_retrieving_non_existing_classes_by_simple_name() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("does not contain");
thrown.expectMessage(Object.class.getSimpleName());
importDefaultPackage().getClassWithSimpleName(Object.class.getSimpleName());
}
@Test
public void creates_single_package() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class);
assertThat(defaultPackage.containsPackage("java.lang"))
.as("default package contains 'java.lang'").isTrue();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.getName()).isEqualTo("java.lang");
assertThat(javaPackage.getDescription()).isEqualTo("Package <java.lang>");
assertThat(javaPackage.getRelativeName()).isEqualTo("lang");
assertThatTypes(javaPackage.getClasses()).contain(Object.class, String.class);
}
@Test
public void keeps_packages_unique() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
assertThat(javaLang).isSameAs(javaLang.getClass(Object.class).getPackage());
}
@Test
public void retrieves_class_by_class_object() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class);
assertThat(defaultPackage.getPackage("java").containsClass(Object.class))
.as("package 'java' contains java.lang.Object").isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClass(Object.class))
.as("java.lang.Object is reported contained by class object").isTrue();
assertThat(javaPackage.getClass(Object.class).isEquivalentTo(Object.class))
.as("java.lang.Object is returned by class object").isTrue();
}
@Test
public void retrieves_class_by_fully_qualified_name() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class);
assertThat(defaultPackage.getPackage("java").containsClassWithFullyQualifiedName(Object.class.getName()))
.as("package 'java' contains java.lang.Object").isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClassWithFullyQualifiedName(Object.class.getName()))
.as("java.lang.Object is reported contained by fully qualified name").isTrue();
assertThat(javaPackage.getClassWithFullyQualifiedName(Object.class.getName()).isEquivalentTo(Object.class))
.as("java.lang.Object is returned by fully qualified name").isTrue();
}
@Test
public void retrieves_class_by_simple_class_name() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class);
assertThat(defaultPackage.getPackage("java").containsClassWithSimpleName(Object.class.getSimpleName()))
.as("package 'java' contains java.lang.Object").isFalse();
JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
assertThat(javaPackage.containsClassWithSimpleName(Object.class.getSimpleName()))
.as("java.lang.Object is reported contained by simple name").isTrue();
assertThat(javaPackage.getClassWithSimpleName(Object.class.getSimpleName()).isEquivalentTo(Object.class))
.as("java.lang.Object is returned by simple name").isTrue();
}
@Test
public void creates_empty_middle_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
assertThat(defaultPackage.containsPackage("java")).as("default package contains 'java'").isTrue();
JavaPackage java = defaultPackage.getPackage("java");
assertThat(java.containsPackage("lang")).isTrue();
assertThat(java.getPackage("lang").getName()).isEqualTo("java.lang");
}
@Test
public void creates_parent_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
assertThat(defaultPackage.getParent()).as("parent of default package").isEmpty();
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
JavaPackage java = javaLang.getParent().get();
assertThat(java.getName()).isEqualTo("java");
assertThat(java.containsPackage("lang")).as("package 'java' contains 'lang'").isTrue();
}
@Test
public void iterates_sub_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Collection.class, File.class, Security.class);
JavaPackage java = defaultPackage.getPackage("java");
assertThatPackages(java.getSubpackages()).containRelativeNames("lang", "util", "io", "security");
assertThatPackages(java.getSubpackages()).containNames("java.lang", "java.util", "java.io", "java.security");
}
@Test
public void iterates_all_classes() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, Annotation.class, Field.class, Security.class);
JavaPackage javaLang = defaultPackage.getPackage("java.lang");
assertThatTypes(javaLang.getAllClasses()).contain(Object.class, String.class, Annotation.class, Field.class);
}
@Test
public void iterates_all_sub_packages() {
JavaPackage defaultPackage = importDefaultPackage(
Object.class, Annotation.class, Collection.class, BlockingQueue.class, Security.class, getClass());
JavaPackage java = defaultPackage.getPackage("java");
assertThatPackages(java.getAllSubpackages()).containPackagesOf(
Object.class, Annotation.class, Collection.class, BlockingQueue.class, Security.class);
}
@Test
public void visits_classes() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, File.class, Serializable.class, Security.class);
final List<JavaClass> visitedClasses = new ArrayList<>();
defaultPackage.accept(startsWith("S"), visitedClasses::add);
assertThatTypes(visitedClasses).contain(String.class, Serializable.class, Security.class);
for (JavaClass visitedClass : visitedClasses) {
assertThat(visitedClass.getSimpleName()).startsWith("S");
}
}
@Test
public void visits_packages() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Annotation.class, File.class, Security.class);
final List<JavaPackage> visitedPackages = new ArrayList<>();
defaultPackage.accept(nameContains(".lang"), visitedPackages::add);
assertThatPackages(visitedPackages).containPackagesOf(Object.class, Annotation.class);
for (JavaPackage visitedPackage : visitedPackages) {
assertThat(visitedPackage.getName()).contains(".lang");
}
}
@Test
public void has_class_dependencies_to_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesFromSelf())
.contain(Second1.class, First2.class)
.contain(SecondSub1.class, ThirdSub1.class)
.contain(SecondSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("third").getClassDependenciesFromSelf())
.contain(ThirdSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesFromSelf())
.doesNotContain(ClassDependingOnOtherSecondClass.class, Second1.class);
assertThatDependencies(examplePackage.getPackage("unrelated").getClassDependenciesFromSelf())
.containOnly(AnyClass.class, Object.class);
}
@Test
public void has_class_dependencies_from_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThatDependencies(examplePackage.getPackage("first").getClassDependenciesToSelf())
.contain(Second1.class, First2.class)
.contain(ThirdSub1.class, First1.class)
.contain(SecondSub1.class, First1.class);
assertThatDependencies(examplePackage.getPackage("third").getClassDependenciesToSelf())
.contain(SecondSub1.class, ThirdSub1.class);
assertThatDependencies(examplePackage.getPackage("second").getClassDependenciesToSelf())
.doesNotContain(ClassDependingOnOtherSecondClass.class, Second1.class);
assertThatDependencies(examplePackage.getPackage("unrelated").getClassDependenciesToSelf())
.isEmpty();
}
@Test
public void has_package_dependencies_to_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThat(examplePackage.getPackage("second").getPackageDependenciesFromSelf())
.containsOnly(
getRoot(examplePackage).getPackage("java.lang"),
examplePackage.getPackage("first"),
examplePackage.getPackage("third.sub"));
assertThat(examplePackage.getPackage("third").getPackageDependenciesFromSelf())
.containsOnly(examplePackage.getPackage("first"));
assertThatPackages(examplePackage.getPackage("unrelated").getPackageDependenciesFromSelf())
.containOnlyNames("java.lang");
}
@Test
public void has_package_dependencies_from_other_packages() {
JavaPackage examplePackage = importPackage("packageexamples");
assertThat(examplePackage.getPackage("first").getPackageDependenciesToSelf())
.containsOnly(
examplePackage.getPackage("second"),
examplePackage.getPackage("second.sub"),
examplePackage.getPackage("third.sub"));
assertThat(examplePackage.getPackage("third").getPackageDependenciesToSelf())
.containsOnly(examplePackage.getPackage("second.sub"));
assertThat(examplePackage.getPackage("second").getPackageDependenciesToSelf())
.doesNotContain(examplePackage.getPackage("second"));
assertThat(examplePackage.getPackage("unrelated").getPackageDependenciesToSelf())
.isEmpty();
}
@Test
public void test_getPackageInfo() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.getPackageInfo()).isNotNull();
assertThatThrownBy(nonAnnotatedPackage::getPackageInfo)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " does not contain a package-info.java");
}
@Test
public void test_tryGetPackageInfo() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetPackageInfo()).isPresent();
assertThat(nonAnnotatedPackage.tryGetPackageInfo()).isEmpty();
}
@Test
public void test_getAnnotations() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
JavaAnnotation<JavaPackage> annotation = getOnlyElement(annotatedPackage.getAnnotations());
assertThatType(annotation.getRawType()).matches(PackageLevelAnnotation.class);
assertThat(annotation.getOwner()).isEqualTo(annotatedPackage);
assertThat(nonAnnotatedPackage.getAnnotations()).isEmpty();
}
@Test
public void test_getAnnotationOfType_type() {
final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class)).isInstanceOf(PackageLevelAnnotation.class);
assertThatThrownBy(() -> annotatedPackage.getAnnotationOfType(Deprecated.class)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());
assertThatThrownBy(() -> nonAnnotatedPackage.getAnnotationOfType(Deprecated.class)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());
}
@Test
public void test_getAnnotationOfType_typeName() {
final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThatType(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class.getName())
.getRawType()).matches(PackageLevelAnnotation.class);
assertThatThrownBy(() -> annotatedPackage.getAnnotationOfType("not.There")).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @not.There");
assertThatThrownBy(() -> nonAnnotatedPackage.getAnnotationOfType("not.There")).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @not.There");
}
@Test
public void test_tryGetAnnotationOfType_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetAnnotationOfType(PackageLevelAnnotation.class)).isPresent();
assertThat(annotatedPackage.tryGetAnnotationOfType(Deprecated.class)).isEmpty();
assertThat(nonAnnotatedPackage.tryGetAnnotationOfType(Deprecated.class)).isEmpty();
}
@Test
public void test_tryGetAnnotationOfType_typeName() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetAnnotationOfType(PackageLevelAnnotation.class.getName())).isPresent();
assertThat(annotatedPackage.tryGetAnnotationOfType(Deprecated.class.getName())).isEmpty();
assertThat(nonAnnotatedPackage.tryGetAnnotationOfType(Deprecated.class.getName())).isEmpty();
}
@Test
public void test_isAnnotatedWith_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class)).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
}
@Test
public void test_isAnnotatedWith_typeName() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class.getName())).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(Deprecated.class.getName())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(Deprecated.class.getName())).isFalse();
}
@Test
public void test_isAnnotatedWith_predicate() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(alwaysTrue())).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(alwaysFalse())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(alwaysTrue())).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(alwaysFalse())).isFalse();
}
@Test
public void function_GET_RELATIVE_NAME() {
JavaPackage defaultPackage = importDefaultPackage(Object.class);
String name = GET_RELATIVE_NAME.apply(defaultPackage.getPackage("java.lang"));
assertThat(name).isEqualTo("lang");
}
@Test
public void function_GET_CLASSES() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, String.class, Collection.class);
Iterable<JavaClass> classes = GET_CLASSES.apply(defaultPackage.getPackage("java.lang"));
assertThatTypes(classes).contain(Object.class, String.class);
for (JavaClass javaClass : classes) {
assertThat(javaClass.getPackageName()).startsWith("java.lang");
}
}
@Test
public void function_GET_SUB_PACKAGES() {
JavaPackage defaultPackage = importDefaultPackage(Object.class, Annotation.class, Field.class, Collection.class);
Iterable<JavaPackage> packages = GET_SUB_PACKAGES.apply(defaultPackage.getPackage("java.lang"));
assertThatPackages(packages).containPackagesOf(Annotation.class, Field.class);
}
private JavaPackage getRoot(JavaPackage javaPackage) {
JavaPackage result = javaPackage;
while (result.getParent().isPresent()) {
result = result.getParent().get();
}
return result;
}
private Predicate<? super JavaPackage> nameContains(String infix) {
return HasName.Predicates.nameMatching(".*" + quote(infix) + ".*");
}
private DescribedPredicate<JavaClass> startsWith(final String prefix) {
return GET_SIMPLE_NAME.is(new DescribedPredicate<String>("starts with '%s'", prefix) {
@Override
public boolean test(String input) {
return input.startsWith(prefix);
}
});
}
private JavaPackage importDefaultPackage(Class<?>... classes) {
return new ClassFileImporter().importClasses(classes).getDefaultPackage();
}
private JavaPackage importPackage(String subpackageName) {
String packageName = getClass().getPackage().getName() + "." + subpackageName;
JavaClasses classes = new ClassFileImporter().importPackages(packageName);
return classes.getPackage(packageName);
}
}
| add missing test for `JavaPackage.containsClass(JavaClass)`
And improve maintainability of the other similar tests a little by introducing and reusing a variable for the searched class `java.lang.Object`.
Signed-off-by: Peter Gafert <[email protected]>
| archunit/src/test/java/com/tngtech/archunit/core/domain/JavaPackageTest.java | add missing test for `JavaPackage.containsClass(JavaClass)` |
|
Java | apache-2.0 | c196a12ce01db7daf61944180583fc06d5353d99 | 0 | mGhassen/secrecy,L-Henke/secrecy,Doplgangr/secrecy,SecrecySupportTeam/secrecy | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with context work for additional information
* regarding copyright ownership. The ASF licenses context file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use context 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.doplgangr.secrecy.adapters;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewAnimator;
import com.doplgangr.secrecy.CustomApp;
import com.doplgangr.secrecy.R;
import com.doplgangr.secrecy.utils.Util;
import com.doplgangr.secrecy.activities.FilesActivity;
import com.doplgangr.secrecy.events.RestoreDoneEvent;
import com.doplgangr.secrecy.events.RestoringFileEvent;
import com.doplgangr.secrecy.filesystem.Storage;
import com.doplgangr.secrecy.filesystem.encryption.Vault;
import com.doplgangr.secrecy.filesystem.encryption.VaultHolder;
import com.doplgangr.secrecy.jobs.RestoreJob;
import com.doplgangr.secrecy.fragments.SettingsFragment;
import com.ipaulpro.afilechooser.FileChooserActivity;
import com.ipaulpro.afilechooser.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import de.greenrobot.event.EventBus;
public class VaultsListFragment extends Fragment {
//Vault restore module
private static final int REQUESTCODE = 1203; //Arbitrary
private LinearLayout mLinearView;
private ScrollView mScrollView;
private View nothing;
private ActionBarActivity context;
private VaultsAdapter adapter;
private OnVaultSelectedListener mOnVaultSelected;
private OnFragmentFinishListener mFinishListener;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
private static InputMethodManager imm = null;
private static View kbdView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
context = (ActionBarActivity) getActivity();
if (context == null) {
return;
}
VaultHolder.getInstance().clear();
if (context.getSupportActionBar() != null) {
context.getSupportActionBar().setTitle(R.string.App__name);
}
if (!Util.canWrite(Storage.getRoot())) {
Util.alert(CustomApp.context,
CustomApp.context.getString(R.string.Error__root_IOException),
CustomApp.context.getString(R.string.Error__root_IOException_message),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFinishListener.onNew(null, new SettingsFragment());
}
},
null
);
return;
}
imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_list_vault, container, false);
((ActionBarActivity) getActivity()).getSupportActionBar()
.setTitle(R.string.Page_header__vaults);
mLinearView = (LinearLayout) view.findViewById(R.id.list);
mScrollView = (ScrollView) view.findViewById(R.id.scrollView);
nothing = view.findViewById(R.id.nothing);
loadVaultList();
showTutorial();
return view;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add_vault:
add();
return true;
case R.id.action_restore:
restore();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.list_vault, menu);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnVaultSelected = (OnVaultSelectedListener) activity;
mFinishListener = (OnFragmentFinishListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement Listener");
}
}
@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public VaultsAdapter getAdapter() {
return adapter;
}
private void refresh(){
VaultHolder.getInstance().clear();
loadVaultList();
}
private void loadVaultList(){
if (mLinearView != null) {
mLinearView.removeAllViews();
}
adapter = new VaultsAdapter(context, null);
ArrayList<File> files = Storage.getDirectories(Storage.getRoot());
for (File file : files) {
adapter.add(file.getName());
}
adapter.sort();
for (int i = 0; i < files.size(); i++){
final View mView = adapter.getView(i, mLinearView); //inject vaults into list
mLinearView.addView(mView, i);
setClickListener(mView, i);
}
if (adapter.getCount() == 0) {
nothing.setVisibility(View.VISIBLE);
mLinearView.setVisibility(View.GONE);
} else {
nothing.setVisibility(View.GONE);
mLinearView.setVisibility(View.VISIBLE);
}
}
public void onEventMainThread(FilesActivity.shouldRefresh ignored) {
refresh();
}
public void setClickListener(final View mView, final int i) {
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
open(adapter.getItem(i), mView, i);
}
});
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
switchView(mView, R.id.vault_rename_layout);
((EditText) mView.findViewById(R.id.rename_name)).setText(adapter.getItem(i));
mView.findViewById(R.id.rename_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
final String newName = ((EditText) mView.findViewById(R.id.rename_name))
.getText().toString();
switchView(mView, R.id.vault_decrypt_layout);
mView.findViewById(R.id.open_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
String password = ((EditText) mView.findViewById(R.id.open_password))
.getText().toString();
rename(i, newName, password);
switchView(mView, R.id.vault_decrypt_layout);
}
});
mView.findViewById(R.id.open_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
switchView(mView, R.id.vault_name_layout);
}
});
}
});
mView.findViewById(R.id.rename_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchView(mView, R.id.vault_name_layout);
}
});
return true;
}
});
}
void add() {
final View dialogView = View.inflate(context, R.layout.new_credentials, null);
final EditText password = new EditText(context);
password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Vault__new))
.setView(dialogView)
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name = ((EditText) dialogView.findViewById(R.id.newName)).getText().toString();
String password = ((EditText) dialogView.findViewById(R.id.stealth_keycode)).getText().toString();
String Confirmpassword = ((EditText) dialogView.findViewById(R.id.confirmPassword)).getText().toString();
File directory = new File(Storage.getRoot().getAbsolutePath() + "/" + name);
if (!password.equals(Confirmpassword) || "".equals(password))
passwordWrong();
else if (directory.mkdirs()) {
// Create vault to initialize the vault header
ProgressDialog progress = new ProgressDialog(context);
progress.setIndeterminate(true);
progress.setMessage(getString(R.string.Vault__initializing));
progress.setCancelable(false);
progress.show();
createVaultInBackground(name, password, directory, dialog, progress);
} else
failedtocreate();
}
}).setNegativeButton(getString(R.string.CANCEL), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
void restore() {
ArrayList<String> INCLUDE_EXTENSIONS_LIST = new ArrayList<String>();
INCLUDE_EXTENSIONS_LIST.add(".zip");
Intent intent = new Intent(context, FileChooserActivity.class);
intent.putStringArrayListExtra(
FileChooserActivity.EXTRA_FILTER_INCLUDE_EXTENSIONS,
INCLUDE_EXTENSIONS_LIST);
intent.putExtra(FileChooserActivity.PATH, Storage.getRoot().getAbsolutePath());
startActivityForResult(intent, REQUESTCODE);
}
void createVaultInBackground(final String name, final String password,
final File directory, final DialogInterface dialog,
final ProgressDialog progressDialog) {
new Thread(new Runnable() {
@Override
public void run() {
VaultHolder.getInstance().createAndRetrieveVault(name, password);
try {
File file = new File(directory + "/.nomedia");
file.delete();
file.createNewFile();
refresh();
} catch (IOException e) {
e.printStackTrace();
}
dialog.dismiss();
progressDialog.dismiss();
}
}).start();
}
void passwordWrong() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Error__wrong_password_confirmation))
.setMessage(getString(R.string.Error__wrong_password_confirmation_message))
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
});
}
void failedtocreate() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Error__cannot_create_vault))
.setMessage(getString(R.string.Error__cannot_create_vault_message))
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
});
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
switch (requestCode) {
case REQUESTCODE:
// If the file selection was successful
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
Util.alert(
context,
null,
CustomApp.context.getString(R.string.Restore__overwrite_alert),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Uri uri = data.getData();
final String path = FileUtils.getPath(context, uri);
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(CustomApp.context.getString(R.string.Restore__title))
.setContentText(CustomApp.context.getString(R.string.Restore__in_progress))
.setSmallIcon(R.drawable.ic_stat_alert)
.setOngoing(true);
mBuilder.setProgress(0, 0, true);
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
CustomApp.jobManager.addJobInBackground(new RestoreJob(context, new File(path)));
}
},
Util.emptyClickListener
);
}
}
break;
}
}
});
}
public void onEventMainThread(RestoreDoneEvent event) {
mBuilder.setProgress(0, 0, false)
.setStyle(new NotificationCompat.BigTextStyle().bigText( //For long long text
String.format(CustomApp.context.getString(R.string.Restore__finish), event.backupFile)))
.setOngoing(false);
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
}
public void onEventMainThread(RestoringFileEvent event) {
mBuilder.setContentText(event.restoredFile.getAbsolutePath());
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
}
public void open(final String vault, final View mView, final int i) {
// vault name
// View of lisitem
// position of listitem in list
switchView(mView, R.id.vault_decrypt_layout);
mView.findViewById(R.id.open_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String value = ((EditText) mView.findViewById(R.id.open_password))
.getText().toString();
mOnVaultSelected.onVaultSelected(vault, value);
imm.hideSoftInputFromWindow(kbdView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
mView.findViewById(R.id.open_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchView(mView, R.id.vault_name_layout);
imm.hideSoftInputFromWindow(kbdView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
}
void rename(final int position, final String newName, final String password) {
Vault newVault = VaultHolder.getInstance().createAndRetrieveVault(
adapter.getItem(position), password)
.rename(newName);
if (newVault == null)
Util.alert(context,
getString(R.string.Error__rename_password_incorrect),
getString(R.string.Error__rename_password_incorrect_message),
Util.emptyClickListener,
null
);
refresh();
}
void switchView(final View parentView, final int showView) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
EditText passwordView = (EditText) parentView.findViewById(R.id.open_password);
final View renameView = parentView.findViewById(R.id.rename_name);
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setInAnimation(context, R.anim.slide_down);
int viewIndex = 0;
switch (showView) {
case R.id.vault_name_layout:
viewIndex = 0;
break;
case R.id.vault_decrypt_layout:
viewIndex = 1;
if (passwordView != null) {
passwordView.requestFocus();
passwordView.setText(""); //Reset password field everytime
}
// Only one vault selected at that time
passwordView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setDisplayedChild(0);
}
}
});
kbdView = passwordView;
imm.showSoftInput(passwordView, InputMethodManager.SHOW_IMPLICIT);
break;
case R.id.vault_delete_layout:
viewIndex = 2;
break;
case R.id.vault_rename_layout:
viewIndex = 3;
if (renameView != null)
renameView.requestFocus();
// Only one vault selected at that time
renameView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setDisplayedChild(0);
}
}
});
kbdView = renameView;
imm.showSoftInput(renameView, InputMethodManager.SHOW_IMPLICIT);
break;
}
viewAnimator.setDisplayedChild(viewIndex);
}
});
}
void finish() {
mFinishListener.onFinish(this);
}
void showTutorial() {
if ((adapter.getCount() > 0
&& PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("showVaultLongClickTutorial", true))) {
final View mView =
context.getLayoutInflater().inflate(R.layout.vault_item_tutorial, mLinearView, false);
TextView mInstructions = (TextView) mView.findViewById(R.id.Tutorial__instruction);
if (mInstructions != null)
mInstructions.setText(R.string.Tutorial__long_click_to_rename);
mLinearView.addView(mView, 0);
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
mLinearView.removeView(mView);
SharedPreferences.Editor editor
= PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("showVaultLongClickTutorial", false);
editor.apply();
return true;
}
});
}
}
public interface OnVaultSelectedListener {
public void onVaultSelected(String vault, String password);
}
public interface OnFragmentFinishListener {
public void onFinish(Fragment fragment);
public void onNew(Bundle bundle, Fragment fragment);
}
public interface onPanic {
void onPanic();
}
}
| app/src/main/java/com/doplgangr/secrecy/adapters/VaultsListFragment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with context work for additional information
* regarding copyright ownership. The ASF licenses context file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use context 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.doplgangr.secrecy.adapters;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewAnimator;
import com.doplgangr.secrecy.CustomApp;
import com.doplgangr.secrecy.R;
import com.doplgangr.secrecy.utils.Util;
import com.doplgangr.secrecy.activities.FilesActivity;
import com.doplgangr.secrecy.events.RestoreDoneEvent;
import com.doplgangr.secrecy.events.RestoringFileEvent;
import com.doplgangr.secrecy.filesystem.Storage;
import com.doplgangr.secrecy.filesystem.encryption.Vault;
import com.doplgangr.secrecy.filesystem.encryption.VaultHolder;
import com.doplgangr.secrecy.jobs.RestoreJob;
import com.doplgangr.secrecy.fragments.SettingsFragment;
import com.ipaulpro.afilechooser.FileChooserActivity;
import com.ipaulpro.afilechooser.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import de.greenrobot.event.EventBus;
public class VaultsListFragment extends Fragment {
//Vault restore module
private static final int REQUESTCODE = 1203; //Arbitrary
private LinearLayout mLinearView;
private ScrollView mScrollView;
private View nothing;
private ActionBarActivity context;
private VaultsAdapter adapter;
private OnVaultSelectedListener mOnVaultSelected;
private OnFragmentFinishListener mFinishListener;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
private static InputMethodManager imm = null;
private static View kbdView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
context = (ActionBarActivity) getActivity();
if (context == null) {
return;
}
VaultHolder.getInstance().clear();
if (context.getSupportActionBar() != null) {
context.getSupportActionBar().setTitle(R.string.App__name);
}
if (!Util.canWrite(Storage.getRoot())) {
Util.alert(CustomApp.context,
CustomApp.context.getString(R.string.Error__root_IOException),
CustomApp.context.getString(R.string.Error__root_IOException_message),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFinishListener.onNew(null, new SettingsFragment());
}
},
null
);
return;
}
imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_list_vault, container, false);
((ActionBarActivity) getActivity()).getSupportActionBar()
.setTitle(R.string.Page_header__vaults);
mLinearView = (LinearLayout) view.findViewById(R.id.list);
mScrollView = (ScrollView) view.findViewById(R.id.scrollView);
nothing = view.findViewById(R.id.nothing);
loadVaultList();
showTutorial();
return view;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add_vault:
add();
return true;
case R.id.action_restore:
restore();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.list_vault, menu);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnVaultSelected = (OnVaultSelectedListener) activity;
mFinishListener = (OnFragmentFinishListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement Listener");
}
}
@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public VaultsAdapter getAdapter() {
return adapter;
}
private void refresh(){
VaultHolder.getInstance().clear();
loadVaultList();
}
private void loadVaultList(){
if (mLinearView != null) {
mLinearView.removeAllViews();
}
adapter = new VaultsAdapter(context, null);
ArrayList<File> files = Storage.getDirectories(Storage.getRoot());
for (File file : files) {
adapter.add(file.getName());
}
adapter.sort();
for (int i = 0; i < files.size(); i++){
final View mView = adapter.getView(i, mLinearView); //inject vaults into list
mLinearView.addView(mView, i);
setClickListener(mView, i);
}
if (adapter.getCount() == 0) {
nothing.setVisibility(View.VISIBLE);
mLinearView.setVisibility(View.GONE);
} else {
nothing.setVisibility(View.GONE);
mLinearView.setVisibility(View.VISIBLE);
}
}
public void onEventMainThread(FilesActivity.shouldRefresh ignored) {
refresh();
}
public void setClickListener(final View mView, final int i) {
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
open(adapter.getItem(i), mView, i);
}
});
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
switchView(mView, R.id.vault_rename_layout);
((EditText) mView.findViewById(R.id.rename_name)).setText(adapter.getItem(i));
mView.findViewById(R.id.rename_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
final String newName = ((EditText) mView.findViewById(R.id.rename_name))
.getText().toString();
switchView(mView, R.id.vault_decrypt_layout);
mView.findViewById(R.id.open_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
String password = ((EditText) mView.findViewById(R.id.open_password))
.getText().toString();
rename(i, newName, password);
switchView(mView, R.id.vault_decrypt_layout);
}
});
mView.findViewById(R.id.open_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View ignored) {
switchView(mView, R.id.vault_name_layout);
}
});
}
});
mView.findViewById(R.id.rename_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchView(mView, R.id.vault_name_layout);
}
});
return true;
}
});
}
void add() {
final View dialogView = View.inflate(context, R.layout.new_credentials, null);
final EditText password = new EditText(context);
password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Vault__new))
.setView(dialogView)
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name = ((EditText) dialogView.findViewById(R.id.newName)).getText().toString();
String password = ((EditText) dialogView.findViewById(R.id.stealth_keycode)).getText().toString();
String Confirmpassword = ((EditText) dialogView.findViewById(R.id.confirmPassword)).getText().toString();
File directory = new File(Storage.getRoot().getAbsolutePath() + "/" + name);
if (!password.equals(Confirmpassword) || "".equals(password))
passwordWrong();
else if (directory.mkdirs()) {
// Create vault to initialize the vault header
ProgressDialog progress = new ProgressDialog(context);
progress.setIndeterminate(true);
progress.setMessage(getString(R.string.Vault__initializing));
progress.setCancelable(false);
progress.show();
createVaultInBackground(name, password, directory, dialog, progress);
} else
failedtocreate();
}
}).setNegativeButton(getString(R.string.CANCEL), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
void restore() {
ArrayList<String> INCLUDE_EXTENSIONS_LIST = new ArrayList<String>();
INCLUDE_EXTENSIONS_LIST.add(".zip");
Intent intent = new Intent(context, FileChooserActivity.class);
intent.putStringArrayListExtra(
FileChooserActivity.EXTRA_FILTER_INCLUDE_EXTENSIONS,
INCLUDE_EXTENSIONS_LIST);
intent.putExtra(FileChooserActivity.PATH, Storage.getRoot().getAbsolutePath());
startActivityForResult(intent, REQUESTCODE);
}
void createVaultInBackground(final String name, final String password,
final File directory, final DialogInterface dialog,
final ProgressDialog progressDialog) {
new Thread(new Runnable() {
@Override
public void run() {
VaultHolder.getInstance().createAndRetrieveVault(name, password);
try {
File file = new File(directory + "/.nomedia");
file.delete();
file.createNewFile();
refresh();
} catch (IOException e) {
e.printStackTrace();
}
dialog.dismiss();
progressDialog.dismiss();
}
}).start();
}
void passwordWrong() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Error__wrong_password_confirmation))
.setMessage(getString(R.string.Error__wrong_password_confirmation_message))
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
});
}
void failedtocreate() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(context)
.setTitle(getString(R.string.Error__cannot_create_vault))
.setMessage(getString(R.string.Error__cannot_create_vault_message))
.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
});
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
switch (requestCode) {
case REQUESTCODE:
// If the file selection was successful
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
Util.alert(
context,
null,
CustomApp.context.getString(R.string.Restore__overwrite_alert),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Uri uri = data.getData();
final String path = FileUtils.getPath(context, uri);
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(CustomApp.context.getString(R.string.Restore__title))
.setContentText(CustomApp.context.getString(R.string.Restore__in_progress))
.setSmallIcon(R.drawable.ic_stat_alert)
.setOngoing(true);
mBuilder.setProgress(0, 0, true);
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
CustomApp.jobManager.addJobInBackground(new RestoreJob(context, new File(path)));
}
},
Util.emptyClickListener
);
}
}
break;
}
}
});
}
public void onEventMainThread(RestoreDoneEvent event) {
mBuilder.setProgress(0, 0, false)
.setStyle(new NotificationCompat.BigTextStyle().bigText( //For long long text
String.format(CustomApp.context.getString(R.string.Restore__finish), event.backupFile)))
.setOngoing(false);
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
}
public void onEventMainThread(RestoringFileEvent event) {
mBuilder.setContentText(event.restoredFile.getAbsolutePath());
mNotifyManager.notify(REQUESTCODE, mBuilder.build());
}
public void open(final String vault, final View mView, final int i) {
// vault name
// View of lisitem
// position of listitem in list
switchView(mView, R.id.vault_decrypt_layout);
mView.findViewById(R.id.open_ok)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String value = ((EditText) mView.findViewById(R.id.open_password))
.getText().toString();
mOnVaultSelected.onVaultSelected(vault, value);
imm.hideSoftInputFromWindow(kbdView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
mView.findViewById(R.id.open_cancel)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchView(mView, R.id.vault_name_layout);
imm.hideSoftInputFromWindow(kbdView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
}
void rename(final int position, final String newName, final String password) {
Vault newVault = VaultHolder.getInstance().createAndRetrieveVault(
adapter.getItem(position), password)
.rename(newName);
if (newVault == null)
Util.alert(context,
getString(R.string.Error__rename_password_incorrect),
getString(R.string.Error__rename_password_incorrect_message),
Util.emptyClickListener,
null
);
refresh();
}
void switchView(final View parentView, final int showView) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
EditText passwordView = (EditText) parentView.findViewById(R.id.open_password);
final View renameView = parentView.findViewById(R.id.rename_name);
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setInAnimation(context, R.anim.slide_down);
int viewIndex = 0;
switch (showView) {
case R.id.vault_name_layout:
viewIndex = 0;
break;
case R.id.vault_decrypt_layout:
viewIndex = 1;
if (passwordView != null) {
passwordView.requestFocus();
passwordView.setText(""); //Reset password field everytime
}
// Only one vault selected at that time
passwordView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setDisplayedChild(0);
}
}
});
kbdView = passwordView;
imm.showSoftInput(passwordView, InputMethodManager.SHOW_IMPLICIT);
break;
case R.id.vault_delete_layout:
viewIndex = 2;
break;
case R.id.vault_rename_layout:
viewIndex = 3;
if (renameView != null)
renameView.requestFocus();
// Only one vault selected at that time
renameView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ViewAnimator viewAnimator = (ViewAnimator) parentView.findViewById(R.id.viewAnimator);
viewAnimator.setDisplayedChild(0);
}
}
});
kbdView = renameView;
imm.showSoftInput(renameView, InputMethodManager.SHOW_IMPLICIT);
break;
}
viewAnimator.setDisplayedChild(viewIndex);
}
});
}
void finish() {
mFinishListener.onFinish(this);
}
void showTutorial() {
if ((adapter.getCount() > 0
&& PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("showVaultLongClickTutorial", true))) {
final View mView =
context.getLayoutInflater().inflate(R.layout.vault_item_tutorial, mLinearView, false);
TextView mInstructions = (TextView) mView.findViewById(R.id.Tutorial__instruction);
if (mInstructions != null)
mInstructions.setText(R.string.Tutorial__long_click_to_rename);
mLinearView.addView(mView, 0);
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
mLinearView.removeView(mView);
SharedPreferences.Editor editor
= PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("showVaultLongClickTutorial", false);
editor.apply();
return true;
}
});
}
}
public interface OnVaultSelectedListener {
public void onVaultSelected(String vault, String password);
}
public interface OnFragmentFinishListener {
public void onFinish(Fragment fragment);
public void onNew(Bundle bundle, Fragment fragment);
}
public interface onPanic {
void onPanic();
}
}
| Fixed menu not shown in vault list
| app/src/main/java/com/doplgangr/secrecy/adapters/VaultsListFragment.java | Fixed menu not shown in vault list |
|
Java | apache-2.0 | 06b7352b870c4c74ef5039edfe9a32d2e62286ab | 0 | google/depan,google/depan,google/depan,google/depan | /*
* Copyright 2007 Google 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.
*/
package com.google.devtools.depan.eclipse.trees;
import com.google.devtools.depan.model.GraphNode;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* Provide a tree view of the graph nodes.
*
* @param <E> Type of data associated to each Node<Element>.
*
* @author [email protected] (Yohann Coppel)
*/
public class NodeTreeView<E> {
/**
* Define a generous limit for the number of tree elements to automatically
* open for display. A more refined implementation might offer a user
* configured choice, but this prevents the most egregious problems from
* over-zealous expansion of tree elements.
*
* Approx 8000 nodes takes ~8sec to expand and display. So a limit of 1000
* should keep the initial open time down to ~1sec.
*/
public static final int AUTO_EXPAND_LIMIT = 1000;
protected TreeViewer tree;
private GraphData<E> data;
static {
NodeViewAdapterFactory.register();
}
public NodeTreeView(Composite parent, int style) {
initWidget(parent, style);
}
protected void initWidget(Composite parent, int style) {
tree = new TreeViewer(parent, style);
tree.setLabelProvider(new WorkbenchLabelProvider());
tree.setContentProvider(new BaseWorkbenchContentProvider());
}
public void updateData(GraphData<E> data) {
// Some updates don't change the nodes.
if (this.data == data)
return;
this.data = data;
updateTree();
updateExpandState();
//$ NEEDED??
tree.refresh();
}
private void updateTree() {
NodeWrapperRoot<E> roots = data.getHierarchyRoots();
tree.setInput(roots);
}
private void updateExpandState() {
TreePath[] expandState = data.getExpandState();
if (expandState.length > 0) {
getTreeViewer().setExpandedTreePaths(expandState);
return;
}
if (data.countTreeNodes() < AUTO_EXPAND_LIMIT) {
getTreeViewer().expandAll();
}
else {
getTreeViewer().expandToLevel(1);
}
data.saveExpandState(getTreeViewer().getExpandedTreePaths());
}
public TreeViewer getTreeViewer() {
return tree;
}
/**
* Gives the NodeWrapper containing the given node. Useful for update
* methods when we just have a node, but need the object actually contained in
* a tree for example.
*
* @param node the node
* @return the NodeWrapper<F> containing the given node.
*/
public NodeWrapper<E> getNodeWrapper(GraphNode node) {
return data.getNodeWrapper(node);
}
/**
* @author [email protected] (Yohann Coppel)
*
* @param <E> Type of data associated to each Node<Element>.
*/
public static class NodeWrapper<E> extends PlatformObject {
private final GraphNode node;
private final E content;
public NodeWrapper<E>[] childs;
public final NodeWrapper<E> parent;
public final GraphData<E> data;
public NodeWrapper(
GraphNode node,
E content,
NodeWrapper<E> parent,
GraphData<E> data) {
this.node = node;
this.content = content;
this.parent= parent;
this.data = data;
}
public GraphNode getNode() {
return node;
}
public E getContent() {
return content;
}
@Override
public String toString() {
return node.toString();
}
}
/**
* @param <E> Type of data associated to each Node<Element>.
*/
public static class NodeWrapperRoot<E> extends PlatformObject {
public NodeWrapper<E>[] roots = null;
}
}
| DepanApp/prod/src/com/google/devtools/depan/eclipse/trees/NodeTreeView.java | /*
* Copyright 2007 Google 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.
*/
package com.google.devtools.depan.eclipse.trees;
import com.google.devtools.depan.model.GraphNode;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import java.util.Calendar;
/**
* Provide a tree view of the graph nodes.
*
* @param <E> Type of data associated to each Node<Element>.
*
* @author [email protected] (Yohann Coppel)
*/
public class NodeTreeView<E> {
/**
* Define a generous limit for the number of tree elements to automatically
* open for display. A more refined implementation might offer a user
* configured choice, but this prevents the most egregious problems from
* over-zealous expansion of tree elements.
*
* Approx 8000 nodes takes ~8sec to expand and display. So a limit of 1000
* should keep the initial open time down to ~1sec.
*/
public static final int AUTO_EXPAND_LIMIT = 1000;
protected TreeViewer tree;
private GraphData<E> data;
static {
NodeViewAdapterFactory.register();
}
public NodeTreeView(Composite parent, int style) {
initWidget(parent, style);
}
protected void initWidget(Composite parent, int style) {
tree = new TreeViewer(parent, style);
tree.setLabelProvider(new WorkbenchLabelProvider());
tree.setContentProvider(new BaseWorkbenchContentProvider());
}
public void updateData(GraphData<E> data) {
// Some updates don't change the nodes.
if (this.data == data)
return;
this.data = data;
updateTree();
updateExpandState();
//$ NEEDED??
tree.refresh();
}
private void updateTree() {
NodeWrapperRoot<E> roots = data.getHierarchyRoots();
tree.setInput(roots);
}
private void updateExpandState() {
TreePath[] expandState = data.getExpandState();
if (expandState.length > 0) {
getTreeViewer().setExpandedTreePaths(expandState);
return;
}
if (data.countTreeNodes() < AUTO_EXPAND_LIMIT) {
getTreeViewer().expandAll();
}
else {
getTreeViewer().expandToLevel(1);
}
data.saveExpandState(getTreeViewer().getExpandedTreePaths());
}
public TreeViewer getTreeViewer() {
return tree;
}
/**
* Gives the NodeWrapper containing the given node. Useful for update
* methods when we just have a node, but need the object actually contained in
* a tree for example.
*
* @param node the node
* @return the NodeWrapper<F> containing the given node.
*/
public NodeWrapper<E> getNodeWrapper(GraphNode node) {
return data.getNodeWrapper(node);
}
/**
* @author [email protected] (Yohann Coppel)
*
* @param <E> Type of data associated to each Node<Element>.
*/
public static class NodeWrapper<E> extends PlatformObject {
private final GraphNode node;
private final E content;
public NodeWrapper<E>[] childs;
public final NodeWrapper<E> parent;
public final GraphData<E> data;
public NodeWrapper(
GraphNode node,
E content,
NodeWrapper<E> parent,
GraphData<E> data) {
this.node = node;
this.content = content;
this.parent= parent;
this.data = data;
}
public GraphNode getNode() {
return node;
}
public E getContent() {
return content;
}
@Override
public String toString() {
return node.toString();
}
}
/**
* @param <E> Type of data associated to each Node<Element>.
*/
public static class NodeWrapperRoot<E> extends PlatformObject {
public NodeWrapper<E>[] roots = null;
}
}
| Remove unnecessary import.
| DepanApp/prod/src/com/google/devtools/depan/eclipse/trees/NodeTreeView.java | Remove unnecessary import. |
|
Java | apache-2.0 | 192e07a9457732bdfa04e7b3702e8933c4c382f5 | 0 | reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.rabbit;
import com.epam.ta.reportportal.core.configs.Conditions;
import com.epam.ta.reportportal.exception.ReportPortalException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ShutdownSignalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
/**
* Finds a queue that doesn't have any connected consumers and set's it
* to consumer that should be restarted, so it can be registered
* with a different queue.
*
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
@Component
@Conditional(Conditions.NotTestCondition.class)
public class ConsumerEventListener implements ApplicationListener<ListenerContainerConsumerFailedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerEventListener.class);
@Autowired
@Qualifier("queues")
private List<Queue> queues;
@Autowired
private ConnectionFactory connectionFactory;
@Override
public void onApplicationEvent(ListenerContainerConsumerFailedEvent event) {
Object source = event.getSource();
if (source instanceof AbstractMessageListenerContainer) {
AbstractMessageListenerContainer listenerContainer = (AbstractMessageListenerContainer) source;
Throwable throwable = event.getThrowable();
if (throwable.getCause() instanceof IOException && throwable.getCause().getCause() instanceof ShutdownSignalException
&& throwable.getCause().getCause().getMessage().contains("in exclusive use")) {
for (Queue q : queues) {
if (getQueueConsumerCount(q) == 0) {
listenerContainer.setQueues(q);
LOGGER.info("Restarting consumer with a queue {}", q.getName());
}
}
}
}
}
private int getQueueConsumerCount(Queue queue) {
try (Channel channel = connectionFactory.createConnection().createChannel(false)) {
return channel.queueDeclarePassive(queue.getName()).getConsumerCount();
} catch (IOException | TimeoutException e) {
throw new ReportPortalException(e.getMessage());
}
}
}
| src/main/java/com/epam/ta/reportportal/ws/rabbit/ConsumerEventListener.java | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.rabbit;
import com.epam.ta.reportportal.core.configs.Conditions;
import com.epam.ta.reportportal.exception.ReportPortalException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ShutdownSignalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
/**
* Finds a queue that doesn't have any connected consumers and set's it
* to consumer that should be restarted, so it can be registered
* with a different queue.
*
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
@Component
@Conditional(Conditions.NotTestCondition.class)
public class ConsumerEventListener implements ApplicationListener<ListenerContainerConsumerFailedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerEventListener.class);
@Autowired
@Qualifier("queues")
private List<Queue> queues;
@Autowired
private ConnectionFactory connectionFactory;
@Override
public void onApplicationEvent(ListenerContainerConsumerFailedEvent event) {
Object source = event.getSource();
if (source instanceof AbstractMessageListenerContainer) {
AbstractMessageListenerContainer listenerContainer = (AbstractMessageListenerContainer) source;
Throwable throwable = event.getThrowable();
if (throwable.getCause() instanceof IOException && throwable.getCause().getCause() instanceof ShutdownSignalException
&& throwable.getCause().getCause().getMessage().contains("in exclusive use")) {
for (Queue q : queues) {
if (getQueueConsumerCount(q) == 0) {
listenerContainer.setQueueNames(q.getName());
LOGGER.info("Restarting consumer with a queue {}", q.getName());
}
}
}
}
}
private int getQueueConsumerCount(Queue queue) {
try (Channel channel = connectionFactory.createConnection().createChannel(false)) {
return channel.queueDeclarePassive(queue.getName()).getConsumerCount();
} catch (IOException | TimeoutException e) {
throw new ReportPortalException(e.getMessage());
}
}
}
| replace changing listener container queue name with a queue
| src/main/java/com/epam/ta/reportportal/ws/rabbit/ConsumerEventListener.java | replace changing listener container queue name with a queue |
|
Java | apache-2.0 | a8b1a3a304b8f1616461b467a5a04ab69f7c5573 | 0 | akosyakov/intellij-community,kdwink/intellij-community,caot/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,retomerz/intellij-community,robovm/robovm-studio,jagguli/intellij-community,joewalnes/idea-community,dslomov/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,jexp/idea2,vladmm/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,izonder/intellij-community,wreckJ/intellij-community,holmes/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,semonte/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,signed/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,consulo/consulo,robovm/robovm-studio,salguarnieri/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,holmes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ernestp/consulo,signed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,caot/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,jexp/idea2,pwoodworth/intellij-community,signed/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,slisson/intellij-community,joewalnes/idea-community,allotria/intellij-community,da1z/intellij-community,amith01994/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,consulo/consulo,nicolargo/intellij-community,blademainer/intellij-community,blademainer/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,slisson/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,samthor/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,samthor/intellij-community,slisson/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,amith01994/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,retomerz/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,suncycheng/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,signed/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,diorcety/intellij-community,kool79/intellij-community,clumsy/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,jexp/idea2,ftomassetti/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,holmes/intellij-community,dslomov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ernestp/consulo,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,youdonghai/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,samthor/intellij-community,hurricup/intellij-community,apixandru/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,joewalnes/idea-community,fitermay/intellij-community,da1z/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,jagguli/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,kool79/intellij-community,xfournet/intellij-community,samthor/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,caot/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,FHannes/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,kdwink/intellij-community,blademainer/intellij-community,izonder/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,supersven/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,supersven/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,signed/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,idea4bsd/idea4bsd,suncycheng/intellij-community,hurricup/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,retomerz/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ibinti/intellij-community,asedunov/intellij-community,jexp/idea2,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,supersven/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,vladmm/intellij-community,kdwink/intellij-community,petteyg/intellij-community,kdwink/intellij-community,jagguli/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,FHannes/intellij-community,fitermay/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,Distrotech/intellij-community,caot/intellij-community,supersven/intellij-community,petteyg/intellij-community,caot/intellij-community,samthor/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,apixandru/intellij-community,clumsy/intellij-community,fitermay/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,jexp/idea2,semonte/intellij-community,kool79/intellij-community,signed/intellij-community,consulo/consulo,Lekanich/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,ryano144/intellij-community,semonte/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,consulo/consulo,ahb0327/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,consulo/consulo,salguarnieri/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,caot/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,jagguli/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,holmes/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,fitermay/intellij-community,jexp/idea2,clumsy/intellij-community,supersven/intellij-community,retomerz/intellij-community,blademainer/intellij-community,vladmm/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,samthor/intellij-community,hurricup/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ernestp/consulo,nicolargo/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,diorcety/intellij-community,izonder/intellij-community,ibinti/intellij-community,asedunov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,signed/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,jexp/idea2,jagguli/intellij-community,slisson/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,supersven/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,caot/intellij-community,joewalnes/idea-community,FHannes/intellij-community,FHannes/intellij-community,slisson/intellij-community,signed/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,jexp/idea2,retomerz/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,gnuhub/intellij-community,kool79/intellij-community,holmes/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,izonder/intellij-community,FHannes/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ernestp/consulo,slisson/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,robovm/robovm-studio,apixandru/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,fnouama/intellij-community,xfournet/intellij-community,signed/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,joewalnes/idea-community,semonte/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,hurricup/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,clumsy/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,signed/intellij-community,clumsy/intellij-community,samthor/intellij-community,Lekanich/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,caot/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,signed/intellij-community,vladmm/intellij-community,dslomov/intellij-community,izonder/intellij-community,hurricup/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,allotria/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,kdwink/intellij-community,consulo/consulo,wreckJ/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ryano144/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,robovm/robovm-studio,joewalnes/idea-community,lucafavatella/intellij-community,retomerz/intellij-community,samthor/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,kool79/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,blademainer/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,semonte/intellij-community,fitermay/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,semonte/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,ernestp/consulo,vvv1559/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,fitermay/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,da1z/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,holmes/intellij-community,youdonghai/intellij-community,da1z/intellij-community,allotria/intellij-community,vladmm/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,amith01994/intellij-community | package com.intellij.psi.impl.source.xml;
import com.intellij.j2ee.ExternalResourceManager;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.impl.PomTransactionBase;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.impl.events.XmlAttributeSetImpl;
import com.intellij.pom.xml.impl.events.XmlTagNameChangedImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.*;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.BidirectionalMap;
import com.intellij.util.containers.CollectionUtil;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import com.intellij.xml.util.XmlTagTextUtil;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author Mike
*/
public class XmlTagImpl extends XmlElementImpl implements XmlTag/*, ModificationTracker */{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlTagImpl");
private static final Class ourReferenceClass = XmlTag.class;
private String myName = null;
private XmlAttribute[] myAttributes = null;
private Map<String, String> myAttributeValueMap = null;
private XmlTag[] myTags = null;
private XmlTagValue myValue = null;
private Map<String, CachedValue<XmlNSDescriptor>> myNSDescriptorsMap = null;
private boolean myHaveNamespaceDeclarations = false;
private BidirectionalMap<String, String> myNamespaceMap = null;
public XmlTagImpl() {
this(XML_TAG);
}
protected XmlTagImpl(IElementType type) {
super(type);
}
public void clearCaches() {
myName = null;
myNamespaceMap = null;
myAttributes = null;
myAttributeValueMap = null;
myHaveNamespaceDeclarations = false;
myValue = null;
myTags = null;
myNSDescriptorsMap = null;
super.clearCaches();
}
@NotNull
public PsiReference[] getReferences() {
ProgressManager.getInstance().checkCanceled();
final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
if (startTagName == null) return PsiReference.EMPTY_ARRAY;
final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
final PsiReference[] referencesFromProviders = ResolveUtil.getReferencesFromProviders(this, ourReferenceClass);
if (endTagName != null){
final PsiReference[] psiReferences = new PsiReference[referencesFromProviders.length + 2];
psiReferences[0] = new TagNameReference(startTagName, true);
psiReferences[1] = new TagNameReference(endTagName, false);
System.arraycopy(referencesFromProviders, 0, psiReferences, 2, referencesFromProviders.length);
return psiReferences;
}
else{
final PsiReference[] psiReferences = new PsiReference[referencesFromProviders.length + 1];
psiReferences[0] = new TagNameReference(startTagName, true);
System.arraycopy(referencesFromProviders, 0, psiReferences, 1, referencesFromProviders.length);
return psiReferences;
}
}
public XmlNSDescriptor getNSDescriptor(final String namespace, boolean strict) {
initNSDescriptorsMap();
final CachedValue<XmlNSDescriptor> descriptor = myNSDescriptorsMap.get(namespace);
if(descriptor != null) return descriptor.getValue();
final XmlTag parent = getParentTag();
if(parent == null){
final XmlDocument parentOfType = PsiTreeUtil.getParentOfType(this, XmlDocument.class);
if(parentOfType == null) return null;
return parentOfType.getDefaultNSDescriptor(namespace, strict);
}
return parent.getNSDescriptor(namespace, strict);
}
public boolean isEmpty() {
return XmlChildRole.CLOSING_TAG_START_FINDER.findChild(this) == null;
}
private Map<String, CachedValue<XmlNSDescriptor>> initNSDescriptorsMap() {
boolean exceptionOccurred = false;
if(myNSDescriptorsMap == null){
try{
{
// XSD aware attributes processing
final String noNamespaceDeclaration = getAttributeValue("noNamespaceSchemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
final String schemaLocationDeclaration = getAttributeValue("schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
if(noNamespaceDeclaration != null){
initializeSchema(XmlUtil.EMPTY_URI, noNamespaceDeclaration);
}
if(schemaLocationDeclaration != null){
final StringTokenizer tokenizer = new StringTokenizer(schemaLocationDeclaration);
while(tokenizer.hasMoreTokens()){
final String uri = tokenizer.nextToken();
if(tokenizer.hasMoreTokens()){
initializeSchema(uri, tokenizer.nextToken());
}
}
}
}
{
// namespace attributes processing (XSD declaration via ExternalResourceManager)
if(hasNamespaceDeclarations()){
final XmlAttribute[] attributes = getAttributes();
for (final XmlAttribute attribute : attributes) {
if (attribute.isNamespaceDeclaration()) {
String ns = attribute.getValue();
if (ns == null) ns = XmlUtil.EMPTY_URI;
if (myNSDescriptorsMap == null || !myNSDescriptorsMap.containsKey(ns)) initializeSchema(ns, ns);
}
}
}
}
}
catch(RuntimeException e){
myNSDescriptorsMap = null;
exceptionOccurred = true;
throw e;
}
finally{
if(myNSDescriptorsMap == null && !exceptionOccurred) {
myNSDescriptorsMap = Collections.emptyMap();
}
}
}
return myNSDescriptorsMap;
}
private boolean initializeSchema(final String namespace, final String fileLocation) {
if(myNSDescriptorsMap == null) myNSDescriptorsMap = new HashMap<String, CachedValue<XmlNSDescriptor>>();
final XmlFile file = XmlUtil.findXmlFile(XmlUtil.getContainingFile(this),
ExternalResourceManager.getInstance().getResourceLocation(fileLocation));
final PsiMetaOwner owner;
if (file == null) {
final String attributeValue = getAttributeValue("targetNamespace");
if (namespace.equals(attributeValue)) {
owner = this;
} else {
owner = null;
}
} else {
owner = file.getDocument();
}
if (owner != null){
myNSDescriptorsMap.put(namespace, getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<XmlNSDescriptor>() {
public CachedValueProvider.Result<XmlNSDescriptor> compute() {
return new Result<XmlNSDescriptor>(
(XmlNSDescriptor)owner.getMetaData(),
new Object[]{file}
);
}
}, false));
}
return true;
}
public PsiReference getReference() {
final PsiReference[] references = getReferences();
if (references != null && references.length > 0){
return references[0];
}
return null;
}
public XmlElementDescriptor getDescriptor() {
final String namespace = getNamespace();
XmlElementDescriptor elementDescriptor;
if (XmlUtil.EMPTY_URI.equals(namespace)) { //nonqualified items
final PsiElement parent = getParent();
if (parent instanceof XmlTag) {
final XmlElementDescriptor descriptor = ((XmlTag)parent).getDescriptor();
if (descriptor != null) {
elementDescriptor = descriptor.getElementDescriptor(this);
if (elementDescriptor != null && !(elementDescriptor instanceof AnyXmlElementDescriptor)) {
return elementDescriptor;
}
}
}
}
final XmlNSDescriptor nsDescriptor = getNSDescriptor(namespace, false);
elementDescriptor = (nsDescriptor != null) ? nsDescriptor.getElementDescriptor(this) : null;
if(elementDescriptor == null){
elementDescriptor = XmlUtil.findXmlDescriptorByType(this);
}
return elementDescriptor;
}
public int getChildRole(ASTNode child) {
LOG.assertTrue(child.getTreeParent() == this);
IElementType i = child.getElementType();
if (i == XML_NAME || i == XML_TAG_NAME) {
return ChildRole.XML_TAG_NAME;
}
else if (i == XML_ATTRIBUTE) {
return ChildRole.XML_ATTRIBUTE;
}
else {
return ChildRole.NONE;
}
}
public String getName() {
if (myName != null) return myName;
final ASTNode nameElement = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
if (nameElement != null){
myName = nameElement.getText();
}
else{
myName = "";
}
return myName;
}
public PsiElement setName(final String name) throws IncorrectOperationException {
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
model.runTransaction(new PomTransactionBase(this, aspect) {
public PomModelEvent runInner() throws IncorrectOperationException{
final String oldName = getName();
final XmlTagImpl dummyTag = (XmlTagImpl)getManager().getElementFactory().createTagFromText(XmlTagTextUtil.composeTagText(name, "aa"));
final XmlTagImpl tag = XmlTagImpl.this;
final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(tag);
ChangeUtil.replaceChild(tag, (TreeElement)XmlChildRole.START_TAG_NAME_FINDER.findChild(tag), ChangeUtil.copyElement((TreeElement)XmlChildRole.START_TAG_NAME_FINDER.findChild(dummyTag), charTableByTree));
final ASTNode childByRole = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(tag);
if(childByRole != null) ChangeUtil.replaceChild(tag, (TreeElement)childByRole, ChangeUtil.copyElement((TreeElement)XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(dummyTag), charTableByTree));
return XmlTagNameChangedImpl.createXmlTagNameChanged(model, tag, oldName);
}
});
return this;
}
public XmlAttribute[] getAttributes() {
if(myAttributes != null) return myAttributes;
myAttributeValueMap = new HashMap<String, String>();
myAttributes = calculateAttributes();
return myAttributes;
}
@NotNull
protected XmlAttribute[] calculateAttributes() {
final List<XmlAttribute> result = new ArrayList<XmlAttribute>(10);
processElements(
new PsiElementProcessor() {
public boolean execute(PsiElement element) {
if (element instanceof XmlAttribute){
XmlAttribute attribute = (XmlAttribute)element;
result.add(attribute);
cacheOneAttributeValue(attribute.getName(),attribute.getValue());
myHaveNamespaceDeclarations = myHaveNamespaceDeclarations || attribute.isNamespaceDeclaration();
}
else if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_TAG_END) {
return false;
}
return true;
}
}, this
);
if (result.isEmpty()) {
myAttributeValueMap = Collections.emptyMap();
return XmlAttribute.EMPTY_ARRAY;
}
else {
return CollectionUtil.toArray(result, new XmlAttribute[result.size()]);
}
}
protected void cacheOneAttributeValue(String name, String value) {
myAttributeValueMap.put(name, value);
}
public String getAttributeValue(String qname) {
if(myAttributeValueMap == null) getAttributes();
return myAttributeValueMap.get(qname);
}
public String getAttributeValue(String name, String namespace) {
final String prefix = getPrefixByNamespace(namespace);
if(prefix != null && prefix.length() > 0) name = prefix + ":" + name;
return getAttributeValue(name);
}
public XmlTag[] getSubTags() {
if(myTags != null) return myTags;
final List<XmlTag> result = new ArrayList<XmlTag>();
processElements(
new PsiElementProcessor() {
public boolean execute(PsiElement element) {
if (element instanceof XmlTag) result.add((XmlTag)element);
return true;
}
}, this);
myTags = result.toArray(new XmlTag[result.size()]);
return myTags;
}
public XmlTag[] findSubTags(String name) {
return findSubTags(name, null);
}
public XmlTag[] findSubTags(final String name, final String namespace) {
final XmlTag[] subTags = getSubTags();
final List<XmlTag> result = new ArrayList<XmlTag>();
for (final XmlTag subTag : subTags) {
if (namespace == null) {
if (name.equals(subTag.getName())) result.add(subTag);
}
else if (name.equals(subTag.getLocalName()) && namespace.equals(subTag.getNamespace())) {
result.add(subTag);
}
}
return result.toArray(new XmlTag[result.size()]);
}
public XmlTag findFirstSubTag(String name) {
final XmlTag[] subTags = findSubTags(name);
if(subTags.length > 0) return subTags[0];
return null;
}
public XmlAttribute getAttribute(String name, String namespace) {
if(namespace == null || namespace == XmlUtil.ANY_URI || namespace.equals(getNamespace())) return getAttribute(name);
final String prefix = getPrefixByNamespace(namespace);
String qname = prefix != null && prefix.length() > 0 ? prefix + ":" + name : name;
return getAttribute(qname);
}
private XmlAttribute getAttribute(String qname){
if(qname == null) return null;
final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(this);
final XmlAttribute[] attributes = getAttributes();
final CharSequence charTableIndex = charTableByTree.intern(qname);
for (final XmlAttribute attribute : attributes) {
final LeafElement attrNameElement = (LeafElement)XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(attribute.getNode());
if (attrNameElement.getInternedText() == charTableIndex) return attribute;
}
return null;
}
public String getNamespace() {
return getNamespaceByPrefix(getNamespacePrefix());
}
@NotNull
public String getNamespacePrefix() {
final String name = getName();
final int index = name.indexOf(':');
if(index >= 0){
return name.substring(0, index);
}
return "";
}
@NotNull
public String getNamespaceByPrefix(String prefix){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
if(myNamespaceMap != null){
final String ns = myNamespaceMap.get(prefix);
if(ns != null) return ns;
}
if(parent instanceof XmlTag) return ((XmlTag)parent).getNamespaceByPrefix(prefix);
return XmlUtil.EMPTY_URI;
}
public String getPrefixByNamespace(String namespace){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
if(myNamespaceMap != null){
List<String> keysByValue = myNamespaceMap.getKeysByValue(namespace);
final String ns = keysByValue == null ? null : keysByValue.get(0);
if(ns != null) return ns;
}
if(parent instanceof XmlTag) return ((XmlTag)parent).getPrefixByNamespace(namespace);
return null;
}
public String[] knownNamespaces(){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
List<String> known = Collections.emptyList();
if(myNamespaceMap != null){
known = new ArrayList<String>(myNamespaceMap.values());
}
if(parent instanceof XmlTag){
if(known.isEmpty()) return ((XmlTag)parent).knownNamespaces();
known.addAll(Arrays.asList(((XmlTag)parent).knownNamespaces()));
}
else if(getContainingFile() instanceof JspFile) {
final XmlTag rootTag = ((JspFile)getContainingFile()).getDocument().getRootTag();
if (rootTag != this) known.addAll(Arrays.asList((rootTag.knownNamespaces())));
}
return known.toArray(new String[known.size()]);
}
private void initNamespaceMaps(PsiElement parent) {
if(myNamespaceMap == null && hasNamespaceDeclarations()){
final BidirectionalMap<String, String> namespaceMap = new BidirectionalMap<String, String>();
final XmlAttribute[] attributes = getAttributes();
for (final XmlAttribute attribute : attributes) {
if (attribute.isNamespaceDeclaration()) {
final String name = attribute.getName();
int splitIndex = name.indexOf(':');
final String value = attribute.getValue();
if (value != null) {
if (splitIndex < 0) {
namespaceMap.put("", value);
}
else {
namespaceMap.put(XmlUtil.findLocalNameByQualifiedName(name), value);
}
}
}
}
myNamespaceMap = namespaceMap; // assign to field should be as last statement, to prevent incomplete initialization due to ProcessCancelledException
}
if(parent instanceof XmlDocument && myNamespaceMap == null){
final BidirectionalMap<String, String> namespaceMap = new BidirectionalMap<String, String>();
final String[][] defaultNamespace = XmlUtil.getDefaultNamespaces((XmlDocument)parent);
for (final String[] prefix2ns : defaultNamespace) {
namespaceMap.put(prefix2ns[0], prefix2ns[1]);
}
myNamespaceMap = namespaceMap; // assign to field should be as last statement, to prevent incomplete initialization due to ProcessCancelledException
}
}
public String getLocalName() {
final String name = getName();
return name.substring(name.indexOf(':') + 1);
}
public boolean hasNamespaceDeclarations() {
getAttributes();
return myHaveNamespaceDeclarations;
}
public Map<String, String> getLocalNamespaceDeclarations() {
Map<String, String> namespaces = new HashMap<String, String>();
for (final XmlAttribute attribute : getAttributes()) {
if (!attribute.isNamespaceDeclaration() || attribute.getValue() == null) continue;
namespaces.put(attribute.getLocalName(), attribute.getValue());
}
return namespaces;
}
public XmlAttribute setAttribute(String qname, String value) throws IncorrectOperationException {
final XmlAttribute attribute = getAttribute(qname);
if(attribute != null){
if(value == null){
deleteChildInternal(attribute.getNode());
return null;
}
attribute.setValue(value);
return attribute;
}
else if (value == null) {
return null;
}
else {
PsiElement xmlAttribute = add(getManager().getElementFactory().createXmlAttribute(qname, value));
while(!(xmlAttribute instanceof XmlAttribute)) xmlAttribute = xmlAttribute.getNextSibling();
return (XmlAttribute)xmlAttribute;
}
}
public XmlAttribute setAttribute(String name, String namespace, String value) throws IncorrectOperationException {
final String prefix = getPrefixByNamespace(namespace);
if(prefix != null && prefix.length() > 0) name = prefix + ":" + name;
return setAttribute(name, value);
}
public XmlTag createChildTag(String localName, String namespace, String bodyText, boolean enforceNamespacesDeep) {
return XmlUtil.createChildTag(this, localName, namespace, bodyText, enforceNamespacesDeep);
}
public XmlTagValue getValue() {
if(myValue != null) return myValue;
final PsiElement[] elements = getElements();
final List<PsiElement> bodyElements = new ArrayList<PsiElement>(elements.length);
boolean insideBody = false;
for (final PsiElement element : elements) {
final ASTNode treeElement = element.getNode();
if (insideBody) {
if (treeElement.getElementType() == XmlTokenType.XML_END_TAG_START) break;
if (!(element instanceof XmlTagChild)) continue;
bodyElements.add(element);
}
else if (treeElement.getElementType() == XmlTokenType.XML_TAG_END) insideBody = true;
}
return myValue = new XmlTagValueImpl(bodyElements.toArray(XmlTagChild.EMPTY_ARRAY), this);
}
private PsiElement[] getElements() {
final List<PsiElement> elements = new ArrayList<PsiElement>();
processElements(new PsiElementProcessor() {
public boolean execute(PsiElement psiElement) {
elements.add(psiElement);
return true;
}
}, this);
return elements.toArray(new PsiElement[elements.size()]);
}
public void accept(PsiElementVisitor visitor) {
visitor.visitXmlTag(this);
}
public String toString() {
return "XmlTag:" + getName();
}
public PsiMetaData getMetaData() {
return MetaRegistry.getMeta(this);
}
public boolean isMetaEnough() {
return true;
}
public TreeElement addInternal(TreeElement first, ASTNode last, ASTNode anchor, Boolean beforeB) {
//ChameleonTransforming.transformChildren(this);
TreeElement firstAppended = null;
boolean before = beforeB != null ? beforeB.booleanValue() : true;
try{
TreeElement next;
do {
next = first.getTreeNext();
if (firstAppended == null) {
firstAppended = addInternal(first, anchor, before);
anchor = firstAppended;
}
else {
anchor = addInternal(first, anchor, false);
}
}
while (first != last && (first = next) != null);
}
catch(IncorrectOperationException ioe){}
finally{
clearCaches();
}
return firstAppended;
}
private TreeElement addInternal(TreeElement child, ASTNode anchor, boolean before) throws IncorrectOperationException{
final PomModel model = getProject().getModel();
final InsertTransaction transaction;
if (anchor != null && child.getElementType() == XmlElementType.XML_TEXT) {
XmlText psi = null;
if(anchor.getPsi() instanceof XmlText)
psi = (XmlText)anchor.getPsi();
else {
final ASTNode other = before ? anchor.getTreePrev() : anchor.getTreeNext();
if(other != null && other.getPsi() instanceof XmlText) {
before = !before;
psi = (XmlText)other.getPsi();
}
}
if(psi != null){
if(before)
psi.insertText(((XmlText)child.getPsi()).getValue(), 0);
else
psi.insertText(((XmlText)child.getPsi()).getValue(), psi.getValue().length());
return (TreeElement)psi.getNode();
}
}
LOG.assertTrue(child.getPsi() instanceof XmlAttribute || child.getPsi() instanceof XmlTagChild);
if (child.getElementType() == XmlElementType.XML_ATTRIBUTE) {
transaction = new InsertAttributeTransaction(child, anchor, before, model);
}
else if (anchor == null){
transaction = getBodyInsertTransaction(child);
}
else{
transaction = new GenericInsertTransaction(child, anchor, before);
}
model.runTransaction(transaction);
return transaction.getFirstInserted();
}
protected InsertTransaction getBodyInsertTransaction(final TreeElement child) {
return new BodyInsertTransaction(child);
}
public void deleteChildInternal(final ASTNode child) {
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
if(child.getElementType() == XmlElementType.XML_ATTRIBUTE){
try {
model.runTransaction(new PomTransactionBase(this, aspect) {
public PomModelEvent runInner() {
final String name = ((XmlAttribute)child).getName();
XmlTagImpl.super.deleteChildInternal(child);
return XmlAttributeSetImpl.createXmlAttributeSet(model, XmlTagImpl.this, name, null);
}
});
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
else{
XmlTagImpl.super.deleteChildInternal(child);
}
}
private ASTNode expandTag() throws IncorrectOperationException{
ASTNode endTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(XmlTagImpl.this);
if(endTagStart == null){
final XmlTagImpl tagFromText = (XmlTagImpl)getManager().getElementFactory().createTagFromText("<" + getName() + "></" + getName() + ">");
final ASTNode startTagStart = XmlChildRole.START_TAG_END_FINDER.findChild(tagFromText);
endTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(tagFromText);
final LeafElement emptyTagEnd = (LeafElement)XmlChildRole.EMPTY_TAG_END_FINDER.findChild(this);
if(emptyTagEnd != null) removeChild(emptyTagEnd);
addChildren(startTagStart, null, null);
}
return endTagStart;
}
public XmlTag getParentTag() {
final PsiElement parent = getParent();
if(parent instanceof XmlTag) return (XmlTag)parent;
return null;
}
public XmlTagChild getNextSiblingInTag() {
final PsiElement nextSibling = getNextSibling();
if(nextSibling instanceof XmlTagChild) return (XmlTagChild)nextSibling;
return null;
}
public XmlTagChild getPrevSiblingInTag() {
final PsiElement prevSibling = getPrevSibling();
if(prevSibling instanceof XmlTagChild) return (XmlTagChild)prevSibling;
return null;
}
protected class BodyInsertTransaction extends InsertTransaction{
private TreeElement myChild;
private ASTNode myNewElement;
public BodyInsertTransaction(TreeElement child) {
super(XmlTagImpl.this);
this.myChild = child;
}
public PomModelEvent runInner() throws IncorrectOperationException {
final ASTNode anchor = expandTag();
if(myChild.getElementType() == XmlElementType.XML_TAG){
// compute where to insert tag according to DTD or XSD
final XmlElementDescriptor parentDescriptor = getDescriptor();
final XmlTag[] subTags = getSubTags();
if (parentDescriptor != null && subTags.length > 0){
final XmlElementDescriptor[] childElementDescriptors = parentDescriptor.getElementsDescriptors(XmlTagImpl.this);
int subTagNum = -1;
for (final XmlElementDescriptor childElementDescriptor : childElementDescriptors) {
final String childElementName = childElementDescriptor.getName();
while (subTagNum < subTags.length - 1 && subTags[subTagNum + 1].getName().equals(childElementName)) {
subTagNum++;
}
if (childElementName.equals(XmlChildRole.START_TAG_NAME_FINDER.findChild(myChild).getText())) {
// insert child just after anchor
// insert into the position specified by index
if (subTagNum >= 0) {
final ASTNode subTag = (ASTNode)subTags[subTagNum];
if (subTag.getTreeParent() != XmlTagImpl.this) {
// in entity
final XmlEntityRef entityRef = PsiTreeUtil.getParentOfType(subTags[subTagNum], XmlEntityRef.class);
throw new IncorrectOperationException(
"Can't insert subtag to entity! Entity reference text: " + entityRef != null ? entityRef.getText() : "");
}
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, subTag, Boolean.FALSE);
}
else {
final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this);
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.FALSE);
}
return null;
}
}
}
}
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, anchor, Boolean.TRUE);
return null;
}
public TreeElement getFirstInserted(){
return (TreeElement)myNewElement;
}
}
protected XmlText splitText(final XmlTextImpl childText, final int displayOffset) throws IncorrectOperationException{
if(displayOffset == 0) return childText;
if(displayOffset >= childText.getValue().length()) return null;
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
class MyTransaction extends PomTransactionBase {
private XmlTextImpl myRight;
public MyTransaction() {
super(XmlTagImpl.this, aspect);
}
public PomModelEvent runInner() throws IncorrectOperationException{
final PsiFile containingFile = getContainingFile();
final FileElement holder = new DummyHolder(containingFile.getManager(), null, ((PsiFileImpl)containingFile).getTreeElement().getCharTable()).getTreeElement();
final XmlTextImpl rightText = (XmlTextImpl)Factory.createCompositeElement(XmlElementType.XML_TEXT);
TreeUtil.addChildren(holder, rightText);
addChild(rightText, childText.getTreeNext());
final String value = childText.getValue();
childText.setValue(value.substring(0, displayOffset));
rightText.setValue(value.substring(displayOffset));
myRight = rightText;
return null;
}
public XmlText getResult() {
return myRight;
}
}
final MyTransaction transaction = new MyTransaction();
model.runTransaction(transaction);
return transaction.getResult();
}
protected class InsertAttributeTransaction extends InsertTransaction{
private final TreeElement myChild;
private final ASTNode myAnchor;
private final boolean myBefore;
private final PomModel myModel;
private TreeElement myFirstInserted = null;
public InsertAttributeTransaction(final TreeElement child, final ASTNode anchor, final boolean before, final PomModel model) {
super(XmlTagImpl.this);
myChild = child;
myAnchor = anchor;
myBefore = before;
myModel = model;
}
public PomModelEvent runInner(){
final String value = ((XmlAttribute)myChild).getValue();
final String name = ((XmlAttribute)myChild).getName();
if (myAnchor == null) {
ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this);
if (startTagEnd == null) startTagEnd = XmlChildRole.EMPTY_TAG_END_FINDER.findChild(XmlTagImpl.this);
if (startTagEnd == null) {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, null, null);
}
else {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, startTagEnd, Boolean.TRUE);
}
}
else {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, myAnchor, Boolean.valueOf(myBefore));
}
return XmlAttributeSetImpl.createXmlAttributeSet(myModel, XmlTagImpl.this, name, value);
}
public TreeElement getFirstInserted(){
return myFirstInserted;
}
}
protected class GenericInsertTransaction extends InsertTransaction{
private final TreeElement myChild;
private final ASTNode myAnchor;
private final boolean myBefore;
private TreeElement myRetHolder;
public GenericInsertTransaction(final TreeElement child, final ASTNode anchor, final boolean before) {
super(XmlTagImpl.this);
myChild = child;
myAnchor = anchor;
myBefore = before;
}
public PomModelEvent runInner() {
myRetHolder = XmlTagImpl.super.addInternal(myChild, myChild, myAnchor, Boolean.valueOf(myBefore));
return null;
}
public TreeElement getFirstInserted() {
return myRetHolder;
}
}
protected abstract class InsertTransaction extends PomTransactionBase{
public InsertTransaction(final PsiElement scope) {
super(scope, getProject().getModel().getModelAspect(XmlAspect.class));
}
public abstract TreeElement getFirstInserted();
}
}
| source/com/intellij/psi/impl/source/xml/XmlTagImpl.java | package com.intellij.psi.impl.source.xml;
import com.intellij.j2ee.ExternalResourceManager;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.impl.PomTransactionBase;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.impl.events.XmlAttributeSetImpl;
import com.intellij.pom.xml.impl.events.XmlTagNameChangedImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.*;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.BidirectionalMap;
import com.intellij.util.containers.CollectionUtil;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import com.intellij.xml.util.XmlTagTextUtil;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author Mike
*/
public class XmlTagImpl extends XmlElementImpl implements XmlTag/*, ModificationTracker */{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlTagImpl");
private static final Class ourReferenceClass = XmlTag.class;
private String myName = null;
private XmlAttribute[] myAttributes = null;
private Map<String, String> myAttributeValueMap = null;
private XmlTag[] myTags = null;
private XmlTagValue myValue = null;
private Map<String, CachedValue<XmlNSDescriptor>> myNSDescriptorsMap = null;
private boolean myHaveNamespaceDeclarations = false;
private BidirectionalMap<String, String> myNamespaceMap = null;
public XmlTagImpl() {
this(XML_TAG);
}
protected XmlTagImpl(IElementType type) {
super(type);
}
public void clearCaches() {
myName = null;
myNamespaceMap = null;
myAttributes = null;
myAttributeValueMap = null;
myHaveNamespaceDeclarations = false;
myValue = null;
myTags = null;
myNSDescriptorsMap = null;
super.clearCaches();
}
@NotNull
public PsiReference[] getReferences() {
ProgressManager.getInstance().checkCanceled();
final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
if (startTagName == null) return PsiReference.EMPTY_ARRAY;
final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
final PsiReference[] referencesFromProviders = ResolveUtil.getReferencesFromProviders(this, ourReferenceClass);
if (endTagName != null){
final PsiReference[] psiReferences = new PsiReference[referencesFromProviders.length + 2];
psiReferences[0] = new TagNameReference(startTagName, true);
psiReferences[1] = new TagNameReference(endTagName, false);
System.arraycopy(referencesFromProviders, 0, psiReferences, 2, referencesFromProviders.length);
return psiReferences;
}
else{
final PsiReference[] psiReferences = new PsiReference[referencesFromProviders.length + 1];
psiReferences[0] = new TagNameReference(startTagName, true);
System.arraycopy(referencesFromProviders, 0, psiReferences, 1, referencesFromProviders.length);
return psiReferences;
}
}
public XmlNSDescriptor getNSDescriptor(final String namespace, boolean strict) {
initNSDescriptorsMap();
final CachedValue<XmlNSDescriptor> descriptor = myNSDescriptorsMap.get(namespace);
if(descriptor != null) return descriptor.getValue();
final XmlTag parent = getParentTag();
if(parent == null){
final XmlDocument parentOfType = PsiTreeUtil.getParentOfType(this, XmlDocument.class);
if(parentOfType == null) return null;
return parentOfType.getDefaultNSDescriptor(namespace, strict);
}
return parent.getNSDescriptor(namespace, strict);
}
public boolean isEmpty() {
return XmlChildRole.CLOSING_TAG_START_FINDER.findChild(this) == null;
}
private Map<String, CachedValue<XmlNSDescriptor>> initNSDescriptorsMap() {
boolean exceptionOccurred = false;
if(myNSDescriptorsMap == null){
try{
{
// XSD aware attributes processing
final String noNamespaceDeclaration = getAttributeValue("noNamespaceSchemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
final String schemaLocationDeclaration = getAttributeValue("schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
if(noNamespaceDeclaration != null){
initializeSchema(XmlUtil.EMPTY_URI, noNamespaceDeclaration);
}
if(schemaLocationDeclaration != null){
final StringTokenizer tokenizer = new StringTokenizer(schemaLocationDeclaration);
while(tokenizer.hasMoreTokens()){
final String uri = tokenizer.nextToken();
if(tokenizer.hasMoreTokens()){
initializeSchema(uri, tokenizer.nextToken());
}
}
}
}
{
// namespace attributes processing (XSD declaration via ExternalResourceManager)
if(hasNamespaceDeclarations()){
final XmlAttribute[] attributes = getAttributes();
for (final XmlAttribute attribute : attributes) {
if (attribute.isNamespaceDeclaration()) {
String ns = attribute.getValue();
if (ns == null) ns = XmlUtil.EMPTY_URI;
if (myNSDescriptorsMap == null || !myNSDescriptorsMap.containsKey(ns)) initializeSchema(ns, ns);
}
}
}
}
}
catch(RuntimeException e){
myNSDescriptorsMap = null;
exceptionOccurred = true;
throw e;
}
finally{
if(myNSDescriptorsMap == null && !exceptionOccurred) {
myNSDescriptorsMap = Collections.emptyMap();
}
}
}
return myNSDescriptorsMap;
}
private boolean initializeSchema(final String namespace, final String fileLocation) {
if(myNSDescriptorsMap == null) myNSDescriptorsMap = new HashMap<String, CachedValue<XmlNSDescriptor>>();
final XmlFile file = XmlUtil.findXmlFile(XmlUtil.getContainingFile(this),
ExternalResourceManager.getInstance().getResourceLocation(fileLocation));
final PsiMetaOwner owner;
if (file == null) {
final String attributeValue = getAttributeValue("targetNamespace");
if (namespace.equals(attributeValue)) {
owner = this;
} else {
owner = null;
}
} else {
owner = file.getDocument();
}
if (owner != null){
myNSDescriptorsMap.put(namespace, getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<XmlNSDescriptor>() {
public CachedValueProvider.Result<XmlNSDescriptor> compute() {
return new Result<XmlNSDescriptor>(
(XmlNSDescriptor)owner.getMetaData(),
new Object[]{file}
);
}
}, false));
}
return true;
}
public PsiReference getReference() {
final PsiReference[] references = getReferences();
if (references != null && references.length > 0){
return references[0];
}
return null;
}
public XmlElementDescriptor getDescriptor() {
final String namespace = getNamespace();
XmlElementDescriptor elementDescriptor;
if (XmlUtil.EMPTY_URI.equals(namespace)) { //nonqualified items
final PsiElement parent = getParent();
if (parent instanceof XmlTag) {
final XmlElementDescriptor descriptor = ((XmlTag)parent).getDescriptor();
if (descriptor != null) {
elementDescriptor = descriptor.getElementDescriptor(this);
if (elementDescriptor != null && !(elementDescriptor instanceof AnyXmlElementDescriptor)) {
return elementDescriptor;
}
}
}
}
final XmlNSDescriptor nsDescriptor = getNSDescriptor(namespace, false);
elementDescriptor = (nsDescriptor != null) ? nsDescriptor.getElementDescriptor(this) : null;
if(elementDescriptor == null){
elementDescriptor = XmlUtil.findXmlDescriptorByType(this);
}
return elementDescriptor;
}
public int getChildRole(ASTNode child) {
LOG.assertTrue(child.getTreeParent() == this);
IElementType i = child.getElementType();
if (i == XML_NAME || i == XML_TAG_NAME) {
return ChildRole.XML_TAG_NAME;
}
else if (i == XML_ATTRIBUTE) {
return ChildRole.XML_ATTRIBUTE;
}
else {
return ChildRole.NONE;
}
}
public String getName() {
if (myName != null) return myName;
final ASTNode nameElement = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
if (nameElement != null){
myName = nameElement.getText();
}
else{
myName = "";
}
return myName;
}
public PsiElement setName(final String name) throws IncorrectOperationException {
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
model.runTransaction(new PomTransactionBase(this, aspect) {
public PomModelEvent runInner() throws IncorrectOperationException{
final String oldName = getName();
final XmlTagImpl dummyTag = (XmlTagImpl)getManager().getElementFactory().createTagFromText(XmlTagTextUtil.composeTagText(name, "aa"));
final XmlTagImpl tag = XmlTagImpl.this;
final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(tag);
ChangeUtil.replaceChild(tag, (TreeElement)XmlChildRole.START_TAG_NAME_FINDER.findChild(tag), ChangeUtil.copyElement((TreeElement)XmlChildRole.START_TAG_NAME_FINDER.findChild(dummyTag), charTableByTree));
final ASTNode childByRole = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(tag);
if(childByRole != null) ChangeUtil.replaceChild(tag, (TreeElement)childByRole, ChangeUtil.copyElement((TreeElement)XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(dummyTag), charTableByTree));
return XmlTagNameChangedImpl.createXmlTagNameChanged(model, tag, oldName);
}
});
return this;
}
public XmlAttribute[] getAttributes() {
if(myAttributes != null) return myAttributes;
myAttributeValueMap = new HashMap<String, String>();
myAttributes = calculateAttributes();
return myAttributes;
}
@NotNull
protected XmlAttribute[] calculateAttributes() {
final List<XmlAttribute> result = new ArrayList<XmlAttribute>(10);
processElements(
new PsiElementProcessor() {
public boolean execute(PsiElement element) {
if (element instanceof XmlAttribute){
XmlAttribute attribute = (XmlAttribute)element;
result.add(attribute);
cacheOneAttributeValue(attribute.getName(),attribute.getValue());
myHaveNamespaceDeclarations = myHaveNamespaceDeclarations || attribute.isNamespaceDeclaration();
}
else if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_TAG_END) {
return false;
}
return true;
}
}, this
);
if (result.isEmpty()) {
myAttributeValueMap = Collections.emptyMap();
return XmlAttribute.EMPTY_ARRAY;
}
else {
return CollectionUtil.toArray(result, new XmlAttribute[result.size()]);
}
}
protected void cacheOneAttributeValue(String name, String value) {
myAttributeValueMap.put(name, value);
}
public String getAttributeValue(String qname) {
if(myAttributeValueMap == null) getAttributes();
return myAttributeValueMap.get(qname);
}
public String getAttributeValue(String name, String namespace) {
final String prefix = getPrefixByNamespace(namespace);
if(prefix != null && prefix.length() > 0) name = prefix + ":" + name;
return getAttributeValue(name);
}
public XmlTag[] getSubTags() {
if(myTags != null) return myTags;
final List<XmlTag> result = new ArrayList<XmlTag>();
processElements(
new PsiElementProcessor() {
public boolean execute(PsiElement element) {
if (element instanceof XmlTag) result.add((XmlTag)element);
return true;
}
}, this);
myTags = result.toArray(new XmlTag[result.size()]);
return myTags;
}
public XmlTag[] findSubTags(String name) {
return findSubTags(name, null);
}
public XmlTag[] findSubTags(final String name, final String namespace) {
final XmlTag[] subTags = getSubTags();
final List<XmlTag> result = new ArrayList<XmlTag>();
for (final XmlTag subTag : subTags) {
if (namespace == null) {
if (name.equals(subTag.getName())) result.add(subTag);
}
else if (name.equals(subTag.getLocalName()) && namespace.equals(subTag.getNamespace())) {
result.add(subTag);
}
}
return result.toArray(new XmlTag[result.size()]);
}
public XmlTag findFirstSubTag(String name) {
final XmlTag[] subTags = findSubTags(name);
if(subTags.length > 0) return subTags[0];
return null;
}
public XmlAttribute getAttribute(String name, String namespace) {
if(namespace == null || namespace == XmlUtil.ANY_URI || namespace.equals(getNamespace())) return getAttribute(name);
final String prefix = getPrefixByNamespace(namespace);
String qname = prefix != null && prefix.length() > 0 ? prefix + ":" + name : name;
return getAttribute(qname);
}
private XmlAttribute getAttribute(String qname){
if(qname == null) return null;
final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(this);
final XmlAttribute[] attributes = getAttributes();
final CharSequence charTableIndex = charTableByTree.intern(qname);
for (final XmlAttribute attribute : attributes) {
final LeafElement attrNameElement = (LeafElement)XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(attribute.getNode());
if (attrNameElement.getInternedText() == charTableIndex) return attribute;
}
return null;
}
public String getNamespace() {
return getNamespaceByPrefix(getNamespacePrefix());
}
@NotNull
public String getNamespacePrefix() {
final String name = getName();
final int index = name.indexOf(':');
if(index >= 0){
return name.substring(0, index);
}
return "";
}
@NotNull
public String getNamespaceByPrefix(String prefix){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
if(myNamespaceMap != null){
final String ns = myNamespaceMap.get(prefix);
if(ns != null) return ns;
}
if(parent instanceof XmlTag) return ((XmlTag)parent).getNamespaceByPrefix(prefix);
return XmlUtil.EMPTY_URI;
}
public String getPrefixByNamespace(String namespace){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
if(myNamespaceMap != null){
List<String> keysByValue = myNamespaceMap.getKeysByValue(namespace);
final String ns = keysByValue == null ? null : keysByValue.get(0);
if(ns != null) return ns;
}
if(parent instanceof XmlTag) return ((XmlTag)parent).getPrefixByNamespace(namespace);
return null;
}
public String[] knownNamespaces(){
final PsiElement parent = getParent();
initNamespaceMaps(parent);
List<String> known = Collections.emptyList();
if(myNamespaceMap != null){
known = new ArrayList<String>(myNamespaceMap.values());
}
if(parent instanceof XmlTag){
if(known.isEmpty()) return ((XmlTag)parent).knownNamespaces();
known.addAll(Arrays.asList(((XmlTag)parent).knownNamespaces()));
}
else if(getContainingFile() instanceof JspFile) {
final XmlTag rootTag = ((JspFile)getContainingFile()).getDocument().getRootTag();
if (rootTag != this) known.addAll(Arrays.asList((rootTag.knownNamespaces())));
}
return known.toArray(new String[known.size()]);
}
private void initNamespaceMaps(PsiElement parent) {
if(myNamespaceMap == null && hasNamespaceDeclarations()){
myNamespaceMap = new BidirectionalMap<String, String>();
final XmlAttribute[] attributes = getAttributes();
for (final XmlAttribute attribute : attributes) {
if (attribute.isNamespaceDeclaration()) {
final String name = attribute.getName();
int splitIndex = name.indexOf(':');
final String value = attribute.getValue();
if (value != null) {
if (splitIndex < 0) {
myNamespaceMap.put("", value);
}
else {
myNamespaceMap.put(XmlUtil.findLocalNameByQualifiedName(name), value);
}
}
}
}
}
if(parent instanceof XmlDocument && myNamespaceMap == null){
myNamespaceMap = new BidirectionalMap<String, String>();
final String[][] defaultNamespace = XmlUtil.getDefaultNamespaces((XmlDocument)parent);
for (final String[] prefix2ns : defaultNamespace) {
myNamespaceMap.put(prefix2ns[0], prefix2ns[1]);
}
}
}
public String getLocalName() {
final String name = getName();
return name.substring(name.indexOf(':') + 1);
}
public boolean hasNamespaceDeclarations() {
getAttributes();
return myHaveNamespaceDeclarations;
}
public Map<String, String> getLocalNamespaceDeclarations() {
Map<String, String> namespaces = new HashMap<String, String>();
for (final XmlAttribute attribute : getAttributes()) {
if (!attribute.isNamespaceDeclaration() || attribute.getValue() == null) continue;
namespaces.put(attribute.getLocalName(), attribute.getValue());
}
return namespaces;
}
public XmlAttribute setAttribute(String qname, String value) throws IncorrectOperationException {
final XmlAttribute attribute = getAttribute(qname);
if(attribute != null){
if(value == null){
deleteChildInternal(attribute.getNode());
return null;
}
attribute.setValue(value);
return attribute;
}
else if (value == null) {
return null;
}
else {
PsiElement xmlAttribute = add(getManager().getElementFactory().createXmlAttribute(qname, value));
while(!(xmlAttribute instanceof XmlAttribute)) xmlAttribute = xmlAttribute.getNextSibling();
return (XmlAttribute)xmlAttribute;
}
}
public XmlAttribute setAttribute(String name, String namespace, String value) throws IncorrectOperationException {
final String prefix = getPrefixByNamespace(namespace);
if(prefix != null && prefix.length() > 0) name = prefix + ":" + name;
return setAttribute(name, value);
}
public XmlTag createChildTag(String localName, String namespace, String bodyText, boolean enforceNamespacesDeep) {
return XmlUtil.createChildTag(this, localName, namespace, bodyText, enforceNamespacesDeep);
}
public XmlTagValue getValue() {
if(myValue != null) return myValue;
final PsiElement[] elements = getElements();
final List<PsiElement> bodyElements = new ArrayList<PsiElement>(elements.length);
boolean insideBody = false;
for (final PsiElement element : elements) {
final ASTNode treeElement = element.getNode();
if (insideBody) {
if (treeElement.getElementType() == XmlTokenType.XML_END_TAG_START) break;
if (!(element instanceof XmlTagChild)) continue;
bodyElements.add(element);
}
else if (treeElement.getElementType() == XmlTokenType.XML_TAG_END) insideBody = true;
}
return myValue = new XmlTagValueImpl(bodyElements.toArray(XmlTagChild.EMPTY_ARRAY), this);
}
private PsiElement[] getElements() {
final List<PsiElement> elements = new ArrayList<PsiElement>();
processElements(new PsiElementProcessor() {
public boolean execute(PsiElement psiElement) {
elements.add(psiElement);
return true;
}
}, this);
return elements.toArray(new PsiElement[elements.size()]);
}
public void accept(PsiElementVisitor visitor) {
visitor.visitXmlTag(this);
}
public String toString() {
return "XmlTag:" + getName();
}
public PsiMetaData getMetaData() {
return MetaRegistry.getMeta(this);
}
public boolean isMetaEnough() {
return true;
}
public TreeElement addInternal(TreeElement first, ASTNode last, ASTNode anchor, Boolean beforeB) {
//ChameleonTransforming.transformChildren(this);
TreeElement firstAppended = null;
boolean before = beforeB != null ? beforeB.booleanValue() : true;
try{
TreeElement next;
do {
next = first.getTreeNext();
if (firstAppended == null) {
firstAppended = addInternal(first, anchor, before);
anchor = firstAppended;
}
else {
anchor = addInternal(first, anchor, false);
}
}
while (first != last && (first = next) != null);
}
catch(IncorrectOperationException ioe){}
finally{
clearCaches();
}
return firstAppended;
}
private TreeElement addInternal(TreeElement child, ASTNode anchor, boolean before) throws IncorrectOperationException{
final PomModel model = getProject().getModel();
final InsertTransaction transaction;
if (anchor != null && child.getElementType() == XmlElementType.XML_TEXT) {
XmlText psi = null;
if(anchor.getPsi() instanceof XmlText)
psi = (XmlText)anchor.getPsi();
else {
final ASTNode other = before ? anchor.getTreePrev() : anchor.getTreeNext();
if(other != null && other.getPsi() instanceof XmlText) {
before = !before;
psi = (XmlText)other.getPsi();
}
}
if(psi != null){
if(before)
psi.insertText(((XmlText)child.getPsi()).getValue(), 0);
else
psi.insertText(((XmlText)child.getPsi()).getValue(), psi.getValue().length());
return (TreeElement)psi.getNode();
}
}
LOG.assertTrue(child.getPsi() instanceof XmlAttribute || child.getPsi() instanceof XmlTagChild);
if (child.getElementType() == XmlElementType.XML_ATTRIBUTE) {
transaction = new InsertAttributeTransaction(child, anchor, before, model);
}
else if (anchor == null){
transaction = getBodyInsertTransaction(child);
}
else{
transaction = new GenericInsertTransaction(child, anchor, before);
}
model.runTransaction(transaction);
return transaction.getFirstInserted();
}
protected InsertTransaction getBodyInsertTransaction(final TreeElement child) {
return new BodyInsertTransaction(child);
}
public void deleteChildInternal(final ASTNode child) {
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
if(child.getElementType() == XmlElementType.XML_ATTRIBUTE){
try {
model.runTransaction(new PomTransactionBase(this, aspect) {
public PomModelEvent runInner() {
final String name = ((XmlAttribute)child).getName();
XmlTagImpl.super.deleteChildInternal(child);
return XmlAttributeSetImpl.createXmlAttributeSet(model, XmlTagImpl.this, name, null);
}
});
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
else{
XmlTagImpl.super.deleteChildInternal(child);
}
}
private ASTNode expandTag() throws IncorrectOperationException{
ASTNode endTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(XmlTagImpl.this);
if(endTagStart == null){
final XmlTagImpl tagFromText = (XmlTagImpl)getManager().getElementFactory().createTagFromText("<" + getName() + "></" + getName() + ">");
final ASTNode startTagStart = XmlChildRole.START_TAG_END_FINDER.findChild(tagFromText);
endTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(tagFromText);
final LeafElement emptyTagEnd = (LeafElement)XmlChildRole.EMPTY_TAG_END_FINDER.findChild(this);
if(emptyTagEnd != null) removeChild(emptyTagEnd);
addChildren(startTagStart, null, null);
}
return endTagStart;
}
public XmlTag getParentTag() {
final PsiElement parent = getParent();
if(parent instanceof XmlTag) return (XmlTag)parent;
return null;
}
public XmlTagChild getNextSiblingInTag() {
final PsiElement nextSibling = getNextSibling();
if(nextSibling instanceof XmlTagChild) return (XmlTagChild)nextSibling;
return null;
}
public XmlTagChild getPrevSiblingInTag() {
final PsiElement prevSibling = getPrevSibling();
if(prevSibling instanceof XmlTagChild) return (XmlTagChild)prevSibling;
return null;
}
protected class BodyInsertTransaction extends InsertTransaction{
private TreeElement myChild;
private ASTNode myNewElement;
public BodyInsertTransaction(TreeElement child) {
super(XmlTagImpl.this);
this.myChild = child;
}
public PomModelEvent runInner() throws IncorrectOperationException {
final ASTNode anchor = expandTag();
if(myChild.getElementType() == XmlElementType.XML_TAG){
// compute where to insert tag according to DTD or XSD
final XmlElementDescriptor parentDescriptor = getDescriptor();
final XmlTag[] subTags = getSubTags();
if (parentDescriptor != null && subTags.length > 0){
final XmlElementDescriptor[] childElementDescriptors = parentDescriptor.getElementsDescriptors(XmlTagImpl.this);
int subTagNum = -1;
for (final XmlElementDescriptor childElementDescriptor : childElementDescriptors) {
final String childElementName = childElementDescriptor.getName();
while (subTagNum < subTags.length - 1 && subTags[subTagNum + 1].getName().equals(childElementName)) {
subTagNum++;
}
if (childElementName.equals(XmlChildRole.START_TAG_NAME_FINDER.findChild(myChild).getText())) {
// insert child just after anchor
// insert into the position specified by index
if (subTagNum >= 0) {
final ASTNode subTag = (ASTNode)subTags[subTagNum];
if (subTag.getTreeParent() != XmlTagImpl.this) {
// in entity
final XmlEntityRef entityRef = PsiTreeUtil.getParentOfType(subTags[subTagNum], XmlEntityRef.class);
throw new IncorrectOperationException(
"Can't insert subtag to entity! Entity reference text: " + entityRef != null ? entityRef.getText() : "");
}
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, subTag, Boolean.FALSE);
}
else {
final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this);
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.FALSE);
}
return null;
}
}
}
}
myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, anchor, Boolean.TRUE);
return null;
}
public TreeElement getFirstInserted(){
return (TreeElement)myNewElement;
}
}
protected XmlText splitText(final XmlTextImpl childText, final int displayOffset) throws IncorrectOperationException{
if(displayOffset == 0) return childText;
if(displayOffset >= childText.getValue().length()) return null;
final PomModel model = getProject().getModel();
final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
class MyTransaction extends PomTransactionBase {
private XmlTextImpl myRight;
public MyTransaction() {
super(XmlTagImpl.this, aspect);
}
public PomModelEvent runInner() throws IncorrectOperationException{
final PsiFile containingFile = getContainingFile();
final FileElement holder = new DummyHolder(containingFile.getManager(), null, ((PsiFileImpl)containingFile).getTreeElement().getCharTable()).getTreeElement();
final XmlTextImpl rightText = (XmlTextImpl)Factory.createCompositeElement(XmlElementType.XML_TEXT);
TreeUtil.addChildren(holder, rightText);
addChild(rightText, childText.getTreeNext());
final String value = childText.getValue();
childText.setValue(value.substring(0, displayOffset));
rightText.setValue(value.substring(displayOffset));
myRight = rightText;
return null;
}
public XmlText getResult() {
return myRight;
}
}
final MyTransaction transaction = new MyTransaction();
model.runTransaction(transaction);
return transaction.getResult();
}
protected class InsertAttributeTransaction extends InsertTransaction{
private final TreeElement myChild;
private final ASTNode myAnchor;
private final boolean myBefore;
private final PomModel myModel;
private TreeElement myFirstInserted = null;
public InsertAttributeTransaction(final TreeElement child, final ASTNode anchor, final boolean before, final PomModel model) {
super(XmlTagImpl.this);
myChild = child;
myAnchor = anchor;
myBefore = before;
myModel = model;
}
public PomModelEvent runInner(){
final String value = ((XmlAttribute)myChild).getValue();
final String name = ((XmlAttribute)myChild).getName();
if (myAnchor == null) {
ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this);
if (startTagEnd == null) startTagEnd = XmlChildRole.EMPTY_TAG_END_FINDER.findChild(XmlTagImpl.this);
if (startTagEnd == null) {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, null, null);
}
else {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, startTagEnd, Boolean.TRUE);
}
}
else {
myFirstInserted = XmlTagImpl.super.addInternal(myChild, myChild, myAnchor, Boolean.valueOf(myBefore));
}
return XmlAttributeSetImpl.createXmlAttributeSet(myModel, XmlTagImpl.this, name, value);
}
public TreeElement getFirstInserted(){
return myFirstInserted;
}
}
protected class GenericInsertTransaction extends InsertTransaction{
private final TreeElement myChild;
private final ASTNode myAnchor;
private final boolean myBefore;
private TreeElement myRetHolder;
public GenericInsertTransaction(final TreeElement child, final ASTNode anchor, final boolean before) {
super(XmlTagImpl.this);
myChild = child;
myAnchor = anchor;
myBefore = before;
}
public PomModelEvent runInner() {
myRetHolder = XmlTagImpl.super.addInternal(myChild, myChild, myAnchor, Boolean.valueOf(myBefore));
return null;
}
public TreeElement getFirstInserted() {
return myRetHolder;
}
}
protected abstract class InsertTransaction extends PomTransactionBase{
public InsertTransaction(final PsiElement scope) {
super(scope, getProject().getModel().getModelAspect(XmlAspect.class));
}
public abstract TreeElement getFirstInserted();
}
}
| fixed issue with incomplete initialization of myNamespaceMap
| source/com/intellij/psi/impl/source/xml/XmlTagImpl.java | fixed issue with incomplete initialization of myNamespaceMap |
|
Java | apache-2.0 | cb17c04b80a41f851c6add74b96c21dbeac3cc47 | 0 | alainjobart/vitess,mattharden/vitess,mahak/vitess,erzel/vitess,vitessio/vitess,pivanof/vitess,alainjobart/vitess,rnavarro/vitess,mapbased/vitess,tinyspeck/vitess,sougou/vitess,davygeek/vitess,mapbased/vitess,vitessio/vitess,davygeek/vitess,vitessio/vitess,mapbased/vitess,erzel/vitess,tirsen/vitess,mapbased/vitess,tinyspeck/vitess,enisoc/vitess,HubSpot/vitess,HubSpot/vitess,rnavarro/vitess,tirsen/vitess,alainjobart/vitess,dcadevil/vitess,applift/vitess,mattharden/vitess,HubSpot/vitess,mahak/vitess,mattharden/vitess,HubSpot/vitess,dcadevil/vitess,alainjobart/vitess,tinyspeck/vitess,sougou/vitess,mahak/vitess,mahak/vitess,applift/vitess,rnavarro/vitess,alainjobart/vitess,erzel/vitess,tinyspeck/vitess,HubSpot/vitess,tinyspeck/vitess,davygeek/vitess,dumbunny/vitess,davygeek/vitess,enisoc/vitess,tirsen/vitess,mattharden/vitess,rnavarro/vitess,enisoc/vitess,dcadevil/vitess,HubSpot/vitess,erzel/vitess,applift/vitess,mahak/vitess,vitessio/vitess,dumbunny/vitess,rnavarro/vitess,tinyspeck/vitess,vitessio/vitess,vitessio/vitess,dcadevil/vitess,dumbunny/vitess,dumbunny/vitess,enisoc/vitess,dumbunny/vitess,dumbunny/vitess,applift/vitess,sougou/vitess,mattharden/vitess,mattharden/vitess,mapbased/vitess,pivanof/vitess,mattharden/vitess,alainjobart/vitess,enisoc/vitess,pivanof/vitess,applift/vitess,davygeek/vitess,sougou/vitess,sougou/vitess,pivanof/vitess,dumbunny/vitess,dumbunny/vitess,tirsen/vitess,pivanof/vitess,erzel/vitess,alainjobart/vitess,erzel/vitess,tirsen/vitess,rnavarro/vitess,erzel/vitess,sougou/vitess,vitessio/vitess,erzel/vitess,tirsen/vitess,rnavarro/vitess,dcadevil/vitess,mapbased/vitess,rnavarro/vitess,davygeek/vitess,mattharden/vitess,mattharden/vitess,mapbased/vitess,sougou/vitess,mapbased/vitess,pivanof/vitess,applift/vitess,dcadevil/vitess,applift/vitess,enisoc/vitess,mapbased/vitess,applift/vitess,dumbunny/vitess,mapbased/vitess,tinyspeck/vitess,HubSpot/vitess,sougou/vitess,pivanof/vitess,enisoc/vitess,tirsen/vitess,dumbunny/vitess,applift/vitess,pivanof/vitess,erzel/vitess,HubSpot/vitess,erzel/vitess,mahak/vitess,davygeek/vitess,rnavarro/vitess,vitessio/vitess,mahak/vitess,pivanof/vitess,tirsen/vitess,applift/vitess,mattharden/vitess,alainjobart/vitess,mahak/vitess,tirsen/vitess,dcadevil/vitess | package com.flipkart.vitess.jdbc.test;
import com.flipkart.vitess.jdbc.VitessJDBCUrl;
import com.youtube.vitess.proto.Topodata;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
/**
* Created by naveen.nahata on 18/02/16.
*/
public class VitessJDBCUrlTest {
@Test public void testURLwithUserNamePwd() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:15991/keyspace/catalog",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithoutUserNamePwd() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://hostname:15991/keyspace/catalog", info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals(vitessJDBCUrl.getHostInfos().get(0).getHostname(), "hostname");
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals(null, vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdinParams() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname:15991/keyspace/catalog?userName=user&password=password",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdinProperties() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://hostname:15991/keyspace/catalog", info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdMultipleHost() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname1:15991,hostname2:15991,"
+ "hostname3:15991/keyspace/catalog?TABLET_TYPE=master", info);
Assert.assertEquals(3, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname1", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("hostname2", vitessJDBCUrl.getHostInfos().get(1).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(1).getPort());
Assert.assertEquals("hostname3", vitessJDBCUrl.getHostInfos().get(2).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(2).getPort());
Assert.assertEquals(Topodata.TabletType.MASTER, vitessJDBCUrl.getTabletType());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testMulitpleJDBCURlURLwithUserNamePwdMultipleHost() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname1:15991,hostname2:15991,hostname3"
+ ":15991/keyspace/catalog?TABLET_TYPE=master", info);
VitessJDBCUrl vitessJDBCUrl1 = new VitessJDBCUrl(
"jdbc:vitess://hostname1:15001,hostname2:15001,hostname3"
+ ":15001/keyspace/catalog?TABLET_TYPE=master", info);
Assert.assertEquals(3, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals(3, vitessJDBCUrl1.getHostInfos().size());
Assert.assertEquals("hostname1", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("hostname1", vitessJDBCUrl1.getHostInfos().get(0).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(0).getPort());
Assert.assertEquals("hostname2", vitessJDBCUrl.getHostInfos().get(1).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(1).getPort());
Assert.assertEquals("hostname2", vitessJDBCUrl1.getHostInfos().get(1).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(1).getPort());
Assert.assertEquals("hostname3", vitessJDBCUrl.getHostInfos().get(2).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(2).getPort());
Assert.assertEquals("hostname3", vitessJDBCUrl1.getHostInfos().get(2).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(2).getPort());
Assert.assertEquals(vitessJDBCUrl.getTabletType(), Topodata.TabletType.MASTER);
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testWithKeyspaceandCatalog() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:port/keyspace/catalog",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("keyspace",vitessJDBCUrl.getKeyspace());
Assert.assertEquals("catalog",vitessJDBCUrl.getCatalog());
}
@Test public void testWithKeyspace() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:15991/keyspace",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("keyspace",vitessJDBCUrl.getKeyspace());
Assert.assertEquals("keyspace",vitessJDBCUrl.getCatalog());
}
}
| java/jdbc/src/test/java/com/flipkart/vitess/jdbc/test/VitessJDBCUrlTest.java | package com.flipkart.vitess.jdbc.test;
import com.flipkart.vitess.jdbc.VitessJDBCUrl;
import com.youtube.vitess.proto.Topodata;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
/**
* Created by naveen.nahata on 18/02/16.
*/
public class VitessJDBCUrlTest {
@Test public void testURLwithUserNamePwd() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:15991/keyspace/catalog",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithoutUserNamePwd() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://hostname:15991/keyspace/catalog", info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals(vitessJDBCUrl.getHostInfos().get(0).getHostname(), "hostname");
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals(null, vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdinParams() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname:15991/keyspace/catalog?userName=user&password=password",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdinProperties() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://hostname:15991/keyspace/catalog", info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testURLwithUserNamePwdMultipleHost() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname1:15991,hostname2:15991,"
+ "hostname3:15991/keyspace/catalog?TABLET_TYPE=master", info);
Assert.assertEquals(3, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("hostname1", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("hostname2", vitessJDBCUrl.getHostInfos().get(1).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(1).getPort());
Assert.assertEquals("hostname3", vitessJDBCUrl.getHostInfos().get(2).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(2).getPort());
Assert.assertEquals(Topodata.TabletType.MASTER, vitessJDBCUrl.getTabletType());
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testMulitpleJDBCURlURLwithUserNamePwdMultipleHost() throws Exception {
Properties info = new Properties();
info.setProperty("userName", "user");
info.setProperty("password", "password");
VitessJDBCUrl vitessJDBCUrl = new VitessJDBCUrl(
"jdbc:vitess://hostname:15991:xyz,10.33.17.232:15991:xyz,10.33.17"
+ ".233:15991:xyz/keyspace/catalog?TABLET_TYPE=master", info);
VitessJDBCUrl vitessJDBCUrl1 = new VitessJDBCUrl(
"jdbc:vitess://11.33.17.231:15001:xyz,11.33.17.232:15001:xyz,11.33.17"
+ ".233:15001:xyz/keyspace/catalog?TABLET_TYPE=master", info);
Assert.assertEquals(3, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals(3, vitessJDBCUrl1.getHostInfos().size());
Assert.assertEquals("hostname", vitessJDBCUrl.getHostInfos().get(0).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(0).getPort());
Assert.assertEquals("11.33.17.231", vitessJDBCUrl1.getHostInfos().get(0).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(0).getPort());
Assert.assertEquals("10.33.17.232", vitessJDBCUrl.getHostInfos().get(1).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(1).getPort());
Assert.assertEquals("11.33.17.232", vitessJDBCUrl1.getHostInfos().get(1).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(1).getPort());
Assert.assertEquals("10.33.17.233", vitessJDBCUrl.getHostInfos().get(2).getHostname());
Assert.assertEquals(15991, vitessJDBCUrl.getHostInfos().get(2).getPort());
Assert.assertEquals("11.33.17.233", vitessJDBCUrl1.getHostInfos().get(2).getHostname());
Assert.assertEquals(15001, vitessJDBCUrl1.getHostInfos().get(2).getPort());
Assert.assertEquals(vitessJDBCUrl.getTabletType(), Topodata.TabletType.MASTER);
Assert.assertEquals("user", vitessJDBCUrl.getUsername());
}
@Test public void testWithKeyspaceandCatalog() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:port/keyspace/catalog",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("keyspace",vitessJDBCUrl.getKeyspace());
Assert.assertEquals("catalog",vitessJDBCUrl.getCatalog());
}
@Test public void testWithKeyspace() throws Exception {
Properties info = new Properties();
VitessJDBCUrl vitessJDBCUrl =
new VitessJDBCUrl("jdbc:vitess://user:password@hostname:15991/keyspace",
info);
Assert.assertEquals(1, vitessJDBCUrl.getHostInfos().size());
Assert.assertEquals("keyspace",vitessJDBCUrl.getKeyspace());
Assert.assertEquals("keyspace",vitessJDBCUrl.getCatalog());
}
}
| [JDBC Driver] Incorporated comments
| java/jdbc/src/test/java/com/flipkart/vitess/jdbc/test/VitessJDBCUrlTest.java | [JDBC Driver] Incorporated comments |
|
Java | apache-2.0 | f4dcfdf92d0c723a438e42d89be2fd881d1c97c7 | 0 | ebean-orm/avaje-ebeanorm-querybean,ebean-orm/avaje-ebeanorm-typequery | package org.avaje.ebean.typequery;
import com.avaje.ebean.*;
import com.avaje.ebean.text.PathProperties;
import com.avaje.ebeaninternal.server.util.ArrayStack;
import org.jetbrains.annotations.Nullable;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
/**
* Base root query bean.
*
* With code generation for each entity bean type a query bean is created that extends this.
* <p>
* Provides common features for all root query beans
* </p>
*
* <h2>Example - QCustomer extends TQRootBean</h2>
* <p>
* These 'query beans' like QCustomer are generated using the <code>avaje-ebeanorm-typequery-generator</code>.
* </p>
* <pre>{@code
*
* public class QCustomer extends TQRootBean<Customer,QCustomer> {
*
* // properties
* public PLong<QCustomer> id;
*
* public PString<QCustomer> name;
* ...
*
* }</pre>
*
* <h2>Example - usage of QCustomer</h2>
* <pre>{@code
*
* Date fiveDaysAgo = ...
*
* List<Customer> customers =
* new QCustomer()
* .name.ilike("rob")
* .status.equalTo(Customer.Status.GOOD)
* .registered.after(fiveDaysAgo)
* .contacts.email.endsWith("@foo.com")
* .orderBy()
* .name.asc()
* .registered.desc()
* .findList();
*
* }</pre>
*
* <h2>Resulting SQL where</h2>
*
* <pre>{@code sql
*
* where lower(t0.name) like ? and t0.status = ? and t0.registered > ? and u1.email like ?
* order by t0.name, t0.registered desc;
*
* --bind(rob,GOOD,Mon Jul 27 12:05:37 NZST 2015,%@foo.com)
* }</pre>
*
*
* @param <T> the entity bean type (normal entity bean type e.g. Customer)
* @param <R> the specific root query bean type (e.g. QCustomer)
*/
public abstract class TQRootBean<T, R> {
/**
* The underlying query.
*/
private final Query<T> query;
/**
* The underlying expression lists held as a stack. Pushed and popped based on and/or (conjunction/disjunction).
*/
private final ArrayStack<ExpressionList<T>> expressionListStack;
/**
* The root query bean instance. Used to provide fluid query construction.
*/
private R root;
/**
* Construct using the type of bean to query on and the default server.
*/
public TQRootBean(Class<T> beanType) {
this(beanType, Ebean.getDefaultServer());
}
/**
* Construct using the type of bean to query on and a given server.
*/
public TQRootBean(Class<T> beanType, EbeanServer server) {
this(server.find(beanType));
}
/**
* Construct using a query.
*/
public TQRootBean(Query<T> query) {
this.expressionListStack = new ArrayStack<>();
this.query = query;
}
/**
* Construct for using as an 'Alias' to use the properties as known string
* values for select() and fetch().
*/
public TQRootBean(boolean aliasDummy) {
this.expressionListStack = null;
this.query = null;
}
/**
* Sets the root query bean instance. Used to provide fluid query construction.
*/
protected void setRoot(R root) {
this.root = root;
}
/**
* Return the underlying query.
* <p>
* Generally it is not expected that you will need to do this but typically use
* the find methods available on this 'root query bean' instance like findList().
* </p>
*/
public Query<T> query() {
return query;
}
/**
* Explicitly set a comma delimited list of the properties to fetch on the
* 'main' root level entity bean (aka partial object). Note that '*' means all
* properties.
* <p>
* You use {@link #fetch(String, String)} to specify specific properties to fetch
* on other non-root level paths of the object graph.
* </p>
*
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* // Only fetch the customer id, name and status.
* // This is described as a "Partial Object"
* .select("name, status")
* .name.ilike("rob%")
* .findList();
*
* }</pre>
*
* @param fetchProperties
* the properties to fetch for this bean (* = all properties).
*/
public R select(String fetchProperties) {
query.select(fetchProperties);
return root;
}
/**
* Tune the query by specifying the properties to be loaded on the
* 'main' root level entity bean (aka partial object).
* <pre>{@code
*
* // alias for the customer properties in select()
* QCustomer cust = QCustomer.alias();
*
* // alias for the contact properties in contacts.fetch()
* QContact contact = QContact.alias();
*
* List<Customer> customers =
* new QCustomer()
* // tune query
* .select(cust.id, cust.name)
* .contacts.fetch(contact.firstName, contact.lastName, contact.email)
*
* // predicates
* .id.greaterThan(1)
* .findList();
*
* }</pre>
* @param properties the list of properties to fetch
*/
@SafeVarargs
public final R select(TQProperty<R>... properties) {
StringBuilder selectProps = new StringBuilder(50);
for (int i = 0; i < properties.length; i++) {
if (i > 0) {
selectProps.append(",");
}
selectProps.append(properties[i].propertyName());
}
query.select(selectProps.toString());
return root;
}
/**
* Specify a path to load including all its properties.
* <p>
* The same as {@link #fetch(String, String)} with the fetchProperties as "*".
* </p>
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* // eager fetch the contacts
* .fetch("contacts")
* .findList();
*
* }</pre>
*
* @param path
* the property of an associated (1-1,1-M,M-1,M-M) bean.
*/
public R fetch(String path) {
query.fetch(path);
return root;
}
/**
* Specify a path to <em>fetch</em> with its specific properties to include
* (aka partial object).
* <p>
* When you specify a join this means that property (associated bean(s)) will
* be fetched and populated. If you specify "*" then all the properties of the
* associated bean will be fetched and populated. You can specify a comma
* delimited list of the properties of that associated bean which means that
* only those properties are fetched and populated resulting in a
* "Partial Object" - a bean that only has some of its properties populated.
* </p>
*
* <pre>{@code
*
* // query orders...
* List<Order> orders =
* ebeanserver.find(Order.class)
* // fetch the customer...
* // ... getting the customers name and phone number
* .fetch("customer", "name, phoneNumber")
*
* // ... also fetch the customers billing address (* = all properties)
* .fetch("customer.billingAddress", "*")
* .findList();
* }</pre>
*
* <p>
* If columns is null or "*" then all columns/properties for that path are
* fetched.
* </p>
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email")
* .findList();
*
* }</pre>
*
* @param path
* the path of an associated (1-1,1-M,M-1,M-M) bean.
* @param fetchProperties
* properties of the associated bean that you want to include in the
* fetch (* means all properties, null also means all properties).
*/
public R fetch(String path, String fetchProperties) {
query.fetch(path, fetchProperties);
return root;
}
/**
* Additionally specify a FetchConfig to use a separate query or lazy loading
* to load this path.
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10))
* .findList();
*
* }</pre>
*/
public R fetch(String path, String fetchProperties, FetchConfig fetchConfig) {
query.fetch(path, fetchProperties, fetchConfig);
return root;
}
/**
* Additionally specify a FetchConfig to specify a "query join" and or define
* the lazy loading query.
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* // lazy fetch contacts with a batch size of 100
* .fetch("contacts", new FetchConfig().lazy(100))
* .findList();
*
* }</pre>
*/
public R fetch(String path, FetchConfig fetchConfig) {
query.fetch(path, fetchConfig);
return root;
}
/**
* Apply the path properties replacing the select and fetch clauses.
* <p>
* This is typically used when the PathProperties is applied to both the query and the JSON output.
* </p>
*/
public R apply(PathProperties pathProperties) {
query.apply(pathProperties);
return root;
}
/**
* Perform an 'As of' query using history tables to return the object graph
* as of a time in the past.
* <p>
* To perform this query the DB must have underlying history tables.
* </p>
*
* @param asOf the date time in the past at which you want to view the data
*/
public R asOf(Timestamp asOf) {
query.asOf(asOf);
return root;
}
/**
* Set root table alias.
*/
public R alias(String alias) {
query.alias(alias);
return root;
}
/**
* Set the maximum number of rows to return in the query.
*
* @param maxRows
* the maximum number of rows to return in the query.
*/
public R setMaxRows(int maxRows) {
query.setMaxRows(maxRows);
return root;
}
/**
* Set the first row to return for this query.
*
* @param firstRow the first row to include in the query result.
*/
public R setFirstRow(int firstRow) {
query.setFirstRow(firstRow);
return root;
}
/**
* Explicitly specify whether to use AutoTune for this query.
* <p>
* If you do not call this method on a query the "Implicit AutoTune mode" is
* used to determine if AutoTune should be used for a given query.
* </p>
* <p>
* AutoTune can add additional fetch paths to the query and specify which
* properties are included for each path. If you have explicitly defined some
* fetch paths AutoTune will not remove them.
* </p>
*/
public R setAutoTune(boolean autoTune) {
query.setAutoTune(autoTune);
return root;
}
/**
* A hint which for JDBC translates to the Statement.fetchSize().
* <p>
* Gives the JDBC driver a hint as to the number of rows that should be
* fetched from the database when more rows are needed for ResultSet.
* </p>
*/
public R setBufferFetchSizeHint(int fetchSize) {
query.setBufferFetchSizeHint(fetchSize);
return root;
}
/**
* Set whether this query uses DISTINCT.
*/
public R setDistinct(boolean distinct) {
query.setDistinct(distinct);
return root;
}
/**
* executed the select with "for update" which should lock the record
* "on read"
*/
public R setForUpdate(boolean forUpdate) {
query.setForUpdate(forUpdate);
return root;
}
/**
* Set the Id value to query. This is used with findUnique().
* <p>
* You can use this to have further control over the query. For example adding
* fetch joins.
* </p>
*
* <pre>{@code
*
* Order order =
* new QOrder()
* .setId(1)
* .fetch("details")
* .findUnique();
*
* // the order details were eagerly fetched
* List<OrderDetail> details = order.getDetails();
*
* }</pre>
*/
public R setId(Object id) {
query.setId(id);
return root;
}
/**
* Set the default lazy loading batch size to use.
* <p>
* When lazy loading is invoked on beans loaded by this query then this sets the
* batch size used to load those beans.
*
* @param lazyLoadBatchSize the number of beans to lazy load in a single batch
*/
public R setLazyLoadBatchSize(int lazyLoadBatchSize) {
query.setLazyLoadBatchSize(lazyLoadBatchSize);
return root;
}
/**
* When set to true all the beans from this query are loaded into the bean
* cache.
*/
public R setLoadBeanCache(boolean loadBeanCache) {
query.setLoadBeanCache(loadBeanCache);
return root;
}
/**
* Set the property to use as keys for a map.
* <p>
* If no property is set then the id property is used.
* </p>
*
* <pre>{@code
*
* // Assuming sku is unique for products...
*
* Map<?,Product> productMap =
* new QProduct()
* // use sku for keys...
* .setMapKey("sku")
* .findMap();
*
* }</pre>
*
* @param mapKey
* the property to use as keys for a map.
*/
public R setMapKey(String mapKey) {
query.setMapKey(mapKey);
return root;
}
/**
* Specify the PersistenceContextScope to use for this query.
* <p/>
* When this is not set the 'default' configured on {@link com.avaje.ebean.config.ServerConfig#setPersistenceContextScope(PersistenceContextScope)}
* is used - this value defaults to {@link com.avaje.ebean.PersistenceContextScope#TRANSACTION}.
* <p/>
* Note that the same persistence Context is used for subsequent lazy loading and query join queries.
* <p/>
* Note that #findEach uses a 'per object graph' PersistenceContext so this scope is ignored for
* queries executed as #findIterate, #findEach, #findEachWhile.
*
* @param scope The scope to use for this query and subsequent lazy loading.
*/
public R setPersistenceContextScope(PersistenceContextScope scope) {
query.setPersistenceContextScope(scope);
return root;
}
/**
* Set RawSql to use for this query.
*/
public R setRawSql(RawSql rawSql) {
query.setRawSql(rawSql);
return root;
}
/**
* When set to true when you want the returned beans to be read only.
*/
public R setReadOnly(boolean readOnly) {
query.setReadOnly(readOnly);
return root;
}
/**
* Set this to true to use the bean cache.
* <p>
* If the query result is in cache then by default this same instance is
* returned. In this sense it should be treated as a read only object graph.
* </p>
*/
public R setUseCache(boolean useCache) {
query.setUseCache(useCache);
return root;
}
/**
* Set this to true to use the query cache.
*/
public R setUseQueryCache(boolean useCache) {
query.setUseQueryCache(useCache);
return root;
}
/**
* Set a timeout on this query.
* <p>
* This will typically result in a call to setQueryTimeout() on a
* preparedStatement. If the timeout occurs an exception will be thrown - this
* will be a SQLException wrapped up in a PersistenceException.
* </p>
*
* @param secs
* the query timeout limit in seconds. Zero means there is no limit.
*/
public R setTimeout(int secs) {
query.setTimeout(secs);
return root;
}
/**
* Add raw expression with no parameters.
* <p>
* When properties in the clause are fully qualified as table-column names
* then they are not translated. logical property name names (not fully
* qualified) will still be translated to their physical name.
* </p>
*
* <pre>{@code
*
* raw("orderQty < shipQty")
*
* }</pre>
*/
public R raw(String rawExpression) {
peekExprList().raw(rawExpression);
return root;
}
/**
* Add raw expression with an array of parameters.
* <p>
* The raw expression should contain the same number of ? as there are
* parameters.
* </p>
* <p>
* When properties in the clause are fully qualified as table-column names
* then they are not translated. logical property name names (not fully
* qualified) will still be translated to their physical name.
* </p>
*/
public R raw(String rawExpression, Object[] bindValues) {
peekExprList().raw(rawExpression, bindValues);
return root;
}
/**
* Add raw expression with a single parameter.
* <p>
* The raw expression should contain a single ? at the location of the
* parameter.
* </p>
* <p>
* When properties in the clause are fully qualified as table-column names
* then they are not translated. logical property name names (not fully
* qualified) will still be translated to their physical name.
* </p>
*
* <h4>Example:</h4>
* <pre>{@code
*
* // use a database function
* raw("add_days(orderDate, 10) < ?", someDate)
*
* }</pre>
*/
public R raw(String rawExpression, Object bindValue) {
peekExprList().raw(rawExpression, bindValue);
return root;
}
/**
* Marker that can be used to indicate that the order by clause is defined after this.
* <p>
* order() and orderBy() are synonyms and both exist for historic reasons.
* </p>
*
* <h2>Example: order by customer name, order date</h2>
* <pre>{@code
* List<Order> orders =
* new QOrder()
* .customer.name.ilike("rob")
* .orderBy()
* .customer.name.asc()
* .orderDate.asc()
* .findList();
*
* }</pre>
*/
public R orderBy() {
// Yes this does not actually do anything! We include it because style wise it makes
// the query nicer to read and suggests that order by definitions are added after this
return root;
}
/**
* Marker that can be used to indicate that the order by clause is defined after this.
* <p>
* order() and orderBy() are synonyms and both exist for historic reasons.
* </p>
*
* <h2>Example: order by customer name, order date</h2>
* <pre>{@code
* List<Order> orders =
* new QOrder()
* .customer.name.ilike("rob")
* .order()
* .customer.name.asc()
* .orderDate.asc()
* .findList();
*
* }</pre>
*/
public R order() {
// Yes this does not actually do anything! We include it because style wise it makes
// the query nicer to read and suggests that order by definitions are added after this
return root;
}
/**
* Set the full raw order by clause replacing the existing order by clause if there is one.
* <p>
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #order(String)}.
* </p>
*/
public R orderBy(String orderByClause) {
query.orderBy(orderByClause);
return root;
}
/**
* Set the full raw order by clause replacing the existing order by clause if there is one.
* <p>
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #orderBy(String)}.
* </p>
*/
public R order(String orderByClause) {
query.order(orderByClause);
return root;
}
/**
* Begin a list of expressions added by 'OR'.
* <p>
* This should have an associated call to endOr() to close the 'OR' expression list.
* </p>
* <h2>Example</h2>
* <p>
* This example uses an 'OR' expression list with an inner 'AND' expression list.
* </p>
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .status.equalTo(Customer.Status.GOOD)
* .or()
* .id.greaterThan(1000)
* .and()
* .name.startsWith("super")
* .registered.after(fiveDaysAgo)
* .endAnd()
* .endOr()
* .orderBy().id.desc()
* .findList();
*
* }</pre>
* <h2>Resulting SQL where clause</h2>
* <pre>{@code sql
* where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) )
* order by t0.id desc;
*
* --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
*
* }</pre>
*/
public R or() {
Junction<T> junction = peekExprList().disjunction();
expressionListStack.push(junction);
return root;
}
/**
* Begin a list of expressions added by 'AND'.
* <p>
* This should have an associated call to endAnd() to close the 'AND' expression list.
* </p>
* <p>
* Note that typically the AND expression is only used inside an outer 'OR' expression.
* This is because the top level expression list is an 'AND' expression list.
* </p>
* <h2>Example</h2>
* <p>
* This example uses an 'OR' expression list with an inner 'AND' expression list.
* </p>
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .status.equalTo(Customer.Status.GOOD)
* .or() // OUTER 'OR'
* .id.greaterThan(1000)
* .and() // NESTED 'AND' expression list
* .name.startsWith("super")
* .registered.after(fiveDaysAgo)
* .endAnd()
* .endOr()
* .orderBy().id.desc()
* .findList();
*
* }</pre>
* <h2>Resulting SQL where clause</h2>
* <pre>{@code sql
* where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) )
* order by t0.id desc;
*
* --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
*
* }</pre>
*/
public R and() {
Junction<T> junction = peekExprList().conjunction();
expressionListStack.push(junction);
return root;
}
/**
* End a list of expressions added by 'OR'.
*/
public R endOr() {
expressionListStack.pop();
return root;
}
/**
* End to a list of expressions joined by 'AND'.
*/
public R endAnd() {
expressionListStack.pop();
return root;
}
/**
* Execute the query returning either a single bean or null (if no matching
* bean is found).
* <p>
* If more than 1 row is found for this query then a PersistenceException is
* thrown.
* </p>
* <p>
* This is useful when your predicates dictate that your query should only
* return 0 or 1 results.
* </p>
*
* <pre>{@code
*
* // assuming the sku of products is unique...
* Product product =
* new QProduct()
* .sku.equalTo("aa113")
* .findUnique();
* ...
* }</pre>
*
* <p>
* It is also useful with finding objects by their id when you want to specify
* further join information to optimise the query.
* </p>
*
* <pre>{@code
*
* // Fetch order 42 and additionally fetch join its order details...
* Order order =
* new QOrder()
* .fetch("details") // eagerly load the order details
* .id.equalTo(42)
* .findUnique();
*
* // the order details were eagerly loaded
* List<OrderDetail> details = order.getDetails();
* ...
* }</pre>
*/
@Nullable
public T findUnique() {
return query.findUnique();
}
/**
* Execute the query returning the list of objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .name.ilike("rob%")
* .findList();
*
* }</pre>
*
* @see EbeanServer#findList(Query, Transaction)
*/
public List<T> findList() {
return query.findList();
}
/**
* Execute the query returning the list of Id's.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*
* @see EbeanServer#findIds(Query, Transaction)
*/
public List<Object> findIds() {
return query.findIds();
}
/**
* Execute the query iterating over the results.
* <p>
* Remember that with {@link QueryIterator} you must call
* {@link QueryIterator#close()} when you have finished iterating the results
* (typically in a finally block).
* </p>
* <p>
* findEach() and findEachWhile() are preferred to findIterate() as they ensure
* the jdbc statement and resultSet are closed at the end of the iteration.
* </p>
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*/
public QueryIterator<T> findIterate() {
return query.findIterate();
}
/**
* Execute the query returning a map of the objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
* <p>
* You can use setMapKey() so specify the property values to be used as keys
* on the map. If one is not specified then the id property is used.
* </p>
*
* <pre>{@code
*
* Map<?, Product> map =
* ebeanServer.find(Product.class)
* .setMapKey("sku")
* .findMap();
*
* }</pre>
*
* @see EbeanServer#findMap(Query, Transaction)
*/
public Map<?,T> findMap() {
return query.findMap();
}
/**
* Return a typed map specifying the key property and type.
*/
public <K> Map<K, T> findMap(String keyProperty, Class<K> keyType) {
return query.findMap(keyProperty, keyType);
}
/**
* Execute the query processing the beans one at a time.
* <p>
* This method is appropriate to process very large query results as the
* beans are consumed one at a time and do not need to be held in memory
* (unlike #findList #findSet etc)
* </p>
* <p>
* Note that internally Ebean can inform the JDBC driver that it is expecting larger
* resultSet and specifically for MySQL this hint is required to stop it's JDBC driver
* from buffering the entire resultSet. As such, for smaller resultSets findList() is
* generally preferable.
* </p>
* <p>
* Compared with #findEachWhile this will always process all the beans where as
* #findEachWhile provides a way to stop processing the query result early before
* all the beans have been read.
* </p>
* <p>
* This method is functionally equivalent to findIterate() but instead of using an
* iterator uses the QueryEachConsumer (SAM) interface which is better suited to use
* with Java8 closures.
* </p>
*
* <pre>{@code
*
* new QCustomer()
* .status.equalTo(Status.NEW)
* .orderBy().id.asc()
* .findEach((Customer customer) -> {
*
* // do something with customer
* System.out.println("-- visit " + customer);
* });
*
* }</pre>
*
* @param consumer
* the consumer used to process the queried beans.
*/
public void findEach(QueryEachConsumer<T> consumer) {
query.findEach(consumer);
}
/**
* Execute the query using callbacks to a visitor to process the resulting
* beans one at a time.
* <p>
* This method is functionally equivalent to findIterate() but instead of using an
* iterator uses the QueryEachWhileConsumer (SAM) interface which is better suited to use
* with Java8 closures.
* </p>
*
* <pre>{@code
*
* new QCustomer()
* .status.equalTo(Status.NEW)
* .order().id.asc()
* .findEachWhile((Customer customer) -> {
*
* // do something with customer
* System.out.println("-- visit " + customer);
*
* // return true to continue processing or false to stop
* return (customer.getId() < 40);
* });
*
* }</pre>
*
* @param consumer
* the consumer used to process the queried beans.
*/
public void findEachWhile(QueryEachWhileConsumer<T> consumer) {
query.findEachWhile(consumer);
}
/**
* Return versions of a @History entity bean.
* <p>
* Generally this query is expected to be a find by id or unique predicates query.
* It will execute the query against the history returning the versions of the bean.
* </p>
*/
public List<Version<T>> findVersions() {
return query.findVersions();
}
/**
* Return the count of entities this query should return.
* <p>
* This is the number of 'top level' or 'root level' entities.
* </p>
*/
public int findRowCount() {
return query.findRowCount();
}
/**
* Execute find row count query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the row count query
*/
public FutureRowCount<T> findFutureRowCount() {
return query.findFutureRowCount();
}
/**
* Execute find Id's query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the list of Id's
*/
public FutureIds<T> findFutureIds() {
return query.findFutureIds();
}
/**
* Execute find list query in a background thread.
* <p>
* This query will execute in it's own PersistenceContext and using its own transaction.
* What that means is that it will not share any bean instances with other queries.
* </p>
*
* @return a Future object for the list result of the query
*/
public FutureList<T> findFutureList() {
return query.findFutureList();
}
/**
* Return a PagedList for this query.
* <p>
* The benefit of using this over just using the normal {@link Query#setFirstRow(int)} and
* {@link Query#setMaxRows(int)} is that it additionally wraps an optional call to
* {@link Query#findFutureRowCount()} to determine total row count, total page count etc.
* </p>
* <p>
* Internally this works using {@link Query#setFirstRow(int)} and {@link Query#setMaxRows(int)} on
* the query. This translates into SQL that uses limit offset, rownum or row_number function to
* limit the result set.
* </p>
*
* <h4>Example: typical use including total row count</h4>
* <pre>{@code
*
* // We want to find the first 100 new orders
* // ... 0 means first page
* // ... page size is 100
*
* PagedList<Order> pagedList
* = new QOrder()
* .status.equalTo(Order.Status.NEW)
* .order().id.asc()
* .findPagedList(0, 100);
*
* // Optional: initiate the loading of the total
* // row count in a background thread
* pagedList.loadRowCount();
*
* // fetch and return the list in the foreground thread
* List<Order> orders = pagedList.getList();
*
* // get the total row count (from the future)
* int totalRowCount = pagedList.getTotalRowCount();
*
* }</pre>
*
* @param pageIndex
* The zero based index of the page.
* @param pageSize
* The number of beans to return per page.
* @return The PagedList
*/
public PagedList<T> findPagedList(int pageIndex, int pageSize) {
return query.findPagedList(pageIndex, pageSize);
}
/**
* Execute as a delete query deleting the 'root level' beans that match the predicates
* in the query.
* <p>
* Note that if the query includes joins then the generated delete statement may not be
* optimal depending on the database platform.
* </p>
*
* @return the number of beans/rows that were deleted.
*/
public int delete() {
return query.delete();
}
/**
* Return the sql that was generated for executing this query.
* <p>
* This is only available after the query has been executed and provided only
* for informational purposes.
* </p>
*/
public String getGeneratedSql() {
return query.getGeneratedSql();
}
/**
* Return the type of beans being queried.
*/
public Class<T> getBeanType() {
return query.getBeanType();
}
/**
* Return the expression list that has been built for this query.
*/
public ExpressionList<T> getExpressionList() {
return query.where();
}
/**
* Return the current expression list that expressions should be added to.
*/
protected ExpressionList<T> peekExprList() {
if (expressionListStack.isEmpty()) {
// empty so push on the queries base expression list
expressionListStack.push(query.where());
}
// return the current expression list
return expressionListStack.peek();
}
}
| src/main/java/org/avaje/ebean/typequery/TQRootBean.java | package org.avaje.ebean.typequery;
import com.avaje.ebean.*;
import com.avaje.ebean.text.PathProperties;
import com.avaje.ebeaninternal.server.util.ArrayStack;
import org.jetbrains.annotations.Nullable;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
/**
* Base root query bean.
*
* With code generation for each entity bean type a query bean is created that extends this.
* <p>
* Provides common features for all root query beans
* </p>
*
* <h2>Example - QCustomer extends TQRootBean</h2>
* <p>
* These 'query beans' like QCustomer are generated using the <code>avaje-ebeanorm-typequery-generator</code>.
* </p>
* <pre>{@code
*
* public class QCustomer extends TQRootBean<Customer,QCustomer> {
*
* // properties
* public PLong<QCustomer> id;
*
* public PString<QCustomer> name;
* ...
*
* }</pre>
*
* <h2>Example - usage of QCustomer</h2>
* <pre>{@code
*
* Date fiveDaysAgo = ...
*
* List<Customer> customers =
* new QCustomer()
* .name.ilike("rob")
* .status.equalTo(Customer.Status.GOOD)
* .registered.after(fiveDaysAgo)
* .contacts.email.endsWith("@foo.com")
* .orderBy()
* .name.asc()
* .registered.desc()
* .findList();
*
* }</pre>
*
* <h2>Resulting SQL where</h2>
*
* <pre>{@code sql
*
* where lower(t0.name) like ? and t0.status = ? and t0.registered > ? and u1.email like ?
* order by t0.name, t0.registered desc;
*
* --bind(rob,GOOD,Mon Jul 27 12:05:37 NZST 2015,%@foo.com)
* }</pre>
*
*
* @param <T> the entity bean type (normal entity bean type e.g. Customer)
* @param <R> the specific root query bean type (e.g. QCustomer)
*/
public abstract class TQRootBean<T, R> {
/**
* The underlying query.
*/
private final Query<T> query;
/**
* The underlying expression lists held as a stack. Pushed and popped based on and/or (conjunction/disjunction).
*/
private final ArrayStack<ExpressionList<T>> expressionListStack;
/**
* The root query bean instance. Used to provide fluid query construction.
*/
private R root;
/**
* Construct using the type of bean to query on and the default server.
*/
public TQRootBean(Class<T> beanType) {
this(beanType, Ebean.getDefaultServer());
}
/**
* Construct using the type of bean to query on and a given server.
*/
public TQRootBean(Class<T> beanType, EbeanServer server) {
this(server.find(beanType));
}
/**
* Construct using a query.
*/
public TQRootBean(Query<T> query) {
this.expressionListStack = new ArrayStack<>();
this.query = query;
}
/**
* Construct for using as an 'Alias' to use the properties as known string
* values for select() and fetch().
*/
public TQRootBean(boolean aliasDummy) {
this.expressionListStack = null;
this.query = null;
}
/**
* Sets the root query bean instance. Used to provide fluid query construction.
*/
protected void setRoot(R root) {
this.root = root;
}
/**
* Return the underlying query.
* <p>
* Generally it is not expected that you will need to do this but typically use
* the find methods available on this 'root query bean' instance like findList().
* </p>
*/
public Query<T> query() {
return query;
}
/**
* Explicitly set a comma delimited list of the properties to fetch on the
* 'main' root level entity bean (aka partial object). Note that '*' means all
* properties.
* <p>
* You use {@link #fetch(String, String)} to specify specific properties to fetch
* on other non-root level paths of the object graph.
* </p>
*
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* // Only fetch the customer id, name and status.
* // This is described as a "Partial Object"
* .select("name, status")
* .name.ilike("rob%")
* .findList();
*
* }</pre>
*
* @param fetchProperties
* the properties to fetch for this bean (* = all properties).
*/
public R select(String fetchProperties) {
query.select(fetchProperties);
return root;
}
/**
* Tune the query by specifying the properties to be loaded on the
* 'main' root level entity bean (aka partial object).
* <pre>{@code
*
* // alias for the customer properties in select()
* QCustomer cust = QCustomer.alias();
*
* // alias for the contact properties in contacts.fetch()
* QContact contact = QContact.alias();
*
* List<Customer> customers =
* new QCustomer()
* // tune query
* .select(cust.id, cust.name)
* .contacts.fetch(contact.firstName, contact.lastName, contact.email)
*
* // predicates
* .id.greaterThan(1)
* .findList();
*
* }</pre>
* @param properties the list of properties to fetch
*/
@SafeVarargs
public final R select(TQProperty<R>... properties) {
StringBuilder selectProps = new StringBuilder(50);
for (int i = 0; i < properties.length; i++) {
if (i > 0) {
selectProps.append(",");
}
selectProps.append(properties[i].propertyName());
}
query.select(selectProps.toString());
return root;
}
/**
* Specify a path to load including all its properties.
* <p>
* The same as {@link #fetch(String, String)} with the fetchProperties as "*".
* </p>
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* // eager fetch the contacts
* .fetch("contacts")
* .findList();
*
* }</pre>
*
* @param path
* the property of an associated (1-1,1-M,M-1,M-M) bean.
*/
public R fetch(String path) {
query.fetch(path);
return root;
}
/**
* Specify a path to <em>fetch</em> with its specific properties to include
* (aka partial object).
* <p>
* When you specify a join this means that property (associated bean(s)) will
* be fetched and populated. If you specify "*" then all the properties of the
* associated bean will be fetched and populated. You can specify a comma
* delimited list of the properties of that associated bean which means that
* only those properties are fetched and populated resulting in a
* "Partial Object" - a bean that only has some of its properties populated.
* </p>
*
* <pre>{@code
*
* // query orders...
* List<Order> orders =
* ebeanserver.find(Order.class)
* // fetch the customer...
* // ... getting the customers name and phone number
* .fetch("customer", "name, phoneNumber")
*
* // ... also fetch the customers billing address (* = all properties)
* .fetch("customer.billingAddress", "*")
* .findList();
* }</pre>
*
* <p>
* If columns is null or "*" then all columns/properties for that path are
* fetched.
* </p>
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email")
* .findList();
*
* }</pre>
*
* @param path
* the path of an associated (1-1,1-M,M-1,M-M) bean.
* @param fetchProperties
* properties of the associated bean that you want to include in the
* fetch (* means all properties, null also means all properties).
*/
public R fetch(String path, String fetchProperties) {
query.fetch(path, fetchProperties);
return root;
}
/**
* Additionally specify a FetchConfig to use a separate query or lazy loading
* to load this path.
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10))
* .findList();
*
* }</pre>
*/
public R fetch(String path, String fetchProperties, FetchConfig fetchConfig) {
query.fetch(path, fetchProperties, fetchConfig);
return root;
}
/**
* Additionally specify a FetchConfig to specify a "query join" and or define
* the lazy loading query.
*
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* new QCustomer()
* // lazy fetch contacts with a batch size of 100
* .fetch("contacts", new FetchConfig().lazy(100))
* .findList();
*
* }</pre>
*/
public R fetch(String path, FetchConfig fetchConfig) {
query.fetch(path, fetchConfig);
return root;
}
/**
* Apply the path properties replacing the select and fetch clauses.
* <p>
* This is typically used when the PathProperties is applied to both the query and the JSON output.
* </p>
*/
public R apply(PathProperties pathProperties) {
query.apply(pathProperties);
return root;
}
/**
* Perform an 'As of' query using history tables to return the object graph
* as of a time in the past.
* <p>
* To perform this query the DB must have underlying history tables.
* </p>
*
* @param asOf the date time in the past at which you want to view the data
*/
public R asOf(Timestamp asOf) {
query.asOf(asOf);
return root;
}
/**
* Set root table alias.
*/
public R alias(String alias) {
query.alias(alias);
return root;
}
/**
* Set the maximum number of rows to return in the query.
*
* @param maxRows
* the maximum number of rows to return in the query.
*/
public R setMaxRows(int maxRows) {
query.setMaxRows(maxRows);
return root;
}
/**
* Set the first row to return for this query.
*
* @param firstRow the first row to include in the query result.
*/
public R setFirstRow(int firstRow) {
query.setFirstRow(firstRow);
return root;
}
/**
* Explicitly specify whether to use AutoTune for this query.
* <p>
* If you do not call this method on a query the "Implicit AutoTune mode" is
* used to determine if AutoTune should be used for a given query.
* </p>
* <p>
* AutoTune can add additional fetch paths to the query and specify which
* properties are included for each path. If you have explicitly defined some
* fetch paths AutoTune will not remove them.
* </p>
*/
public R setAutoTune(boolean autoTune) {
query.setAutoTune(autoTune);
return root;
}
/**
* A hint which for JDBC translates to the Statement.fetchSize().
* <p>
* Gives the JDBC driver a hint as to the number of rows that should be
* fetched from the database when more rows are needed for ResultSet.
* </p>
*/
public R setBufferFetchSizeHint(int fetchSize) {
query.setBufferFetchSizeHint(fetchSize);
return root;
}
/**
* Set whether this query uses DISTINCT.
*/
public R setDistinct(boolean distinct) {
query.setDistinct(distinct);
return root;
}
/**
* executed the select with "for update" which should lock the record
* "on read"
*/
public R setForUpdate(boolean forUpdate) {
query.setForUpdate(forUpdate);
return root;
}
/**
* Set the Id value to query. This is used with findUnique().
* <p>
* You can use this to have further control over the query. For example adding
* fetch joins.
* </p>
*
* <pre>{@code
*
* Order order =
* new QOrder()
* .setId(1)
* .fetch("details")
* .findUnique();
*
* // the order details were eagerly fetched
* List<OrderDetail> details = order.getDetails();
*
* }</pre>
*/
public R setId(Object id) {
query.setId(id);
return root;
}
/**
* Set the default lazy loading batch size to use.
* <p>
* When lazy loading is invoked on beans loaded by this query then this sets the
* batch size used to load those beans.
*
* @param lazyLoadBatchSize the number of beans to lazy load in a single batch
*/
public R setLazyLoadBatchSize(int lazyLoadBatchSize) {
query.setLazyLoadBatchSize(lazyLoadBatchSize);
return root;
}
/**
* When set to true all the beans from this query are loaded into the bean
* cache.
*/
public R setLoadBeanCache(boolean loadBeanCache) {
query.setLoadBeanCache(loadBeanCache);
return root;
}
/**
* Set the property to use as keys for a map.
* <p>
* If no property is set then the id property is used.
* </p>
*
* <pre>{@code
*
* // Assuming sku is unique for products...
*
* Map<?,Product> productMap =
* new QProduct()
* // use sku for keys...
* .setMapKey("sku")
* .findMap();
*
* }</pre>
*
* @param mapKey
* the property to use as keys for a map.
*/
public R setMapKey(String mapKey) {
query.setMapKey(mapKey);
return root;
}
/**
* Specify the PersistenceContextScope to use for this query.
* <p/>
* When this is not set the 'default' configured on {@link com.avaje.ebean.config.ServerConfig#setPersistenceContextScope(PersistenceContextScope)}
* is used - this value defaults to {@link com.avaje.ebean.PersistenceContextScope#TRANSACTION}.
* <p/>
* Note that the same persistence Context is used for subsequent lazy loading and query join queries.
* <p/>
* Note that #findEach uses a 'per object graph' PersistenceContext so this scope is ignored for
* queries executed as #findIterate, #findEach, #findEachWhile.
*
* @param scope The scope to use for this query and subsequent lazy loading.
*/
public R setPersistenceContextScope(PersistenceContextScope scope) {
query.setPersistenceContextScope(scope);
return root;
}
/**
* Set RawSql to use for this query.
*/
public R setRawSql(RawSql rawSql) {
query.setRawSql(rawSql);
return root;
}
/**
* When set to true when you want the returned beans to be read only.
*/
public R setReadOnly(boolean readOnly) {
query.setReadOnly(readOnly);
return root;
}
/**
* Set this to true to use the bean cache.
* <p>
* If the query result is in cache then by default this same instance is
* returned. In this sense it should be treated as a read only object graph.
* </p>
*/
public R setUseCache(boolean useCache) {
query.setUseCache(useCache);
return root;
}
/**
* Set this to true to use the query cache.
*/
public R setUseQueryCache(boolean useCache) {
query.setUseQueryCache(useCache);
return root;
}
/**
* Set a timeout on this query.
* <p>
* This will typically result in a call to setQueryTimeout() on a
* preparedStatement. If the timeout occurs an exception will be thrown - this
* will be a SQLException wrapped up in a PersistenceException.
* </p>
*
* @param secs
* the query timeout limit in seconds. Zero means there is no limit.
*/
public R setTimeout(int secs) {
query.setTimeout(secs);
return root;
}
/**
* Marker that can be used to indicate that the order by clause is defined after this.
* <p>
* order() and orderBy() are synonyms and both exist for historic reasons.
* </p>
*
* <h2>Example: order by customer name, order date</h2>
* <pre>{@code
* List<Order> orders =
* new QOrder()
* .customer.name.ilike("rob")
* .orderBy()
* .customer.name.asc()
* .orderDate.asc()
* .findList();
*
* }</pre>
*/
public R orderBy() {
// Yes this does not actually do anything! We include it because style wise it makes
// the query nicer to read and suggests that order by definitions are added after this
return root;
}
/**
* Marker that can be used to indicate that the order by clause is defined after this.
* <p>
* order() and orderBy() are synonyms and both exist for historic reasons.
* </p>
*
* <h2>Example: order by customer name, order date</h2>
* <pre>{@code
* List<Order> orders =
* new QOrder()
* .customer.name.ilike("rob")
* .order()
* .customer.name.asc()
* .orderDate.asc()
* .findList();
*
* }</pre>
*/
public R order() {
// Yes this does not actually do anything! We include it because style wise it makes
// the query nicer to read and suggests that order by definitions are added after this
return root;
}
/**
* Set the full raw order by clause replacing the existing order by clause if there is one.
* <p>
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #order(String)}.
* </p>
*/
public R orderBy(String orderByClause) {
query.orderBy(orderByClause);
return root;
}
/**
* Set the full raw order by clause replacing the existing order by clause if there is one.
* <p>
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #orderBy(String)}.
* </p>
*/
public R order(String orderByClause) {
query.order(orderByClause);
return root;
}
/**
* Begin a list of expressions added by 'OR'.
* <p>
* This should have an associated call to endOr() to close the 'OR' expression list.
* </p>
* <h2>Example</h2>
* <p>
* This example uses an 'OR' expression list with an inner 'AND' expression list.
* </p>
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .status.equalTo(Customer.Status.GOOD)
* .or()
* .id.greaterThan(1000)
* .and()
* .name.startsWith("super")
* .registered.after(fiveDaysAgo)
* .endAnd()
* .endOr()
* .orderBy().id.desc()
* .findList();
*
* }</pre>
* <h2>Resulting SQL where clause</h2>
* <pre>{@code sql
* where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) )
* order by t0.id desc;
*
* --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
*
* }</pre>
*/
public R or() {
Junction<T> junction = peekExprList().disjunction();
expressionListStack.push(junction);
return root;
}
/**
* Begin a list of expressions added by 'AND'.
* <p>
* This should have an associated call to endAnd() to close the 'AND' expression list.
* </p>
* <p>
* Note that typically the AND expression is only used inside an outer 'OR' expression.
* This is because the top level expression list is an 'AND' expression list.
* </p>
* <h2>Example</h2>
* <p>
* This example uses an 'OR' expression list with an inner 'AND' expression list.
* </p>
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .status.equalTo(Customer.Status.GOOD)
* .or() // OUTER 'OR'
* .id.greaterThan(1000)
* .and() // NESTED 'AND' expression list
* .name.startsWith("super")
* .registered.after(fiveDaysAgo)
* .endAnd()
* .endOr()
* .orderBy().id.desc()
* .findList();
*
* }</pre>
* <h2>Resulting SQL where clause</h2>
* <pre>{@code sql
* where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) )
* order by t0.id desc;
*
* --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
*
* }</pre>
*/
public R and() {
Junction<T> junction = peekExprList().conjunction();
expressionListStack.push(junction);
return root;
}
/**
* End a list of expressions added by 'OR'.
*/
public R endOr() {
expressionListStack.pop();
return root;
}
/**
* End to a list of expressions joined by 'AND'.
*/
public R endAnd() {
expressionListStack.pop();
return root;
}
/**
* Execute the query returning either a single bean or null (if no matching
* bean is found).
* <p>
* If more than 1 row is found for this query then a PersistenceException is
* thrown.
* </p>
* <p>
* This is useful when your predicates dictate that your query should only
* return 0 or 1 results.
* </p>
*
* <pre>{@code
*
* // assuming the sku of products is unique...
* Product product =
* new QProduct()
* .sku.equalTo("aa113")
* .findUnique();
* ...
* }</pre>
*
* <p>
* It is also useful with finding objects by their id when you want to specify
* further join information to optimise the query.
* </p>
*
* <pre>{@code
*
* // Fetch order 42 and additionally fetch join its order details...
* Order order =
* new QOrder()
* .fetch("details") // eagerly load the order details
* .id.equalTo(42)
* .findUnique();
*
* // the order details were eagerly loaded
* List<OrderDetail> details = order.getDetails();
* ...
* }</pre>
*/
@Nullable
public T findUnique() {
return query.findUnique();
}
/**
* Execute the query returning the list of objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*
* <pre>{@code
*
* List<Customer> customers =
* new QCustomer()
* .name.ilike("rob%")
* .findList();
*
* }</pre>
*
* @see EbeanServer#findList(Query, Transaction)
*/
public List<T> findList() {
return query.findList();
}
/**
* Execute the query returning the list of Id's.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*
* @see EbeanServer#findIds(Query, Transaction)
*/
public List<Object> findIds() {
return query.findIds();
}
/**
* Execute the query iterating over the results.
* <p>
* Remember that with {@link QueryIterator} you must call
* {@link QueryIterator#close()} when you have finished iterating the results
* (typically in a finally block).
* </p>
* <p>
* findEach() and findEachWhile() are preferred to findIterate() as they ensure
* the jdbc statement and resultSet are closed at the end of the iteration.
* </p>
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
*/
public QueryIterator<T> findIterate() {
return query.findIterate();
}
/**
* Execute the query returning a map of the objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* </p>
* <p>
* You can use setMapKey() so specify the property values to be used as keys
* on the map. If one is not specified then the id property is used.
* </p>
*
* <pre>{@code
*
* Map<?, Product> map =
* ebeanServer.find(Product.class)
* .setMapKey("sku")
* .findMap();
*
* }</pre>
*
* @see EbeanServer#findMap(Query, Transaction)
*/
public Map<?,T> findMap() {
return query.findMap();
}
/**
* Return a typed map specifying the key property and type.
*/
public <K> Map<K, T> findMap(String keyProperty, Class<K> keyType) {
return query.findMap(keyProperty, keyType);
}
/**
* Execute the query processing the beans one at a time.
* <p>
* This method is appropriate to process very large query results as the
* beans are consumed one at a time and do not need to be held in memory
* (unlike #findList #findSet etc)
* </p>
* <p>
* Note that internally Ebean can inform the JDBC driver that it is expecting larger
* resultSet and specifically for MySQL this hint is required to stop it's JDBC driver
* from buffering the entire resultSet. As such, for smaller resultSets findList() is
* generally preferable.
* </p>
* <p>
* Compared with #findEachWhile this will always process all the beans where as
* #findEachWhile provides a way to stop processing the query result early before
* all the beans have been read.
* </p>
* <p>
* This method is functionally equivalent to findIterate() but instead of using an
* iterator uses the QueryEachConsumer (SAM) interface which is better suited to use
* with Java8 closures.
* </p>
*
* <pre>{@code
*
* new QCustomer()
* .status.equalTo(Status.NEW)
* .orderBy().id.asc()
* .findEach((Customer customer) -> {
*
* // do something with customer
* System.out.println("-- visit " + customer);
* });
*
* }</pre>
*
* @param consumer
* the consumer used to process the queried beans.
*/
public void findEach(QueryEachConsumer<T> consumer) {
query.findEach(consumer);
}
/**
* Execute the query using callbacks to a visitor to process the resulting
* beans one at a time.
* <p>
* This method is functionally equivalent to findIterate() but instead of using an
* iterator uses the QueryEachWhileConsumer (SAM) interface which is better suited to use
* with Java8 closures.
* </p>
*
* <pre>{@code
*
* new QCustomer()
* .status.equalTo(Status.NEW)
* .order().id.asc()
* .findEachWhile((Customer customer) -> {
*
* // do something with customer
* System.out.println("-- visit " + customer);
*
* // return true to continue processing or false to stop
* return (customer.getId() < 40);
* });
*
* }</pre>
*
* @param consumer
* the consumer used to process the queried beans.
*/
public void findEachWhile(QueryEachWhileConsumer<T> consumer) {
query.findEachWhile(consumer);
}
/**
* Return versions of a @History entity bean.
* <p>
* Generally this query is expected to be a find by id or unique predicates query.
* It will execute the query against the history returning the versions of the bean.
* </p>
*/
public List<Version<T>> findVersions() {
return query.findVersions();
}
/**
* Return the count of entities this query should return.
* <p>
* This is the number of 'top level' or 'root level' entities.
* </p>
*/
public int findRowCount() {
return query.findRowCount();
}
/**
* Execute find row count query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the row count query
*/
public FutureRowCount<T> findFutureRowCount() {
return query.findFutureRowCount();
}
/**
* Execute find Id's query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the list of Id's
*/
public FutureIds<T> findFutureIds() {
return query.findFutureIds();
}
/**
* Execute find list query in a background thread.
* <p>
* This query will execute in it's own PersistenceContext and using its own transaction.
* What that means is that it will not share any bean instances with other queries.
* </p>
*
* @return a Future object for the list result of the query
*/
public FutureList<T> findFutureList() {
return query.findFutureList();
}
/**
* Return a PagedList for this query.
* <p>
* The benefit of using this over just using the normal {@link Query#setFirstRow(int)} and
* {@link Query#setMaxRows(int)} is that it additionally wraps an optional call to
* {@link Query#findFutureRowCount()} to determine total row count, total page count etc.
* </p>
* <p>
* Internally this works using {@link Query#setFirstRow(int)} and {@link Query#setMaxRows(int)} on
* the query. This translates into SQL that uses limit offset, rownum or row_number function to
* limit the result set.
* </p>
*
* <h4>Example: typical use including total row count</h4>
* <pre>{@code
*
* // We want to find the first 100 new orders
* // ... 0 means first page
* // ... page size is 100
*
* PagedList<Order> pagedList
* = new QOrder()
* .status.equalTo(Order.Status.NEW)
* .order().id.asc()
* .findPagedList(0, 100);
*
* // Optional: initiate the loading of the total
* // row count in a background thread
* pagedList.loadRowCount();
*
* // fetch and return the list in the foreground thread
* List<Order> orders = pagedList.getList();
*
* // get the total row count (from the future)
* int totalRowCount = pagedList.getTotalRowCount();
*
* }</pre>
*
* @param pageIndex
* The zero based index of the page.
* @param pageSize
* The number of beans to return per page.
* @return The PagedList
*/
public PagedList<T> findPagedList(int pageIndex, int pageSize) {
return query.findPagedList(pageIndex, pageSize);
}
/**
* Execute as a delete query deleting the 'root level' beans that match the predicates
* in the query.
* <p>
* Note that if the query includes joins then the generated delete statement may not be
* optimal depending on the database platform.
* </p>
*
* @return the number of beans/rows that were deleted.
*/
public int delete() {
return query.delete();
}
/**
* Return the sql that was generated for executing this query.
* <p>
* This is only available after the query has been executed and provided only
* for informational purposes.
* </p>
*/
public String getGeneratedSql() {
return query.getGeneratedSql();
}
/**
* Return the type of beans being queried.
*/
public Class<T> getBeanType() {
return query.getBeanType();
}
/**
* Return the expression list that has been built for this query.
*/
public ExpressionList<T> getExpressionList() {
return query.where();
}
/**
* Return the current expression list that expressions should be added to.
*/
protected ExpressionList<T> peekExprList() {
if (expressionListStack.isEmpty()) {
// empty so push on the queries base expression list
expressionListStack.push(query.where());
}
// return the current expression list
return expressionListStack.peek();
}
}
| #7 - Add raw() expression support to root 'Query Beans'
| src/main/java/org/avaje/ebean/typequery/TQRootBean.java | #7 - Add raw() expression support to root 'Query Beans' |
|
Java | apache-2.0 | 2e17416f72361850e1611a0186d1b169374ae227 | 0 | codeaudit/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,jerome79/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,nssales/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.mongo;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.SingletonFactoryBean;
/**
* Factory bean to provide Mongo database connectors.
* <p>
* This class provides a simple-to-setup and simple-to-use way to access Mongo databases.
* The main benefit is simpler configuration, especially if that configuration is in XML.
*/
public class MongoConnectorFactoryBean extends SingletonFactoryBean<MongoConnector> {
/**
* The configuration name.
*/
private String _name;
/**
* The Mongo instance.
*/
private Mongo _mongo;
/**
* The database.
*/
private DB _database;
/**
* The host name.
*/
private String _host = "localhost";
/**
* The host port.
*/
private int _port = 27017;
/**
* The database name.
*/
private String _databaseName = "OpenGamma";
/**
* The collection suffix.
*/
private String _collectionSuffix = "";
/**
* Creates an instance.
*/
public MongoConnectorFactoryBean() {
}
/**
* Creates an instance based on an existing connector.
* <p>
* This copies the name, mongo and database.
*
* @param base the base connector to copy, not null
*/
public MongoConnectorFactoryBean(MongoConnector base) {
setName(base.getName());
setMongo(base.getMongo());
setDB(base.getDB());
}
//-------------------------------------------------------------------------
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public Mongo getMongo() {
return _mongo;
}
public void setMongo(Mongo mongo) {
_mongo = mongo;
}
public DB getDB() {
return _database;
}
public void setDB(DB database) {
_database = database;
}
public String getHost() {
return _host;
}
public void setHost(String host) {
_host = host;
}
public int getPort() {
return _port;
}
public void setPort(int port) {
_port = port;
}
public String getDatabaseName() {
return _databaseName;
}
public void setDatabaseName(String databaseName) {
_databaseName = databaseName;
}
public String getCollectionSuffix() {
return _collectionSuffix;
}
public void setCollectionSuffix(String collectionSuffix) {
_collectionSuffix = collectionSuffix;
}
//-------------------------------------------------------------------------
@Override
public MongoConnector createObject() {
final String name = getName(); // store in variable to protect against change by subclass
ArgumentChecker.notNull(name, "name");
final Mongo mongo = createMongo();
final DB db = createDatabase(mongo);
return new MongoConnector(name, mongo, db, getCollectionSuffix());
}
/**
* Creates the Mongo instance, using the host and port.
*
* @return the Mongo instance, not null
*/
protected Mongo createMongo() {
final Mongo mongo = getMongo(); // store in variable to protect against change by subclass
if (mongo != null) {
return mongo;
}
final String host = getHost(); // store in variable to protect against change by subclass
final int port = getPort(); // store in variable to protect against change by subclass
ArgumentChecker.notNull(host, "host");
try {
return new Mongo(host, port);
} catch (UnknownHostException ex) {
throw new MongoException(ex.getMessage(), ex);
}
}
/**
* Creates the database.
*
* @param mongo the Mongo instance, not null
* @return the database, may be null
*/
protected DB createDatabase(Mongo mongo) {
final DB db = getDB();
if (db != null) {
return db;
}
final String databaseName = getDatabaseName(); // store in variable to protect against change by subclass
ArgumentChecker.notNull(databaseName, "databaseName");
return mongo.getDB(databaseName);
}
//-------------------------------------------------------------------------
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| projects/OG-Util/src/com/opengamma/util/mongo/MongoConnectorFactoryBean.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.mongo;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.SingletonFactoryBean;
/**
* Factory bean to provide Mongo database connectors.
* <p>
* This class provides a simple-to-setup and simple-to-use way to access Mongo databases.
* The main benefit is simpler configuration, especially if that configuration is in XML.
*/
public class MongoConnectorFactoryBean extends SingletonFactoryBean<MongoConnector> {
/**
* The configuration name.
*/
private String _name;
/**
* The Mongo instance.
*/
private Mongo _mongo;
/**
* The database.
*/
private DB _database;
/**
* The host name.
*/
private String _host = "localhost";
/**
* The host port.
*/
private int _port = 27017;
/**
* The database name.
*/
private String _databaseName = "OpenGamma";
/**
* The collection suffix.
*/
private String _collectionSuffix = "";
/**
* Creates an instance.
*/
public MongoConnectorFactoryBean() {
}
/**
* Creates an instance based on an existing connector.
* <p>
* This copies the name, mongo and databse.
*
* @param base the base connector to copy, not null
*/
public MongoConnectorFactoryBean(MongoConnector base) {
setName(base.getName());
setMongo(base.getMongo());
setDB(base.getDB());
}
//-------------------------------------------------------------------------
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public Mongo getMongo() {
return _mongo;
}
public void setMongo(Mongo mongo) {
_mongo = mongo;
}
public DB getDB() {
return _database;
}
public void setDB(DB database) {
_database = database;
}
public String getHost() {
return _host;
}
public void setHost(String host) {
_host = host;
}
public int getPort() {
return _port;
}
public void setPort(int port) {
_port = port;
}
public String getDatabaseName() {
return _databaseName;
}
public void setDatabaseName(String databaseName) {
_databaseName = databaseName;
}
public String getCollectionSuffix() {
return _collectionSuffix;
}
public void setCollectionSuffix(String collectionSuffix) {
_collectionSuffix = collectionSuffix;
}
//-------------------------------------------------------------------------
@Override
public MongoConnector createObject() {
ArgumentChecker.notNull(getName(), "name");
final Mongo mongo = createMongo();
final DB db = createDatabase(mongo);
return new MongoConnector(getName(), mongo, db, getCollectionSuffix());
}
/**
* Creates the Mongo instance, using the host and port.
*
* @return the Mongo instance, not null
*/
protected Mongo createMongo() {
final Mongo mongo = getMongo(); // store in variable to protect against change by subclass
if (mongo != null) {
return mongo;
}
ArgumentChecker.notNull(getHost(), "host");
try {
return new Mongo(getHost(), getPort());
} catch (UnknownHostException ex) {
throw new MongoException(ex.getMessage(), ex);
}
}
/**
* Creates the database.
*
* @param mongo the Mongo instance, not null
* @return the database, may be null
*/
protected DB createDatabase(Mongo mongo) {
final DB db = getDB();
if (db != null) {
return db;
}
final String databaseName = getDatabaseName(); // store in variable to protect against change by subclass
ArgumentChecker.notNull(databaseName, "databaseName");
return mongo.getDB(databaseName);
}
//-------------------------------------------------------------------------
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| [PLAT-1644] Enhance Mongo connectors
| projects/OG-Util/src/com/opengamma/util/mongo/MongoConnectorFactoryBean.java | [PLAT-1644] Enhance Mongo connectors |
|
Java | apache-2.0 | 41e365b782440e72ab5b44d12e3549576ad08cb5 | 0 | apache/httpcomponents-core,apache/httpcore,ok2c/httpcore,apache/httpcore | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl;
import java.io.IOException;
import java.net.SocketTimeoutException;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.entity.ContentLengthStrategy;
import org.apache.http.impl.entity.EntityDeserializer;
import org.apache.http.impl.entity.EntitySerializer;
import org.apache.http.impl.entity.LaxContentLengthStrategy;
import org.apache.http.impl.entity.StrictContentLengthStrategy;
import org.apache.http.impl.io.HttpRequestWriter;
import org.apache.http.impl.io.HttpResponseParser;
import org.apache.http.io.EofSensor;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.HttpMessageWriter;
import org.apache.http.io.HttpTransportMetrics;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.io.SessionOutputBuffer;
import org.apache.http.message.LineFormatter;
import org.apache.http.message.LineParser;
import org.apache.http.params.HttpParams;
/**
* Abstract client-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public abstract class AbstractHttpClientConnection implements HttpClientConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser<HttpResponse> responseParser = null;
private HttpMessageWriter<HttpRequest> requestWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpClientConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* for creating {@link HttpResponse} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP responses received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpResponseParser}.
*
* @param buffer the session input buffer.
* @param responseFactory the HTTP response factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new HttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP requests sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpRequestWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpRequestWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpResponseFactory()},
* {@link #createRequestWriter(SessionOutputBuffer, HttpParams)}
* and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)}
* methods to initialize HTTP request writer and response parser for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.responseParser = createResponseParser(
inbuffer,
createHttpResponseFactory(),
params);
this.requestWriter = createRequestWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public boolean isResponseAvailable(int timeout) throws IOException {
assertOpen();
return this.inbuffer.isDataAvailable(timeout);
}
public void sendRequestHeader(final HttpRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
this.requestWriter.write(request);
this.metrics.incrementRequestCount();
}
public void sendRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
if (request.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
request,
request.getEntity());
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
assertOpen();
HttpResponse response = this.responseParser.parse();
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
return response;
}
public void receiveResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response);
response.setEntity(entity);
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (SocketTimeoutException ex) {
return false;
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
| httpcore/src/main/java/org/apache/http/impl/AbstractHttpClientConnection.java | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl;
import java.io.IOException;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.entity.ContentLengthStrategy;
import org.apache.http.impl.entity.EntityDeserializer;
import org.apache.http.impl.entity.EntitySerializer;
import org.apache.http.impl.entity.LaxContentLengthStrategy;
import org.apache.http.impl.entity.StrictContentLengthStrategy;
import org.apache.http.impl.io.HttpRequestWriter;
import org.apache.http.impl.io.HttpResponseParser;
import org.apache.http.io.EofSensor;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.HttpMessageWriter;
import org.apache.http.io.HttpTransportMetrics;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.io.SessionOutputBuffer;
import org.apache.http.message.LineFormatter;
import org.apache.http.message.LineParser;
import org.apache.http.params.HttpParams;
/**
* Abstract client-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public abstract class AbstractHttpClientConnection implements HttpClientConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser<HttpResponse> responseParser = null;
private HttpMessageWriter<HttpRequest> requestWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpClientConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* for creating {@link HttpResponse} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP responses received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpResponseParser}.
*
* @param buffer the session input buffer.
* @param responseFactory the HTTP response factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new HttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP requests sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpRequestWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpRequestWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpResponseFactory()},
* {@link #createRequestWriter(SessionOutputBuffer, HttpParams)}
* and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)}
* methods to initialize HTTP request writer and response parser for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.responseParser = createResponseParser(
inbuffer,
createHttpResponseFactory(),
params);
this.requestWriter = createRequestWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public boolean isResponseAvailable(int timeout) throws IOException {
assertOpen();
return this.inbuffer.isDataAvailable(timeout);
}
public void sendRequestHeader(final HttpRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
this.requestWriter.write(request);
this.metrics.incrementRequestCount();
}
public void sendRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
if (request.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
request,
request.getEntity());
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
assertOpen();
HttpResponse response = this.responseParser.parse();
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
return response;
}
public void receiveResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response);
response.setEntity(entity);
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
| Fixed incorrect handling of socket timeouts in AbstractHttpClientConnection#isStale()
git-svn-id: 6006d5852951f43e4bf20b1aa071d815bf420463@1153976 13f79535-47bb-0310-9956-ffa450edef68
| httpcore/src/main/java/org/apache/http/impl/AbstractHttpClientConnection.java | Fixed incorrect handling of socket timeouts in AbstractHttpClientConnection#isStale() |
|
Java | apache-2.0 | 4d74fa694802bba81f72c69355ff766a5ffa655f | 0 | ejlchina/bean-searcher,ejlchina/bean-searcher,ejlchina/bean-searcher,ejlchina/bean-searcher | package com.ejlchina.searcher.implement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.ejlchina.searcher.SearchSql;
import com.ejlchina.searcher.SearchSqlResolver;
import com.ejlchina.searcher.SearcherException;
import com.ejlchina.searcher.beanmap.SearchBeanMap;
import com.ejlchina.searcher.dialect.Dialect;
import com.ejlchina.searcher.dialect.Dialect.PaginateSql;
import com.ejlchina.searcher.param.FilterParam;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.param.SearchParam;
import com.ejlchina.searcher.util.StringUtils;
/**
* 默认查询SQL解析器
*
* @author Troy.Zhou @ 2017-03-20
* @since V1.1.1
*/
public class MainSearchSqlResolver implements SearchSqlResolver {
static final Pattern DATE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
static final Pattern DATE_MINUTE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}");
static final Pattern DATE_SECOND_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
/**
* 数据库方言
*/
private Dialect dialect;
private String virtualParamPrefix = ":";
private String[] vertualParamEndFlags = new String[] {" ", "\t", "\n", "\r", "+", "-", "*", "/", "=", "!", ">", "<", ",", ")", "'", "%"};
@Override
public SearchSql resolve(SearchBeanMap searchBeanMap, SearchParam searchParam) {
if (!searchBeanMap.isVirtualResolved()) {
resolveVirtualParams(searchBeanMap);
}
List<String> fieldList = searchBeanMap.getFieldList();
Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap();
Map<String, String> fieldDbAliasMap = searchBeanMap.getFieldDbAliasMap();
Map<String, Class<?>> fieldTypeMap = searchBeanMap.getFieldTypeMap();
Map<String, String> virtualParamMap = searchParam.getVirtualParamMap();
SearchSql searchSql = new SearchSql();
StringBuilder builder = new StringBuilder("select ");
if (searchBeanMap.isDistinct()) {
builder.append("distinct ");
}
int fieldCount = fieldList.size();
for (int i = 0; i < fieldCount; i++) {
String field = fieldList.get(i);
String dbField = fieldDbMap.get(field);
String dbAlias = fieldDbAliasMap.get(field);
builder.append(dbField).append(" ").append(dbAlias);
if (i < fieldCount - 1) {
builder.append(", ");
}
for (String key: searchBeanMap.getFieldVirtualParams(field)) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
if (searchBeanMap.isDistinct()) {
searchSql.addClusterSqlParam(sqlParam);
}
}
searchSql.addListAlias(dbAlias);
}
String fieldSelectSql = builder.toString();
builder = new StringBuilder(" from ");
builder.append(searchBeanMap.getTalbes());
for (String key: searchBeanMap.getTableVirtualParams()) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
String joinCond = searchBeanMap.getJoinCond();
boolean hasJoinCond = joinCond != null && !"".equals(joinCond.trim());
List<FilterParam> filterParamList = searchParam.getFilterParamList();
if (hasJoinCond || filterParamList.size() > 0) {
builder.append(" where ");
if (hasJoinCond) {
builder.append("(").append(joinCond).append(")");
for (String key: searchBeanMap.getJoinCondVirtualParams()) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
}
}
for (int i = 0; i < filterParamList.size(); i++) {
if (i > 0 || hasJoinCond) {
builder.append(" and ");
}
FilterParam filterParam = filterParamList.get(i);
String fieldName = filterParam.getName();
List<Object> sqlParams = appendFilterConditionSql(builder, fieldTypeMap.get(fieldName),
fieldDbMap.get(fieldName), filterParam);
for (Object sqlParam : sqlParams) {
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
}
String groupBy = searchBeanMap.getGroupBy();
String[] summaryFields = searchParam.getSummaryFields();
boolean shouldQueryTotal = searchParam.isShouldQueryTotal();
if (StringUtils.isBlank(groupBy)) {
if (searchBeanMap.isDistinct()) {
String originalSql = fieldSelectSql + builder.toString();
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, originalSql);
String tableAlias = generateTableAlias(originalSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (" + originalSql + ") " + tableAlias);
} else {
String fromWhereSql = builder.toString();
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, fromWhereSql);
searchSql.setClusterSqlString(clusterSelectSql + fromWhereSql);
}
} else {
builder.append(" group by " + groupBy);
String fromWhereSql = builder.toString();
if (searchBeanMap.isDistinct()) {
String originalSql = fieldSelectSql + fromWhereSql;
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, originalSql);
String tableAlias = generateTableAlias(originalSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (" + originalSql + ") " + tableAlias);
} else {
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, fromWhereSql);
String tableAlias = generateTableAlias(fromWhereSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (select count(1) " + fromWhereSql + ") " + tableAlias);
}
}
String sortDbAlias = fieldDbAliasMap.get(searchParam.getSort());
if (sortDbAlias != null) {
builder.append(" order by ").append(sortDbAlias);
String order = searchParam.getOrder();
if (order != null) {
builder.append(" ").append(order);
}
}
String fromWhereSql = builder.toString();
PaginateSql paginateSql = dialect.forPaginate(fieldSelectSql, fromWhereSql, searchParam.getMax(),
searchParam.getOffset());
searchSql.setListSqlString(paginateSql.getSql());
searchSql.addListSqlParams(paginateSql.getParams());
return searchSql;
}
private String resolveClusterSelectSql(Map<String, String> fieldDbMap,
SearchSql searchSql, String[] summaryFields, boolean shouldQueryTotal, String originalSql) {
StringBuilder clusterSelectSqlBuilder = new StringBuilder("select ");
if (shouldQueryTotal) {
String countAlias = generateColumnAlias("count", originalSql);
clusterSelectSqlBuilder.append("count(1) ").append(countAlias);
searchSql.setCountAlias(countAlias);
}
if (summaryFields != null) {
if (shouldQueryTotal && summaryFields.length > 0) {
clusterSelectSqlBuilder.append(", ");
}
for (int i = 0; i < summaryFields.length; i++) {
String summaryField = summaryFields[i];
String summaryAlias = generateColumnAlias(summaryField, originalSql);
String dbField = fieldDbMap.get(summaryField);
if (dbField == null) {
throw new SearcherException("求和属性【" + summaryField + "】没有和数据库字段做映射,请检查该属性是否被@DbField正确注解!");
}
clusterSelectSqlBuilder.append("sum(").append(dbField)
.append(") ").append(summaryAlias);
if (i < summaryFields.length - 1) {
clusterSelectSqlBuilder.append(", ");
}
searchSql.addSummaryAlias(summaryAlias);
}
}
clusterSelectSqlBuilder.append(" ");
return clusterSelectSqlBuilder.toString();
}
private void resolveVirtualParams(SearchBeanMap searchBeanMap) {
VirtualSolution solution = resolveVirtualParams(searchBeanMap.getTalbes());
searchBeanMap.setTalbes(solution.getSqlSnippet());
searchBeanMap.setTableVirtualParams(solution.getVirtualParams());
solution = resolveVirtualParams(searchBeanMap.getJoinCond());
searchBeanMap.setJoinCond(solution.getSqlSnippet());
searchBeanMap.setJoinCondVirtualParams(solution.getVirtualParams());
Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap();
for (String field : searchBeanMap.getFieldList()) {
solution = resolveVirtualParams(fieldDbMap.get(field));
fieldDbMap.put(field, solution.getSqlSnippet());
searchBeanMap.putFieldVirtualParam(field, solution.getVirtualParams());
}
searchBeanMap.setVirtualResolved(true);
}
private int findVitualParamEndIndex(String sqlSnippet, int fromIndex) {
int index = -1;
for (String flag : vertualParamEndFlags) {
int index0 = sqlSnippet.indexOf(flag, fromIndex);
if (index < 0) {
index = index0;
} else if (index0 > 0) {
index = Math.min(index, index0);
}
}
return index;
}
private VirtualSolution resolveVirtualParams(String sqlSnippet) {
VirtualSolution solution = new VirtualSolution();
int index1 = sqlSnippet.indexOf(virtualParamPrefix);
while (index1 >= 0) {
int index2 = findVitualParamEndIndex(sqlSnippet, index1);
String virtualParam = null;
if (index2 > 0) {
virtualParam = sqlSnippet.substring(index1, index2);
} else {
virtualParam = sqlSnippet.substring(index1);
}
if (StringUtils.isBlank(virtualParam) || virtualParam.length() < 2) {
throw new SearcherException("这里有一个语法错误:" + sqlSnippet);
}
sqlSnippet = sqlSnippet.replaceFirst(virtualParam, "?");
solution.addVirtualParam(virtualParam.substring(1));
index1 = sqlSnippet.indexOf(virtualParamPrefix);
}
solution.setSqlSnippet(sqlSnippet);
return solution;
}
private String generateTableAlias(String originalSql) {
return generateAlias("tbl_", originalSql);
}
private String generateColumnAlias(String seed, String originalSql) {
return generateAlias("col_" + seed, originalSql);
}
private String generateAlias(String seed, String originalSql) {
int index = 0;
String tableAlias = seed;
while (originalSql.contains(tableAlias)) {
tableAlias = seed + index++;
}
return tableAlias;
}
/**
* @return 查询参数值
*/
private List<Object> appendFilterConditionSql(StringBuilder builder, Class<?> fieldType,
String dbField, FilterParam filterParam) {
String[] values = filterParam.getValues();
boolean ignoreCase = filterParam.isIgnoreCase();
Operator operator = filterParam.getOperator();
String firstRealValue = filterParam.firstNotNullValue();
if (ignoreCase) {
for (int i = 0; i < values.length; i++) {
String val = values[i];
if (val != null) {
values[i] = val.toUpperCase();
}
}
if (firstRealValue != null) {
firstRealValue = firstRealValue.toUpperCase();
}
}
if (operator != Operator.MultiValue) {
if (ignoreCase) {
dialect.toUpperCase(builder, dbField);
} else if (Date.class.isAssignableFrom(fieldType) && firstRealValue != null) {
appendDateFieldWithDialect(builder, dbField, firstRealValue);
} else {
builder.append(dbField);
}
}
List<Object> params = new ArrayList<>(2);
switch (operator) {
case Include:
builder.append(" like ?");
params.add("%" + firstRealValue + "%");
break;
case Equal:
builder.append(" = ?");
params.add(firstRealValue);
break;
case GreaterEqual:
builder.append(" >= ?");
params.add(firstRealValue);
break;
case GreaterThan:
builder.append(" > ?");
params.add(firstRealValue);
break;
case LessEqual:
builder.append(" <= ?");
params.add(firstRealValue);
break;
case LessThan:
builder.append(" < ?");
params.add(firstRealValue);
break;
case NotEqual:
builder.append(" != ?");
params.add(firstRealValue);
break;
case Empty:
builder.append(" is null");
break;
case NotEmpty:
builder.append(" is not null");
break;
case StartWith:
builder.append(" like ?");
params.add(firstRealValue + "%");
break;
case EndWith:
builder.append(" like ?");
params.add("%" + firstRealValue);
break;
case Between:
boolean val1Null = false;
boolean val2Null = false;
if (values[0] == null || StringUtils.isBlank(values[0])) {
val1Null = true;
}
if (values[1] == null || StringUtils.isBlank(values[1])) {
val2Null = true;
}
if (!val1Null && !val2Null) {
builder.append(" between ? and ? ");
params.add(values[0]);
params.add(values[1]);
} else if (val1Null && !val2Null) {
builder.append(" <= ? ");
params.add(values[1]);
} else if (!val1Null && val2Null) {
builder.append(" >= ? ");
params.add(values[0]);
}
break;
case MultiValue:
builder.append("(");
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value != null && "NULL".equals(value.toUpperCase())) {
builder.append(dbField).append(" is null");
} else if (ignoreCase) {
dialect.toUpperCase(builder, dbField);
builder.append(" = ?");
params.add(value);
} else if (Date.class.isAssignableFrom(fieldType)) {
appendDateFieldWithDialect(builder, dbField, value);
builder.append(" = ?");
params.add(value);
} else {
builder.append(dbField).append(" = ?");
params.add(value);
}
if (i < values.length - 1) {
builder.append(" or ");
}
}
builder.append(")");
break;
}
return params;
}
private void appendDateFieldWithDialect(StringBuilder builder, String dbField, String value) {
if (DATE_PATTERN.matcher(value).matches()) {
dialect.truncateToDateStr(builder, dbField);
} else if (DATE_MINUTE_PATTERN.matcher(value).matches()) {
dialect.truncateToDateMinuteStr(builder, dbField);
} else if (DATE_SECOND_PATTERN.matcher(value).matches()) {
dialect.truncateToDateSecondStr(builder, dbField);
} else {
builder.append(dbField);
}
}
public void setDialect(Dialect dialect) {
this.dialect = dialect;
}
public void setVirtualParamPrefix(String virtualParamPrefix) {
this.virtualParamPrefix = virtualParamPrefix;
}
public void setVertualParamEndFlags(String[] vertualParamEndFlags) {
this.vertualParamEndFlags = vertualParamEndFlags;
}
class VirtualSolution {
String sqlSnippet;
List<String> virtualParams = new ArrayList<>();
public String getSqlSnippet() {
return sqlSnippet;
}
public void setSqlSnippet(String sqlSnippet) {
this.sqlSnippet = sqlSnippet;
}
public List<String> getVirtualParams() {
return virtualParams;
}
public void addVirtualParam(String virtualParam) {
this.virtualParams.add(virtualParam);
}
}
}
| src/main/java/com/ejlchina/searcher/implement/MainSearchSqlResolver.java | package com.ejlchina.searcher.implement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.ejlchina.searcher.SearchSql;
import com.ejlchina.searcher.SearchSqlResolver;
import com.ejlchina.searcher.SearcherException;
import com.ejlchina.searcher.beanmap.SearchBeanMap;
import com.ejlchina.searcher.dialect.Dialect;
import com.ejlchina.searcher.dialect.Dialect.PaginateSql;
import com.ejlchina.searcher.param.FilterParam;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.param.SearchParam;
import com.ejlchina.searcher.util.StringUtils;
/**
* 默认查询SQL解析器
*
* @author Troy.Zhou @ 2017-03-20
* @since V1.1.1
*/
public class MainSearchSqlResolver implements SearchSqlResolver {
static final Pattern DATE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
static final Pattern DATE_MINUTE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}");
static final Pattern DATE_SECOND_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
static final String[] VERTUAL_PARAM_END_FLAGS = new String[] {" ", "\t", "\n", "\r", "+", "-", "*","/", "=", "!", ">", "<", ",", ")"};
/**
* 数据库方言
*/
private Dialect dialect;
private String virtualParamPrefix = ":";
@Override
public SearchSql resolve(SearchBeanMap searchBeanMap, SearchParam searchParam) {
if (!searchBeanMap.isVirtualResolved()) {
resolveVirtualParams(searchBeanMap);
}
List<String> fieldList = searchBeanMap.getFieldList();
Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap();
Map<String, String> fieldDbAliasMap = searchBeanMap.getFieldDbAliasMap();
Map<String, Class<?>> fieldTypeMap = searchBeanMap.getFieldTypeMap();
Map<String, String> virtualParamMap = searchParam.getVirtualParamMap();
SearchSql searchSql = new SearchSql();
StringBuilder builder = new StringBuilder("select ");
if (searchBeanMap.isDistinct()) {
builder.append("distinct ");
}
int fieldCount = fieldList.size();
for (int i = 0; i < fieldCount; i++) {
String field = fieldList.get(i);
String dbField = fieldDbMap.get(field);
String dbAlias = fieldDbAliasMap.get(field);
builder.append(dbField).append(" ").append(dbAlias);
if (i < fieldCount - 1) {
builder.append(", ");
}
for (String key: searchBeanMap.getFieldVirtualParams(field)) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
if (searchBeanMap.isDistinct()) {
searchSql.addClusterSqlParam(sqlParam);
}
}
searchSql.addListAlias(dbAlias);
}
String fieldSelectSql = builder.toString();
builder = new StringBuilder(" from ");
builder.append(searchBeanMap.getTalbes());
for (String key: searchBeanMap.getTableVirtualParams()) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
String joinCond = searchBeanMap.getJoinCond();
boolean hasJoinCond = joinCond != null && !"".equals(joinCond.trim());
List<FilterParam> filterParamList = searchParam.getFilterParamList();
if (hasJoinCond || filterParamList.size() > 0) {
builder.append(" where ");
if (hasJoinCond) {
builder.append("(").append(joinCond).append(")");
for (String key: searchBeanMap.getJoinCondVirtualParams()) {
String sqlParam = virtualParamMap.get(key);
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
}
}
for (int i = 0; i < filterParamList.size(); i++) {
if (i > 0 || hasJoinCond) {
builder.append(" and ");
}
FilterParam filterParam = filterParamList.get(i);
String fieldName = filterParam.getName();
List<Object> sqlParams = appendFilterConditionSql(builder, fieldTypeMap.get(fieldName),
fieldDbMap.get(fieldName), filterParam);
for (Object sqlParam : sqlParams) {
searchSql.addListSqlParam(sqlParam);
searchSql.addClusterSqlParam(sqlParam);
}
}
String groupBy = searchBeanMap.getGroupBy();
String[] summaryFields = searchParam.getSummaryFields();
boolean shouldQueryTotal = searchParam.isShouldQueryTotal();
if (StringUtils.isBlank(groupBy)) {
if (searchBeanMap.isDistinct()) {
String originalSql = fieldSelectSql + builder.toString();
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, originalSql);
String tableAlias = generateTableAlias(originalSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (" + originalSql + ") " + tableAlias);
} else {
String fromWhereSql = builder.toString();
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, fromWhereSql);
searchSql.setClusterSqlString(clusterSelectSql + fromWhereSql);
}
} else {
builder.append(" group by " + groupBy);
String fromWhereSql = builder.toString();
if (searchBeanMap.isDistinct()) {
String originalSql = fieldSelectSql + fromWhereSql;
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, originalSql);
String tableAlias = generateTableAlias(originalSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (" + originalSql + ") " + tableAlias);
} else {
String clusterSelectSql = resolveClusterSelectSql(fieldDbMap, searchSql,
summaryFields, shouldQueryTotal, fromWhereSql);
String tableAlias = generateTableAlias(fromWhereSql);
searchSql.setClusterSqlString(clusterSelectSql + " from (select count(1) " + fromWhereSql + ") " + tableAlias);
}
}
String sortDbAlias = fieldDbAliasMap.get(searchParam.getSort());
if (sortDbAlias != null) {
builder.append(" order by ").append(sortDbAlias);
String order = searchParam.getOrder();
if (order != null) {
builder.append(" ").append(order);
}
}
String fromWhereSql = builder.toString();
PaginateSql paginateSql = dialect.forPaginate(fieldSelectSql, fromWhereSql, searchParam.getMax(),
searchParam.getOffset());
searchSql.setListSqlString(paginateSql.getSql());
searchSql.addListSqlParams(paginateSql.getParams());
return searchSql;
}
private String resolveClusterSelectSql(Map<String, String> fieldDbMap,
SearchSql searchSql, String[] summaryFields, boolean shouldQueryTotal, String originalSql) {
StringBuilder clusterSelectSqlBuilder = new StringBuilder("select ");
if (shouldQueryTotal) {
String countAlias = generateColumnAlias("count", originalSql);
clusterSelectSqlBuilder.append("count(1) ").append(countAlias);
searchSql.setCountAlias(countAlias);
}
if (summaryFields != null) {
if (shouldQueryTotal && summaryFields.length > 0) {
clusterSelectSqlBuilder.append(", ");
}
for (int i = 0; i < summaryFields.length; i++) {
String summaryField = summaryFields[i];
String summaryAlias = generateColumnAlias(summaryField, originalSql);
String dbField = fieldDbMap.get(summaryField);
if (dbField == null) {
throw new SearcherException("求和属性【" + summaryField + "】没有和数据库字段做映射,请检查该属性是否被@DbField正确注解!");
}
clusterSelectSqlBuilder.append("sum(").append(dbField)
.append(") ").append(summaryAlias);
if (i < summaryFields.length - 1) {
clusterSelectSqlBuilder.append(", ");
}
searchSql.addSummaryAlias(summaryAlias);
}
}
clusterSelectSqlBuilder.append(" ");
return clusterSelectSqlBuilder.toString();
}
private void resolveVirtualParams(SearchBeanMap searchBeanMap) {
VirtualSolution solution = resolveVirtualParams(searchBeanMap.getTalbes());
searchBeanMap.setTalbes(solution.getSqlSnippet());
searchBeanMap.setTableVirtualParams(solution.getVirtualParams());
solution = resolveVirtualParams(searchBeanMap.getJoinCond());
searchBeanMap.setJoinCond(solution.getSqlSnippet());
searchBeanMap.setJoinCondVirtualParams(solution.getVirtualParams());
Map<String, String> fieldDbMap = searchBeanMap.getFieldDbMap();
for (String field : searchBeanMap.getFieldList()) {
solution = resolveVirtualParams(fieldDbMap.get(field));
fieldDbMap.put(field, solution.getSqlSnippet());
searchBeanMap.putFieldVirtualParam(field, solution.getVirtualParams());
}
searchBeanMap.setVirtualResolved(true);
}
private int findVitualParamEndIndex(String sqlSnippet, int fromIndex) {
int index = -1;
for (String flag : VERTUAL_PARAM_END_FLAGS) {
int index0 = sqlSnippet.indexOf(flag, fromIndex);
if (index < 0) {
index = index0;
} else if (index0 > 0) {
index = Math.min(index, index0);
}
}
return index;
}
private VirtualSolution resolveVirtualParams(String sqlSnippet) {
VirtualSolution solution = new VirtualSolution();
int index1 = sqlSnippet.indexOf(virtualParamPrefix);
while (index1 >= 0) {
int index2 = findVitualParamEndIndex(sqlSnippet, index1);
String virtualParam = null;
if (index2 > 0) {
virtualParam = sqlSnippet.substring(index1, index2);
} else {
virtualParam = sqlSnippet.substring(index1);
}
if (StringUtils.isBlank(virtualParam) || virtualParam.length() < 2) {
throw new SearcherException("这里有一个语法错误:" + sqlSnippet);
}
sqlSnippet = sqlSnippet.replaceFirst(virtualParam, "?");
solution.addVirtualParam(virtualParam.substring(1));
index1 = sqlSnippet.indexOf(virtualParamPrefix);
}
solution.setSqlSnippet(sqlSnippet);
return solution;
}
private String generateTableAlias(String originalSql) {
return generateAlias("tbl_", originalSql);
}
private String generateColumnAlias(String seed, String originalSql) {
return generateAlias("col_" + seed, originalSql);
}
private String generateAlias(String seed, String originalSql) {
int index = 0;
String tableAlias = seed;
while (originalSql.contains(tableAlias)) {
tableAlias = seed + index++;
}
return tableAlias;
}
/**
* @return 查询参数值
*/
private List<Object> appendFilterConditionSql(StringBuilder builder, Class<?> fieldType,
String dbField, FilterParam filterParam) {
String[] values = filterParam.getValues();
boolean ignoreCase = filterParam.isIgnoreCase();
Operator operator = filterParam.getOperator();
String firstRealValue = filterParam.firstNotNullValue();
if (ignoreCase) {
for (int i = 0; i < values.length; i++) {
String val = values[i];
if (val != null) {
values[i] = val.toUpperCase();
}
}
if (firstRealValue != null) {
firstRealValue = firstRealValue.toUpperCase();
}
}
if (operator != Operator.MultiValue) {
if (ignoreCase) {
dialect.toUpperCase(builder, dbField);
} else if (Date.class.isAssignableFrom(fieldType) && firstRealValue != null) {
appendDateFieldWithDialect(builder, dbField, firstRealValue);
} else {
builder.append(dbField);
}
}
List<Object> params = new ArrayList<>(2);
switch (operator) {
case Include:
builder.append(" like ?");
params.add("%" + firstRealValue + "%");
break;
case Equal:
builder.append(" = ?");
params.add(firstRealValue);
break;
case GreaterEqual:
builder.append(" >= ?");
params.add(firstRealValue);
break;
case GreaterThan:
builder.append(" > ?");
params.add(firstRealValue);
break;
case LessEqual:
builder.append(" <= ?");
params.add(firstRealValue);
break;
case LessThan:
builder.append(" < ?");
params.add(firstRealValue);
break;
case NotEqual:
builder.append(" != ?");
params.add(firstRealValue);
break;
case Empty:
builder.append(" is null");
break;
case NotEmpty:
builder.append(" is not null");
break;
case StartWith:
builder.append(" like ?");
params.add(firstRealValue + "%");
break;
case EndWith:
builder.append(" like ?");
params.add("%" + firstRealValue);
break;
case Between:
boolean val1Null = false;
boolean val2Null = false;
if (values[0] == null || StringUtils.isBlank(values[0])) {
val1Null = true;
}
if (values[1] == null || StringUtils.isBlank(values[1])) {
val2Null = true;
}
if (!val1Null && !val2Null) {
builder.append(" between ? and ? ");
params.add(values[0]);
params.add(values[1]);
} else if (val1Null && !val2Null) {
builder.append(" <= ? ");
params.add(values[1]);
} else if (!val1Null && val2Null) {
builder.append(" >= ? ");
params.add(values[0]);
}
break;
case MultiValue:
builder.append("(");
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value != null && "NULL".equals(value.toUpperCase())) {
builder.append(dbField).append(" is null");
} else if (ignoreCase) {
dialect.toUpperCase(builder, dbField);
builder.append(" = ?");
params.add(value);
} else if (Date.class.isAssignableFrom(fieldType)) {
appendDateFieldWithDialect(builder, dbField, value);
builder.append(" = ?");
params.add(value);
} else {
builder.append(dbField).append(" = ?");
params.add(value);
}
if (i < values.length - 1) {
builder.append(" or ");
}
}
builder.append(")");
break;
}
return params;
}
private void appendDateFieldWithDialect(StringBuilder builder, String dbField, String value) {
if (DATE_PATTERN.matcher(value).matches()) {
dialect.truncateToDateStr(builder, dbField);
} else if (DATE_MINUTE_PATTERN.matcher(value).matches()) {
dialect.truncateToDateMinuteStr(builder, dbField);
} else if (DATE_SECOND_PATTERN.matcher(value).matches()) {
dialect.truncateToDateSecondStr(builder, dbField);
} else {
builder.append(dbField);
}
}
public void setDialect(Dialect dialect) {
this.dialect = dialect;
}
public void setVirtualParamPrefix(String virtualParamPrefix) {
this.virtualParamPrefix = virtualParamPrefix;
}
class VirtualSolution {
String sqlSnippet;
List<String> virtualParams = new ArrayList<>();
public String getSqlSnippet() {
return sqlSnippet;
}
public void setSqlSnippet(String sqlSnippet) {
this.sqlSnippet = sqlSnippet;
}
public List<String> getVirtualParams() {
return virtualParams;
}
public void addVirtualParam(String virtualParam) {
this.virtualParams.add(virtualParam);
}
}
}
| 使虚拟参在模糊查询条件内也可以使用 | src/main/java/com/ejlchina/searcher/implement/MainSearchSqlResolver.java | 使虚拟参在模糊查询条件内也可以使用 |
|
Java | apache-2.0 | 639d324e2d5f2f83b843259035db624c6dca13f8 | 0 | rohlfingt/blockly-android,rohlfingt/blockly-android,google/blockly-android,google/blockly-android,google/blockly-android,rohlfingt/blockly-android | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.blockly.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.MotionEvent;
import com.google.blockly.R;
import com.google.blockly.control.ConnectionManager;
import com.google.blockly.model.Block;
import com.google.blockly.model.Connection;
import com.google.blockly.model.Input;
import com.google.blockly.model.WorkspacePoint;
import java.util.ArrayList;
import java.util.List;
/**
* Draws a block and handles laying out all its inputs/fields.
*/
@SuppressLint("ViewConstructor")
public class BlockView extends NonPropagatingViewGroup {
// TODO: Replace with dimens so it gets scaled correctly, or better yet, somehow derive from
// ninepatch measurements.
private static final int MIN_BLOCK_WIDTH = 40;
private final WorkspaceHelper mHelper;
private final WorkspaceHelper.BlockTouchHandler mTouchHandler;
private final Block mBlock;
private final ConnectionManager mConnectionManager;
// Child views for the block inputs and their children.
private final ArrayList<InputView> mInputViews = new ArrayList<>();
private int mInputCount;
// Reference points for connectors relative to this view (needed for selective highlighting).
private final ViewPoint mOutputConnectorOffset = new ViewPoint();
private final ViewPoint mPreviousConnectorOffset = new ViewPoint();
private final ViewPoint mNextConnectorOffset = new ViewPoint();
private final ArrayList<ViewPoint> mInputConnectorOffsets = new ArrayList<>();
// Current measured size of this block view.
private final ViewPoint mBlockViewSize = new ViewPoint();
// Position of the connection currently being updated, for temporary use during
// layoutPatchesAndConnectors.
private final ViewPoint mTempConnectionPosition = new ViewPoint();
// Layout coordinates for inputs in this Block, so they don't have to be computed repeatedly.
private final ArrayList<ViewPoint> mInputLayoutOrigins = new ArrayList<>();
// List of widths of multi-field rows when rendering inline inputs.
private final ArrayList<Integer> mInlineRowWidth = new ArrayList<>();
private final WorkspacePoint mTempWorkspacePoint = new WorkspacePoint();
// Currently highlighted connection.
@Nullable private Connection mHighlightConnection = null;
// Offset of the block origin inside the view's measured area.
private int mLayoutMarginLeft;
private int mMaxStatementFieldsWidth;
// Vertical offset for positioning the "Next" block (if one exists).
private int mNextBlockVerticalOffset;
// Width and height of the block "content", i.e., all its input fields. Unlike the view size,
// this does not include extruding connectors (e.g., Output, Next) and connected input blocks.
private int mBlockContentWidth;
private int mBlockContentHeight;
// Objects for drawing the block.
private final PatchManager mPatchManager;
private final ArrayList<Drawable> mBlockPatches = new ArrayList<>();
// Overlay patches used to draw a selection border when mHighlightBlock is true.
private final ArrayList<Drawable> mBlockBorderPatches = new ArrayList<>();
@Nullable private Drawable mOutputConnectorHighlightPatch = null;
@Nullable private Drawable mPreviousConnectorHighlightPatch = null;
@Nullable private Drawable mNextConnectionHighlightPatch = null;
private final ArrayList<Drawable> mInputConnectionHighlightPatches = new ArrayList<>();
private final ArrayList<Rect> mFillRects = new ArrayList<>();
@Nullable private Rect mNextFillRect = null;
private ColorFilter mBlockColorFilter;
private final Paint mFillPaint = new Paint();
// Flag is set to true if this block has at least one "Value" input.
private boolean mHasValueInput = false;
private final Rect tempRect = new Rect(); // Only use in main thread functions.
/**
* Create a new BlockView and associated InputViews for the given block using the
* WorkspaceHelper's provided style.
* <p>
* App developers should not call this constructor directly. Instead use
* {@link WorkspaceHelper#buildBlockViewTree(Block, BlockGroup, ConnectionManager, WorkspaceHelper.BlockTouchHandler)}.
*
* @param context The context for creating this view.
* @param block The {@link Block} represented by this view.
* @param helper The helper for loading workspace configs and doing calculations.
* @param connectionManager The {@link ConnectionManager} to update when moving connections.
* @param touchHandler The handler for forwarding touch events on this block to the
* {@link WorkspaceHelper}.
*/
public BlockView(Context context, Block block, WorkspaceHelper helper,
ConnectionManager connectionManager,
WorkspaceHelper.BlockTouchHandler touchHandler) {
super(context, null, 0);
mBlock = block;
mConnectionManager = connectionManager;
mHelper = helper;
mTouchHandler = touchHandler;
mPatchManager = mHelper.getPatchManager(); // Shortcut.
setClickable(true);
setFocusable(true);
block.setView(this);
createInputViews(); // BlockView is responsible for creating InputViews.
setWillNotDraw(false);
initDrawingObjects();
}
/**
* Select a connection for highlighted drawing.
*
* @param connection The connection whose port to highlight. This must be a connection
* associated with the {@link Block} represented by this {@link BlockView}
* instance. Disables all connection highlights if connection is null.
*/
public void setHighlightedConnection(@Nullable Connection connection) {
mHighlightConnection = connection;
invalidate();
}
/**
* Check if border highlight is rendered.
*/
protected boolean isEntireBlockHighlighted() {
return isPressed() || isFocused() || isSelected();
}
/**
* Test whether event hits visible parts of this block and notify {@link WorkspaceView} if it
* does.
*
* @param event The {@link MotionEvent} to handle.
*
* @return False if the touch was on the view but not on a visible part of the block; otherwise
* returns whether the {@link WorkspaceView} says that the event is being handled properly.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
return hitTest(event) && mTouchHandler.onTouchBlock(this, event);
}
@Override
protected void onDraw(Canvas c) {
for (int i = 0; i < mFillRects.size(); ++i) {
c.drawRect(mFillRects.get(i), mFillPaint);
}
for (int i = 0; i < mBlockPatches.size(); ++i) {
mBlockPatches.get(i).draw(c);
}
// drawConnectorCenters(c); // Enable to debug connection positions.
drawHighlights(c);
}
/**
* Measure all children (i.e., block inputs) and compute their sizes and relative positions
* for use in {@link #onLayout}.
*/
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getBlock().getInputsInline()) {
measureInlineInputs(widthMeasureSpec, heightMeasureSpec);
} else {
measureExternalInputs(widthMeasureSpec, heightMeasureSpec);
}
mNextBlockVerticalOffset = mBlockContentHeight;
mBlockViewSize.y = mBlockContentHeight;
if (mBlock.getNextConnection() != null) {
mBlockViewSize.y += mPatchManager.mNextConnectorHeight;
}
if (mBlock.getOutputConnection() != null) {
mLayoutMarginLeft = mPatchManager.mOutputConnectorWidth;
mBlockViewSize.x += mLayoutMarginLeft;
} else {
mLayoutMarginLeft = 0;
}
setMeasuredDimension(mBlockViewSize.x, mBlockViewSize.y);
}
@Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
// Note that layout must be done regardless of the value of the "changed" parameter.
boolean rtl = mHelper.useRtl();
int rtlSign = rtl ? -1 : +1;
int xFrom = mLayoutMarginLeft;
if (rtl) {
xFrom = mBlockViewSize.x - xFrom;
}
for (int i = 0; i < mInputViews.size(); i++) {
int rowTop = mInputLayoutOrigins.get(i).y;
InputView inputView = mInputViews.get(i);
int inputViewWidth = inputView.getMeasuredWidth();
int rowFrom = xFrom + rtlSign * mInputLayoutOrigins.get(i).x;
if (rtl) {
rowFrom -= inputViewWidth;
}
inputView.layout(rowFrom, rowTop, rowFrom + inputViewWidth,
rowTop + inputView.getMeasuredHeight());
}
layoutPatchesAndConnectors();
updateConnectorLocations();
}
/**
* @return The block for this view.
*/
public Block getBlock() {
return mBlock;
}
/**
* Update the position of the block in workspace coordinates based on the view's location.
*/
private void updateBlockPosition() {
// Only update the block position if it isn't a top level block.
if (mBlock.getPreviousBlock() != null
|| (mBlock.getOutputConnection() != null
&& mBlock.getOutputConnection().getTargetBlock() != null)) {
mHelper.getWorkspaceCoordinates(this, mTempWorkspacePoint);
mBlock.setPosition(mTempWorkspacePoint.x, mTempWorkspacePoint.y);
}
}
/**
* Test whether a {@link MotionEvent} event is (approximately) hitting a visible part of this
* view.
* <p/>
* This is used to determine whether the event should be handled by this view, e.g., to activate
* dragging or to open a context menu. Since the actual block interactions are implemented at
* the {@link WorkspaceView} level, there is no need to store the event data in this class.
*
* @param event The {@link MotionEvent} to check.
*
* @return True if the coordinate of the motion event is on the visible, non-transparent part of
* this view; false otherwise.
*/
private boolean hitTest(MotionEvent event) {
final int eventX = (int) event.getX();
final int eventY = (int) event.getY();
// Do the exact same thing for RTL and LTR, with reversed left and right block bounds. Note
// that the bounds of each InputView include any connected child blocks, so in RTL mode,
// the left-hand side of the input fields must be obtained from the right-hand side of the
// input and the field layout width.
if (mHelper.useRtl()) {
// First check whether event is in the general horizontal range of the block outline
// (minus children) and exit if it is not.
final int blockEnd = mBlockViewSize.x - mLayoutMarginLeft;
final int blockBegin = blockEnd - mBlockContentWidth;
if (eventX < blockBegin || eventX > blockEnd) {
return false;
}
// In the ballpark - now check whether event is on a field of any of this block's
// inputs. If it is, then the event belongs to this BlockView, otherwise it does not.
for (int i = 0; i < mInputViews.size(); ++i) {
final InputView inputView = mInputViews.get(i);
if (inputView.isOnFields(
eventX - (inputView.getRight() - inputView.getFieldLayoutWidth()),
eventY - inputView.getTop())) {
return true;
}
}
} else {
final int blockBegin = mLayoutMarginLeft;
final int blockEnd = mBlockContentWidth;
if (eventX < blockBegin || eventX > blockEnd) {
return false;
}
for (int i = 0; i < mInputViews.size(); ++i) {
final InputView inputView = mInputViews.get(i);
if (inputView.isOnFields(
eventX - inputView.getLeft(), eventY - inputView.getTop())) {
return true;
}
}
}
return false;
}
/**
* Draw highlights of block-level connections, or the entire block, if necessary.
*
* @param c The canvas to draw on.
*/
private void drawHighlights(Canvas c) {
if (isEntireBlockHighlighted()) {
// Draw entire block highlighted..
for (int i = 0; i < mBlockBorderPatches.size(); ++i) {
mBlockBorderPatches.get(i).draw(c);
}
} else if (mHighlightConnection != null) {
if (mHighlightConnection == mBlock.getOutputConnection()) {
assert mOutputConnectorHighlightPatch != null; // Never null with output.
mOutputConnectorHighlightPatch.draw(c);
} else if (mHighlightConnection == mBlock.getPreviousConnection()) {
assert mPreviousConnectorHighlightPatch != null; // Never null with previous.
mPreviousConnectorHighlightPatch.draw(c);
} else if (mHighlightConnection == mBlock.getNextConnection()) {
assert (mNextConnectionHighlightPatch != null); // Never null with next.
mNextConnectionHighlightPatch.draw(c);
} else {
// If the connection to highlight is not one of the three block-level connectors,
// then it must be one of the inputs (either a "Next" connector for a Statement or
// "Input" connector for a Value input). Figure out which input the connection
// belongs to.
final Input input = mHighlightConnection.getInput();
for (int i = 0; i < mInputViews.size(); ++i) {
if (mInputViews.get(i).getInput() == input) {
Drawable connectionHighlight = mInputConnectionHighlightPatches.get(i);
if (connectionHighlight != null) {
connectionHighlight.draw(c);
}
break;
}
}
}
}
}
/**
* Measure view and its children with inline inputs.
* <p>
* This function does not return a value but has the following side effects. Upon return:
* <ol>
* <li>The {@link InputView#measure(int, int)} method has been called for all inputs in
* this block,</li>
* <li>{@link #mBlockViewSize} contains the size of the total size of the block view
* including all its inputs, and</li>
* <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within
* the block.</li>
* </ol>
* </p>
*/
private void measureInlineInputs(int widthMeasureSpec, int heightMeasureSpec) {
int inputViewsSize = mInputViews.size();
// First pass - measure all fields and inputs; compute maximum width of fields and children
// over all Statement inputs.
mMaxStatementFieldsWidth = 0;
int maxStatementChildWidth = 0;
for (int i = 0; i < inputViewsSize; i++) {
InputView inputView = mInputViews.get(i);
inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
mMaxStatementFieldsWidth =
Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth());
maxStatementChildWidth =
Math.max(maxStatementChildWidth, inputView.getTotalChildWidth());
}
}
// Second pass - compute layout positions and sizes of all inputs.
int rowLeft = 0;
int rowTop = 0;
int rowHeight = 0;
int maxRowWidth = 0;
mInlineRowWidth.clear();
for (int i = 0; i < inputViewsSize; i++) {
InputView inputView = mInputViews.get(i);
// If this is a Statement input, force its field width to be the maximum over all
// Statements, and begin a new layout row.
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
// If the first input is a Statement, add vertical space above to draw top of
// connector just below block top boundary.
if (i == 0) {
rowTop += mPatchManager.mBlockTopPadding;
}
// Force all Statement inputs to have the same field width.
inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth);
// New row BEFORE each Statement input.
mInlineRowWidth.add(Math.max(rowLeft,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent));
rowTop += rowHeight;
rowHeight = 0;
rowLeft = 0;
}
mInputLayoutOrigins.get(i).set(rowLeft, rowTop);
// Measure input view and update row height and width accordingly.
inputView.measure(widthMeasureSpec, heightMeasureSpec);
rowHeight = Math.max(rowHeight, inputView.getMeasuredHeight());
// Set row height for the current input view as maximum over all views in this row so
// far. A separate, reverse loop below propagates the maximum to earlier inputs in the
// same row.
inputView.setRowHeight(rowHeight);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
// The block width is that of the widest row.
maxRowWidth = Math.max(maxRowWidth, inputView.getMeasuredWidth());
// If the last input is a Statement, add vertical space below to draw bottom of
// connector just above block top boundary.
if (i == mInputCount - 1) {
rowTop += mPatchManager.mBlockBottomPadding;
}
// New row AFTER each Statement input.
rowTop += rowHeight;
rowLeft = 0;
rowHeight = 0;
} else {
// For Dummy and Value inputs, row width accumulates. Update maximum width
// accordingly.
rowLeft += inputView.getMeasuredWidth();
maxRowWidth = Math.max(maxRowWidth, rowLeft);
}
}
// Add height of final row. This is non-zero with inline inputs if the final input in the
// block is not a Statement input.
rowTop += rowHeight;
// Third pass - propagate row height maximums backwards. Reset height whenever a Statement
// input is encoutered.
int maxRowHeight = 0;
for (int i = inputViewsSize; i > 0; --i) {
InputView inputView = mInputViews.get(i - 1);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
maxRowHeight = 0;
} else {
maxRowHeight = Math.max(maxRowHeight, inputView.getRowHeight());
inputView.setRowHeight(maxRowHeight);
}
}
// If there was at least one Statement input, make sure block is wide enough to fit at least
// an empty Statement connector. If there were non-empty Statement connectors, they were
// already taken care of in the loop above.
if (mMaxStatementFieldsWidth > 0) {
maxRowWidth = Math.max(maxRowWidth,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent);
}
// Push width of last input row.
mInlineRowWidth.add(Math.max(rowLeft,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent));
// Block width is the computed width of the widest input row, and at least MIN_BLOCK_WIDTH.
mBlockContentWidth = Math.max(MIN_BLOCK_WIDTH, maxRowWidth);
mBlockViewSize.x = mBlockContentWidth;
// View width is the computed width of the widest statement input, including child blocks
// and padding, and at least the width of the widest input row.
mBlockViewSize.x = Math.max(mBlockContentWidth,
mMaxStatementFieldsWidth + maxStatementChildWidth +
mPatchManager.mBlockStartPadding + mPatchManager.mStatementInputPadding);
// Height is vertical position of next (non-existent) inputs row, and at least MIN_HEIGHT.
mBlockContentHeight = Math.max(mPatchManager.mMinBlockHeight, rowTop);
}
/**
* Measure view and its children with external inputs.
* <p>
* This function does not return a value but has the following side effects. Upon return:
* <ol>
* <li>The {@link InputView#measure(int, int)} method has been called for all inputs in
* this block,</li>
* <li>{@link #mBlockViewSize} contains the size of the total size of the block view
* including all its inputs, and</li>
* <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within
* the block (but note that for external inputs, only the y coordinate of each
* position is later used for positioning.)</li>
* </ol>
* </p>
*/
private void measureExternalInputs(int widthMeasureSpec, int heightMeasureSpec) {
int maxInputFieldsWidth = MIN_BLOCK_WIDTH;
// Initialize max Statement width as zero so presence of Statement inputs can be determined
// later; apply minimum size after that.
mMaxStatementFieldsWidth = 0;
int maxInputChildWidth = 0;
int maxStatementChildWidth = 0;
// First pass - measure fields and children of all inputs.
for (int i = 0; i < mInputViews.size(); i++) {
InputView inputView = mInputViews.get(i);
inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec);
switch (inputView.getInput().getType()) {
case Input.TYPE_VALUE: {
maxInputChildWidth =
Math.max(maxInputChildWidth, inputView.getTotalChildWidth());
// fall through
}
default:
case Input.TYPE_DUMMY: {
maxInputFieldsWidth =
Math.max(maxInputFieldsWidth, inputView.getTotalFieldWidth());
break;
}
case Input.TYPE_STATEMENT: {
mMaxStatementFieldsWidth =
Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth());
maxStatementChildWidth =
Math.max(maxStatementChildWidth, inputView.getTotalChildWidth());
break;
}
}
}
// If there was a statement, force all other input fields to be at least as wide as required
// by the Statement field plus port width.
if (mMaxStatementFieldsWidth > 0) {
mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, MIN_BLOCK_WIDTH);
maxInputFieldsWidth = Math.max(maxInputFieldsWidth,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent);
}
// Second pass - force all inputs to render fields with the same width and compute positions
// for all inputs.
int rowTop = 0;
for (int i = 0; i < mInputViews.size(); i++) {
InputView inputView = mInputViews.get(i);
final int inputType = inputView.getInput().getType();
if (inputType == Input.TYPE_STATEMENT) {
// If the first input is a Statement, add vertical space above to draw top of
// connector just below block top boundary.
if (i == 0) {
rowTop += mPatchManager.mBlockTopPadding;
}
// Force all Statement inputs to have the same field width.
inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth);
} else {
// Force all Dummy and Value inputs to have the same field width.
inputView.setFieldLayoutWidth(maxInputFieldsWidth);
}
inputView.measure(widthMeasureSpec, heightMeasureSpec);
mInputLayoutOrigins.get(i).set(0, rowTop);
// If the last input is a Statement, add vertical space below to draw bottom of
// connector just above block top boundary.
if ((inputType == Input.TYPE_STATEMENT) && (i == mInputCount - 1)) {
rowTop += mPatchManager.mBlockBottomPadding;
}
// The block height is the sum of all the row heights.
rowTop += inputView.getMeasuredHeight();
}
// Block content width is the width of the longest row.
mBlockContentWidth = Math.max(maxInputFieldsWidth, mMaxStatementFieldsWidth);
mBlockContentHeight = Math.max(mPatchManager.mMinBlockHeight, rowTop);
// Add space for connector if there is at least one Value input.
mBlockContentWidth += mPatchManager.mBlockTotalPaddingX;
if (mHasValueInput) {
mBlockContentWidth += mPatchManager.mValueInputWidth;
}
// Maximum total width of all value inputs is the sum of maximum field and child widths,
// plus space for field padding and Value input connector, minus overlap of input and output
// connectors.
final int maxValueInputTotalWidth = maxInputFieldsWidth + maxInputChildWidth +
mPatchManager.mBlockTotalPaddingX + mPatchManager.mValueInputWidth -
mPatchManager.mOutputConnectorWidth;
// Maximum total width of all Statement inputs is the sum of maximum field and and widths,
// plus field padding on the left and C-connector padding in the middle.
final int maxStatementInputTotalWidth = mMaxStatementFieldsWidth + maxStatementChildWidth +
mPatchManager.mBlockStartPadding +
mPatchManager.mStatementInputPadding;
// View width is maximum of content width and the Value input and Statement input total
// widths.
mBlockViewSize.x = Math.max(mBlockContentWidth,
Math.max(maxValueInputTotalWidth, maxStatementInputTotalWidth));
}
/**
* Instantiates new InputViews for this Block, using the block style from mHelper.
*/
private void createInputViews() {
mInputViews.clear();
List<Input> inputs = mBlock.getInputs();
for (int i = 0; i < inputs.size(); ++i) {
Input in = inputs.get(i);
InputView inputView = new InputView(getContext(), mHelper.getBlockStyle(), in, mHelper);
addView(inputView);
if (in.getType() == Input.TYPE_VALUE) {
mHasValueInput = true;
}
mInputViews.add(inputView);
}
mInputCount = mInputViews.size();
resizeList(mInputConnectorOffsets);
resizeList(mInputLayoutOrigins);
}
private void initDrawingObjects() {
final int blockColor = mBlock.getColour();
// Highlight color channels are added to each color-multiplied color channel, and since the
// patches are 50% gray, the addition should be 50% of the base value.
final int highlight = Color.argb(255, Color.red(blockColor) / 2,
Color.green(blockColor) / 2, Color.blue(blockColor) / 2);
mBlockColorFilter = new LightingColorFilter(blockColor, highlight);
mFillPaint.setColor(mBlock.getColour());
mFillPaint.setStyle(Paint.Style.FILL);
}
/**
* Adjust size of an {@link ArrayList} of {@link ViewPoint} objects to match the size of
* {@link #mInputViews}.
*/
private void resizeList(ArrayList<ViewPoint> list) {
if (list.size() != mInputCount) {
list.ensureCapacity(mInputCount);
if (list.size() < mInputCount) {
for (int i = list.size(); i < mInputCount; i++) {
list.add(new ViewPoint());
}
} else {
while (list.size() > mInputCount) {
list.remove(list.size() - 1);
}
}
}
}
/**
* Position patches for block rendering and connectors.
*/
private void layoutPatchesAndConnectors() {
mBlockPatches.clear();
mBlockBorderPatches.clear();
mFillRects.clear();
// Leave room on the left for margin (accomodates optional output connector) and block
// padding (accomodates block boundary).
int xFrom = mLayoutMarginLeft + mPatchManager.mBlockStartPadding;
// For inline inputs, the upper horizontal coordinate of the block boundary varies by
// section and changes after each Statement input. For external inputs, it is constant as
// computed in measureExternalInputs.
int xTo = mLayoutMarginLeft;
int inlineRowIdx = 0;
if (mBlock.getInputsInline()) {
xTo += mInlineRowWidth.get(inlineRowIdx);
} else {
xTo += mBlockContentWidth;
}
// Position top-left corner drawable. Retain drawable object so we can position bottom-left
// drawable correctly.
int yTop = 0;
final NinePatchDrawable topStartDrawable = addTopLeftPatch(xTo, yTop);
// Position inputs and connectors.
mInputConnectionHighlightPatches.clear();
mInputConnectionHighlightPatches.ensureCapacity(mInputCount);
for (int i = 0; i < mInputCount; ++i) {
final InputView inputView = mInputViews.get(i);
final ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i);
// Placeholder for connection patch. Even if input does not have a connection, makes
// sure later patches use indices matching their inputs.
mInputConnectionHighlightPatches.add(null);
// Start filling background of the input based on its origin and measured size.
fillRectBySize(xFrom + inputLayoutOrigin.x, inputLayoutOrigin.y,
inputView.getFieldLayoutWidth(), inputView.getRowHeight());
switch (inputView.getInput().getType()) {
default:
case Input.TYPE_DUMMY: {
boolean isLastInput = (i + 1 == mInputCount);
boolean nextIsStatement = !isLastInput
&& mInputViews.get(i+1).getInput().getType() == Input.TYPE_STATEMENT;
boolean isEndOfLine = !mBlock.getInputsInline() || isLastInput
|| nextIsStatement;
if (isEndOfLine) {
addDummyBoundaryPatch(xTo, inputView, inputLayoutOrigin);
}
break;
}
case Input.TYPE_VALUE: {
if (mBlock.getInputsInline()) {
addInlineValueInputPatch(
i, inlineRowIdx, xFrom, inputView, inputLayoutOrigin);
} else {
addExternalValueInputPatch(i, xTo, inputView, inputLayoutOrigin);
}
break;
}
case Input.TYPE_STATEMENT: {
// For external inputs, the horizontal end coordinate of the connector bottom is
// the same as the one on top. For inline inputs, however, it is the next entry
// in the width-by-row table.
int xToBottom = xTo;
if (mBlock.getInputsInline()) {
++inlineRowIdx;
xToBottom = xFrom + mInlineRowWidth.get(inlineRowIdx) -
mPatchManager.mBlockStartPadding;
}
// Place the connector patches.
addStatementInputPatches(
i, xFrom, xTo, xToBottom, inputView, inputLayoutOrigin);
// Set new horizontal end coordinate for subsequent inputs.
xTo = xToBottom;
break;
}
}
}
// Select and position correct patch for bottom and left-hand side of the block, including
// bottom-left corner.
int bottomStartResourceId = R.drawable.bottom_start_default;
int bottomStartBorderResourceId = R.drawable.bottom_start_default_border;
if (mBlock.getNextConnection() != null) {
setPointMaybeFlip(mNextConnectorOffset, mLayoutMarginLeft, mNextBlockVerticalOffset);
bottomStartResourceId = R.drawable.bottom_start_next;
bottomStartBorderResourceId = R.drawable.bottom_start_next_border;
}
final NinePatchDrawable bottomStartDrawable =
getColoredPatchDrawable(bottomStartResourceId);
final NinePatchDrawable bottomStartBorderDrawable =
mPatchManager.getPatchDrawable(bottomStartBorderResourceId);
calculateRtlAwareBounds(tempRect,
mLayoutMarginLeft, topStartDrawable.getIntrinsicHeight(), xTo, mBlockViewSize.y);
bottomStartDrawable.setBounds(tempRect);
bottomStartBorderDrawable.setBounds(tempRect);
if (mBlock.getNextConnection() != null) {
mNextConnectionHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.bottom_start_next_connection);
mNextConnectionHighlightPatch.setBounds(tempRect);
}
mBlockPatches.add(bottomStartDrawable);
mBlockBorderPatches.add(bottomStartBorderDrawable);
// Finish the final rect, if there is one.
finishFillRect();
}
/**
* Add the top-left corner drawable.
*
* @param xTo Horizontal end position for the drawable.
* @param yTop Vertical position for the drawable.
*
* @return The added drawable. This can be used to position other drawables, e.g., the
* bottom-left drawable, relative to it.
*/
@NonNull
private NinePatchDrawable addTopLeftPatch(int xTo, int yTop) {
// Select and position the correct patch for the top and left block sides including the
// top-left corner.
NinePatchDrawable topStartDrawable;
NinePatchDrawable topStartBorderDrawable;
if (mBlock.getPreviousConnection() != null) {
setPointMaybeFlip(mPreviousConnectorOffset, mLayoutMarginLeft, yTop);
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_previous);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_previous_border);
mPreviousConnectorHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.top_start_previous_connection);
} else if (mBlock.getOutputConnection() != null) {
setPointMaybeFlip(mOutputConnectorOffset, mLayoutMarginLeft, yTop);
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_output);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_output_border);
mOutputConnectorHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.top_start_output_connection);
} else {
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_default);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_default_border);
}
calculateRtlAwareBounds(tempRect, 0, 0, xTo, topStartDrawable.getIntrinsicHeight());
topStartDrawable.setBounds(tempRect);
topStartBorderDrawable.setBounds(tempRect);
if (mPreviousConnectorHighlightPatch != null) {
mPreviousConnectorHighlightPatch.setBounds(tempRect);
}
if (mOutputConnectorHighlightPatch != null) {
mOutputConnectorHighlightPatch.setBounds(tempRect);
}
mBlockPatches.add(topStartDrawable);
mBlockBorderPatches.add(topStartBorderDrawable);
return topStartDrawable;
}
/**
* Add boundary patch for external Dummy input.
*
* @param xTo Horizontal coordinate to which the patch should extend. The starting coordinate
* is determined from this by subtracting patch width.
* @param inputView The {@link InputView} for the current input. This is used to determine patch
* height.
* @param inputLayoutOrigin The layout origin for the current input. This is used to determine
* the vertical position for the patch.
*/
private void addDummyBoundaryPatch(int xTo, InputView inputView, ViewPoint inputLayoutOrigin) {
// For external dummy inputs, put a patch for the block boundary.
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable inputBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
int width = inputDrawable.getIntrinsicWidth();
if (mHasValueInput) {
// Stretch the patch horizontally if this block has at least one value
// input, so that the dummy input block boundary is as thick as the
// boundary with value input connector.
width += mPatchManager.mValueInputWidth;
}
boolean inTopRow = (inputLayoutOrigin.y == 0);
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xTo - width,
/* top */ inputLayoutOrigin.y + (inTopRow ? mPatchManager.mBlockTopPadding : 0),
/* ltrEnd */ xTo,
/* bottom */ inputLayoutOrigin.y + inputView.getRowHeight());
inputDrawable.setBounds(tempRect);
inputBorderDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mBlockBorderPatches.add(inputBorderDrawable);
}
/**
* Add connector patch for external Value inputs.
*
* @param i The index of the current input. This is used to determine whether to position patch
* vertically below the field top boundary to account for the block's top boundary.
* @param xTo Horizontal coordinate to which the patch should extend. The starting coordinate
* is determined from this by subtracting patch width.
* @param inputView The {@link InputView} for the current input. This is used to determine patch
* height.
* @param inputLayoutOrigin The layout origin for the current input. This is used to determine
* the vertical position for the patch.
*/
private void addExternalValueInputPatch(int i, int xTo,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Position patch and connector for external value input.
setPointMaybeFlip(mInputConnectorOffsets.get(i), xTo, inputLayoutOrigin.y);
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.value_input_external);
final NinePatchDrawable inputBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_external_border);
final NinePatchDrawable connectionHighlightDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_external_connection);
int patchLeft = xTo - inputDrawable.getIntrinsicWidth();
int patchRight = xTo;
int connectorTop = inputLayoutOrigin.y + mPatchManager.mBlockTopPadding;
int connectorBottom = inputLayoutOrigin.y + inputView.getMeasuredHeight();
calculateRtlAwareBounds(tempRect, patchLeft, connectorTop, patchRight, connectorBottom);
inputDrawable.setBounds(tempRect);
inputBorderDrawable.setBounds(tempRect);
connectionHighlightDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mBlockBorderPatches.add(inputBorderDrawable);
mInputConnectionHighlightPatches.set(i, connectionHighlightDrawable);
if (i > 0) {
// If this is not the first input in the block, then a gap above the
// input connector patch must be closed by a non-input boundary patch.
// The gap is the result of the need to not draw over the top block
// boundary.
final NinePatchDrawable boundaryGapDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable boundaryGapBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
calculateRtlAwareBounds(tempRect,
patchLeft, inputLayoutOrigin.y, patchRight, connectorTop);
boundaryGapDrawable.setBounds(tempRect);
boundaryGapBorderDrawable.setBounds(tempRect);
mBlockPatches.add(boundaryGapDrawable);
mBlockBorderPatches.add(boundaryGapBorderDrawable);
}
}
/**
* Add cutout patch for inline Value inputs.
* <p/>
* The inline input nine patch includes the entirety of the cutout shape, including the
* connector, and stretches to fit all child blocks.
* <p/>
* An inline input is usually drawn with an input 9-patch and three rects for padding between
* inputs: one above, one below, and one after (i.e., to the right in LTR and to the left in
* RTL).
*
* @param i The index of the input in the block.
* @param inlineRowIdx The (horizontal) index of the input in the current input row.
* @param blockFromX The horizontal start position input views in the block.
* @param inputView The input view.
* @param inputLayoutOrigin Layout origin for the current input view.
*/
private void addInlineValueInputPatch(int i, int inlineRowIdx, int blockFromX,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Determine position for inline connector cutout.
final int cutoutX = blockFromX + inputLayoutOrigin.x + inputView.getInlineInputX();
final int cutoutY = inputLayoutOrigin.y + mPatchManager.mBlockTopPadding;
// Set connector position - shift w.r.t. patch location to where the corner of connected
// blocks will be positioned.
setPointMaybeFlip(mInputConnectorOffsets.get(i),
cutoutX + mPatchManager.mInlineInputStartPadding +
mPatchManager.mOutputConnectorWidth,
cutoutY + mPatchManager.mInlineInputTopPadding);
// Fill above inline input connector, unless first row, where connector top
// is aligned with block boundary patch.
if (inlineRowIdx > 0) {
fillRectBySize(cutoutX, inputLayoutOrigin.y,
inputView.getTotalChildWidth(), mPatchManager.mBlockTopPadding);
finishFillRect(); // Prevent filling through the inline connector.
}
// Position a properly-sized input cutout patch.
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.value_input_inline);
final NinePatchDrawable connectionHighlightDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_inline_connection);
calculateRtlAwareBounds(tempRect,
cutoutX, cutoutY,
cutoutX + inputView.getTotalChildWidth(),
cutoutY + inputView.getTotalChildHeight());
inputDrawable.setBounds(tempRect);
connectionHighlightDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mInputConnectionHighlightPatches.set(i, connectionHighlightDrawable);
// Fill below inline input cutout.
final int cutoutEndX = cutoutX + inputView.getTotalChildWidth();
final int cutoutEndY = inputLayoutOrigin.y + inputView.getRowHeight();
fillRect(cutoutX, cutoutY + inputView.getTotalChildHeight(), cutoutEndX, cutoutEndY);
// Fill after inline input cutout.
fillRect(cutoutEndX, inputLayoutOrigin.y,
inputLayoutOrigin.x + inputView.getMeasuredWidth(), cutoutEndY);
// If this is either the last input in the block, or the next input is a Statement, then
// this is the final input in the current row. In this case, put a boundary patch.
final int nextI = i + 1;
if ((nextI == mInputCount) ||
(mInputViews.get(nextI).getInput().getType() == Input.TYPE_STATEMENT)) {
// Horizontal patch position is the position of inputs in the block, plus offset of the
// current input in its row, plus padding before and after the input fields.
final int patchX = blockFromX + mInlineRowWidth.get(inlineRowIdx) -
mPatchManager.mBlockTotalPaddingX;
// Vertical patch position is the input layout origin, plus room for block boundary if
// this is the first input row.
final int patchY = inputLayoutOrigin.y +
(inlineRowIdx > 0 ? 0 : mPatchManager.mBlockTopPadding);
final int patchRight = patchX + mPatchManager.mBlockEndPadding;
final NinePatchDrawable blockFillDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable blockFillBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
calculateRtlAwareBounds(tempRect, patchX, patchY, patchRight, cutoutEndY);
blockFillDrawable.setBounds(tempRect);
blockFillBorderDrawable.setBounds(tempRect);
mBlockPatches.add(blockFillDrawable);
mBlockBorderPatches.add(blockFillBorderDrawable);
// Also at the end of the current input row, fill background up to
// block boundary.
fillRect(inputLayoutOrigin.x + mPatchManager.mBlockStartPadding +
inputView.getMeasuredWidth(), patchY, patchX, cutoutEndY);
}
}
/**
* Add patches (top and bottom) for a Statement input connector.
*
* @param i Index of the input.
* @param xFrom Horizontal offset of block content.
* @param xToAbove Horizontal end coordinate for connector above input.
* @param xToBelow Horizontal end coordinate for connector below input.
* @param inputView The view for this input.
* @param inputLayoutOrigin Layout origin for this input.
*/
private void addStatementInputPatches(int i, int xFrom, int xToAbove, int xToBelow,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Position connector. Shift by horizontal and vertical patch thickness to line up with
// "Previous" connector on child block.
int xOffset = xFrom + inputView.getFieldLayoutWidth();
setPointMaybeFlip(mInputConnectorOffsets.get(i),
xOffset + mPatchManager.mStatementInputPadding,
inputLayoutOrigin.y + mPatchManager.mStatementTopThickness);
// Position patch for the top part of the Statement connector. This patch is
// stretched only horizontally to extend to the block boundary.
final NinePatchDrawable statementTopDrawable =
getColoredPatchDrawable(R.drawable.statementinput_top);
final NinePatchDrawable statementTopBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.statementinput_top_border);
final NinePatchDrawable statementConnectionHighlight =
mPatchManager.getPatchDrawable(R.drawable.statementinput_top_connection);
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xOffset,
/* top */ inputLayoutOrigin.y,
/* ltrEnd */ xToAbove,
/* bottom */ inputLayoutOrigin.y + statementTopDrawable.getIntrinsicHeight());
statementTopDrawable.setBounds(tempRect);
statementTopBorderDrawable.setBounds(tempRect);
statementConnectionHighlight.setBounds(tempRect);
mBlockPatches.add(statementTopDrawable);
mBlockBorderPatches.add(statementTopBorderDrawable);
mInputConnectionHighlightPatches.set(i, statementConnectionHighlight);
// Position patch for the bottom part of the Statement connector. The bottom
// patch is stretched horizontally, like the top patch, but also vertically to
// accomodate height of the input fields as well as the size of any connected
// blocks.
final NinePatchDrawable statementBottomDrawable =
getColoredPatchDrawable(R.drawable.statementinput_bottom);
final NinePatchDrawable statementBottomBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.statementinput_bottom_border);
final int connectorHeight =
Math.max(inputView.getTotalChildHeight(),
inputView.getMeasuredHeight());
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xOffset,
/* top */ inputLayoutOrigin.y + statementTopDrawable.getIntrinsicHeight(),
/* ltrEnd */ xToBelow,
/* bottom */ inputLayoutOrigin.y + connectorHeight);
statementBottomDrawable.setBounds(tempRect);
statementBottomBorderDrawable.setBounds(tempRect);
mBlockPatches.add(statementBottomDrawable);
mBlockBorderPatches.add(statementBottomBorderDrawable);
}
/**
* Draw dots at the model's location of all connections on this block, for debugging.
*
* @param c The canvas to draw on.
*/
private void drawConnectorCenters(Canvas c) {
List<Connection> connections = mBlock.getAllConnections();
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
for (int i = 0; i < connections.size(); i++) {
Connection conn = connections.get(i);
if (conn.inDragMode()) {
if (conn.isConnected()) {
paint.setColor(Color.RED);
} else {
paint.setColor(Color.MAGENTA);
}
} else {
if (conn.isConnected()) {
paint.setColor(Color.GREEN);
} else {
paint.setColor(Color.CYAN);
}
}
// Compute connector position relative to this view from its offset to block origin in
// Workspace coordinates.
mTempWorkspacePoint.set(
conn.getPosition().x - mBlock.getPosition().x,
conn.getPosition().y - mBlock.getPosition().y);
mHelper.workspaceToVirtualViewDelta(mTempWorkspacePoint, mTempConnectionPosition);
if (mHelper.useRtl()) {
// In RTL mode, add block view size to x coordinate. This is counter-intuitive, but
// equivalent to "x = size - (-x)", with the inner negation "-x" undoing the
// side-effect of workspaceToVirtualViewDelta reversing the x coordinate. This is,
// the addition mirrors the re-negated in-block x coordinate w.r.t. the right-hand
// side of the block view, which is the origin of the block in RTL mode.
mTempConnectionPosition.x += mBlockViewSize.x;
}
c.drawCircle(mTempConnectionPosition.x, mTempConnectionPosition.y, 10, paint);
}
}
/**
* @return The number of {@link InputView} instances inside this view.
*/
@VisibleForTesting
int getInputViewCount() {
return mInputViews.size();
}
/**
* @return The {@link InputView} for the {@link Input} at the given index.
*/
@VisibleForTesting
InputView getInputView(int index) {
return mInputViews.get(index);
}
/**
* Correctly set the locations of the connections based on their offsets within the
* {@link BlockView} and the position of the {@link BlockView} itself. Can be used when the
* block has moved but not changed shape (e.g. during a drag).
*/
@VisibleForTesting
public void updateConnectorLocations() {
// Ensure we have the right block location before we update the connections.
updateBlockPosition();
if (mConnectionManager == null) {
return;
}
final WorkspacePoint blockWorkspacePosition = mBlock.getPosition();
final Connection previousConnection = mBlock.getPreviousConnection();
if (previousConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mPreviousConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
previousConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
final Connection nextConnection = mBlock.getNextConnection();
if (nextConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mNextConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
nextConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
final Connection outputConnection = mBlock.getOutputConnection();
if (outputConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mOutputConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
outputConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
for (int i = 0; i < mInputViews.size(); i++) {
final InputView inputView = mInputViews.get(i);
final Connection connection = inputView.getInput().getConnection();
if (connection != null) {
mHelper.virtualViewToWorkspaceDelta(
mInputConnectorOffsets.get(i), mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
connection, blockWorkspacePosition, mTempWorkspacePoint);
if (connection.isConnected()) {
((BlockGroup) inputView.getChildView()).updateAllConnectorLocations();
}
}
}
}
/**
* Add a rectangular area for filling either by creating a new rectangle or extending an
* existing one.
* <p/>
* If the rectangle defined by the method arguments is aligned with the in-progress rectangle
* {@link #mNextFillRect} either horizontally or vertically, then the two are joined. Otherwise,
* {@link #mNextFillRect} is finished and committed to the list of rectangles to draw and a new
* rectangle is begun with the given method arguments.
* <p/>
* Note that rectangles are joined even if there is a gap between them. This fills padding areas
* between inline inputs in the same row without any additional code. However, this assumes that
* whenever there is an intended gap between aligned rectangles, then there is at last one
* rectangle of different size (or with unaligned position) between them. If this assumption is
* violated, call {@link #finishFillRect()} prior to the next call to this method.
*
* @param left Left coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param top Top coordinate of the new rectangle.
* @param right Right coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param bottom Bottom coordinate of the new rectangle.
*/
private void fillRect(int left, int top, int right, int bottom) {
if (mNextFillRect != null) {
if ((mNextFillRect.left == left) && (mNextFillRect.right == right)) {
assert mNextFillRect.top <= top; // New rectangle must not start above current.
mNextFillRect.bottom = bottom;
return;
} else if ((mNextFillRect.top == top) && (mNextFillRect.bottom == bottom)) {
assert mNextFillRect.left <= left; // New rectangle must not start left of current.
mNextFillRect.right = right;
return;
} else {
finishFillRect();
}
}
mNextFillRect = new Rect(left, top, right, bottom);
}
/**
* Convenience wrapper for {@link #fillRect(int, int, int, int)} taking rectangle size
* rather than upper bounds.
* <p/>
* This wrapper converts width and height of the given rectangle to right and bottom
* coordinates, respectively. That makes client code more readable in places where the rectangle
* is naturally defined by its origin and size.
*
* @param left Left coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param top Top coordinate of the new rectangle.
* @param width Width of the new rectangle.
* @param height Height of the new rectangle.
*/
private void fillRectBySize(int left, int top, int width, int height) {
fillRect(left, top, left + width, top + height);
}
/**
* Finish the current fill rectangle.
* <p/>
* The current rectangle is cropped against the vertical block boundaries with padding
* considered, and afterwards committed to the {@link #mFillRects} list.
* <p/>
* Note that horizontal block padding is assumed to have been considered prior to calling
* {@link #fillRect(int, int, int, int)}. This is because horizontal block size can
* vary across rows in a block with inline inputs.
* <p/>
* In Right-to-Left mode, the horizontal rectangle boundaries are mirrored w.r.t. the right-hand
* side of the view.
*/
private void finishFillRect() {
if (mNextFillRect != null) {
mNextFillRect.top = Math.max(mNextFillRect.top, mPatchManager.mBlockTopPadding);
mNextFillRect.bottom = Math.min(mNextFillRect.bottom,
mBlockContentHeight - mPatchManager.mBlockBottomPadding);
// In RTL mode, mirror Rect w.r.t. right-hand side of the block area.
if (mHelper.useRtl()) {
final int left = mNextFillRect.left;
mNextFillRect.left = mBlockViewSize.x - mNextFillRect.right;
mNextFillRect.right = mBlockViewSize.x - left;
}
mFillRects.add(mNextFillRect);
mNextFillRect = null;
}
}
/**
* Assigned rect given bounds, possibly flipping horizontal bounds in RtL mode.
*
* @param ltrStart The left coordinate in LTR mode.
* @param top The top coordinate.
* @param ltrEnd The right coordinate in LTR mode.
* @param bottom The bottom coordinate.
*/
private void calculateRtlAwareBounds(Rect rect, int ltrStart, int top, int ltrEnd, int bottom) {
boolean isRtl = mHelper.useRtL();
rect.left = isRtl ? mBlockViewSize.x - ltrEnd : ltrStart;
rect.top = top;
rect.right = isRtl ? mBlockViewSize.x - ltrStart : ltrEnd;
rect.bottom = bottom;
}
/**
* Set a {@link ViewPoint} and flip x coordinate in RTL mode.
*
* @param viewPoint The point in view coordinates to set.
* @param x The new x coordinate in LTR mode.
* @param y The new y coordinate.
*/
private void setPointMaybeFlip(ViewPoint viewPoint, int x, int y) {
viewPoint.set(mHelper.useRtl() ? -x : x, y);
}
private NinePatchDrawable getColoredPatchDrawable(int id) {
NinePatchDrawable drawable = mPatchManager.getPatchDrawable(id);
drawable.setColorFilter(mBlockColorFilter);
return drawable;
}
/**
* @return Vertical offset for positioning the "Next" block (if one exists). This is relative to
* the top of this view's area.
*/
int getNextBlockVerticalOffset() {
return mNextBlockVerticalOffset;
}
/**
* @return Layout margin on the left-hand side of the block (for optional Output connector).
*/
int getLayoutMarginLeft() {
return mLayoutMarginLeft;
}
}
| blocklylib/src/main/java/com/google/blockly/ui/BlockView.java | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.blockly.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.MotionEvent;
import com.google.blockly.R;
import com.google.blockly.control.ConnectionManager;
import com.google.blockly.model.Block;
import com.google.blockly.model.Connection;
import com.google.blockly.model.Input;
import com.google.blockly.model.WorkspacePoint;
import java.util.ArrayList;
import java.util.List;
/**
* Draws a block and handles laying out all its inputs/fields.
*/
@SuppressLint("ViewConstructor")
public class BlockView extends NonPropagatingViewGroup {
// TODO: Replace with dimens so it gets scaled correctly, or better yet, somehow derive from
// ninepatch measurements.
private static final int MIN_BLOCK_WIDTH = 40;
private final WorkspaceHelper mHelper;
private final WorkspaceHelper.BlockTouchHandler mTouchHandler;
private final Block mBlock;
private final ConnectionManager mConnectionManager;
// Child views for the block inputs and their children.
private final ArrayList<InputView> mInputViews = new ArrayList<>();
private int mInputCount;
// Reference points for connectors relative to this view (needed for selective highlighting).
private final ViewPoint mOutputConnectorOffset = new ViewPoint();
private final ViewPoint mPreviousConnectorOffset = new ViewPoint();
private final ViewPoint mNextConnectorOffset = new ViewPoint();
private final ArrayList<ViewPoint> mInputConnectorOffsets = new ArrayList<>();
// Current measured size of this block view.
private final ViewPoint mBlockViewSize = new ViewPoint();
// Position of the connection currently being updated, for temporary use during
// layoutPatchesAndConnectors.
private final ViewPoint mTempConnectionPosition = new ViewPoint();
// Layout coordinates for inputs in this Block, so they don't have to be computed repeatedly.
private final ArrayList<ViewPoint> mInputLayoutOrigins = new ArrayList<>();
// List of widths of multi-field rows when rendering inline inputs.
private final ArrayList<Integer> mInlineRowWidth = new ArrayList<>();
private final WorkspacePoint mTempWorkspacePoint = new WorkspacePoint();
// Currently highlighted connection.
@Nullable private Connection mHighlightConnection = null;
// Offset of the block origin inside the view's measured area.
private int mLayoutMarginLeft;
private int mMaxStatementFieldsWidth;
// Vertical offset for positioning the "Next" block (if one exists).
private int mNextBlockVerticalOffset;
// Width and height of the block "content", i.e., all its input fields. Unlike the view size,
// this does not include extruding connectors (e.g., Output, Next) and connected input blocks.
private int mBlockContentWidth;
private int mBlockContentHeight;
// Objects for drawing the block.
private final PatchManager mPatchManager;
private final ArrayList<Drawable> mBlockPatches = new ArrayList<>();
// Overlay patches used to draw a selection border when mHighlightBlock is true.
private final ArrayList<Drawable> mBlockBorderPatches = new ArrayList<>();
@Nullable private Drawable mOutputConnectorHighlightPatch = null;
@Nullable private Drawable mPreviousConnectorHighlightPatch = null;
@Nullable private Drawable mNextConnectionHighlightPatch = null;
private final ArrayList<Drawable> mInputConnectionHighlightPatches = new ArrayList<>();
private final ArrayList<Rect> mFillRects = new ArrayList<>();
@Nullable private Rect mNextFillRect = null;
private ColorFilter mBlockColorFilter;
private final Paint mFillPaint = new Paint();
// Flag is set to true if this block has at least one "Value" input.
private boolean mHasValueInput = false;
private final Rect tempRect = new Rect(); // Only use in main thread functions.
/**
* Create a new BlockView and associated InputViews for the given block using the
* WorkspaceHelper's provided style.
* <p>
* App developers should not call this constructor directly. Instead use
* {@link WorkspaceHelper#buildBlockViewTree(Block, BlockGroup, ConnectionManager, WorkspaceHelper.BlockTouchHandler)}.
*
* @param context The context for creating this view.
* @param block The {@link Block} represented by this view.
* @param helper The helper for loading workspace configs and doing calculations.
* @param connectionManager The {@link ConnectionManager} to update when moving connections.
* @param touchHandler The handler for forwarding touch events on this block to the
* {@link WorkspaceHelper}.
*/
public BlockView(Context context, Block block, WorkspaceHelper helper,
ConnectionManager connectionManager,
WorkspaceHelper.BlockTouchHandler touchHandler) {
super(context, null, 0);
mBlock = block;
mConnectionManager = connectionManager;
mHelper = helper;
mTouchHandler = touchHandler;
mPatchManager = mHelper.getPatchManager(); // Shortcut.
setClickable(true);
setFocusable(true);
block.setView(this);
createInputViews(); // BlockView is responsible for creating InputViews.
setWillNotDraw(false);
initDrawingObjects();
}
/**
* Select a connection for highlighted drawing.
*
* @param connection The connection whose port to highlight. This must be a connection
* associated with the {@link Block} represented by this {@link BlockView}
* instance. Disables all connection highlights if connection is null.
*/
public void setHighlightedConnection(@Nullable Connection connection) {
mHighlightConnection = connection;
invalidate();
}
/**
* Check if border highlight is rendered.
*/
protected boolean isEntireBlockHighlighted() {
return isPressed() || isFocused() || isSelected();
}
/**
* Test whether event hits visible parts of this block and notify {@link WorkspaceView} if it
* does.
*
* @param event The {@link MotionEvent} to handle.
*
* @return False if the touch was on the view but not on a visible part of the block; otherwise
* returns whether the {@link WorkspaceView} says that the event is being handled properly.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
return hitTest(event) && mTouchHandler.onTouchBlock(this, event);
}
@Override
protected void onDraw(Canvas c) {
for (int i = 0; i < mFillRects.size(); ++i) {
c.drawRect(mFillRects.get(i), mFillPaint);
}
for (int i = 0; i < mBlockPatches.size(); ++i) {
mBlockPatches.get(i).draw(c);
}
// drawConnectorCenters(c); // Enable to debug connection positions.
drawHighlights(c);
}
/**
* Measure all children (i.e., block inputs) and compute their sizes and relative positions
* for use in {@link #onLayout}.
*/
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getBlock().getInputsInline()) {
measureInlineInputs(widthMeasureSpec, heightMeasureSpec);
} else {
measureExternalInputs(widthMeasureSpec, heightMeasureSpec);
}
mNextBlockVerticalOffset = mBlockContentHeight;
mBlockViewSize.y = mBlockContentHeight;
if (mBlock.getNextConnection() != null) {
mBlockViewSize.y += mPatchManager.mNextConnectorHeight;
}
if (mBlock.getOutputConnection() != null) {
mLayoutMarginLeft = mPatchManager.mOutputConnectorWidth;
mBlockViewSize.x += mLayoutMarginLeft;
} else {
mLayoutMarginLeft = 0;
}
setMeasuredDimension(mBlockViewSize.x, mBlockViewSize.y);
}
@Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
// Note that layout must be done regardless of the value of the "changed" parameter.
boolean rtl = mHelper.useRtl();
int rtlSign = rtl ? -1 : +1;
int xFrom = mLayoutMarginLeft;
if (rtl) {
xFrom = mBlockViewSize.x - xFrom;
}
for (int i = 0; i < mInputViews.size(); i++) {
int rowTop = mInputLayoutOrigins.get(i).y;
InputView inputView = mInputViews.get(i);
int inputViewWidth = inputView.getMeasuredWidth();
int rowFrom = xFrom + rtlSign * mInputLayoutOrigins.get(i).x;
if (rtl) {
rowFrom -= inputViewWidth;
}
inputView.layout(rowFrom, rowTop, rowFrom + inputViewWidth,
rowTop + inputView.getMeasuredHeight());
}
layoutPatchesAndConnectors();
updateConnectorLocations();
}
/**
* @return The block for this view.
*/
public Block getBlock() {
return mBlock;
}
/**
* Update the position of the block in workspace coordinates based on the view's location.
*/
private void updateBlockPosition() {
// Only update the block position if it isn't a top level block.
if (mBlock.getPreviousBlock() != null
|| (mBlock.getOutputConnection() != null
&& mBlock.getOutputConnection().getTargetBlock() != null)) {
mHelper.getWorkspaceCoordinates(this, mTempWorkspacePoint);
mBlock.setPosition(mTempWorkspacePoint.x, mTempWorkspacePoint.y);
}
}
/**
* Test whether a {@link MotionEvent} event is (approximately) hitting a visible part of this
* view.
* <p/>
* This is used to determine whether the event should be handled by this view, e.g., to activate
* dragging or to open a context menu. Since the actual block interactions are implemented at
* the {@link WorkspaceView} level, there is no need to store the event data in this class.
*
* @param event The {@link MotionEvent} to check.
*
* @return True if the coordinate of the motion event is on the visible, non-transparent part of
* this view; false otherwise.
*/
private boolean hitTest(MotionEvent event) {
final int eventX = (int) event.getX();
final int eventY = (int) event.getY();
// Do the exact same thing for RTL and LTR, with reversed left and right block bounds. Note
// that the bounds of each InputView include any connected child blocks, so in RTL mode,
// the left-hand side of the input fields must be obtained from the right-hand side of the
// input and the field layout width.
if (mHelper.useRtl()) {
// First check whether event is in the general horizontal range of the block outline
// (minus children) and exit if it is not.
final int blockEnd = mBlockViewSize.x - mLayoutMarginLeft;
final int blockBegin = blockEnd - mBlockContentWidth;
if (eventX < blockBegin || eventX > blockEnd) {
return false;
}
// In the ballpark - now check whether event is on a field of any of this block's
// inputs. If it is, then the event belongs to this BlockView, otherwise it does not.
for (int i = 0; i < mInputViews.size(); ++i) {
final InputView inputView = mInputViews.get(i);
if (inputView.isOnFields(
eventX - (inputView.getRight() - inputView.getFieldLayoutWidth()),
eventY - inputView.getTop())) {
return true;
}
}
} else {
final int blockBegin = mLayoutMarginLeft;
final int blockEnd = mBlockContentWidth;
if (eventX < blockBegin || eventX > blockEnd) {
return false;
}
for (int i = 0; i < mInputViews.size(); ++i) {
final InputView inputView = mInputViews.get(i);
if (inputView.isOnFields(
eventX - inputView.getLeft(), eventY - inputView.getTop())) {
return true;
}
}
}
return false;
}
/**
* Draw highlights of block-level connections, or the entire block, if necessary.
*
* @param c The canvas to draw on.
*/
private void drawHighlights(Canvas c) {
if (isEntireBlockHighlighted()) {
// Draw entire block highlighted..
for (int i = 0; i < mBlockBorderPatches.size(); ++i) {
mBlockBorderPatches.get(i).draw(c);
}
} else if (mHighlightConnection != null) {
if (mHighlightConnection == mBlock.getOutputConnection()) {
mOutputConnectorHighlightPatch.draw(c);
} else if (mHighlightConnection == mBlock.getPreviousConnection()) {
mPreviousConnectorHighlightPatch.draw(c);
} else if (mHighlightConnection == mBlock.getNextConnection()) {
mNextConnectionHighlightPatch.draw(c);
} else {
// If the connection to highlight is not one of the three block-level connectors,
// then it must be one of the inputs (either a "Next" connector for a Statement or
// "Input" connector for a Value input). Figure out which input the connection
// belongs to.
final Input input = mHighlightConnection.getInput();
for (int i = 0; i < mInputViews.size(); ++i) {
if (mInputViews.get(i).getInput() == input) {
Drawable connectionHighlight = mInputConnectionHighlightPatches.get(i);
if (connectionHighlight != null) {
connectionHighlight.draw(c);
}
break;
}
}
}
}
}
/**
* Measure view and its children with inline inputs.
* <p>
* This function does not return a value but has the following side effects. Upon return:
* <ol>
* <li>The {@link InputView#measure(int, int)} method has been called for all inputs in
* this block,</li>
* <li>{@link #mBlockViewSize} contains the size of the total size of the block view
* including all its inputs, and</li>
* <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within
* the block.</li>
* </ol>
* </p>
*/
private void measureInlineInputs(int widthMeasureSpec, int heightMeasureSpec) {
int inputViewsSize = mInputViews.size();
// First pass - measure all fields and inputs; compute maximum width of fields and children
// over all Statement inputs.
mMaxStatementFieldsWidth = 0;
int maxStatementChildWidth = 0;
for (int i = 0; i < inputViewsSize; i++) {
InputView inputView = mInputViews.get(i);
inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
mMaxStatementFieldsWidth =
Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth());
maxStatementChildWidth =
Math.max(maxStatementChildWidth, inputView.getTotalChildWidth());
}
}
// Second pass - compute layout positions and sizes of all inputs.
int rowLeft = 0;
int rowTop = 0;
int rowHeight = 0;
int maxRowWidth = 0;
mInlineRowWidth.clear();
for (int i = 0; i < inputViewsSize; i++) {
InputView inputView = mInputViews.get(i);
// If this is a Statement input, force its field width to be the maximum over all
// Statements, and begin a new layout row.
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
// If the first input is a Statement, add vertical space above to draw top of
// connector just below block top boundary.
if (i == 0) {
rowTop += mPatchManager.mBlockTopPadding;
}
// Force all Statement inputs to have the same field width.
inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth);
// New row BEFORE each Statement input.
mInlineRowWidth.add(Math.max(rowLeft,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent));
rowTop += rowHeight;
rowHeight = 0;
rowLeft = 0;
}
mInputLayoutOrigins.get(i).set(rowLeft, rowTop);
// Measure input view and update row height and width accordingly.
inputView.measure(widthMeasureSpec, heightMeasureSpec);
rowHeight = Math.max(rowHeight, inputView.getMeasuredHeight());
// Set row height for the current input view as maximum over all views in this row so
// far. A separate, reverse loop below propagates the maximum to earlier inputs in the
// same row.
inputView.setRowHeight(rowHeight);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
// The block width is that of the widest row.
maxRowWidth = Math.max(maxRowWidth, inputView.getMeasuredWidth());
// If the last input is a Statement, add vertical space below to draw bottom of
// connector just above block top boundary.
if (i == mInputCount - 1) {
rowTop += mPatchManager.mBlockBottomPadding;
}
// New row AFTER each Statement input.
rowTop += rowHeight;
rowLeft = 0;
rowHeight = 0;
} else {
// For Dummy and Value inputs, row width accumulates. Update maximum width
// accordingly.
rowLeft += inputView.getMeasuredWidth();
maxRowWidth = Math.max(maxRowWidth, rowLeft);
}
}
// Add height of final row. This is non-zero with inline inputs if the final input in the
// block is not a Statement input.
rowTop += rowHeight;
// Third pass - propagate row height maximums backwards. Reset height whenever a Statement
// input is encoutered.
int maxRowHeight = 0;
for (int i = inputViewsSize; i > 0; --i) {
InputView inputView = mInputViews.get(i - 1);
if (inputView.getInput().getType() == Input.TYPE_STATEMENT) {
maxRowHeight = 0;
} else {
maxRowHeight = Math.max(maxRowHeight, inputView.getRowHeight());
inputView.setRowHeight(maxRowHeight);
}
}
// If there was at least one Statement input, make sure block is wide enough to fit at least
// an empty Statement connector. If there were non-empty Statement connectors, they were
// already taken care of in the loop above.
if (mMaxStatementFieldsWidth > 0) {
maxRowWidth = Math.max(maxRowWidth,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent);
}
// Push width of last input row.
mInlineRowWidth.add(Math.max(rowLeft,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent));
// Block width is the computed width of the widest input row, and at least MIN_BLOCK_WIDTH.
mBlockContentWidth = Math.max(MIN_BLOCK_WIDTH, maxRowWidth);
mBlockViewSize.x = mBlockContentWidth;
// View width is the computed width of the widest statement input, including child blocks
// and padding, and at least the width of the widest input row.
mBlockViewSize.x = Math.max(mBlockContentWidth,
mMaxStatementFieldsWidth + maxStatementChildWidth +
mPatchManager.mBlockStartPadding + mPatchManager.mStatementInputPadding);
// Height is vertical position of next (non-existent) inputs row, and at least MIN_HEIGHT.
mBlockContentHeight = Math.max(mPatchManager.mMinBlockHeight, rowTop);
}
/**
* Measure view and its children with external inputs.
* <p>
* This function does not return a value but has the following side effects. Upon return:
* <ol>
* <li>The {@link InputView#measure(int, int)} method has been called for all inputs in
* this block,</li>
* <li>{@link #mBlockViewSize} contains the size of the total size of the block view
* including all its inputs, and</li>
* <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within
* the block (but note that for external inputs, only the y coordinate of each
* position is later used for positioning.)</li>
* </ol>
* </p>
*/
private void measureExternalInputs(int widthMeasureSpec, int heightMeasureSpec) {
int maxInputFieldsWidth = MIN_BLOCK_WIDTH;
// Initialize max Statement width as zero so presence of Statement inputs can be determined
// later; apply minimum size after that.
mMaxStatementFieldsWidth = 0;
int maxInputChildWidth = 0;
int maxStatementChildWidth = 0;
// First pass - measure fields and children of all inputs.
for (int i = 0; i < mInputViews.size(); i++) {
InputView inputView = mInputViews.get(i);
inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec);
switch (inputView.getInput().getType()) {
case Input.TYPE_VALUE: {
maxInputChildWidth =
Math.max(maxInputChildWidth, inputView.getTotalChildWidth());
// fall through
}
default:
case Input.TYPE_DUMMY: {
maxInputFieldsWidth =
Math.max(maxInputFieldsWidth, inputView.getTotalFieldWidth());
break;
}
case Input.TYPE_STATEMENT: {
mMaxStatementFieldsWidth =
Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth());
maxStatementChildWidth =
Math.max(maxStatementChildWidth, inputView.getTotalChildWidth());
break;
}
}
}
// If there was a statement, force all other input fields to be at least as wide as required
// by the Statement field plus port width.
if (mMaxStatementFieldsWidth > 0) {
mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, MIN_BLOCK_WIDTH);
maxInputFieldsWidth = Math.max(maxInputFieldsWidth,
mMaxStatementFieldsWidth + mPatchManager.mStatementInputIndent);
}
// Second pass - force all inputs to render fields with the same width and compute positions
// for all inputs.
int rowTop = 0;
for (int i = 0; i < mInputViews.size(); i++) {
InputView inputView = mInputViews.get(i);
final int inputType = inputView.getInput().getType();
if (inputType == Input.TYPE_STATEMENT) {
// If the first input is a Statement, add vertical space above to draw top of
// connector just below block top boundary.
if (i == 0) {
rowTop += mPatchManager.mBlockTopPadding;
}
// Force all Statement inputs to have the same field width.
inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth);
} else {
// Force all Dummy and Value inputs to have the same field width.
inputView.setFieldLayoutWidth(maxInputFieldsWidth);
}
inputView.measure(widthMeasureSpec, heightMeasureSpec);
mInputLayoutOrigins.get(i).set(0, rowTop);
// If the last input is a Statement, add vertical space below to draw bottom of
// connector just above block top boundary.
if ((inputType == Input.TYPE_STATEMENT) && (i == mInputCount - 1)) {
rowTop += mPatchManager.mBlockBottomPadding;
}
// The block height is the sum of all the row heights.
rowTop += inputView.getMeasuredHeight();
}
// Block content width is the width of the longest row.
mBlockContentWidth = Math.max(maxInputFieldsWidth, mMaxStatementFieldsWidth);
mBlockContentHeight = Math.max(mPatchManager.mMinBlockHeight, rowTop);
// Add space for connector if there is at least one Value input.
mBlockContentWidth += mPatchManager.mBlockTotalPaddingX;
if (mHasValueInput) {
mBlockContentWidth += mPatchManager.mValueInputWidth;
}
// Maximum total width of all value inputs is the sum of maximum field and child widths,
// plus space for field padding and Value input connector, minus overlap of input and output
// connectors.
final int maxValueInputTotalWidth = maxInputFieldsWidth + maxInputChildWidth +
mPatchManager.mBlockTotalPaddingX + mPatchManager.mValueInputWidth -
mPatchManager.mOutputConnectorWidth;
// Maximum total width of all Statement inputs is the sum of maximum field and and widths,
// plus field padding on the left and C-connector padding in the middle.
final int maxStatementInputTotalWidth = mMaxStatementFieldsWidth + maxStatementChildWidth +
mPatchManager.mBlockStartPadding +
mPatchManager.mStatementInputPadding;
// View width is maximum of content width and the Value input and Statement input total
// widths.
mBlockViewSize.x = Math.max(mBlockContentWidth,
Math.max(maxValueInputTotalWidth, maxStatementInputTotalWidth));
}
/**
* Instantiates new InputViews for this Block, using the block style from mHelper.
*/
private void createInputViews() {
mInputViews.clear();
List<Input> inputs = mBlock.getInputs();
for (int i = 0; i < inputs.size(); ++i) {
Input in = inputs.get(i);
InputView inputView = new InputView(getContext(), mHelper.getBlockStyle(), in, mHelper);
addView(inputView);
if (in.getType() == Input.TYPE_VALUE) {
mHasValueInput = true;
}
mInputViews.add(inputView);
}
mInputCount = mInputViews.size();
resizeList(mInputConnectorOffsets);
resizeList(mInputLayoutOrigins);
}
private void initDrawingObjects() {
final int blockColor = mBlock.getColour();
// Highlight color channels are added to each color-multiplied color channel, and since the
// patches are 50% gray, the addition should be 50% of the base value.
final int highlight = Color.argb(255, Color.red(blockColor) / 2,
Color.green(blockColor) / 2, Color.blue(blockColor) / 2);
mBlockColorFilter = new LightingColorFilter(blockColor, highlight);
mFillPaint.setColor(mBlock.getColour());
mFillPaint.setStyle(Paint.Style.FILL);
}
/**
* Adjust size of an {@link ArrayList} of {@link ViewPoint} objects to match the size of
* {@link #mInputViews}.
*/
private void resizeList(ArrayList<ViewPoint> list) {
if (list.size() != mInputCount) {
list.ensureCapacity(mInputCount);
if (list.size() < mInputCount) {
for (int i = list.size(); i < mInputCount; i++) {
list.add(new ViewPoint());
}
} else {
while (list.size() > mInputCount) {
list.remove(list.size() - 1);
}
}
}
}
/**
* Position patches for block rendering and connectors.
*/
private void layoutPatchesAndConnectors() {
mBlockPatches.clear();
mBlockBorderPatches.clear();
mFillRects.clear();
// Leave room on the left for margin (accomodates optional output connector) and block
// padding (accomodates block boundary).
int xFrom = mLayoutMarginLeft + mPatchManager.mBlockStartPadding;
// For inline inputs, the upper horizontal coordinate of the block boundary varies by
// section and changes after each Statement input. For external inputs, it is constant as
// computed in measureExternalInputs.
int xTo = mLayoutMarginLeft;
int inlineRowIdx = 0;
if (mBlock.getInputsInline()) {
xTo += mInlineRowWidth.get(inlineRowIdx);
} else {
xTo += mBlockContentWidth;
}
// Position top-left corner drawable. Retain drawable object so we can position bottom-left
// drawable correctly.
int yTop = 0;
final NinePatchDrawable topStartDrawable = addTopLeftPatch(xTo, yTop);
// Position inputs and connectors.
mInputConnectionHighlightPatches.clear();
mInputConnectionHighlightPatches.ensureCapacity(mInputCount);
for (int i = 0; i < mInputCount; ++i) {
final InputView inputView = mInputViews.get(i);
final ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i);
// Placeholder for connection patch. Even if input does not have a connection, makes
// sure later patches use indices matching their inputs.
mInputConnectionHighlightPatches.add(null);
// Start filling background of the input based on its origin and measured size.
fillRectBySize(xFrom + inputLayoutOrigin.x, inputLayoutOrigin.y,
inputView.getFieldLayoutWidth(), inputView.getRowHeight());
switch (inputView.getInput().getType()) {
default:
case Input.TYPE_DUMMY: {
if (!mBlock.getInputsInline()) {
addDummyBoundaryPatch(i, xTo, inputView, inputLayoutOrigin);
}
break;
}
case Input.TYPE_VALUE: {
if (mBlock.getInputsInline()) {
addInlineValueInputPatch(
i, inlineRowIdx, xFrom, inputView, inputLayoutOrigin);
} else {
addExternalValueInputPatch(i, xTo, inputView, inputLayoutOrigin);
}
break;
}
case Input.TYPE_STATEMENT: {
// For external inputs, the horizontal end coordinate of the connector bottom is
// the same as the one on top. For inline inputs, however, it is the next entry
// in the width-by-row table.
int xToBottom = xTo;
if (mBlock.getInputsInline()) {
++inlineRowIdx;
xToBottom = xFrom + mInlineRowWidth.get(inlineRowIdx) -
mPatchManager.mBlockStartPadding;
}
// Place the connector patches.
addStatementInputPatches(
i, xFrom, xTo, xToBottom, inputView, inputLayoutOrigin);
// Set new horizontal end coordinate for subsequent inputs.
xTo = xToBottom;
break;
}
}
}
// Select and position correct patch for bottom and left-hand side of the block, including
// bottom-left corner.
int bottomStartResourceId = R.drawable.bottom_start_default;
int bottomStartBorderResourceId = R.drawable.bottom_start_default_border;
if (mBlock.getNextConnection() != null) {
setPointMaybeFlip(mNextConnectorOffset, mLayoutMarginLeft, mNextBlockVerticalOffset);
bottomStartResourceId = R.drawable.bottom_start_next;
bottomStartBorderResourceId = R.drawable.bottom_start_next_border;
}
final NinePatchDrawable bottomStartDrawable =
getColoredPatchDrawable(bottomStartResourceId);
final NinePatchDrawable bottomStartBorderDrawable =
mPatchManager.getPatchDrawable(bottomStartBorderResourceId);
calculateRtlAwareBounds(tempRect,
mLayoutMarginLeft, topStartDrawable.getIntrinsicHeight(), xTo, mBlockViewSize.y);
bottomStartDrawable.setBounds(tempRect);
bottomStartBorderDrawable.setBounds(tempRect);
if (mBlock.getNextConnection() != null) {
mNextConnectionHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.bottom_start_next_connection);
mNextConnectionHighlightPatch.setBounds(tempRect);
}
mBlockPatches.add(bottomStartDrawable);
mBlockBorderPatches.add(bottomStartBorderDrawable);
// Finish the final rect, if there is one.
finishFillRect();
}
/**
* Add the top-left corner drawable.
*
* @param xTo Horizontal end position for the drawable.
* @param yTop Vertical position for the drawable.
*
* @return The added drawable. This can be used to position other drawables, e.g., the
* bottom-left drawable, relative to it.
*/
@NonNull
private NinePatchDrawable addTopLeftPatch(int xTo, int yTop) {
// Select and position the correct patch for the top and left block sides including the
// top-left corner.
NinePatchDrawable topStartDrawable;
NinePatchDrawable topStartBorderDrawable;
if (mBlock.getPreviousConnection() != null) {
setPointMaybeFlip(mPreviousConnectorOffset, mLayoutMarginLeft, yTop);
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_previous);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_previous_border);
mPreviousConnectorHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.top_start_previous_connection);
} else if (mBlock.getOutputConnection() != null) {
setPointMaybeFlip(mOutputConnectorOffset, mLayoutMarginLeft, yTop);
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_output);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_output_border);
mOutputConnectorHighlightPatch =
mPatchManager.getPatchDrawable(R.drawable.top_start_output_connection);
} else {
topStartDrawable = getColoredPatchDrawable(R.drawable.top_start_default);
topStartBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.top_start_default_border);
}
calculateRtlAwareBounds(tempRect, 0, 0, xTo, topStartDrawable.getIntrinsicHeight());
topStartDrawable.setBounds(tempRect);
topStartBorderDrawable.setBounds(tempRect);
if (mPreviousConnectorHighlightPatch != null) {
mPreviousConnectorHighlightPatch.setBounds(tempRect);
}
if (mOutputConnectorHighlightPatch != null) {
mOutputConnectorHighlightPatch.setBounds(tempRect);
}
mBlockPatches.add(topStartDrawable);
mBlockBorderPatches.add(topStartBorderDrawable);
return topStartDrawable;
}
/**
* Add boundary patch for external Dummy input.
*
* @param i The index of the current input. This is used to determine whether to position patch
* vertically below the field top boundary to account for the block's top boundary.
* @param xTo Horizontal coordinate to which the patch should extend. The starting coordinate
* is determined from this by subtracting patch width.
* @param inputView The {@link InputView} for the current input. This is used to determine patch
* height.
* @param inputLayoutOrigin The layout origin for the current input. This is used to determine
* the vertical position for the patch.
*/
private void addDummyBoundaryPatch(int i, int xTo, InputView inputView,
ViewPoint inputLayoutOrigin) {
// For external dummy inputs, put a patch for the block boundary.
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable inputBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
int width = inputDrawable.getIntrinsicWidth();
if (mHasValueInput) {
// Stretch the patch horizontally if this block has at least one value
// input, so that the dummy input block boundary is as thick as the
// boundary with value input connector.
width += mPatchManager.mValueInputWidth;
}
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xTo - width,
/* top */ inputLayoutOrigin.y + (i > 0 ? 0 : mPatchManager.mBlockTopPadding),
/* ltrEnd */ xTo,
/* bottom */ inputLayoutOrigin.y + inputView.getMeasuredHeight());
inputDrawable.setBounds(tempRect);
inputBorderDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mBlockBorderPatches.add(inputBorderDrawable);
}
/**
* Add connector patch for external Value inputs.
*
* @param i The index of the current input. This is used to determine whether to position patch
* vertically below the field top boundary to account for the block's top boundary.
* @param xTo Horizontal coordinate to which the patch should extend. The starting coordinate
* is determined from this by subtracting patch width.
* @param inputView The {@link InputView} for the current input. This is used to determine patch
* height.
* @param inputLayoutOrigin The layout origin for the current input. This is used to determine
* the vertical position for the patch.
*/
private void addExternalValueInputPatch(int i, int xTo,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Position patch and connector for external value input.
setPointMaybeFlip(mInputConnectorOffsets.get(i), xTo, inputLayoutOrigin.y);
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.value_input_external);
final NinePatchDrawable inputBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_external_border);
final NinePatchDrawable connectionHighlightDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_external_connection);
int patchLeft = xTo - inputDrawable.getIntrinsicWidth();
int patchRight = xTo;
int connectorTop = inputLayoutOrigin.y + mPatchManager.mBlockTopPadding;
int connectorBottom = inputLayoutOrigin.y + inputView.getMeasuredHeight();
calculateRtlAwareBounds(tempRect, patchLeft, connectorTop, patchRight, connectorBottom);
inputDrawable.setBounds(tempRect);
inputBorderDrawable.setBounds(tempRect);
connectionHighlightDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mBlockBorderPatches.add(inputBorderDrawable);
mInputConnectionHighlightPatches.set(i, connectionHighlightDrawable);
if (i > 0) {
// If this is not the first input in the block, then a gap above the
// input connector patch must be closed by a non-input boundary patch.
// The gap is the result of the need to not draw over the top block
// boundary.
final NinePatchDrawable boundaryGapDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable boundaryGapBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
calculateRtlAwareBounds(tempRect,
patchLeft, inputLayoutOrigin.y, patchRight, connectorTop);
boundaryGapDrawable.setBounds(tempRect);
boundaryGapBorderDrawable.setBounds(tempRect);
mBlockPatches.add(boundaryGapDrawable);
mBlockBorderPatches.add(boundaryGapBorderDrawable);
}
}
/**
* Add cutout patch for inline Value inputs.
* <p/>
* The inline input nine patch includes the entirety of the cutout shape, including the
* connector, and stretches to fit all child blocks.
* <p/>
* An inline input is usually drawn with an input 9-patch and three rects for padding between
* inputs: one above, one below, and one after (i.e., to the right in LTR and to the left in
* RTL).
*
* @param i The index of the input in the block.
* @param inlineRowIdx The (horizontal) index of the input in the current input row.
* @param blockFromX The horizontal start position input views in the block.
* @param inputView The input view.
* @param inputLayoutOrigin Layout origin for the current input view.
*/
private void addInlineValueInputPatch(int i, int inlineRowIdx, int blockFromX,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Determine position for inline connector cutout.
final int cutoutX = blockFromX + inputLayoutOrigin.x + inputView.getInlineInputX();
final int cutoutY = inputLayoutOrigin.y + mPatchManager.mBlockTopPadding;
// Set connector position - shift w.r.t. patch location to where the corner of connected
// blocks will be positioned.
setPointMaybeFlip(mInputConnectorOffsets.get(i),
cutoutX + mPatchManager.mInlineInputStartPadding +
mPatchManager.mOutputConnectorWidth,
cutoutY + mPatchManager.mInlineInputTopPadding);
// Fill above inline input connector, unless first row, where connector top
// is aligned with block boundary patch.
if (inlineRowIdx > 0) {
fillRectBySize(cutoutX, inputLayoutOrigin.y,
inputView.getTotalChildWidth(), mPatchManager.mBlockTopPadding);
finishFillRect(); // Prevent filling through the inline connector.
}
// Position a properly-sized input cutout patch.
final NinePatchDrawable inputDrawable =
getColoredPatchDrawable(R.drawable.value_input_inline);
final NinePatchDrawable connectionHighlightDrawable =
mPatchManager.getPatchDrawable(R.drawable.value_input_inline_connection);
calculateRtlAwareBounds(tempRect,
cutoutX, cutoutY,
cutoutX + inputView.getTotalChildWidth(),
cutoutY + inputView.getTotalChildHeight());
inputDrawable.setBounds(tempRect);
connectionHighlightDrawable.setBounds(tempRect);
mBlockPatches.add(inputDrawable);
mInputConnectionHighlightPatches.set(i, connectionHighlightDrawable);
// Fill below inline input cutout.
final int cutoutEndX = cutoutX + inputView.getTotalChildWidth();
final int cutoutEndY = inputLayoutOrigin.y + inputView.getRowHeight();
fillRect(cutoutX, cutoutY + inputView.getTotalChildHeight(), cutoutEndX, cutoutEndY);
// Fill after inline input cutout.
fillRect(cutoutEndX, inputLayoutOrigin.y,
inputLayoutOrigin.x + inputView.getMeasuredWidth(), cutoutEndY);
// If this is either the last input in the block, or the next input is a Statement, then
// this is the final input in the current row. In this case, put a boundary patch.
final int nextI = i + 1;
if ((nextI == mInputCount) ||
(mInputViews.get(nextI).getInput().getType() == Input.TYPE_STATEMENT)) {
// Horizontal patch position is the position of inputs in the block, plus offset of the
// current input in its row, plus padding before and after the input fields.
final int patchX = blockFromX + mInlineRowWidth.get(inlineRowIdx) -
mPatchManager.mBlockTotalPaddingX;
// Vertical patch position is the input layout origin, plus room for block boundary if
// this is the first input row.
final int patchY = inputLayoutOrigin.y +
(inlineRowIdx > 0 ? 0 : mPatchManager.mBlockTopPadding);
final int patchRight = patchX + mPatchManager.mBlockEndPadding;
final NinePatchDrawable blockFillDrawable =
getColoredPatchDrawable(R.drawable.dummy_input);
final NinePatchDrawable blockFillBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.dummy_input_border);
calculateRtlAwareBounds(tempRect, patchX, patchY, patchRight, cutoutEndY);
blockFillDrawable.setBounds(tempRect);
blockFillBorderDrawable.setBounds(tempRect);
mBlockPatches.add(blockFillDrawable);
mBlockBorderPatches.add(blockFillBorderDrawable);
// Also at the end of the current input row, fill background up to
// block boundary.
fillRect(inputLayoutOrigin.x + mPatchManager.mBlockStartPadding +
inputView.getMeasuredWidth(), patchY, patchX, cutoutEndY);
}
}
/**
* Add patches (top and bottom) for a Statement input connector.
*
* @param i Index of the input.
* @param xFrom Horizontal offset of block content.
* @param xToAbove Horizontal end coordinate for connector above input.
* @param xToBelow Horizontal end coordinate for connector below input.
* @param inputView The view for this input.
* @param inputLayoutOrigin Layout origin for this input.
*/
private void addStatementInputPatches(int i, int xFrom, int xToAbove, int xToBelow,
InputView inputView, ViewPoint inputLayoutOrigin) {
// Position connector. Shift by horizontal and vertical patch thickness to line up with
// "Previous" connector on child block.
int xOffset = xFrom + inputView.getFieldLayoutWidth();
setPointMaybeFlip(mInputConnectorOffsets.get(i),
xOffset + mPatchManager.mStatementInputPadding,
inputLayoutOrigin.y + mPatchManager.mStatementTopThickness);
// Position patch for the top part of the Statement connector. This patch is
// stretched only horizontally to extend to the block boundary.
final NinePatchDrawable statementTopDrawable =
getColoredPatchDrawable(R.drawable.statementinput_top);
final NinePatchDrawable statementTopBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.statementinput_top_border);
final NinePatchDrawable statementConnectionHighlight =
mPatchManager.getPatchDrawable(R.drawable.statementinput_top_connection);
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xOffset,
/* top */ inputLayoutOrigin.y,
/* ltrEnd */ xToAbove,
/* bottom */ inputLayoutOrigin.y + statementTopDrawable.getIntrinsicHeight());
statementTopDrawable.setBounds(tempRect);
statementTopBorderDrawable.setBounds(tempRect);
statementConnectionHighlight.setBounds(tempRect);
mBlockPatches.add(statementTopDrawable);
mBlockBorderPatches.add(statementTopBorderDrawable);
mInputConnectionHighlightPatches.set(i, statementConnectionHighlight);
// Position patch for the bottom part of the Statement connector. The bottom
// patch is stretched horizontally, like the top patch, but also vertically to
// accomodate height of the input fields as well as the size of any connected
// blocks.
final NinePatchDrawable statementBottomDrawable =
getColoredPatchDrawable(R.drawable.statementinput_bottom);
final NinePatchDrawable statementBottomBorderDrawable =
mPatchManager.getPatchDrawable(R.drawable.statementinput_bottom_border);
final int connectorHeight =
Math.max(inputView.getTotalChildHeight(),
inputView.getMeasuredHeight());
calculateRtlAwareBounds(tempRect,
/* ltrStart */ xOffset,
/* top */ inputLayoutOrigin.y + statementTopDrawable.getIntrinsicHeight(),
/* ltrEnd */ xToBelow,
/* bottom */ inputLayoutOrigin.y + connectorHeight);
statementBottomDrawable.setBounds(tempRect);
statementBottomBorderDrawable.setBounds(tempRect);
mBlockPatches.add(statementBottomDrawable);
mBlockBorderPatches.add(statementBottomBorderDrawable);
}
/**
* Draw dots at the model's location of all connections on this block, for debugging.
*
* @param c The canvas to draw on.
*/
private void drawConnectorCenters(Canvas c) {
List<Connection> connections = mBlock.getAllConnections();
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
for (int i = 0; i < connections.size(); i++) {
Connection conn = connections.get(i);
if (conn.inDragMode()) {
if (conn.isConnected()) {
paint.setColor(Color.RED);
} else {
paint.setColor(Color.MAGENTA);
}
} else {
if (conn.isConnected()) {
paint.setColor(Color.GREEN);
} else {
paint.setColor(Color.CYAN);
}
}
// Compute connector position relative to this view from its offset to block origin in
// Workspace coordinates.
mTempWorkspacePoint.set(
conn.getPosition().x - mBlock.getPosition().x,
conn.getPosition().y - mBlock.getPosition().y);
mHelper.workspaceToVirtualViewDelta(mTempWorkspacePoint, mTempConnectionPosition);
if (mHelper.useRtl()) {
// In RTL mode, add block view size to x coordinate. This is counter-intuitive, but
// equivalent to "x = size - (-x)", with the inner negation "-x" undoing the
// side-effect of workspaceToVirtualViewDelta reversing the x coordinate. This is,
// the addition mirrors the re-negated in-block x coordinate w.r.t. the right-hand
// side of the block view, which is the origin of the block in RTL mode.
mTempConnectionPosition.x += mBlockViewSize.x;
}
c.drawCircle(mTempConnectionPosition.x, mTempConnectionPosition.y, 10, paint);
}
}
/**
* @return The number of {@link InputView} instances inside this view.
*/
@VisibleForTesting
int getInputViewCount() {
return mInputViews.size();
}
/**
* @return The {@link InputView} for the {@link Input} at the given index.
*/
@VisibleForTesting
InputView getInputView(int index) {
return mInputViews.get(index);
}
/**
* Correctly set the locations of the connections based on their offsets within the
* {@link BlockView} and the position of the {@link BlockView} itself. Can be used when the
* block has moved but not changed shape (e.g. during a drag).
*/
@VisibleForTesting
public void updateConnectorLocations() {
// Ensure we have the right block location before we update the connections.
updateBlockPosition();
if (mConnectionManager == null) {
return;
}
final WorkspacePoint blockWorkspacePosition = mBlock.getPosition();
final Connection previousConnection = mBlock.getPreviousConnection();
if (previousConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mPreviousConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
previousConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
final Connection nextConnection = mBlock.getNextConnection();
if (nextConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mNextConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
nextConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
final Connection outputConnection = mBlock.getOutputConnection();
if (outputConnection != null) {
mHelper.virtualViewToWorkspaceDelta(mOutputConnectorOffset, mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
outputConnection, blockWorkspacePosition, mTempWorkspacePoint);
}
for (int i = 0; i < mInputViews.size(); i++) {
final InputView inputView = mInputViews.get(i);
final Connection connection = inputView.getInput().getConnection();
if (connection != null) {
mHelper.virtualViewToWorkspaceDelta(
mInputConnectorOffsets.get(i), mTempWorkspacePoint);
mConnectionManager.moveConnectionTo(
connection, blockWorkspacePosition, mTempWorkspacePoint);
if (connection.isConnected()) {
((BlockGroup) inputView.getChildView()).updateAllConnectorLocations();
}
}
}
}
/**
* Add a rectangular area for filling either by creating a new rectangle or extending an
* existing one.
* <p/>
* If the rectangle defined by the method arguments is aligned with the in-progress rectangle
* {@link #mNextFillRect} either horizontally or vertically, then the two are joined. Otherwise,
* {@link #mNextFillRect} is finished and committed to the list of rectangles to draw and a new
* rectangle is begun with the given method arguments.
* <p/>
* Note that rectangles are joined even if there is a gap between them. This fills padding areas
* between inline inputs in the same row without any additional code. However, this assumes that
* whenever there is an intended gap between aligned rectangles, then there is at last one
* rectangle of different size (or with unaligned position) between them. If this assumption is
* violated, call {@link #finishFillRect()} prior to the next call to this method.
*
* @param left Left coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param top Top coordinate of the new rectangle.
* @param right Right coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param bottom Bottom coordinate of the new rectangle.
*/
private void fillRect(int left, int top, int right, int bottom) {
if (mNextFillRect != null) {
if ((mNextFillRect.left == left) && (mNextFillRect.right == right)) {
assert mNextFillRect.top <= top; // New rectangle must not start above current.
mNextFillRect.bottom = bottom;
return;
} else if ((mNextFillRect.top == top) && (mNextFillRect.bottom == bottom)) {
assert mNextFillRect.left <= left; // New rectangle must not start left of current.
mNextFillRect.right = right;
return;
} else {
finishFillRect();
}
}
mNextFillRect = new Rect(left, top, right, bottom);
}
/**
* Convenience wrapper for {@link #fillRect(int, int, int, int)} taking rectangle size
* rather than upper bounds.
* <p/>
* This wrapper converts width and height of the given rectangle to right and bottom
* coordinates, respectively. That makes client code more readable in places where the rectangle
* is naturally defined by its origin and size.
*
* @param left Left coordinate of the new rectangle in LTR mode. In RTL mode, coordinates are
* automatically flipped when the rectangle is committed by calling {@link #finishFillRect()}.
* @param top Top coordinate of the new rectangle.
* @param width Width of the new rectangle.
* @param height Height of the new rectangle.
*/
private void fillRectBySize(int left, int top, int width, int height) {
fillRect(left, top, left + width, top + height);
}
/**
* Finish the current fill rectangle.
* <p/>
* The current rectangle is cropped against the vertical block boundaries with padding
* considered, and afterwards committed to the {@link #mFillRects} list.
* <p/>
* Note that horizontal block padding is assumed to have been considered prior to calling
* {@link #fillRect(int, int, int, int)}. This is because horizontal block size can
* vary across rows in a block with inline inputs.
* <p/>
* In Right-to-Left mode, the horizontal rectangle boundaries are mirrored w.r.t. the right-hand
* side of the view.
*/
private void finishFillRect() {
if (mNextFillRect != null) {
mNextFillRect.top = Math.max(mNextFillRect.top, mPatchManager.mBlockTopPadding);
mNextFillRect.bottom = Math.min(mNextFillRect.bottom,
mBlockContentHeight - mPatchManager.mBlockBottomPadding);
// In RTL mode, mirror Rect w.r.t. right-hand side of the block area.
if (mHelper.useRtl()) {
final int left = mNextFillRect.left;
mNextFillRect.left = mBlockViewSize.x - mNextFillRect.right;
mNextFillRect.right = mBlockViewSize.x - left;
}
mFillRects.add(mNextFillRect);
mNextFillRect = null;
}
}
/**
* Assigned rect given bounds, possibly flipping horizontal bounds in RtL mode.
*
* @param ltrStart The left coordinate in LTR mode.
* @param top The top coordinate.
* @param ltrEnd The right coordinate in LTR mode.
* @param bottom The bottom coordinate.
*/
private void calculateRtlAwareBounds(Rect rect, int ltrStart, int top, int ltrEnd, int bottom) {
boolean isRtl = mHelper.useRtL();
rect.left = isRtl ? mBlockViewSize.x - ltrEnd : ltrStart;
rect.top = top;
rect.right = isRtl ? mBlockViewSize.x - ltrStart : ltrEnd;
rect.bottom = bottom;
}
/**
* Set a {@link ViewPoint} and flip x coordinate in RTL mode.
*
* @param viewPoint The point in view coordinates to set.
* @param x The new x coordinate in LTR mode.
* @param y The new y coordinate.
*/
private void setPointMaybeFlip(ViewPoint viewPoint, int x, int y) {
viewPoint.set(mHelper.useRtl() ? -x : x, y);
}
private NinePatchDrawable getColoredPatchDrawable(int id) {
NinePatchDrawable drawable = mPatchManager.getPatchDrawable(id);
drawable.setColorFilter(mBlockColorFilter);
return drawable;
}
/**
* @return Vertical offset for positioning the "Next" block (if one exists). This is relative to
* the top of this view's area.
*/
int getNextBlockVerticalOffset() {
return mNextBlockVerticalOffset;
}
/**
* @return Layout margin on the left-hand side of the block (for optional Output connector).
*/
int getLayoutMarginLeft() {
return mLayoutMarginLeft;
}
}
| Correct rendering of the border of a end-of-line dummy import. Also, correct some warnings with asserts.
| blocklylib/src/main/java/com/google/blockly/ui/BlockView.java | Correct rendering of the border of a end-of-line dummy import. Also, correct some warnings with asserts. |
|
Java | apache-2.0 | a772acbd898bb728e00543771c43998f9eabe58a | 0 | polyvi/xface-android,mmig/cordova-android,hgl888/crosswalk-cordova-android,0359xiaodong/cordova-android,synaptek/cordova-android,grigorkh/cordova-android,rohngonnarock/cordova-android,GroupAhead/cordova-android,tony--/cordova-android,apache/cordova-android,net19880504/cordova-android,MetSystem/cordova-android,davibe/incubator-cordova-android,vionescu/cordova-android,forcedotcom/incubator-cordova-android,ttiurani/cordova-android,sxagan/cordova-android,crosswalk-project/crosswalk-cordova-android,adobe-marketing-cloud-mobile/aemm-android,archananaik/cordova-amazon-fireos-old,ogoguel/cordova-android,corimf/cordova-android,grigorkh/cordova-android,apache/cordova-android,mmig/cordova-android,mleoking/cordova-android,cesine/cordova-android,ttiurani/cordova-android,CloudCom/cordova-android,rakuco/crosswalk-cordova-android,bso-intel/cordova-android,rakuco/crosswalk-cordova-android,thedracle/cordova-android-chromeview,archananaik/cordova-amazon-fireos-old,lybvinci/cordova-android,lvrookie/cordova-android,cesine/cordova-android,lvrookie/cordova-android,imhotep/incubator-cordova-android,CrandellWS/cordova-android,leixinstar/cordova-android,filmaj/cordova-android,alpache/cordova-android,crosswalk-project/crosswalk-cordova-android,imhotep/incubator-cordova-android,lybvinci/cordova-android,xandroidx/cordova-android,rohngonnarock/cordova-android,filmaj/cordova-android,dpogue/cordova-android,mokelab/cordova-android,jfrumar/cordova-android,chengxiaole/crosswalk-cordova-android,imhotep/incubator-cordova-android,egirshov/cordova-android,crosswalk-project/crosswalk-cordova-android,apache/cordova-android,forcedotcom/incubator-cordova-android,leixinstar/cordova-android,bso-intel/cordova-android,hgl888/cordova-android-chromeview,grigorkh/cordova-android,Icenium/cordova-android,archananaik/cordova-amazon-fireos-old,vionescu/cordova-android,alsorokin/cordova-android,chengxiaole/crosswalk-cordova-android,timkim/callback-android,leixinstar/cordova-android,mleoking/cordova-android,alsorokin/cordova-android,egirshov/cordova-android,GroupAhead/cordova-android,infil00p/cordova-android,grigorkh/cordova-android,forcedotcom/callback-android,awesome-niu/crosswalk-cordova-android,devgeeks/cordova-android,csantanapr/cordova-android,GroupAhead/cordova-android,manuelbrand/cordova-android,askyheller/testgithub,hgl888/crosswalk-cordova-android,ecit241/cordova-android,askyheller/testgithub,mmig/cordova-android,macdonst/cordova-android,ecit241/cordova-android,sxagan/cordova-android,tony--/cordova-android,honger05/cordova-android,MetSystem/cordova-android,wikimedia/incubator-cordova-android,Icenium/cordova-android,jasongin/cordova-android,CloudCom/cordova-android,mokelab/cordova-android,hgl888/cordova-android-chromeview,synaptek/cordova-android,net19880504/cordova-android,honger05/cordova-android,tony--/cordova-android,corimf/cordova-android,revolunet/cordova-android,ogoguel/cordova-android,matb33/cordova-android,infil00p/cordova-android,alpache/cordova-android,csantanapr/cordova-android,xandroidx/cordova-android,timkim/callback-android,hgl888/cordova-android-chromeview,mleoking/cordova-android,infil00p/cordova-android,adobe-marketing-cloud-mobile/aemm-android,cesine/cordova-android,thedracle/cordova-android-chromeview,Philzen/cordova-android-multitouch-polyfill,revolunet/cordova-android,hgl888/cordova-android,jasongin/cordova-android,egirshov/cordova-android,0359xiaodong/cordova-android,jfrumar/cordova-android,forcedotcom/callback-android,bso-intel/cordova-android,polyvi/xface-android,chengxiaole/crosswalk-cordova-android,macdonst/cordova-android,thedracle/cordova-android-chromeview,devgeeks/cordova-android,rohngonnarock/cordova-android,honger05/cordova-android,ecit241/cordova-android,MetSystem/cordova-android,hgl888/crosswalk-cordova-android,matb33/cordova-android,ogoguel/cordova-android,filmaj/cordova-android,synaptek/cordova-android,Philzen/cordova-android-multitouch-polyfill,CrandellWS/cordova-android,manuelbrand/cordova-android,xandroidx/cordova-android,CrandellWS/cordova-android,dpogue/cordova-android,jasongin/cordova-android,manuelbrand/cordova-android,CloudCom/cordova-android,wikimedia/incubator-cordova-android,lvrookie/cordova-android,revolunet/cordova-android,lybvinci/cordova-android,awesome-niu/crosswalk-cordova-android,0359xiaodong/cordova-android,alsorokin/cordova-android,forcedotcom/incubator-cordova-android,ttiurani/cordova-android,awesome-niu/crosswalk-cordova-android,matb33/cordova-android,polyvi/xface-android,forcedotcom/callback-android,hgl888/cordova-android-chromeview,davibe/incubator-cordova-android,davibe/incubator-cordova-android,adobe-marketing-cloud-mobile/aemm-android,mokelab/cordova-android,askyheller/testgithub,rakuco/crosswalk-cordova-android,hgl888/cordova-android,jfrumar/cordova-android,hgl888/cordova-android,wikimedia/incubator-cordova-android,dpogue/cordova-android,devgeeks/cordova-android,corimf/cordova-android,forcedotcom/callback-android,macdonst/cordova-android,alpache/cordova-android,timkim/callback-android,net19880504/cordova-android,Icenium/cordova-android,Philzen/cordova-android-multitouch-polyfill,timkim/callback-android,sxagan/cordova-android,vionescu/cordova-android,csantanapr/cordova-android | package com.phonegap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import android.content.Intent;
import android.webkit.WebView;
/**
* This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z.
*/
public class AccelListener implements SensorEventListener, Plugin {
public static int STOPPED = 0;
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
public float TIMEOUT = 30000; // Timeout in msec to shut off listener
WebView webView; // WebView object
DroidGap ctx; // DroidGap object
float x,y,z; // most recent acceleration values
long timestamp; // time of most recent value
int status; // status of listener
long lastAccessTime; // time the value was last retrieved
private SensorManager sensorManager;// Sensor manager
Sensor mSensor; // Acceleration sensor returned by sensor manager
/**
* Create an accelerometer listener.
*/
public AccelListener() {
this.x = 0;
this.y = 0;
this.z = 0;
this.timestamp = 0;
this.setStatus(AccelListener.STOPPED);
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(DroidGap ctx) {
this.ctx = ctx;
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
}
/**
* Sets the main View of the application, this is the WebView within which
* a PhoneGap app runs.
*
* @param webView The PhoneGap WebView
*/
public void setView(WebView webView) {
this.webView = webView;
}
/**
* Executes the request and returns CommandResult.
*
* @param action The command to execute.
* @param args JSONArry of arguments for the command.
* @return A CommandResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("getStatus")) {
int i = this.getStatus();
return new PluginResult(status, i);
}
else if (action.equals("start")) {
int i = this.start();
return new PluginResult(status, i);
}
else if (action.equals("stop")) {
this.stop();
return new PluginResult(status, 0);
}
else if (action.equals("getAcceleration")) {
// If not running, then this is an async call, so don't worry about waiting
if (this.status != AccelListener.RUNNING) {
int r = this.start();
if (r == AccelListener.ERROR_FAILED_TO_START) {
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
}
// Wait until running
long timeout = 2000;
while ((this.status == STARTING) && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (timeout == 0) {
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
}
}
this.lastAccessTime = System.currentTimeMillis();
JSONObject r = new JSONObject();
r.put("x", this.x);
r.put("y", this.y);
r.put("z", this.z);
// TODO: Should timestamp be sent?
r.put("timestamp", this.timestamp);
return new PluginResult(status, r);
}
else if (action.equals("setTimeout")) {
try {
float timeout = Float.parseFloat(args.getString(0));
this.setTimeout(timeout);
return new PluginResult(status, 0);
} catch (NumberFormatException e) {
status = PluginResult.Status.INVALID_ACTION;
e.printStackTrace();
} catch (JSONException e) {
status = PluginResult.Status.JSON_EXCEPTION;
e.printStackTrace();
}
}
else if (action.equals("getTimeout")) {
float f = this.getTimeout();
return new PluginResult(status, f);
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("getStatus")) {
return true;
}
else if (action.equals("getAcceleration")) {
// Can only return value if RUNNING
if (this.status == RUNNING) {
return true;
}
}
else if (action.equals("getTimeout")) {
return true;
}
return false;
}
/**
* Called when the system is about to start resuming a previous activity.
*/
public void onPause() {
}
/**
* Called when the activity will start interacting with the user.
*/
public void onResume() {
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
this.stop();
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Start listening for acceleration sensor.
*
* @return status of listener
*/
public int start() {
// If already starting or running, then just return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
return this.status;
}
// Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_FASTEST);
this.setStatus(AccelListener.STARTING);
this.lastAccessTime = System.currentTimeMillis();
}
// If error, then set status to error
else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
}
return this.status;
}
/**
* Stop listening to acceleration sensor.
*/
public void stop() {
if (this.status != AccelListener.STOPPED) {
this.sensorManager.unregisterListener(this);
}
this.setStatus(AccelListener.STOPPED);
}
/**
* Called when the accuracy of the sensor has changed.
*
* @param sensor
* @param accuracy
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/**
* Sensor listener event.
*
* @param SensorEvent event
*/
public void onSensorChanged(SensorEvent event) {
// Only look at accelerometer events
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
// Save time that event was received
this.timestamp = System.currentTimeMillis();
this.x = event.values[0];
this.y = event.values[1];
this.z = event.values[2];
this.setStatus(AccelListener.RUNNING);
// If values haven't been read for TIMEOUT time, then turn off accelerometer sensor to save power
if ((this.timestamp - this.lastAccessTime) > this.TIMEOUT) {
this.stop();
}
}
/**
* Get status of accelerometer sensor.
*
* @return status
*/
public int getStatus() {
return this.status;
}
/**
* Set the timeout to turn off accelerometer sensor if getX() hasn't been called.
*
* @param timeout Timeout in msec.
*/
public void setTimeout(float timeout) {
this.TIMEOUT = timeout;
}
/**
* Get the timeout to turn off accelerometer sensor if getX() hasn't been called.
*
* @return timeout in msec
*/
public float getTimeout() {
return this.TIMEOUT;
}
/**
* Set the status and send it to JavaScript.
* @param status
*/
private void setStatus(int status) {
this.status = status;
}
}
| framework/src/com/phonegap/AccelListener.java | package com.phonegap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import android.content.Intent;
import android.webkit.WebView;
/**
* This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z.
*/
public class AccelListener implements SensorEventListener, Plugin{
public static int STOPPED = 0;
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
public float TIMEOUT = 30000; // Timeout in msec to shut off listener
WebView webView; // WebView object
DroidGap ctx; // DroidGap object
float x,y,z; // most recent acceleration values
long timestamp; // time of most recent value
int status; // status of listener
long lastAccessTime; // time the value was last retrieved
private SensorManager sensorManager;// Sensor manager
Sensor mSensor; // Acceleration sensor returned by sensor manager
/**
* Create an accelerometer listener.
*/
public AccelListener() {
this.x = 0;
this.y = 0;
this.z = 0;
this.timestamp = 0;
this.setStatus(AccelListener.STOPPED);
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(DroidGap ctx) {
this.ctx = ctx;
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
}
/**
* Sets the main View of the application, this is the WebView within which
* a PhoneGap app runs.
*
* @param webView The PhoneGap WebView
*/
public void setView(WebView webView) {
this.webView = webView;
}
/**
* Executes the request and returns CommandResult.
*
* @param action The command to execute.
* @param args JSONArry of arguments for the command.
* @return A CommandResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("getStatus")) {
int i = this.getStatus();
return new PluginResult(status, i);
}
else if (action.equals("start")) {
int i = this.start();
return new PluginResult(status, i);
}
else if (action.equals("stop")) {
this.stop();
return new PluginResult(status, 0);
}
else if (action.equals("getAcceleration")) {
// If not running, then this is an async call, so don't worry about waiting
if (this.status != AccelListener.RUNNING) {
int r = this.start();
if (r == AccelListener.ERROR_FAILED_TO_START) {
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
}
// Wait until running
long timeout = 2000;
while ((this.status == STARTING) && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (timeout == 0) {
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
}
}
JSONObject r = new JSONObject();
r.put("x", this.x);
r.put("y", this.y);
r.put("z", this.z);
// TODO: Should timestamp be sent?
r.put("timestamp", this.timestamp);
return new PluginResult(status, r);
}
else if (action.equals("setTimeout")) {
try {
float timeout = Float.parseFloat(args.getString(0));
this.setTimeout(timeout);
return new PluginResult(status, 0);
} catch (NumberFormatException e) {
status = PluginResult.Status.INVALID_ACTION;
e.printStackTrace();
} catch (JSONException e) {
status = PluginResult.Status.JSON_EXCEPTION;
e.printStackTrace();
}
}
else if (action.equals("getTimeout")) {
float f = this.getTimeout();
return new PluginResult(status, f);
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("getStatus")) {
return true;
}
else if (action.equals("getAcceleration")) {
// Can only return value if RUNNING
if (this.status == RUNNING) {
return true;
}
}
else if (action.equals("getTimeout")) {
return true;
}
return false;
}
/**
* Called when the system is about to start resuming a previous activity.
*/
public void onPause() {
}
/**
* Called when the activity will start interacting with the user.
*/
public void onResume() {
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
this.stop();
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Start listening for acceleration sensor.
*
* @return status of listener
*/
public int start() {
// If already starting or running, then just return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
return this.status;
}
// Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_FASTEST);
this.setStatus(AccelListener.STARTING);
this.lastAccessTime = System.currentTimeMillis();
}
// If error, then set status to error
else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
}
return this.status;
}
/**
* Stop listening to acceleration sensor.
*/
public void stop() {
if (this.status != AccelListener.STOPPED) {
this.sensorManager.unregisterListener(this);
}
this.setStatus(AccelListener.STOPPED);
}
/**
* Called when the accuracy of the sensor has changed.
*
* @param sensor
* @param accuracy
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/**
* Sensor listener event.
*
* @param SensorEvent event
*/
public void onSensorChanged(SensorEvent event) {
// Only look at accelerometer events
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
// Save time that event was received
this.timestamp = System.currentTimeMillis();
this.x = event.values[0];
this.y = event.values[1];
this.z = event.values[2];
this.setStatus(AccelListener.RUNNING);
// If values haven't been read for TIMEOUT time, then turn off accelerometer sensor to save power
if ((this.timestamp - this.lastAccessTime) > this.TIMEOUT) {
this.stop();
}
}
/**
* Get status of accelerometer sensor.
*
* @return status
*/
public int getStatus() {
return this.status;
}
/**
* Set the timeout to turn off accelerometer sensor if getX() hasn't been called.
*
* @param timeout Timeout in msec.
*/
public void setTimeout(float timeout) {
this.TIMEOUT = timeout;
}
/**
* Get the timeout to turn off accelerometer sensor if getX() hasn't been called.
*
* @return timeout in msec
*/
public float getTimeout() {
return this.TIMEOUT;
}
/**
* Set the status and send it to JavaScript.
* @param status
*/
private void setStatus(int status) {
this.status = status;
}
}
| Update lastAccessTime when calling getAcceleration() so we don't timeout.
| framework/src/com/phonegap/AccelListener.java | Update lastAccessTime when calling getAcceleration() so we don't timeout. |
|
Java | apache-2.0 | 070f883cb0990a94b3caaf2071fdbcfc655bf705 | 0 | BrunoEberhard/minimal-j,BrunoEberhard/minimal-j,BrunoEberhard/minimal-j | src/main/java/org/minimalj/model/annotation/Access.java | package org.minimalj.model.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation specifies the needed role to access a field or
* a transaction class. If more than role is listed
* the user must have at least one of the roles.
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Access {
// roles
String[] value() default {};
}
| Access: removed dead class | src/main/java/org/minimalj/model/annotation/Access.java | Access: removed dead class |
||
Java | apache-2.0 | e91a1642943ba586f259d05949d1fbedd6260b42 | 0 | bonigarcia/mastering-junit5,bonigarcia/mastering-junit5 | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 io.github.bonigarcia;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class LoginControllerLoginTest {
// Mocking objects
@InjectMocks
LoginController loginController;
@Mock
LoginService loginService;
// Test data
UserForm userForm = new UserForm("foo", "bar");
@Test
void testLoginOk() {
// Setting expectations (stubbing methods)
when(loginService.login(userForm)).thenReturn(true);
// Exercise SUT
String reseponseLogin = loginController.login(userForm);
// Verification
assertEquals("OK", reseponseLogin);
verify(loginService).login(userForm);
verifyNoMoreInteractions(loginService);
}
@Test
void testLoginKo() {
// Setting expectations (stubbing methods)
when(loginService.login(userForm)).thenReturn(false);
// Exercise SUT
String reseponseLogin = loginController.login(userForm);
// Verification
assertEquals("KO", reseponseLogin);
verify(loginService).login(userForm);
}
}
| junit5-mockito/src/test/java/io/github/bonigarcia/LoginControllerLoginTest.java | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 io.github.bonigarcia;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class LoginControllerLoginTest {
// Mocking objects
@InjectMocks
LoginController loginController;
@Mock
LoginService loginService;
// Test data
UserForm userForm = new UserForm("foo", "bar");
@Test
void testLoginOk() {
// Setting expectations (stubbing methods)
when(loginService.login(userForm)).thenReturn(true);
// Exercise SUT
String reseponseLogin = loginController.login(userForm);
// Verification
assertEquals("OK", reseponseLogin);
verify(loginService).login(userForm);
verifyNoMoreInteractions(loginService);
}
@Test
void testLoginKo() {
// Setting expectations (stubbing methods)
when(loginService.login(userForm)).thenReturn(false);
// Exercise SUT
String reseponseLogin = loginController.login(userForm);
// Verification
assertEquals("KO", reseponseLogin);
verify(loginService).login(userForm);
verifyNoInteractions(loginService);
}
}
| Fix assertion in mockito test
| junit5-mockito/src/test/java/io/github/bonigarcia/LoginControllerLoginTest.java | Fix assertion in mockito test |
|
Java | bsd-3-clause | 5a5e91e98d412cad37bb6fa7eb6d396eb992ce67 | 0 | interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl | // @@@ msg combining AND lrmc at the same time is not supported
// @@@ TODO? LRMC echt een ring maken, zodat je weet dat de mcast klaar is ->
// handig als een node om updates/object vraagt
/*
* Created on Apr 26, 2006 by rob
*/
package ibis.satin.impl.sharedObjects;
import ibis.ipl.IbisIdentifier;
import ibis.ipl.PortType;
import ibis.ipl.ReadMessage;
import ibis.ipl.ReceivePort;
import ibis.ipl.ReceivePortIdentifier;
import ibis.ipl.SendPort;
import ibis.ipl.WriteMessage;
import ibis.satin.SharedObject;
import ibis.satin.impl.Config;
import ibis.satin.impl.Satin;
import ibis.satin.impl.communication.Communication;
import ibis.satin.impl.communication.Protocol;
import ibis.satin.impl.loadBalancing.Victim;
import ibis.satin.impl.spawnSync.InvocationRecord;
import ibis.util.DeepCopy;
import ibis.util.Timer;
import ibis.util.TypedProperties;
import ibis.util.messagecombining.MessageCombiner;
import ibis.util.messagecombining.MessageSplitter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import mcast.object.ObjectMulticaster;
import mcast.object.SendDoneUpcaller;
class OmcInfo implements Config {
HashMap<Integer, Timer> map = new HashMap<Integer, Timer>();
Timer total = Timer.createTimer();
Satin s;
public OmcInfo(Satin s) {
this.s = s;
}
synchronized void registerSend(int id) {
Timer t = Timer.createTimer();
map.put(id, t);
t.start();
}
public synchronized void sendDone(int id) {
Timer t = map.remove(id);
if (t == null) {
soLogger.info("SATIN '" + s.ident
+ "': got upcall for unknow id: " + id);
return;
}
t.stop();
total.add(t);
soLogger.info("SATIN '" + s.ident + "': broadcast " + id
+ " took " + t.totalTime());
}
void end() {
soLogger.info("SATIN '" + s.ident
+ "': total broadcast time was: " + total.totalTime());
}
}
final class SOCommunication implements Config, Protocol, SendDoneUpcaller {
private static final boolean ASYNC_SO_BCAST = false;
private final static int WAIT_FOR_UPDATES_TIME = 60000;
public static final boolean DISABLE_SO_BCAST = false;
private Satin s;
/** the current size of the accumulated so messages */
private long soCurrTotalMessageSize = 0;
private long soInvocationsDelayTimer = -1;
/** used to broadcast shared object invocations */
private SendPort soSendPort;
private PortType soPortType;
/** used to do message combining on soSendPort */
private MessageCombiner soMessageCombiner;
/** a list of ibis identifiers that we still need to connect to */
private ArrayList<IbisIdentifier> toConnect =
new ArrayList<IbisIdentifier>();
private HashMap<IbisIdentifier, ReceivePortIdentifier> ports =
new HashMap<IbisIdentifier, ReceivePortIdentifier>();
private ObjectMulticaster omc;
private SharedObject sharedObject = null;
private boolean receivedNack = false;
private OmcInfo omcInfo;
protected SOCommunication(Satin s) {
this.s = s;
}
protected void init() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
try {
omc = new ObjectMulticaster(s.comm.ibis,
true /* efficient multi-cluster */, false,
"satinSO", this);
omcInfo = new OmcInfo(s);
} catch (Exception e) {
System.err.println("cannot create OMC: " + e);
e.printStackTrace();
System.exit(1);
}
new SOInvocationReceiver(s, omc).start();
} else {
try {
soPortType = createSOPortType();
// Create a multicast port to bcast shared object invocations.
// Connections are established later.
soSendPort =
s.comm.ibis.createSendPort(soPortType,
"satin so port on " + s.ident);
if (SO_MAX_INVOCATION_DELAY > 0) {
TypedProperties props = new TypedProperties();
props.setProperty("ibis.serialization", "ibis");
soMessageCombiner = new MessageCombiner(props, soSendPort);
}
} catch (Exception e) {
commLogger.fatal("SATIN '" + s.ident
+ "': Could not start ibis: " + e, e);
System.exit(1); // Could not start ibis
}
}
}
private PortType createSOPortType() throws IOException {
return new PortType(
PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS,
PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS,
PortType.SERIALIZATION_OBJECT);
}
/**
* Creates SO receive ports for new Satin instances. Do this first, to make
* them available as soon as possible.
*/
protected void handleJoins(IbisIdentifier[] joiners) {
if(DISABLE_SO_BCAST) return;
// lrmc uses its own ports
if (LABEL_ROUTING_MCAST) {
for (int i = 0; i < joiners.length; i++) {
omc.addIbis(joiners[i]);
}
// Set the destination for the multicast.
// The victimtable does not contain the new joiners yet.
IbisIdentifier[] victims;
synchronized (s) {
victims = s.victims.getIbises();
}
HashSet<IbisIdentifier> destinations = new HashSet<IbisIdentifier>();
for (IbisIdentifier id : victims) {
destinations.add(id);
}
for (IbisIdentifier id : joiners) {
destinations.add(id);
}
omc.setDestination(destinations.toArray(new IbisIdentifier[destinations.size()]));
return;
}
for (int i = 0; i < joiners.length; i++) {
// create a receive port for this guy
try {
SOInvocationHandler soInvocationHandler =
new SOInvocationHandler(s);
ReceivePort rec;
rec =
s.comm.ibis.createReceivePort(soPortType,
"satin so receive port for " + joiners[i],
soInvocationHandler, s.ft
.getReceivePortConnectHandler(), null);
if (SO_MAX_INVOCATION_DELAY > 0) {
TypedProperties s = new TypedProperties();
s.setProperty("ibis.serialization", "ibis");
soInvocationHandler.setMessageSplitter(new MessageSplitter(
s, rec));
}
rec.enableConnections();
rec.enableMessageUpcalls();
} catch (Exception e) {
commLogger.fatal("SATIN '" + s.ident
+ "': Could not start ibis: " + e, e);
System.exit(1); // Could not start ibis
}
}
/** Add new connections to the soSendPort */
synchronized (s) {
for (int i = 0; i < joiners.length; i++) {
toConnect.add(joiners[i]);
}
}
}
protected void sendAccumulatedSOInvocations() {
if (SO_MAX_INVOCATION_DELAY <= 0) return;
long currTime = System.currentTimeMillis();
long elapsed = currTime - soInvocationsDelayTimer;
if (soInvocationsDelayTimer > 0
&& (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) {
try {
s.stats.broadcastSOInvocationsTimer.start();
soMessageCombiner.sendAccumulatedMessages();
} catch (IOException e) {
System.err.println("SATIN '" + s.ident
+ "': unable to broadcast shared object invocations " + e);
}
s.stats.soRealMessageCount++;
soCurrTotalMessageSize = 0;
soInvocationsDelayTimer = -1;
s.stats.broadcastSOInvocationsTimer.stop();
}
}
protected void broadcastSOInvocation(SOInvocationRecord r) {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
doBroadcastSOInvocationLRMC(r);
} else {
if (ASYNC_SO_BCAST) {
// We have to make a copy of the object first, the caller might modify it.
SOInvocationRecord copy =
(SOInvocationRecord) DeepCopy.deepCopy(r);
new AsyncBcaster(this, copy).start();
} else {
doBroadcastSOInvocation(r);
}
}
}
public void sendDone(int id) {
if (soLogger.isDebugEnabled()) {
soLogger.debug("SATIN '" + s.ident + "': got ACK for send "
+ id);
}
omcInfo.sendDone(id);
}
/** Broadcast an so invocation */
protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
if (tmp.length == 0) return;
}
soLogger.debug("SATIN '" + s.ident
+ "': broadcasting so invocation for: " + r.getObjectId());
s.stats.broadcastSOInvocationsTimer.start();
s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp);
try {
int id = omc.send(r);
omcInfo.registerSend(id);
} catch (Exception e) {
soLogger.warn("SOI mcast failed: " + e + " msg: " + e.getMessage());
}
s.stats.soInvocations++;
s.stats.soRealMessageCount++;
s.stats.soInvocationsBytes += omc.lastSize();
s.stats.broadcastSOInvocationsTimer.stop();
}
/** Broadcast an so invocation */
protected void doBroadcastSOInvocation(SOInvocationRecord r) {
long byteCount = 0;
WriteMessage w = null;
s.stats.broadcastSOInvocationsTimer.start();
connectSendPortToNewReceivers();
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
}
s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp);
if (soSendPort != null && soSendPort.connectedTo().length > 0) {
try {
if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining
w = soMessageCombiner.newMessage();
if (soInvocationsDelayTimer == -1) {
soInvocationsDelayTimer = System.currentTimeMillis();
}
} else {
w = soSendPort.newMessage();
}
w.writeByte(SO_INVOCATION);
w.writeObject(r);
byteCount = w.finish();
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
System.err
.println("SATIN '" + s.ident
+ "': unable to broadcast a shared object invocation: "
+ e);
}
if (SO_MAX_INVOCATION_DELAY > 0) {
soCurrTotalMessageSize += byteCount;
} else {
s.stats.soRealMessageCount++;
}
}
s.stats.soInvocations++;
s.stats.soInvocationsBytes += byteCount;
s.stats.broadcastSOInvocationsTimer.stop();
// Try to send immediately if needed.
// We might not reach a safe point for a considerable time.
if (SO_MAX_INVOCATION_DELAY > 0) {
sendAccumulatedSOInvocations();
}
}
/**
* This basicaly is optional, if nodes don't have the object, they will
* retrieve it. However, one broadcast is more efficient (serialization is
* done only once). We MUST use message combining here, we use the same receiveport
* as the SO invocation messages. This is only called by exportObject.
*/
protected void broadcastSharedObject(SharedObject object) {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
doBroadcastSharedObjectLRMC(object);
} else {
doBroadcastSharedObject(object);
}
}
protected void doBroadcastSharedObject(SharedObject object) {
WriteMessage w = null;
long size = 0;
s.stats.soBroadcastTransferTimer.start();
connectSendPortToNewReceivers();
if (soSendPort == null) {
s.stats.soBroadcastTransferTimer.stop();
return;
}
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
}
s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp);
try {
if (SO_MAX_INVOCATION_DELAY > 0) {
//do message combining
w = soMessageCombiner.newMessage();
} else {
w = soSendPort.newMessage();
}
w.writeByte(SO_TRANSFER);
s.stats.soBroadcastSerializationTimer.start();
w.writeObject(object);
s.stats.soBroadcastSerializationTimer.stop();
size = w.finish();
w = null;
if (SO_MAX_INVOCATION_DELAY > 0) {
soMessageCombiner.sendAccumulatedMessages();
}
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
System.err.println("SATIN '" + s.ident
+ "': unable to broadcast a shared object: " + e);
}
s.stats.soBcasts++;
s.stats.soBcastBytes += size;
s.stats.soBroadcastTransferTimer.stop();
}
/** Broadcast an so invocation */
protected void doBroadcastSharedObjectLRMC(SharedObject object) {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
if (tmp.length == 0) return;
}
soLogger.debug("SATIN '" + s.ident + "': broadcasting object: "
+ object.getObjectId());
s.stats.soBroadcastTransferTimer.start();
s.so.registerMulticast(object, tmp);
try {
s.stats.soBroadcastSerializationTimer.start();
int id = omc.send(object);
omcInfo.registerSend(id);
s.stats.soBroadcastSerializationTimer.stop();
} catch (Exception e) {
System.err.println("WARNING, SO mcast failed: " + e + " msg: "
+ e.getMessage());
e.printStackTrace();
}
s.stats.soBcasts++;
s.stats.soBcastBytes += omc.lastSize();
s.stats.soBroadcastTransferTimer.stop();
}
/** Remove a connection to the soSendPort */
protected void removeSOConnection(IbisIdentifier id) {
Satin.assertLocked(s);
ReceivePortIdentifier r = ports.remove(id);
if (r != null) {
Communication.disconnect(soSendPort, r);
}
}
/** Fetch a shared object from another node.
* If the Invocation record is null, any version is OK, we just test that we have a
* version of the object. If it is not null, we try to satisfy the guard of the
* invocation record. It might not be satisfied when this method returns, the
* guard might depend on more than one shared object. */
protected void fetchObject(String objectId, IbisIdentifier source,
InvocationRecord r) throws SOReferenceSourceCrashedException {
/*
soLogger.debug("SATIN '" + s.ident + "': sending SO request "
+ (r == null ? "FIRST TIME" : "GUARD"));
// first, ask for the object
sendSORequest(objectId, source, false);
boolean gotIt = waitForSOReply();
if (gotIt) {
soLogger.debug("SATIN '" + s.ident
+ "': received the object after requesting it");
return;
}
soLogger
.debug("SATIN '"
+ s.ident
+ "': received NACK, the object is probably already being broadcast to me, WAITING");
*/
// got a nack back, the source thinks it sent it to me.
// wait for the object to arrive. If it doesn't, demand the object.
long start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - start > WAIT_FOR_UPDATES_TIME)
break;
synchronized (s) {
try {
s.wait(500);
} catch (InterruptedException e) {
// Ignore
}
}
s.handleDelayedMessages();
if (r == null) {
if (s.so.getSOInfo(objectId) != null) {
soLogger.debug("SATIN '" + s.ident
+ "': received new object from a bcast");
return; // got it!
}
} else {
if (r.guard()) {
soLogger.debug("SATIN '" + s.ident
+ "': received object, guard satisfied");
return;
}
}
}
soLogger.debug("SATIN '" + s.ident
+ "': did not receive object in time, demanding it now");
// haven't got it, demand it now.
sendSORequest(objectId, source, true);
boolean gotIt = waitForSOReply();
if (gotIt) {
soLogger.debug("SATIN '" + s.ident
+ "': received demanded object");
return;
}
soLogger
.fatal("SATIN '"
+ s.ident
+ "': internal error: did not receive shared object after I demanded it. ");
}
private void sendSORequest(String objectId, IbisIdentifier source,
boolean demand) throws SOReferenceSourceCrashedException {
// request the shared object from the source
WriteMessage w = null;
try {
s.lb.setCurrentVictim(source);
Victim v;
synchronized (s) {
v = s.victims.getVictim(source);
}
if (v == null) {
// hm we've got a problem here
// push the job somewhere else?
soLogger.error("SATIN '" + s.ident + "': could not "
+ "write shared-object request");
throw new SOReferenceSourceCrashedException();
}
w = v.newMessage();
if (demand) {
w.writeByte(SO_DEMAND);
} else {
w.writeByte(SO_REQUEST);
}
w.writeString(objectId);
v.finish(w);
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
// hm we've got a problem here
// push the job somewhere else?
soLogger.error("SATIN '" + s.ident + "': could not "
+ "write shared-object request", e);
throw new SOReferenceSourceCrashedException();
}
}
private boolean waitForSOReply() throws SOReferenceSourceCrashedException {
// wait for the reply
// there are three possibilities:
// 1. we get the object back -> return true
// 2. we get a nack back -> return false
// 3. the source crashed -> exception
while (true) {
synchronized (s) {
if (sharedObject != null) {
s.so.addObject(sharedObject);
sharedObject = null;
s.currentVictimCrashed = false;
soLogger.info("SATIN '" + s.ident
+ "': received shared object");
return true;
}
if (s.currentVictimCrashed) {
s.currentVictimCrashed = false;
// the source has crashed, abort the job
soLogger.info("SATIN '" + s.ident
+ "': source crashed while waiting for SO reply");
throw new SOReferenceSourceCrashedException();
}
if (receivedNack) {
receivedNack = false;
s.currentVictimCrashed = false;
soLogger.info("SATIN '" + s.ident
+ "': received shared object NACK");
return false;
}
try {
s.wait();
} catch (Exception e) {
// ignore
}
}
}
}
boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) {
if (System.currentTimeMillis() - info.lastBroadcastTime > WAIT_FOR_UPDATES_TIME) {
return false;
}
for (int i = 0; i < info.destinations.length; i++) {
if (info.destinations[i].equals(dest)) return true;
}
return false;
}
protected void handleSORequests() {
WriteMessage wm = null;
IbisIdentifier origin;
String objid;
boolean demand;
while (true) {
Victim v;
synchronized (s) {
if (s.so.SORequestList.getCount() == 0) {
s.so.gotSORequests = false;
return;
}
origin = s.so.SORequestList.getRequester(0);
objid = s.so.SORequestList.getobjID(0);
demand = s.so.SORequestList.isDemand(0);
s.so.SORequestList.removeIndex(0);
v = s.victims.getVictim(origin);
}
if (v == null) {
soLogger.debug("SATIN '" + s.ident
+ "': vicim crached in handleSORequest");
continue; // node might have crashed
}
SharedObjectInfo info = s.so.getSOInfo(objid);
if (ASSERTS && info == null) {
soLogger.fatal("SATIN '" + s.ident
+ "': EEEK, requested shared object: " + objid
+ " not found! Exiting..");
System.exit(1); // Failed assertion
}
if (!demand && broadcastInProgress(info, v.getIdent())) {
soLogger.debug("SATIN '" + s.ident
+ "': send NACK back in handleSORequest");
// send NACK back
try {
wm = v.newMessage();
wm.writeByte(SO_NACK);
v.finish(wm);
} catch (IOException e) {
if (wm != null) {
wm.finish(e);
}
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending"
+ " shared object NACK", e);
}
continue;
}
soLogger.debug("SATIN '" + s.ident
+ "': send object back in handleSORequest");
sendObjectBack(v, info);
}
}
private void sendObjectBack(Victim v, SharedObjectInfo info) {
WriteMessage wm = null;
long size;
// No need to hold the lock while writing the object.
// Updates cannot change the state of the object during the send,
// they are delayed until safe a point.
s.stats.soTransferTimer.start();
SharedObject so = info.sharedObject;
try {
wm = v.newMessage();
wm.writeByte(SO_TRANSFER);
} catch (IOException e) {
s.stats.soTransferTimer.stop();
if (wm != null) {
wm.finish(e);
}
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
return;
}
s.stats.soSerializationTimer.start();
try {
wm.writeObject(so);
} catch (IOException e) {
s.stats.soSerializationTimer.stop();
s.stats.soTransferTimer.stop();
wm.finish(e);
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
return;
}
s.stats.soSerializationTimer.stop();
try {
size = v.finish(wm);
} catch (IOException e) {
s.stats.soTransferTimer.stop();
wm.finish(e);
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
return;
}
s.stats.soTransfers++;
s.stats.soTransfersBytes += size;
s.stats.soTransferTimer.stop();
}
protected void handleSORequest(ReadMessage m, boolean demand) {
String objid = null;
IbisIdentifier origin = m.origin().ibisIdentifier();
soLogger.info("SATIN '" + s.ident + "': got so request");
try {
objid = m.readString();
// no need to finish the message. We don't do any communication
} catch (IOException e) {
soLogger.warn("SATIN '" + s.ident
+ "': got exception while reading" + " shared object request: "
+ e.getMessage());
}
synchronized (s) {
s.so.addToSORequestList(origin, objid, demand);
}
}
/**
* Receive a shared object from another node (called by the MessageHandler
*/
protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject)
SharedObject obj = null;
s.stats.soDeserializationTimer.start();
try {
obj = (SharedObject) m.readObject();
} catch (IOException e) {
soLogger.error("SATIN '" + s.ident
+ "': got exception while reading" + " shared object", e);
} catch (ClassNotFoundException e) {
soLogger.error("SATIN '" + s.ident
+ "': got exception while reading" + " shared object", e);
}
s.stats.soDeserializationTimer.stop();
// no need to finish the read message here.
// We don't block and don't do any communication
synchronized (s) {
sharedObject = obj;
s.notifyAll();
}
}
protected void handleSONack(ReadMessage m) {
synchronized (s) {
receivedNack = true;
s.notifyAll();
}
}
private void connectSOSendPort(IbisIdentifier ident) {
ReceivePortIdentifier r =
Communication.connect(soSendPort, ident,
"satin so receiveport for " + s.ident,
Satin.CONNECT_TIMEOUT);
if (r != null) {
synchronized (s) {
ports.put(ident, r);
}
} else {
soLogger.warn("SATIN '" + s.ident
+ "': unable to connect to SO receive port ");
// We won't broadcast the object to this receiver.
// This is not really a problem, it will get the object if it
// needs it. But the node has probably crashed anyway.
return;
}
}
private void connectSendPortToNewReceivers() {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = new IbisIdentifier[toConnect.size()];
for (int i = 0; i < toConnect.size(); i++) {
tmp[i] = toConnect.get(i);
}
toConnect.clear();
}
// do not keep the lock during connection setup
for (int i = 0; i < tmp.length; i++) {
connectSOSendPort(tmp[i]);
}
}
public void handleMyOwnJoin() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
omc.addIbis(s.ident);
}
}
public void handleCrash(IbisIdentifier id) {
if (LABEL_ROUTING_MCAST) {
omc.removeIbis(id);
omc.setDestination(s.victims.getIbises());
}
}
protected void exit() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
omc.done();
omcInfo.end();
}
}
static class AsyncBcaster extends Thread {
private SOCommunication c;
private SOInvocationRecord r;
AsyncBcaster(SOCommunication c, SOInvocationRecord r) {
this.c = c;
this.r = r;
}
public void run() {
c.doBroadcastSOInvocation(r);
}
}
}
| src/ibis/satin/impl/sharedObjects/SOCommunication.java | // @@@ msg combining AND lrmc at the same time is not supported
// @@@ TODO? LRMC echt een ring maken, zodat je weet dat de mcast klaar is ->
// handig als een node om updates/object vraagt
/*
* Created on Apr 26, 2006 by rob
*/
package ibis.satin.impl.sharedObjects;
import ibis.ipl.IbisIdentifier;
import ibis.ipl.PortType;
import ibis.ipl.ReadMessage;
import ibis.ipl.ReceivePort;
import ibis.ipl.ReceivePortIdentifier;
import ibis.ipl.SendPort;
import ibis.ipl.WriteMessage;
import ibis.satin.SharedObject;
import ibis.satin.impl.Config;
import ibis.satin.impl.Satin;
import ibis.satin.impl.communication.Communication;
import ibis.satin.impl.communication.Protocol;
import ibis.satin.impl.loadBalancing.Victim;
import ibis.satin.impl.spawnSync.InvocationRecord;
import ibis.util.DeepCopy;
import ibis.util.Timer;
import ibis.util.TypedProperties;
import ibis.util.messagecombining.MessageCombiner;
import ibis.util.messagecombining.MessageSplitter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import mcast.object.ObjectMulticaster;
import mcast.object.SendDoneUpcaller;
class OmcInfo implements Config {
HashMap<Integer, Timer> map = new HashMap<Integer, Timer>();
Timer total = Timer.createTimer();
Satin s;
public OmcInfo(Satin s) {
this.s = s;
}
synchronized void registerSend(int id) {
Timer t = Timer.createTimer();
map.put(id, t);
t.start();
}
public synchronized void sendDone(int id) {
Timer t = map.remove(id);
if (t == null) {
soLogger.info("SATIN '" + s.ident
+ "': got upcall for unknow id: " + id);
return;
}
t.stop();
total.add(t);
soLogger.info("SATIN '" + s.ident + "': broadcast " + id
+ " took " + t.totalTime());
}
void end() {
soLogger.info("SATIN '" + s.ident
+ "': total broadcast time was: " + total.totalTime());
}
}
final class SOCommunication implements Config, Protocol, SendDoneUpcaller {
private static final boolean ASYNC_SO_BCAST = false;
private final static int WAIT_FOR_UPDATES_TIME = 60000;
public static final boolean DISABLE_SO_BCAST = false;
private Satin s;
/** the current size of the accumulated so messages */
private long soCurrTotalMessageSize = 0;
private long soInvocationsDelayTimer = -1;
/** used to broadcast shared object invocations */
private SendPort soSendPort;
private PortType soPortType;
/** used to do message combining on soSendPort */
private MessageCombiner soMessageCombiner;
/** a list of ibis identifiers that we still need to connect to */
private ArrayList<IbisIdentifier> toConnect =
new ArrayList<IbisIdentifier>();
private HashMap<IbisIdentifier, ReceivePortIdentifier> ports =
new HashMap<IbisIdentifier, ReceivePortIdentifier>();
private ObjectMulticaster omc;
private SharedObject sharedObject = null;
private boolean receivedNack = false;
private OmcInfo omcInfo;
protected SOCommunication(Satin s) {
this.s = s;
}
protected void init() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
try {
omc = new ObjectMulticaster(s.comm.ibis,
true /* efficient multi-cluster */, false,
"satinSO", this);
omcInfo = new OmcInfo(s);
} catch (Exception e) {
System.err.println("cannot create OMC: " + e);
e.printStackTrace();
System.exit(1);
}
new SOInvocationReceiver(s, omc).start();
} else {
try {
soPortType = createSOPortType();
// Create a multicast port to bcast shared object invocations.
// Connections are established later.
soSendPort =
s.comm.ibis.createSendPort(soPortType,
"satin so port on " + s.ident);
if (SO_MAX_INVOCATION_DELAY > 0) {
TypedProperties props = new TypedProperties();
props.setProperty("ibis.serialization", "ibis");
soMessageCombiner = new MessageCombiner(props, soSendPort);
}
} catch (Exception e) {
commLogger.fatal("SATIN '" + s.ident
+ "': Could not start ibis: " + e, e);
System.exit(1); // Could not start ibis
}
}
}
private PortType createSOPortType() throws IOException {
return new PortType(
PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS,
PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS,
PortType.SERIALIZATION_OBJECT);
}
/**
* Creates SO receive ports for new Satin instances. Do this first, to make
* them available as soon as possible.
*/
protected void handleJoins(IbisIdentifier[] joiners) {
if(DISABLE_SO_BCAST) return;
// lrmc uses its own ports
if (LABEL_ROUTING_MCAST) {
for (int i = 0; i < joiners.length; i++) {
omc.addIbis(joiners[i]);
}
// Set the destination for the multicast.
// The victimtable does not contain the new joiners yet.
IbisIdentifier[] victims;
synchronized (s) {
victims = s.victims.getIbises();
}
HashSet<IbisIdentifier> destinations = new HashSet<IbisIdentifier>();
for (IbisIdentifier id : victims) {
destinations.add(id);
}
for (IbisIdentifier id : joiners) {
destinations.add(id);
}
omc.setDestination(destinations.toArray(new IbisIdentifier[destinations.size()]));
return;
}
for (int i = 0; i < joiners.length; i++) {
// create a receive port for this guy
try {
SOInvocationHandler soInvocationHandler =
new SOInvocationHandler(s);
ReceivePort rec;
rec =
s.comm.ibis.createReceivePort(soPortType,
"satin so receive port for " + joiners[i],
soInvocationHandler, s.ft
.getReceivePortConnectHandler(), null);
if (SO_MAX_INVOCATION_DELAY > 0) {
TypedProperties s = new TypedProperties();
s.setProperty("ibis.serialization", "ibis");
soInvocationHandler.setMessageSplitter(new MessageSplitter(
s, rec));
}
rec.enableConnections();
rec.enableMessageUpcalls();
} catch (Exception e) {
commLogger.fatal("SATIN '" + s.ident
+ "': Could not start ibis: " + e, e);
System.exit(1); // Could not start ibis
}
}
/** Add new connections to the soSendPort */
synchronized (s) {
for (int i = 0; i < joiners.length; i++) {
toConnect.add(joiners[i]);
}
}
}
protected void sendAccumulatedSOInvocations() {
if (SO_MAX_INVOCATION_DELAY <= 0) return;
long currTime = System.currentTimeMillis();
long elapsed = currTime - soInvocationsDelayTimer;
if (soInvocationsDelayTimer > 0
&& (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) {
try {
s.stats.broadcastSOInvocationsTimer.start();
soMessageCombiner.sendAccumulatedMessages();
} catch (IOException e) {
System.err.println("SATIN '" + s.ident
+ "': unable to broadcast shared object invocations " + e);
}
s.stats.soRealMessageCount++;
soCurrTotalMessageSize = 0;
soInvocationsDelayTimer = -1;
s.stats.broadcastSOInvocationsTimer.stop();
}
}
protected void broadcastSOInvocation(SOInvocationRecord r) {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
doBroadcastSOInvocationLRMC(r);
} else {
if (ASYNC_SO_BCAST) {
// We have to make a copy of the object first, the caller might modify it.
SOInvocationRecord copy =
(SOInvocationRecord) DeepCopy.deepCopy(r);
new AsyncBcaster(this, copy).start();
} else {
doBroadcastSOInvocation(r);
}
}
}
public void sendDone(int id) {
if (soLogger.isDebugEnabled()) {
soLogger.debug("SATIN '" + s.ident + "': got ACK for send "
+ id);
}
omcInfo.sendDone(id);
}
/** Broadcast an so invocation */
protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
if (tmp.length == 0) return;
}
soLogger.debug("SATIN '" + s.ident
+ "': broadcasting so invocation for: " + r.getObjectId());
s.stats.broadcastSOInvocationsTimer.start();
s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp);
try {
int id = omc.send(r);
omcInfo.registerSend(id);
} catch (Exception e) {
soLogger.warn("SOI mcast failed: " + e + " msg: " + e.getMessage());
}
s.stats.soInvocations++;
s.stats.soRealMessageCount++;
s.stats.soInvocationsBytes += omc.lastSize();
s.stats.broadcastSOInvocationsTimer.stop();
}
/** Broadcast an so invocation */
protected void doBroadcastSOInvocation(SOInvocationRecord r) {
long byteCount = 0;
WriteMessage w = null;
s.stats.broadcastSOInvocationsTimer.start();
connectSendPortToNewReceivers();
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
}
s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp);
if (soSendPort != null && soSendPort.connectedTo().length > 0) {
try {
if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining
w = soMessageCombiner.newMessage();
if (soInvocationsDelayTimer == -1) {
soInvocationsDelayTimer = System.currentTimeMillis();
}
} else {
w = soSendPort.newMessage();
}
w.writeByte(SO_INVOCATION);
w.writeObject(r);
byteCount = w.finish();
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
System.err
.println("SATIN '" + s.ident
+ "': unable to broadcast a shared object invocation: "
+ e);
}
if (SO_MAX_INVOCATION_DELAY > 0) {
soCurrTotalMessageSize += byteCount;
} else {
s.stats.soRealMessageCount++;
}
}
s.stats.soInvocations++;
s.stats.soInvocationsBytes += byteCount;
s.stats.broadcastSOInvocationsTimer.stop();
// Try to send immediately if needed.
// We might not reach a safe point for a considerable time.
if (SO_MAX_INVOCATION_DELAY > 0) {
sendAccumulatedSOInvocations();
}
}
/**
* This basicaly is optional, if nodes don't have the object, they will
* retrieve it. However, one broadcast is more efficient (serialization is
* done only once). We MUST use message combining here, we use the same receiveport
* as the SO invocation messages. This is only called by exportObject.
*/
protected void broadcastSharedObject(SharedObject object) {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
doBroadcastSharedObjectLRMC(object);
} else {
doBroadcastSharedObject(object);
}
}
protected void doBroadcastSharedObject(SharedObject object) {
WriteMessage w = null;
long size = 0;
s.stats.soBroadcastTransferTimer.start();
connectSendPortToNewReceivers();
if (soSendPort == null) {
s.stats.soBroadcastTransferTimer.stop();
return;
}
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
}
s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp);
try {
if (SO_MAX_INVOCATION_DELAY > 0) {
//do message combining
w = soMessageCombiner.newMessage();
} else {
w = soSendPort.newMessage();
}
w.writeByte(SO_TRANSFER);
s.stats.soBroadcastSerializationTimer.start();
w.writeObject(object);
s.stats.soBroadcastSerializationTimer.stop();
size = w.finish();
w = null;
if (SO_MAX_INVOCATION_DELAY > 0) {
soMessageCombiner.sendAccumulatedMessages();
}
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
System.err.println("SATIN '" + s.ident
+ "': unable to broadcast a shared object: " + e);
}
s.stats.soBcasts++;
s.stats.soBcastBytes += size;
s.stats.soBroadcastTransferTimer.stop();
}
/** Broadcast an so invocation */
protected void doBroadcastSharedObjectLRMC(SharedObject object) {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = s.victims.getIbises();
if (tmp.length == 0) return;
}
soLogger.debug("SATIN '" + s.ident + "': broadcasting object: "
+ object.getObjectId());
s.stats.soBroadcastTransferTimer.start();
s.so.registerMulticast(object, tmp);
try {
s.stats.soBroadcastSerializationTimer.start();
int id = omc.send(object);
omcInfo.registerSend(id);
s.stats.soBroadcastSerializationTimer.stop();
} catch (Exception e) {
System.err.println("WARNING, SO mcast failed: " + e + " msg: "
+ e.getMessage());
e.printStackTrace();
}
s.stats.soBcasts++;
s.stats.soBcastBytes += omc.lastSize();
s.stats.soBroadcastTransferTimer.stop();
}
/** Remove a connection to the soSendPort */
protected void removeSOConnection(IbisIdentifier id) {
Satin.assertLocked(s);
ReceivePortIdentifier r = ports.remove(id);
if (r != null) {
Communication.disconnect(soSendPort, r);
}
}
/** Fetch a shared object from another node.
* If the Invocation record is null, any version is OK, we just test that we have a
* version of the object. If it is not null, we try to satisfy the guard of the
* invocation record. It might not be satisfied when this method returns, the
* guard might depend on more than one shared object. */
protected void fetchObject(String objectId, IbisIdentifier source,
InvocationRecord r) throws SOReferenceSourceCrashedException {
/*
soLogger.debug("SATIN '" + s.ident + "': sending SO request "
+ (r == null ? "FIRST TIME" : "GUARD"));
// first, ask for the object
sendSORequest(objectId, source, false);
boolean gotIt = waitForSOReply();
if (gotIt) {
soLogger.debug("SATIN '" + s.ident
+ "': received the object after requesting it");
return;
}
soLogger
.debug("SATIN '"
+ s.ident
+ "': received NACK, the object is probably already being broadcast to me, WAITING");
*/
// got a nack back, the source thinks it sent it to me.
// wait for the object to arrive. If it doesn't, demand the object.
long start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - start > WAIT_FOR_UPDATES_TIME)
break;
synchronized (s) {
try {
s.wait(500);
} catch (InterruptedException e) {
// Ignore
}
}
s.handleDelayedMessages();
if (r == null) {
if (s.so.getSOInfo(objectId) != null) {
soLogger.debug("SATIN '" + s.ident
+ "': received new object from a bcast");
return; // got it!
}
} else {
if (r.guard()) {
soLogger.debug("SATIN '" + s.ident
+ "': received object, guard satisfied");
return;
}
}
}
soLogger.debug("SATIN '" + s.ident
+ "': did not receive object in time, demanding it now");
// haven't got it, demand it now.
sendSORequest(objectId, source, true);
boolean gotIt = waitForSOReply();
if (gotIt) {
soLogger.debug("SATIN '" + s.ident
+ "': received demanded object");
return;
}
soLogger
.fatal("SATIN '"
+ s.ident
+ "': internal error: did not receive shared object after I demanded it. ");
}
private void sendSORequest(String objectId, IbisIdentifier source,
boolean demand) throws SOReferenceSourceCrashedException {
// request the shared object from the source
WriteMessage w = null;
try {
s.lb.setCurrentVictim(source);
Victim v;
synchronized (s) {
v = s.victims.getVictim(source);
}
if (v == null) {
// hm we've got a problem here
// push the job somewhere else?
soLogger.error("SATIN '" + s.ident + "': could not "
+ "write shared-object request");
throw new SOReferenceSourceCrashedException();
}
w = v.newMessage();
if (demand) {
w.writeByte(SO_DEMAND);
} else {
w.writeByte(SO_REQUEST);
}
w.writeString(objectId);
v.finish(w);
} catch (IOException e) {
if (w != null) {
w.finish(e);
}
// hm we've got a problem here
// push the job somewhere else?
soLogger.error("SATIN '" + s.ident + "': could not "
+ "write shared-object request", e);
throw new SOReferenceSourceCrashedException();
}
}
private boolean waitForSOReply() throws SOReferenceSourceCrashedException {
// wait for the reply
// there are three possibilities:
// 1. we get the object back -> return true
// 2. we get a nack back -> return false
// 3. the source crashed -> exception
while (true) {
synchronized (s) {
if (sharedObject != null) {
s.so.addObject(sharedObject);
sharedObject = null;
s.currentVictimCrashed = false;
soLogger.info("SATIN '" + s.ident
+ "': received shared object");
return true;
}
if (s.currentVictimCrashed) {
s.currentVictimCrashed = false;
// the source has crashed, abort the job
soLogger.info("SATIN '" + s.ident
+ "': source crashed while waiting for SO reply");
throw new SOReferenceSourceCrashedException();
}
if (receivedNack) {
receivedNack = false;
s.currentVictimCrashed = false;
soLogger.info("SATIN '" + s.ident
+ "': received shared object NACK");
return false;
}
try {
s.wait();
} catch (Exception e) {
// ignore
}
}
}
}
boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) {
if (System.currentTimeMillis() - info.lastBroadcastTime > WAIT_FOR_UPDATES_TIME) {
return false;
}
for (int i = 0; i < info.destinations.length; i++) {
if (info.destinations[i].equals(dest)) return true;
}
return false;
}
protected void handleSORequests() {
WriteMessage wm = null;
IbisIdentifier origin;
String objid;
boolean demand;
while (true) {
Victim v;
synchronized (s) {
if (s.so.SORequestList.getCount() == 0) {
s.so.gotSORequests = false;
return;
}
origin = s.so.SORequestList.getRequester(0);
objid = s.so.SORequestList.getobjID(0);
demand = s.so.SORequestList.isDemand(0);
s.so.SORequestList.removeIndex(0);
v = s.victims.getVictim(origin);
}
if (v == null) {
soLogger.debug("SATIN '" + s.ident
+ "': vicim crached in handleSORequest");
continue; // node might have crashed
}
SharedObjectInfo info = s.so.getSOInfo(objid);
if (ASSERTS && info == null) {
soLogger.fatal("SATIN '" + s.ident
+ "': EEEK, requested shared object: " + objid
+ " not found! Exiting..");
System.exit(1); // Failed assertion
}
if (!demand && broadcastInProgress(info, v.getIdent())) {
soLogger.debug("SATIN '" + s.ident
+ "': send NACK back in handleSORequest");
// send NACK back
try {
wm = v.newMessage();
wm.writeByte(SO_NACK);
v.finish(wm);
} catch (IOException e) {
if (wm != null) {
wm.finish(e);
}
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending"
+ " shared object NACK", e);
}
continue;
}
soLogger.debug("SATIN '" + s.ident
+ "': send object back in handleSORequest");
sendObjectBack(v, info);
}
}
private void sendObjectBack(Victim v, SharedObjectInfo info) {
WriteMessage wm = null;
long size;
// No need to hold the lock while writing the object.
// Updates cannot change the state of the object during the send,
// they are delayed until safe a point.
s.stats.soTransferTimer.start();
SharedObject so = info.sharedObject;
try {
wm = v.newMessage();
wm.writeByte(SO_TRANSFER);
} catch (IOException e) {
if (wm != null) {
wm.finish(e);
}
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
s.stats.soTransferTimer.stop();
return;
}
s.stats.soSerializationTimer.start();
try {
wm.writeObject(so);
} catch (IOException e) {
wm.finish(e);
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
s.stats.soSerializationTimer.stop();
s.stats.soTransferTimer.stop();
return;
}
s.stats.soSerializationTimer.stop();
try {
size = v.finish(wm);
} catch (IOException e) {
wm.finish(e);
soLogger.error("SATIN '" + s.ident
+ "': got exception while sending" + " shared object", e);
s.stats.soTransferTimer.stop();
return;
}
s.stats.soTransfers++;
s.stats.soTransfersBytes += size;
s.stats.soTransferTimer.stop();
}
protected void handleSORequest(ReadMessage m, boolean demand) {
String objid = null;
IbisIdentifier origin = m.origin().ibisIdentifier();
soLogger.info("SATIN '" + s.ident + "': got so request");
try {
objid = m.readString();
// no need to finish the message. We don't do any communication
} catch (IOException e) {
soLogger.warn("SATIN '" + s.ident
+ "': got exception while reading" + " shared object request: "
+ e.getMessage());
}
synchronized (s) {
s.so.addToSORequestList(origin, objid, demand);
}
}
/**
* Receive a shared object from another node (called by the MessageHandler
*/
protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject)
SharedObject obj = null;
s.stats.soDeserializationTimer.start();
try {
obj = (SharedObject) m.readObject();
} catch (IOException e) {
soLogger.error("SATIN '" + s.ident
+ "': got exception while reading" + " shared object", e);
} catch (ClassNotFoundException e) {
soLogger.error("SATIN '" + s.ident
+ "': got exception while reading" + " shared object", e);
}
s.stats.soDeserializationTimer.stop();
// no need to finish the read message here.
// We don't block and don't do any communication
synchronized (s) {
sharedObject = obj;
s.notifyAll();
}
}
protected void handleSONack(ReadMessage m) {
synchronized (s) {
receivedNack = true;
s.notifyAll();
}
}
private void connectSOSendPort(IbisIdentifier ident) {
ReceivePortIdentifier r =
Communication.connect(soSendPort, ident,
"satin so receiveport for " + s.ident,
Satin.CONNECT_TIMEOUT);
if (r != null) {
synchronized (s) {
ports.put(ident, r);
}
} else {
soLogger.warn("SATIN '" + s.ident
+ "': unable to connect to SO receive port ");
// We won't broadcast the object to this receiver.
// This is not really a problem, it will get the object if it
// needs it. But the node has probably crashed anyway.
return;
}
}
private void connectSendPortToNewReceivers() {
IbisIdentifier[] tmp;
synchronized (s) {
tmp = new IbisIdentifier[toConnect.size()];
for (int i = 0; i < toConnect.size(); i++) {
tmp[i] = toConnect.get(i);
}
toConnect.clear();
}
// do not keep the lock during connection setup
for (int i = 0; i < tmp.length; i++) {
connectSOSendPort(tmp[i]);
}
}
public void handleMyOwnJoin() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
omc.addIbis(s.ident);
}
}
public void handleCrash(IbisIdentifier id) {
if (LABEL_ROUTING_MCAST) {
omc.removeIbis(id);
omc.setDestination(s.victims.getIbises());
}
}
protected void exit() {
if(DISABLE_SO_BCAST) return;
if (LABEL_ROUTING_MCAST) {
omc.done();
omcInfo.end();
}
}
static class AsyncBcaster extends Thread {
private SOCommunication c;
private SOInvocationRecord r;
AsyncBcaster(SOCommunication c, SOInvocationRecord r) {
this.c = c;
this.r = r;
}
public void run() {
c.doBroadcastSOInvocation(r);
}
}
}
|
git-svn-id: http://gforge.cs.vu.nl/svn/ibis/ibis/trunk@5875 aaf88347-d911-0410-b711-e54d386773bb
| src/ibis/satin/impl/sharedObjects/SOCommunication.java | ||
Java | isc | c0ebef23fbb36ed80ccc47969ea3423b13b53c45 | 0 | bsudekum/react-native-mapbox-gl,bsudekum/react-native-mapbox-gl,bsudekum/react-native-mapbox-gl,bsudekum/react-native-mapbox-gl |
package com.mapbox.reactnativemapboxgl;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.support.annotation.MainThread;
import android.support.annotation.UiThread;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.mapbox.mapboxsdk.MapboxAccountManager;
import com.mapbox.mapboxsdk.constants.MyLocationTracking;
import com.mapbox.mapboxsdk.constants.MyBearingTracking;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.offline.OfflineManager;
import com.mapbox.mapboxsdk.offline.OfflineRegion;
import com.mapbox.mapboxsdk.offline.OfflineRegionDefinition;
import com.mapbox.mapboxsdk.offline.OfflineRegionError;
import com.mapbox.mapboxsdk.offline.OfflineRegionStatus;
import com.mapbox.mapboxsdk.offline.OfflineTilePyramidRegionDefinition;
import com.mapbox.mapboxsdk.telemetry.MapboxEventManager;
import javax.annotation.Nullable;
public class ReactNativeMapboxGLModule extends ReactContextBaseJavaModule {
private static final String TAG = ReactNativeMapboxGLModule.class.getSimpleName();
private ReactApplicationContext context;
private ReactNativeMapboxGLPackage aPackage;
Handler mainHandler;
private int throttleInterval = 300;
private static boolean initialized = false;
public ReactNativeMapboxGLModule(ReactApplicationContext reactContext, ReactNativeMapboxGLPackage thePackage) {
super(reactContext);
this.mainHandler = new Handler(reactContext.getApplicationContext().getMainLooper());
this.context = reactContext;
this.aPackage = thePackage;
Log.d(TAG, "Context " + context);
Log.d(TAG, "reactContext " + reactContext);
}
@Override
public String getName() {
return "MapboxGLManager";
}
static private ArrayList<Integer> serializeTracking(int locationTracking, int bearingTracking) {
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(locationTracking);
result.add(bearingTracking);
return result;
}
public static final int[] locationTrackingModes = new int[] {
MyLocationTracking.TRACKING_NONE,
MyLocationTracking.TRACKING_FOLLOW,
MyLocationTracking.TRACKING_FOLLOW,
MyLocationTracking.TRACKING_FOLLOW
};
public static final int[] bearingTrackingModes = new int[] {
MyBearingTracking.NONE,
MyBearingTracking.NONE,
MyBearingTracking.GPS,
MyBearingTracking.COMPASS
};
@Override
public @Nullable Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
HashMap<String, Object> userTrackingMode = new HashMap<String, Object>();
HashMap<String, Object> mapStyles = new HashMap<String, Object>();
HashMap<String, Object> userLocationVerticalAlignment = new HashMap<String, Object>();
// User tracking constants
userTrackingMode.put("none", 0);
userTrackingMode.put("follow", 1);
userTrackingMode.put("followWithCourse", 2);
userTrackingMode.put("followWithHeading", 3);
// Style constants
mapStyles.put("light", Style.LIGHT);
mapStyles.put("dark", Style.DARK);
mapStyles.put("streets", Style.MAPBOX_STREETS);
mapStyles.put("emerald", Style.EMERALD);
mapStyles.put("satellite", Style.SATELLITE);
mapStyles.put("hybrid", Style.SATELLITE_STREETS);
// These need to be here for compatibility, even if they're not supported on Android
userLocationVerticalAlignment.put("center", 0);
userLocationVerticalAlignment.put("top", 1);
userLocationVerticalAlignment.put("bottom", 2);
// Other constants
constants.put("unknownResourceCount", Long.MAX_VALUE);
constants.put("metricsEnabled", MapboxEventManager.getMapboxEventManager().isTelemetryEnabled());
constants.put("userTrackingMode", userTrackingMode);
constants.put("mapStyles", mapStyles);
constants.put("userLocationVerticalAlignment", userLocationVerticalAlignment);
return constants;
}
// Access Token
@ReactMethod
public void setAccessToken(final String accessToken) {
if (accessToken == null || accessToken.length() == 0 || accessToken.equals("your-mapbox.com-access-token")) {
throw new JSApplicationIllegalArgumentException("Invalid access token. Register to mapbox.com and request an access token, then pass it to setAccessToken()");
}
if (initialized) {
String oldToken = MapboxAccountManager.getInstance().getAccessToken();
if (!oldToken.equals(accessToken)) {
throw new JSApplicationIllegalArgumentException("Mapbox access token cannot be initialized twice with different values");
}
return;
}
initialized = true;
mainHandler.post(new Runnable() {
@Override
public void run() {
MapboxAccountManager.start(context.getApplicationContext(), accessToken);
}
});
initializeOfflinePacks();
}
// Metrics
@ReactMethod
public void setMetricsEnabled(boolean value) {
MapboxEventManager.getMapboxEventManager().setTelemetryEnabled(value);
}
// Offline packs
// Offline pack events and initialization
class OfflineRegionProgressObserver implements OfflineRegion.OfflineRegionObserver {
ReactNativeMapboxGLModule module;
OfflineRegion region;
OfflineRegionStatus status;
String name;
boolean recentlyUpdated = false;
boolean throttled = true;
boolean invalid = false;
OfflineRegionProgressObserver(ReactNativeMapboxGLModule module, OfflineRegion region, String name) {
this.module = module;
this.region = region;
if (name == null) {
this.name = getOfflineRegionName(region);
} else {
this.name = name;
}
}
void fireUpdateEvent() {
if (invalid) { return; }
recentlyUpdated = true;
WritableMap event = serializeOfflineRegionStatus(region, this.status);
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineProgressDidChange", event);
module.mainHandler.postDelayed(new Runnable() {
@Override
public void run() {
recentlyUpdated = false;
if (throttled) {
throttled = false;
fireUpdateEvent();
}
}
}, throttleInterval);
}
@Override
public void onStatusChanged(OfflineRegionStatus status) {
if (invalid) { return; }
this.status = status;
if (!recentlyUpdated) {
fireUpdateEvent();
} else {
throttled = true;
}
}
@Override
public void onError(OfflineRegionError error) {
if (invalid) { return; }
WritableMap event = Arguments.createMap();
event.putString("name", getOfflineRegionName(region));
event.putString("error", error.toString());
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineError", event);
}
@Override
public void mapboxTileCountLimitExceeded(long limit) {
if (invalid) { return; }
WritableMap event = Arguments.createMap();
event.putString("name", getOfflineRegionName(region));
event.putDouble("maxTiles", limit);
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineMaxAllowedTiles", event);
}
public void invalidate() {
invalid = true;
}
}
private int uninitializedObserverCount = -1;
private ArrayList<OfflineRegionProgressObserver> offlinePackObservers = new ArrayList<>();
private ArrayList<Promise> offlinePackListingRequests = new ArrayList<>();
void flushListingRequests() {
WritableArray result = _getOfflinePacks();
for (Promise promise : offlinePackListingRequests) {
promise.resolve(result);
}
offlinePackListingRequests.clear();
}
class OfflineRegionsInitialRequest implements OfflineManager.ListOfflineRegionsCallback {
ReactNativeMapboxGLModule module;
OfflineRegionsInitialRequest(ReactNativeMapboxGLModule module) {
this.module = module;
}
@Override
public void onList(OfflineRegion[] offlineRegions) {
uninitializedObserverCount = offlineRegions.length;
for (OfflineRegion region : offlineRegions) {
final OfflineRegionProgressObserver observer = new OfflineRegionProgressObserver(module, region, null);
offlinePackObservers.add(observer);
region.setObserver(observer);
region.setDownloadState(OfflineRegion.STATE_ACTIVE);
region.getStatus(new OfflineRegion.OfflineRegionStatusCallback() {
@Override
public void onStatus(OfflineRegionStatus status) {
observer.onStatusChanged(status);
uninitializedObserverCount--;
if (uninitializedObserverCount == 0) {
flushListingRequests();
}
}
@Override
public void onError(String error) {
Log.e(context.getApplicationContext().getPackageName(), error);
}
});
}
}
@Override
public void onError(String error) {
Log.e(module.getReactApplicationContext().getPackageName(), error);
}
}
void initializeOfflinePacks() {
final ReactNativeMapboxGLModule _this = this;
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineManager.getInstance(context.getApplicationContext()).listOfflineRegions(
new OfflineRegionsInitialRequest(_this)
);
}
});
}
// Offline pack utils
static WritableMap serializeOfflineRegionStatus(OfflineRegion region, OfflineRegionStatus status) {
WritableMap result = Arguments.createMap();
try {
ByteArrayInputStream bis = new ByteArrayInputStream(region.getMetadata());
ObjectInputStream ois = new ObjectInputStream(bis);
result.putString("name", (String)ois.readObject());
result.putString("metadata", (String)ois.readObject());
ois.close();
} catch (Throwable e) {
e.printStackTrace();
}
result.putInt("countOfBytesCompleted", (int)status.getCompletedResourceSize());
result.putInt("countOfResourcesCompleted", (int)status.getCompletedResourceCount());
result.putInt("countOfResourcesExpected", (int)status.getRequiredResourceCount());
result.putInt("maximumResourcesExpected", (int)status.getRequiredResourceCount());
return result;
}
static String getOfflineRegionName(OfflineRegion region) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(region.getMetadata());
ObjectInputStream ois = new ObjectInputStream(bis);
String name = (String)ois.readObject();
ois.close();
return name;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
// Offline pack listing
WritableArray _getOfflinePacks() {
WritableArray result = Arguments.createArray();
for (OfflineRegionProgressObserver observer : offlinePackObservers) {
result.pushMap(serializeOfflineRegionStatus(observer.region, observer.status));
}
return result;
}
@ReactMethod
public void getOfflinePacks(final Promise promise) {
mainHandler.post(new Runnable() {
@Override
public void run() {
promise.resolve(_getOfflinePacks());
}
});
}
// Offline pack insertion
@ReactMethod
public void addOfflinePack(ReadableMap options, final Promise promise) {
if (!options.hasKey("name")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): name is required."));
return;
}
if (!options.hasKey("minZoomLevel")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): minZoomLevel is required."));
return;
}
if (!options.hasKey("maxZoomLevel")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): maxZoomLevel is required."));
return;
}
if (!options.hasKey("bounds")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): bounds is required."));
return;
}
if (!options.hasKey("styleURL")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): styleURL is required."));
return;
}
if (!options.hasKey("type")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): type is required."));
return;
}
if (!options.getString("type").equals("bbox")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): Offline pack type " +
options.getString("type") +
" not supported. Only \"bbox\" is currently supported."));
return;
}
float pixelRatio = context.getResources().getDisplayMetrics().density;
pixelRatio = pixelRatio < 1.5f ? 1.0f : 2.0f;
ReadableArray boundsArray = options.getArray("bounds");
LatLngBounds bounds = new LatLngBounds.Builder()
.include(new LatLng(boundsArray.getDouble(0), boundsArray.getDouble(1)))
.include(new LatLng(boundsArray.getDouble(2), boundsArray.getDouble(3)))
.build();
final OfflineTilePyramidRegionDefinition regionDef = new OfflineTilePyramidRegionDefinition(
options.getString("styleURL"),
bounds,
options.getDouble("minZoomLevel"),
options.getDouble("maxZoomLevel"),
pixelRatio
);
byte [] metadata;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(options.getString("name"));
oos.writeObject(options.getString("metadata"));
oos.close();
metadata = bos.toByteArray();
} catch (IOException e) {
promise.reject(e);
return;
}
final ReactNativeMapboxGLModule _this = this;
final byte [] _metadata = metadata;
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineManager.getInstance(context.getApplicationContext()).createOfflineRegion(
regionDef,
_metadata,
new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
OfflineRegionProgressObserver observer = new OfflineRegionProgressObserver(_this, offlineRegion, null);
offlinePackObservers.add(observer);
offlineRegion.setObserver(observer);
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
promise.resolve(null);
}
@Override
public void onError(String error) {
promise.reject(new JSApplicationIllegalArgumentException(error));
}
}
);
}
});
}
// Offline pack removal
@ReactMethod
public void removeOfflinePack(final String packName, final Promise promise) {
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineRegionProgressObserver foundObserver = null;
for (OfflineRegionProgressObserver observer : offlinePackObservers) {
if (packName.equals(observer.name)) {
foundObserver = observer;
break;
}
}
if (foundObserver == null) {
promise.resolve(Arguments.createMap());
return;
}
offlinePackObservers.remove(foundObserver);
foundObserver.invalidate();
foundObserver.region.setDownloadState(OfflineRegion.STATE_INACTIVE);
final OfflineRegionProgressObserver _foundObserver = foundObserver;
foundObserver.region.delete(new OfflineRegion.OfflineRegionDeleteCallback() {
@Override
public void onDelete() {
WritableMap result = Arguments.createMap();
result.putString("deleted", _foundObserver.name);
promise.resolve(result);
}
@Override
public void onError(String error) {
promise.reject(new JSApplicationIllegalArgumentException(error));
}
});
}
});
}
// Offline throttle control
@ReactMethod
public void setOfflinePackProgressThrottleInterval(int milis) {
throttleInterval = milis;
}
} | android/src/main/java/com/mapbox/reactnativemapboxgl/ReactNativeMapboxGLModule.java |
package com.mapbox.reactnativemapboxgl;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.support.annotation.MainThread;
import android.support.annotation.UiThread;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.mapbox.mapboxsdk.MapboxAccountManager;
import com.mapbox.mapboxsdk.constants.MyLocationTracking;
import com.mapbox.mapboxsdk.constants.MyBearingTracking;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.offline.OfflineManager;
import com.mapbox.mapboxsdk.offline.OfflineRegion;
import com.mapbox.mapboxsdk.offline.OfflineRegionDefinition;
import com.mapbox.mapboxsdk.offline.OfflineRegionError;
import com.mapbox.mapboxsdk.offline.OfflineRegionStatus;
import com.mapbox.mapboxsdk.offline.OfflineTilePyramidRegionDefinition;
import com.mapbox.mapboxsdk.telemetry.MapboxEventManager;
import javax.annotation.Nullable;
public class ReactNativeMapboxGLModule extends ReactContextBaseJavaModule {
private static final String TAG = ReactNativeMapboxGLModule.class.getSimpleName();
private ReactApplicationContext context;
private ReactNativeMapboxGLPackage aPackage;
Handler mainHandler;
private int throttleInterval = 300;
private static boolean initialized = false;
public ReactNativeMapboxGLModule(ReactApplicationContext reactContext, ReactNativeMapboxGLPackage thePackage) {
super(reactContext);
this.mainHandler = new Handler(reactContext.getApplicationContext().getMainLooper());
this.context = reactContext;
this.aPackage = thePackage;
Log.d(TAG, "Context " + context);
Log.d(TAG, "reactContext " + reactContext);
}
@Override
public String getName() {
return "MapboxGLManager";
}
static private ArrayList<Integer> serializeTracking(int locationTracking, int bearingTracking) {
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(locationTracking);
result.add(bearingTracking);
return result;
}
public static final int[] locationTrackingModes = new int[] {
MyLocationTracking.TRACKING_NONE,
MyLocationTracking.TRACKING_FOLLOW,
MyLocationTracking.TRACKING_FOLLOW,
MyLocationTracking.TRACKING_FOLLOW
};
public static final int[] bearingTrackingModes = new int[] {
MyBearingTracking.NONE,
MyBearingTracking.NONE,
MyBearingTracking.GPS,
MyBearingTracking.COMPASS
};
@Override
public @Nullable Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
HashMap<String, Object> userTrackingMode = new HashMap<String, Object>();
HashMap<String, Object> mapStyles = new HashMap<String, Object>();
HashMap<String, Object> userLocationVerticalAlignment = new HashMap<String, Object>();
// User tracking constants
userTrackingMode.put("none", 0);
userTrackingMode.put("follow", 1);
userTrackingMode.put("followWithCourse", 2);
userTrackingMode.put("followWithHeading", 3);
// Style constants
mapStyles.put("light", Style.LIGHT);
mapStyles.put("dark", Style.DARK);
mapStyles.put("streets", Style.MAPBOX_STREETS);
mapStyles.put("emerald", Style.EMERALD);
mapStyles.put("satellite", Style.SATELLITE);
mapStyles.put("hybrid", Style.SATELLITE_STREETS);
// These need to be here for compatibility, even if they're not supported on Android
userLocationVerticalAlignment.put("center", 0);
userLocationVerticalAlignment.put("top", 1);
userLocationVerticalAlignment.put("bottom", 2);
// Other constants
constants.put("unknownResourceCount", Long.MAX_VALUE);
constants.put("metricsEnabled", MapboxEventManager.getMapboxEventManager().isTelemetryEnabled());
constants.put("userTrackingMode", userTrackingMode);
constants.put("mapStyles", mapStyles);
constants.put("userLocationVerticalAlignment", userLocationVerticalAlignment);
return constants;
}
// Access Token
@ReactMethod
public void setAccessToken(String accessToken) {
if (accessToken == null || accessToken.length() == 0 || accessToken.equals("your-mapbox.com-access-token")) {
throw new JSApplicationIllegalArgumentException("Invalid access token. Register to mapbox.com and request an access token, then pass it to setAccessToken()");
}
if (initialized) {
String oldToken = MapboxAccountManager.getInstance().getAccessToken();
if (!oldToken.equals(accessToken)) {
throw new JSApplicationIllegalArgumentException("Mapbox access token cannot be initialized twice with different values");
}
return;
}
initialized = true;
MapboxAccountManager.start(context.getApplicationContext(), accessToken);
initializeOfflinePacks();
}
// Metrics
@ReactMethod
public void setMetricsEnabled(boolean value) {
MapboxEventManager.getMapboxEventManager().setTelemetryEnabled(value);
}
// Offline packs
// Offline pack events and initialization
class OfflineRegionProgressObserver implements OfflineRegion.OfflineRegionObserver {
ReactNativeMapboxGLModule module;
OfflineRegion region;
OfflineRegionStatus status;
String name;
boolean recentlyUpdated = false;
boolean throttled = true;
boolean invalid = false;
OfflineRegionProgressObserver(ReactNativeMapboxGLModule module, OfflineRegion region, String name) {
this.module = module;
this.region = region;
if (name == null) {
this.name = getOfflineRegionName(region);
} else {
this.name = name;
}
}
void fireUpdateEvent() {
if (invalid) { return; }
recentlyUpdated = true;
WritableMap event = serializeOfflineRegionStatus(region, this.status);
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineProgressDidChange", event);
module.mainHandler.postDelayed(new Runnable() {
@Override
public void run() {
recentlyUpdated = false;
if (throttled) {
throttled = false;
fireUpdateEvent();
}
}
}, throttleInterval);
}
@Override
public void onStatusChanged(OfflineRegionStatus status) {
if (invalid) { return; }
this.status = status;
if (!recentlyUpdated) {
fireUpdateEvent();
} else {
throttled = true;
}
}
@Override
public void onError(OfflineRegionError error) {
if (invalid) { return; }
WritableMap event = Arguments.createMap();
event.putString("name", getOfflineRegionName(region));
event.putString("error", error.toString());
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineError", event);
}
@Override
public void mapboxTileCountLimitExceeded(long limit) {
if (invalid) { return; }
WritableMap event = Arguments.createMap();
event.putString("name", getOfflineRegionName(region));
event.putDouble("maxTiles", limit);
module.getReactApplicationContext().getJSModule(RCTNativeAppEventEmitter.class)
.emit("MapboxOfflineMaxAllowedTiles", event);
}
public void invalidate() {
invalid = true;
}
}
private int uninitializedObserverCount = -1;
private ArrayList<OfflineRegionProgressObserver> offlinePackObservers = new ArrayList<>();
private ArrayList<Promise> offlinePackListingRequests = new ArrayList<>();
void flushListingRequests() {
WritableArray result = _getOfflinePacks();
for (Promise promise : offlinePackListingRequests) {
promise.resolve(result);
}
offlinePackListingRequests.clear();
}
class OfflineRegionsInitialRequest implements OfflineManager.ListOfflineRegionsCallback {
ReactNativeMapboxGLModule module;
OfflineRegionsInitialRequest(ReactNativeMapboxGLModule module) {
this.module = module;
}
@Override
public void onList(OfflineRegion[] offlineRegions) {
uninitializedObserverCount = offlineRegions.length;
for (OfflineRegion region : offlineRegions) {
final OfflineRegionProgressObserver observer = new OfflineRegionProgressObserver(module, region, null);
offlinePackObservers.add(observer);
region.setObserver(observer);
region.setDownloadState(OfflineRegion.STATE_ACTIVE);
region.getStatus(new OfflineRegion.OfflineRegionStatusCallback() {
@Override
public void onStatus(OfflineRegionStatus status) {
observer.onStatusChanged(status);
uninitializedObserverCount--;
if (uninitializedObserverCount == 0) {
flushListingRequests();
}
}
@Override
public void onError(String error) {
Log.e(context.getApplicationContext().getPackageName(), error);
}
});
}
}
@Override
public void onError(String error) {
Log.e(module.getReactApplicationContext().getPackageName(), error);
}
}
void initializeOfflinePacks() {
final ReactNativeMapboxGLModule _this = this;
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineManager.getInstance(context.getApplicationContext()).listOfflineRegions(
new OfflineRegionsInitialRequest(_this)
);
}
});
}
// Offline pack utils
static WritableMap serializeOfflineRegionStatus(OfflineRegion region, OfflineRegionStatus status) {
WritableMap result = Arguments.createMap();
try {
ByteArrayInputStream bis = new ByteArrayInputStream(region.getMetadata());
ObjectInputStream ois = new ObjectInputStream(bis);
result.putString("name", (String)ois.readObject());
result.putString("metadata", (String)ois.readObject());
ois.close();
} catch (Throwable e) {
e.printStackTrace();
}
result.putInt("countOfBytesCompleted", (int)status.getCompletedResourceSize());
result.putInt("countOfResourcesCompleted", (int)status.getCompletedResourceCount());
result.putInt("countOfResourcesExpected", (int)status.getRequiredResourceCount());
result.putInt("maximumResourcesExpected", (int)status.getRequiredResourceCount());
return result;
}
static String getOfflineRegionName(OfflineRegion region) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(region.getMetadata());
ObjectInputStream ois = new ObjectInputStream(bis);
String name = (String)ois.readObject();
ois.close();
return name;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
// Offline pack listing
WritableArray _getOfflinePacks() {
WritableArray result = Arguments.createArray();
for (OfflineRegionProgressObserver observer : offlinePackObservers) {
result.pushMap(serializeOfflineRegionStatus(observer.region, observer.status));
}
return result;
}
@ReactMethod
public void getOfflinePacks(final Promise promise) {
mainHandler.post(new Runnable() {
@Override
public void run() {
promise.resolve(_getOfflinePacks());
}
});
}
// Offline pack insertion
@ReactMethod
public void addOfflinePack(ReadableMap options, final Promise promise) {
if (!options.hasKey("name")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): name is required."));
return;
}
if (!options.hasKey("minZoomLevel")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): minZoomLevel is required."));
return;
}
if (!options.hasKey("maxZoomLevel")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): maxZoomLevel is required."));
return;
}
if (!options.hasKey("bounds")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): bounds is required."));
return;
}
if (!options.hasKey("styleURL")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): styleURL is required."));
return;
}
if (!options.hasKey("type")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): type is required."));
return;
}
if (!options.getString("type").equals("bbox")) {
promise.reject(new JSApplicationIllegalArgumentException("addOfflinePack(): Offline pack type " +
options.getString("type") +
" not supported. Only \"bbox\" is currently supported."));
return;
}
float pixelRatio = context.getResources().getDisplayMetrics().density;
pixelRatio = pixelRatio < 1.5f ? 1.0f : 2.0f;
ReadableArray boundsArray = options.getArray("bounds");
LatLngBounds bounds = new LatLngBounds.Builder()
.include(new LatLng(boundsArray.getDouble(0), boundsArray.getDouble(1)))
.include(new LatLng(boundsArray.getDouble(2), boundsArray.getDouble(3)))
.build();
final OfflineTilePyramidRegionDefinition regionDef = new OfflineTilePyramidRegionDefinition(
options.getString("styleURL"),
bounds,
options.getDouble("minZoomLevel"),
options.getDouble("maxZoomLevel"),
pixelRatio
);
byte [] metadata;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(options.getString("name"));
oos.writeObject(options.getString("metadata"));
oos.close();
metadata = bos.toByteArray();
} catch (IOException e) {
promise.reject(e);
return;
}
final ReactNativeMapboxGLModule _this = this;
final byte [] _metadata = metadata;
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineManager.getInstance(context.getApplicationContext()).createOfflineRegion(
regionDef,
_metadata,
new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
OfflineRegionProgressObserver observer = new OfflineRegionProgressObserver(_this, offlineRegion, null);
offlinePackObservers.add(observer);
offlineRegion.setObserver(observer);
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
promise.resolve(null);
}
@Override
public void onError(String error) {
promise.reject(new JSApplicationIllegalArgumentException(error));
}
}
);
}
});
}
// Offline pack removal
@ReactMethod
public void removeOfflinePack(final String packName, final Promise promise) {
mainHandler.post(new Runnable() {
@Override
public void run() {
OfflineRegionProgressObserver foundObserver = null;
for (OfflineRegionProgressObserver observer : offlinePackObservers) {
if (packName.equals(observer.name)) {
foundObserver = observer;
break;
}
}
if (foundObserver == null) {
promise.resolve(Arguments.createMap());
return;
}
offlinePackObservers.remove(foundObserver);
foundObserver.invalidate();
foundObserver.region.setDownloadState(OfflineRegion.STATE_INACTIVE);
final OfflineRegionProgressObserver _foundObserver = foundObserver;
foundObserver.region.delete(new OfflineRegion.OfflineRegionDeleteCallback() {
@Override
public void onDelete() {
WritableMap result = Arguments.createMap();
result.putString("deleted", _foundObserver.name);
promise.resolve(result);
}
@Override
public void onError(String error) {
promise.reject(new JSApplicationIllegalArgumentException(error));
}
});
}
});
}
// Offline throttle control
@ReactMethod
public void setOfflinePackProgressThrottleInterval(int milis) {
throttleInterval = milis;
}
} | ensure that MapboxAccountManager class is always created from the main thread; fixes crash from Android SDK 4.2.0-beta.4 and up (#517)
| android/src/main/java/com/mapbox/reactnativemapboxgl/ReactNativeMapboxGLModule.java | ensure that MapboxAccountManager class is always created from the main thread; fixes crash from Android SDK 4.2.0-beta.4 and up (#517) |
|
Java | mit | d31310ace87476cee260fd2afaa7627eb07ba471 | 0 | MylesIsCool/ViaVersion | package us.myles.ViaVersion.api.protocol;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.platform.ViaPlatform;
import us.myles.ViaVersion.packets.Direction;
import us.myles.ViaVersion.packets.State;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
public class ProtocolPipeline extends SimpleProtocol {
private List<Protocol> protocolList;
private UserConnection userConnection;
public ProtocolPipeline(UserConnection userConnection) {
super();
init(userConnection);
}
@Override
protected void registerPackets() {
protocolList = new CopyOnWriteArrayList<>();
// This is a pipeline so we register basic pipes
protocolList.add(ProtocolRegistry.BASE_PROTOCOL);
}
@Override
public void init(UserConnection userConnection) {
this.userConnection = userConnection;
ProtocolInfo protocolInfo = new ProtocolInfo(userConnection);
protocolInfo.setPipeline(this);
userConnection.setProtocolInfo(protocolInfo);
/* Init through all our pipes */
for (Protocol protocol : protocolList) {
protocol.init(userConnection);
}
}
/**
* Add a protocol to the current pipeline
* This will call the {@link Protocol#init(UserConnection)} method.
*
* @param protocol The protocol to add to the end
*/
public void add(Protocol protocol) {
if (protocolList != null) {
protocolList.add(protocol);
protocol.init(userConnection);
// Move base Protocols to the end, so the login packets can be modified by other protocols
List<Protocol> toMove = new ArrayList<>();
for (Protocol p : protocolList) {
if (ProtocolRegistry.isBaseProtocol(p)) {
toMove.add(p);
}
}
protocolList.removeAll(toMove);
protocolList.addAll(toMove);
} else {
throw new NullPointerException("Tried to add protocol too early");
}
}
@Override
public void transform(Direction direction, State state, PacketWrapper packetWrapper) throws Exception {
int originalID = packetWrapper.getId();
List<Protocol> protocols = new ArrayList<>(protocolList);
// Other way if outgoing
if (direction == Direction.OUTGOING)
Collections.reverse(protocols);
// Apply protocols
packetWrapper.apply(direction, state, 0, protocols);
super.transform(direction, state, packetWrapper);
if (Via.getManager().isDebug()) {
// Debug packet
int serverProtocol = userConnection.getProtocolInfo().getServerProtocolVersion();
int clientProtocol = userConnection.getProtocolInfo().getProtocolVersion();
ViaPlatform platform = Via.getPlatform();
String actualUsername = packetWrapper.user().getProtocolInfo().getUsername();
String username = actualUsername != null ? actualUsername + " " : "";
platform.getLogger().log(Level.INFO, "{0}{1} {2}: {3} (0x{4}) -> {5} (0x{6}) [{7}] {8}",
new Object[]{
username,
direction,
state,
originalID,
Integer.toHexString(originalID),
packetWrapper.getId(),
Integer.toHexString(packetWrapper.getId()),
Integer.toString(clientProtocol),
packetWrapper
});
}
}
/**
* Check if the pipeline contains a protocol
*
* @param pipeClass The class to check
* @return True if the protocol class is in the pipeline
*/
public boolean contains(Class<? extends Protocol> pipeClass) {
for (Protocol protocol : protocolList) {
if (protocol.getClass().equals(pipeClass)) return true;
}
return false;
}
public <P extends Protocol> P getProtocol(Class<P> pipeClass) {
for (Protocol protocol : protocolList) {
if (protocol.getClass() == pipeClass) return (P) protocol;
}
return null;
}
/**
* Use the pipeline to filter a NMS packet
*
* @param o The NMS packet object
* @param list The output list to write to
* @return If it should not write the input object to te list.
* @throws Exception If it failed to convert / packet cancelld.
*/
public boolean filter(Object o, List list) throws Exception {
for (Protocol protocol : protocolList) {
if (protocol.isFiltered(o.getClass())) {
protocol.filterPacket(userConnection, o, list);
return true;
}
}
return false;
}
public List<Protocol> pipes() {
return protocolList;
}
/**
* Cleans the pipe and adds {@link us.myles.ViaVersion.protocols.base.BaseProtocol}
* /!\ WARNING - It doesn't add version-specific base Protocol
*/
public void cleanPipes() {
pipes().clear();
registerPackets();
}
}
| common/src/main/java/us/myles/ViaVersion/api/protocol/ProtocolPipeline.java | package us.myles.ViaVersion.api.protocol;
import com.google.common.collect.Lists;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.platform.ViaPlatform;
import us.myles.ViaVersion.packets.Direction;
import us.myles.ViaVersion.packets.State;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
public class ProtocolPipeline extends SimpleProtocol {
private List<Protocol> incoming;
private List<Protocol> outgoing;
private UserConnection userConnection;
public ProtocolPipeline(UserConnection userConnection) {
super();
init(userConnection);
}
@Override
protected void registerPackets() {
incoming = new CopyOnWriteArrayList<>();
outgoing = Lists.reverse(incoming);
// This is a pipeline so we register basic pipes
incoming.add(ProtocolRegistry.BASE_PROTOCOL);
}
@Override
public void init(UserConnection userConnection) {
this.userConnection = userConnection;
ProtocolInfo protocolInfo = new ProtocolInfo(userConnection);
protocolInfo.setPipeline(this);
userConnection.setProtocolInfo(protocolInfo);
/* Init through all our pipes */
for (Protocol protocol : incoming) {
protocol.init(userConnection);
}
}
/**
* Add a protocol to the current pipeline
* This will call the {@link Protocol#init(UserConnection)} method.
*
* @param protocol The protocol to add to the end
*/
public void add(Protocol protocol) {
if (incoming != null) {
incoming.add(protocol);
protocol.init(userConnection);
// Move base Protocols to the end, so the login packets can be modified by other protocols
List<Protocol> toMove = new ArrayList<>();
for (Protocol p : incoming) {
if (ProtocolRegistry.isBaseProtocol(p)) {
toMove.add(p);
}
}
incoming.removeAll(toMove);
incoming.addAll(toMove);
} else {
throw new NullPointerException("Tried to add protocol too early");
}
}
@Override
public void transform(Direction direction, State state, PacketWrapper packetWrapper) throws Exception {
int originalID = packetWrapper.getId();
List<Protocol> protocols = direction == Direction.OUTGOING ? outgoing : incoming;
// Apply protocols
packetWrapper.apply(direction, state, 0, protocols);
super.transform(direction, state, packetWrapper);
if (Via.getManager().isDebug()) {
logPacket(direction, state, packetWrapper, originalID);
}
}
private void logPacket(Direction direction, State state, PacketWrapper packetWrapper, int originalID) {
// Debug packet
int clientProtocol = userConnection.getProtocolInfo().getProtocolVersion();
ViaPlatform platform = Via.getPlatform();
String actualUsername = packetWrapper.user().getProtocolInfo().getUsername();
String username = actualUsername != null ? actualUsername + " " : "";
platform.getLogger().log(Level.INFO, "{0}{1} {2}: {3} (0x{4}) -> {5} (0x{6}) [{7}] {8}",
new Object[]{
username,
direction,
state,
originalID,
Integer.toHexString(originalID),
packetWrapper.getId(),
Integer.toHexString(packetWrapper.getId()),
Integer.toString(clientProtocol),
packetWrapper
});
}
/**
* Check if the pipeline contains a protocol
*
* @param pipeClass The class to check
* @return True if the protocol class is in the pipeline
*/
public boolean contains(Class<? extends Protocol> pipeClass) {
for (Protocol protocol : incoming) {
if (protocol.getClass().equals(pipeClass)) return true;
}
return false;
}
public <P extends Protocol> P getProtocol(Class<P> pipeClass) {
for (Protocol protocol : incoming) {
if (protocol.getClass() == pipeClass) return (P) protocol;
}
return null;
}
/**
* Use the pipeline to filter a NMS packet
*
* @param o The NMS packet object
* @param list The output list to write to
* @return If it should not write the input object to te list.
* @throws Exception If it failed to convert / packet cancelld.
*/
public boolean filter(Object o, List list) throws Exception {
for (Protocol protocol : incoming) {
if (protocol.isFiltered(o.getClass())) {
protocol.filterPacket(userConnection, o, list);
return true;
}
}
return false;
}
public List<Protocol> pipes() {
return incoming;
}
/**
* Cleans the pipe and adds {@link us.myles.ViaVersion.protocols.base.BaseProtocol}
* /!\ WARNING - It doesn't add version-specific base Protocol
*/
public void cleanPipes() {
pipes().clear();
registerPackets();
}
}
| Fix bad ProtocolPipeline changes
| common/src/main/java/us/myles/ViaVersion/api/protocol/ProtocolPipeline.java | Fix bad ProtocolPipeline changes |
|
Java | mit | 74d8c5c2528e5540c5b385bcb3d3a25be5ed146a | 0 | Carboni/jenkins-jobs,davidcarboni/jenkins-jobs | //package com.github.davidcanboni.jenkins;
//
//import com.github.davidcanboni.jenkins.values.Environment;
//import com.github.davidcanboni.jenkins.values.JobCategory;
//import com.github.davidcanboni.jenkins.xml.Xml;
//import com.github.davidcarboni.ResourceUtils;
//import com.github.onsdigital.http.Endpoint;
//import com.github.onsdigital.http.Http;
//import com.github.onsdigital.http.Response;
//import org.apache.commons.lang3.StringUtils;
//import org.w3c.dom.Document;
//import org.w3c.dom.Node;
//
//import javax.xml.xpath.*;
//import java.io.IOException;
//import java.net.URL;
//import java.nio.file.Path;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Handles jobs in the Monitoring category.
// */
//public class MonitorJobs {
//
// static String xpath = "//hudson.model.StringParameterDefinition/defaultValue";
//
// public static Document setUrl(URL url) throws IOException {
// Document document = ResourceUtils.getXml(Templates.configMonitor);
// setUrl(url, document);
// return document;
// }
//
// public static void setUrl(URL url, Document document) throws IOException {
// Xml.setTextValue(document, xpath, url.toString());
// XPath xPath = XPathFactory.newInstance().newXPath();
// Node node;
// try {
// XPathExpression xPathExpression = xPath.compile(xpath);
// node = (Node) xPathExpression.evaluate(document, XPathConstants.NODE);
// } catch (XPathExpressionException e) {
// throw new RuntimeException("Invalid xpath expression: " + xpath);
// }
// node.setTextContent(url.toString());
// }
//
//
// public static void create(String jobName, URL url) throws IOException {
//
// String host = url.getHost() + url.getPath();
// String password = StringUtils.isNotBlank(url.getUserInfo()) ? " (with password)" : "";
//
// if (StringUtils.isNotBlank(jobName)) {
// try (Http http = new Http()) {
//
// http.addHeader("Content-Type", "application/xml");
//
// if (!Jobs.exists(jobName)) {
//
// System.out.println("Creating job " + jobName + " - " + host + password);
//
// // Set the URL and create:
// Document config = setUrl(url);
// create(jobName, config, http);
//
// } else {
//
// System.out.println("Updating job " + jobName + " - " + host + password);
// Endpoint endpoint = new Endpoint(Jobs.jenkins, "/job/" + jobName + "/config.xml");
// Response<Path> xml = http.get(endpoint);
// if (xml.statusLine.getStatusCode() != 200)
// throw new RuntimeException("Error reading configuration for job " + jobName + ": " + xml.statusLine.getReasonPhrase());
// Document config = Xml.fromFile(xml.body);
//
// // Set the URL and update:
// setUrl(url, config);
// update(jobName, config, http, endpoint);
//
// }
//
// }
// }
// }
//
// public static String jobName(String name) {
// return JobCategory.Monitor + " " + name;
// }
//
// public static String jobNameWebsite(Environment environment) {
// return JobCategory.Monitor + " Website " + environment.name();
// }
//
// public static String jobNamePublishing(Environment environment) {
// return JobCategory.Monitor + " Publishing " + environment.name();
// }
//
// private static void create(String jobName, Document config, Http http) throws IOException {
//
//
// // Post the config XML to create the job
// Endpoint endpoint = Jobs.createItem.setParameter("name", jobName);
// Response<String> create = http.post(endpoint, config, String.class);
// if (create.statusLine.getStatusCode() != 200) {
// System.out.println(create.body);
// throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase());
// }
// }
//
// private static void update(String jobName, Document config, Http http, Endpoint endpoint) throws IOException {
//
// // Post the config XML to update the job
// Response<String> create = http.post(endpoint, config, String.class);
// if (create.statusLine.getStatusCode() != 200) {
// System.out.println(create.body);
// throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase());
// }
// }
//
//
// public static void main(String[] args) throws IOException {
// Map<String, URL> monitors = new HashMap<>();
//
// for (Environment environment : Environment.values()) {
// monitors.put(jobNameWebsite(environment), environment.website());
// monitors.put(jobNamePublishing(environment), environment.publishing());
// }
//
// monitors.put(jobName("Jenkins"), Environment.jenkins());
// // Unlikely we need to monitor Docker Hub
// //monitors.put(jobName("Registry"), Environment.registry());
// monitors.put(jobName("Nexus"), Environment.nexus());
//
// for (Map.Entry<String, URL> entry : monitors.entrySet()) {
// String name = entry.getKey();
// URL url = entry.getValue();
// //create(name, url);
// }
// }
//}
| src/main/java/com/github/davidcanboni/jenkins/MonitorJobs.java | package com.github.davidcanboni.jenkins;
import com.github.davidcanboni.jenkins.values.Environment;
import com.github.davidcanboni.jenkins.values.JobCategory;
import com.github.davidcanboni.jenkins.xml.Xml;
import com.github.davidcarboni.ResourceUtils;
import com.github.onsdigital.http.Endpoint;
import com.github.onsdigital.http.Http;
import com.github.onsdigital.http.Response;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.xpath.*;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* Handles jobs in the Monitoring category.
*/
public class MonitorJobs {
static String xpath = "//hudson.model.StringParameterDefinition/defaultValue";
public static Document setUrl(URL url) throws IOException {
Document document = ResourceUtils.getXml(Templates.configMonitor);
setUrl(url, document);
return document;
}
public static void setUrl(URL url, Document document) throws IOException {
Xml.setTextValue(document, xpath, url.toString());
XPath xPath = XPathFactory.newInstance().newXPath();
Node node;
try {
XPathExpression xPathExpression = xPath.compile(xpath);
node = (Node) xPathExpression.evaluate(document, XPathConstants.NODE);
} catch (XPathExpressionException e) {
throw new RuntimeException("Invalid xpath expression: " + xpath);
}
node.setTextContent(url.toString());
}
public static void create(String jobName, URL url) throws IOException {
String host = url.getHost() + url.getPath();
String password = StringUtils.isNotBlank(url.getUserInfo()) ? " (with password)" : "";
if (StringUtils.isNotBlank(jobName)) {
try (Http http = new Http()) {
http.addHeader("Content-Type", "application/xml");
if (!Jobs.exists(jobName)) {
System.out.println("Creating job " + jobName + " - " + host + password);
// Set the URL and create:
Document config = setUrl(url);
create(jobName, config, http);
} else {
System.out.println("Updating job " + jobName + " - " + host + password);
Endpoint endpoint = new Endpoint(Jobs.jenkins, "/job/" + jobName + "/config.xml");
Response<Path> xml = http.get(endpoint);
if (xml.statusLine.getStatusCode() != 200)
throw new RuntimeException("Error reading configuration for job " + jobName + ": " + xml.statusLine.getReasonPhrase());
Document config = Xml.fromFile(xml.body);
// Set the URL and update:
setUrl(url, config);
update(jobName, config, http, endpoint);
}
}
}
}
public static String jobName(String name) {
return JobCategory.Monitor + " " + name;
}
public static String jobNameWebsite(Environment environment) {
return JobCategory.Monitor + " Website " + environment.name();
}
public static String jobNamePublishing(Environment environment) {
return JobCategory.Monitor + " Publishing " + environment.name();
}
private static void create(String jobName, Document config, Http http) throws IOException {
// Post the config XML to create the job
Endpoint endpoint = Jobs.createItem.setParameter("name", jobName);
Response<String> create = http.post(endpoint, config, String.class);
if (create.statusLine.getStatusCode() != 200) {
System.out.println(create.body);
throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase());
}
}
private static void update(String jobName, Document config, Http http, Endpoint endpoint) throws IOException {
// Post the config XML to update the job
Response<String> create = http.post(endpoint, config, String.class);
if (create.statusLine.getStatusCode() != 200) {
System.out.println(create.body);
throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase());
}
}
public static void main(String[] args) throws IOException {
Map<String, URL> monitors = new HashMap<>();
for (Environment environment : Environment.values()) {
monitors.put(jobNameWebsite(environment), environment.website());
monitors.put(jobNamePublishing(environment), environment.publishing());
}
monitors.put(jobName("Jenkins"), Environment.jenkins());
// Unlikely we need to monitor Docker Hub
//monitors.put(jobName("Registry"), Environment.registry());
monitors.put(jobName("Nexus"), Environment.nexus());
for (Map.Entry<String, URL> entry : monitors.entrySet()) {
String name = entry.getKey();
URL url = entry.getValue();
//create(name, url);
}
}
}
| No longer used, so commented out.
| src/main/java/com/github/davidcanboni/jenkins/MonitorJobs.java | No longer used, so commented out. |
|
Java | mit | 48fb8f66d6852c938dc77d22c4fb8e914d973dbd | 0 | lare96/luna | package io.luna.game.model.mobile;
import io.luna.LunaContext;
import io.luna.game.action.Action;
import io.luna.game.action.ActionSet;
import io.luna.game.model.Direction;
import io.luna.game.model.Entity;
import io.luna.game.model.EntityType;
import io.luna.game.model.Position;
import io.luna.game.model.mobile.attr.AttributeMap;
import io.luna.game.model.mobile.update.UpdateFlagHolder;
import io.luna.game.model.mobile.update.UpdateFlagHolder.UpdateFlag;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
/**
* Something that exists in the Runescape world and is able to move around.
*
* @author lare96 <http://github.org/lare96>
*/
public abstract class MobileEntity extends Entity {
/**
* An {@link AttributeMap} instance assigned to this {@code MobileEntity}.
*/
protected final AttributeMap attributes = new AttributeMap();
/**
* An {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}.
*/
protected final UpdateFlagHolder updateFlags = new UpdateFlagHolder();
/**
* The {@link SkillSet} for this {@code MobileEntity}.
*/
protected final SkillSet skills = new SkillSet(this);
/**
* The {@link ActionSet} for this {@code MobileEntity}.
*/
protected final ActionSet actions = new ActionSet();
/**
* The {@link WalkingQueue} assigned to this {@code MobileEntity}.
*/
protected final WalkingQueue walkingQueue = new WalkingQueue(this);
/**
* The index of this mob in its list.
*/
private int index = -1;
/**
* The walking direction of this {@code MobileEntity}.
*/
private Direction walkingDirection = Direction.NONE;
/**
* The running direction of this {@code MobileEntity}.
*/
private Direction runningDirection = Direction.NONE;
/**
* If this {@code MobileEntity} is teleporting.
*/
private boolean teleporting = true;
/**
* The {@link Animation} to perform this cycle.
*/
private Animation animation;
/**
* The {@link Position} to face this cycle.
*/
private Position facePosition;
/**
* The chat to forcibly display this cycle.
*/
private String forceChat;
/**
* The {@link Graphic} to perform this cycle.
*/
private Graphic graphic;
/**
* The {@code MobileEntity} to interact with this cycle.
*/
private int interactionIndex = -1;
/**
* The primary {@link Hit} to display this cycle.
*/
private Hit primaryHit;
/**
* The secondary {@link Hit} to perform this cycle.
*/
private Hit secondaryHit;
/**
* The {@link Entity} currently being interacted with.
*/
private Optional<Entity> interactingWith = Optional.empty();
/**
* Creates a new {@link MobileEntity}.
*
* @param context The context to be managed in.
*/
public MobileEntity(LunaContext context) {
super(context);
}
/**
* Clears flags specific to certain types of {@code MobileEntity}s.
*/
public abstract void reset();
/**
* Shortcut to function {@link ActionSet#submit(Action)}.
*/
public final void submitAction(Action<? extends MobileEntity> pending) {
actions.submit(pending);
}
/**
* Shortcut to function {@link ActionSet#interrupt()}.
*/
public final void interruptAction() {
actions.interrupt();
}
/**
* Teleports this {@code MobileEntity} to {@code position}.
*
* @param position The {@link Position} to teleport to.
*/
public final void teleport(Position position) {
setPosition(position);
teleporting = true;
walkingQueue.clear();
}
/**
* Perform {@code animation} on this cycle.
*
* @param newAnimation The {@link Animation} to perform this cycle.
*/
public final void animation(Animation newAnimation) {
if (animation == null || animation.getPriority().getValue() <= newAnimation.getPriority().getValue()) {
animation = requireNonNull(newAnimation);
updateFlags.flag(UpdateFlag.ANIMATION);
}
}
/**
* Face {@code facePosition} on this cycle.
*
* @param facePosition The {@link Position} to face this cycle.
*/
public final void face(Position facePosition) {
this.facePosition = requireNonNull(facePosition);
updateFlags.flag(UpdateFlag.FACE_POSITION);
}
/**
* Force the chat message {@code forceChat} on this cycle.
*
* @param forceChat The chat to forcibly display this cycle.
*/
public final void forceChat(String forceChat) {
this.forceChat = requireNonNull(forceChat);
updateFlags.flag(UpdateFlag.FORCE_CHAT);
}
/**
* Perform {@code graphic} on this cycle.
*
* @param graphic The {@link Graphic} to perform this cycle.
*/
public final void graphic(Graphic graphic) {
this.graphic = requireNonNull(graphic);
updateFlags.flag(UpdateFlag.GRAPHIC);
}
/**
* Interact with {@code entity} on this cycle.
*
* @param entity The {@code Entity} to interact with this cycle.
*/
public final void interact(Entity entity) {
if (entity == null) {
interactWithMob(65535);
interactingWith = Optional.empty();
return;
}
if (entity instanceof MobileEntity) {
MobileEntity mob = (MobileEntity) entity;
interactWithMob(mob.type() == EntityType.PLAYER ? mob.index + 32768 : mob.index);
} else {
face(entity.getPosition());
}
interactingWith = Optional.of(entity);
}
/**
* Sets the mob interaction index.
*/
private void interactWithMob(int index) {
interactionIndex = index;
updateFlags.flag(UpdateFlag.INTERACTION);
}
/**
* Display {@code primaryHit} on this cycle.
*
* @param primaryHit The primary {@link Hit} to display this cycle.
*/
private void primaryHit(Hit primaryHit) {
this.primaryHit = requireNonNull(primaryHit);
updateFlags.flag(UpdateFlag.PRIMARY_HIT);
}
/**
* Display {@code secondaryHit} on this cycle.
*
* @param secondaryHit The secondary {@link Hit} to display this cycle.
*/
private void secondaryHit(Hit secondaryHit) {
this.secondaryHit = requireNonNull(secondaryHit);
updateFlags.flag(UpdateFlag.SECONDARY_HIT);
}
/**
* @return The index of this {@link MobileEntity} in its list.
*/
public final int getIndex() {
return index;
}
/**
* Sets the value for {@link #index}, cannot be below {@code 1} unless the value is {@code -1}.
*/
public final void setIndex(int index) {
if (index != -1) {
checkArgument(index >= 1, "index < 1");
}
this.index = index;
}
/**
* Clears all of the various flags for this cycle.
*/
public final void clearFlags() {
reset();
teleporting = false;
animation = null;
forceChat = null;
facePosition = null;
interactionIndex = -1;
primaryHit = null;
secondaryHit = null;
updateFlags.clear();
}
/**
* Retrieves a skill from the backing {@link SkillSet}.
*/
public Skill skill(int id) {
return skills.getSkill(id);
}
/**
* @return The {@link AttributeMap} instance assigned to this {@code MobileEntity}.
*/
public final AttributeMap getAttributes() {
return attributes;
}
/**
* @return The {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}.
*/
public final UpdateFlagHolder getUpdateFlags() {
return updateFlags;
}
/**
* @return The walking direction of this {@code MobileEntity}.
*/
public final Direction getWalkingDirection() {
return walkingDirection;
}
/**
* Sets the value for {@link #walkingDirection}.
*/
public final void setWalkingDirection(Direction walkingDirection) {
this.walkingDirection = walkingDirection;
}
/**
* @return The running direction of this {@code MobileEntity}.
*/
public Direction getRunningDirection() {
return runningDirection;
}
/**
* Sets the value for {@link #runningDirection}.
*/
public void setRunningDirection(Direction runningDirection) {
this.runningDirection = runningDirection;
}
/**
* @return {@code true} if this {@code MobileEntity} is teleporting, {@code false} otherwise.
*/
public final boolean isTeleporting() {
return teleporting;
}
/**
* @return The {@link Animation} to perform this cycle.
*/
public final Animation getAnimation() {
return animation;
}
/**
* @return The {@link Position} to face this cycle.
*/
public final Position getFacePosition() {
return facePosition;
}
/**
* @return The chat to forcibly display this cycle.
*/
public final String getForceChat() {
return forceChat;
}
/**
* @return The {@link Graphic} to perform this cycle..
*/
public final Graphic getGraphic() {
return graphic;
}
/**
* @return The {@code MobileEntity} to interact with this cycle.
*/
public final int getInteractionIndex() {
return interactionIndex;
}
/**
* @return The primary {@link Hit} to display this cycle.
*/
public final Hit getPrimaryHit() {
return primaryHit;
}
/**
* @return The secondary {@link Hit} to display this cycle.
*/
public final Hit getSecondaryHit() {
return secondaryHit;
}
/**
* @return The {@link WalkingQueue} assigned to this {@code MobileEntity}.
*/
public WalkingQueue getWalkingQueue() {
return walkingQueue;
}
/**
* @return The {@link SkillSet} for this {@code MobileEntity}.
*/
public SkillSet getSkills() {
return skills;
}
/**
* @return The combat level of this {@code MobileEntity}.
*/
public int getCombatLevel() {
return skills.getCombatLevel();
}
/**
* @return The {@link Entity} currently being interacted with.
*/
public Optional<Entity> getInteractingWith() {
return interactingWith;
}
}
| src/main/java/io/luna/game/model/mobile/MobileEntity.java | package io.luna.game.model.mobile;
import io.luna.LunaContext;
import io.luna.game.action.Action;
import io.luna.game.action.ActionSet;
import io.luna.game.model.Direction;
import io.luna.game.model.Entity;
import io.luna.game.model.EntityType;
import io.luna.game.model.Position;
import io.luna.game.model.mobile.attr.AttributeMap;
import io.luna.game.model.mobile.update.UpdateFlagHolder;
import io.luna.game.model.mobile.update.UpdateFlagHolder.UpdateFlag;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
/**
* Something that exists in the Runescape world and is able to move around.
*
* @author lare96 <http://github.org/lare96>
*/
public abstract class MobileEntity extends Entity {
/**
* An {@link AttributeMap} instance assigned to this {@code MobileEntity}.
*/
protected final AttributeMap attributes = new AttributeMap();
/**
* An {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}.
*/
protected final UpdateFlagHolder updateFlags = new UpdateFlagHolder();
/**
* The {@link SkillSet} for this {@code MobileEntity}.
*/
protected final SkillSet skills = new SkillSet(this);
/**
* The {@link ActionSet} for this {@code MobileEntity}.
*/
protected final ActionSet actions = new ActionSet();
/**
* The {@link WalkingQueue} assigned to this {@code MobileEntity}.
*/
private final WalkingQueue walkingQueue = new WalkingQueue(this);
/**
* The index of this mob in its list.
*/
private int index = -1;
/**
* The walking direction of this {@code MobileEntity}.
*/
private Direction walkingDirection = Direction.NONE;
/**
* The running direction of this {@code MobileEntity}.
*/
private Direction runningDirection = Direction.NONE;
/**
* If this {@code MobileEntity} is teleporting.
*/
private boolean teleporting = true;
/**
* The {@link Animation} to perform this cycle.
*/
private Animation animation;
/**
* The {@link Position} to face this cycle.
*/
private Position facePosition;
/**
* The chat to forcibly display this cycle.
*/
private String forceChat;
/**
* The {@link Graphic} to perform this cycle.
*/
private Graphic graphic;
/**
* The {@code MobileEntity} to interact with this cycle.
*/
private int interactionIndex = -1;
/**
* The primary {@link Hit} to display this cycle.
*/
private Hit primaryHit;
/**
* The secondary {@link Hit} to perform this cycle.
*/
private Hit secondaryHit;
/**
* The {@link Entity} currently being interacted with.
*/
private Optional<Entity> interactingWith = Optional.empty();
/**
* Creates a new {@link MobileEntity}.
*
* @param context The context to be managed in.
*/
public MobileEntity(LunaContext context) {
super(context);
}
/**
* Clears flags specific to certain types of {@code MobileEntity}s.
*/
public abstract void reset();
/**
* Shortcut to function {@link ActionSet#submit(Action)}.
*/
public final void submitAction(Action<? extends MobileEntity> pending) {
actions.submit(pending);
}
/**
* Shortcut to function {@link ActionSet#interrupt()}.
*/
public final void interruptAction() {
actions.interrupt();
}
/**
* Teleports this {@code MobileEntity} to {@code position}.
*
* @param position The {@link Position} to teleport to.
*/
public final void teleport(Position position) {
setPosition(position);
teleporting = true;
walkingQueue.clear();
}
/**
* Perform {@code animation} on this cycle.
*
* @param newAnimation The {@link Animation} to perform this cycle.
*/
public final void animation(Animation newAnimation) {
if (animation == null || animation.getPriority().getValue() <= newAnimation.getPriority().getValue()) {
animation = requireNonNull(newAnimation);
updateFlags.flag(UpdateFlag.ANIMATION);
}
}
/**
* Face {@code facePosition} on this cycle.
*
* @param facePosition The {@link Position} to face this cycle.
*/
public final void face(Position facePosition) {
this.facePosition = requireNonNull(facePosition);
updateFlags.flag(UpdateFlag.FACE_POSITION);
}
/**
* Force the chat message {@code forceChat} on this cycle.
*
* @param forceChat The chat to forcibly display this cycle.
*/
public final void forceChat(String forceChat) {
this.forceChat = requireNonNull(forceChat);
updateFlags.flag(UpdateFlag.FORCE_CHAT);
}
/**
* Perform {@code graphic} on this cycle.
*
* @param graphic The {@link Graphic} to perform this cycle.
*/
public final void graphic(Graphic graphic) {
this.graphic = requireNonNull(graphic);
updateFlags.flag(UpdateFlag.GRAPHIC);
}
/**
* Interact with {@code entity} on this cycle.
*
* @param entity The {@code Entity} to interact with this cycle.
*/
public final void interact(Entity entity) {
if (entity == null) {
interactWithMob(65535);
interactingWith = Optional.empty();
return;
}
if (entity instanceof MobileEntity) {
MobileEntity mob = (MobileEntity) entity;
interactWithMob(mob.type() == EntityType.PLAYER ? mob.index + 32768 : mob.index);
} else {
face(entity.getPosition());
}
interactingWith = Optional.of(entity);
}
/**
* Sets the mob interaction index.
*/
private void interactWithMob(int index) {
interactionIndex = index;
updateFlags.flag(UpdateFlag.INTERACTION);
}
/**
* Display {@code primaryHit} on this cycle.
*
* @param primaryHit The primary {@link Hit} to display this cycle.
*/
private void primaryHit(Hit primaryHit) {
this.primaryHit = requireNonNull(primaryHit);
updateFlags.flag(UpdateFlag.PRIMARY_HIT);
}
/**
* Display {@code secondaryHit} on this cycle.
*
* @param secondaryHit The secondary {@link Hit} to display this cycle.
*/
private void secondaryHit(Hit secondaryHit) {
this.secondaryHit = requireNonNull(secondaryHit);
updateFlags.flag(UpdateFlag.SECONDARY_HIT);
}
/**
* @return The index of this {@link MobileEntity} in its list.
*/
public final int getIndex() {
return index;
}
/**
* Sets the value for {@link #index}, cannot be below {@code 1} unless the value is {@code -1}.
*/
public final void setIndex(int index) {
if (index != -1) {
checkArgument(index >= 1, "index < 1");
}
this.index = index;
}
/**
* Clears all of the various flags for this cycle.
*/
public final void clearFlags() {
reset();
teleporting = false;
animation = null;
forceChat = null;
facePosition = null;
interactionIndex = -1;
primaryHit = null;
secondaryHit = null;
updateFlags.clear();
}
/**
* Retrieves a skill from the backing {@link SkillSet}.
*/
public Skill skill(int id) {
return skills.getSkill(id);
}
/**
* @return The {@link AttributeMap} instance assigned to this {@code MobileEntity}.
*/
public final AttributeMap getAttributes() {
return attributes;
}
/**
* @return The {@link UpdateFlagHolder} instance assigned to this {@code MobileEntity}.
*/
public final UpdateFlagHolder getUpdateFlags() {
return updateFlags;
}
/**
* @return The walking direction of this {@code MobileEntity}.
*/
public final Direction getWalkingDirection() {
return walkingDirection;
}
/**
* Sets the value for {@link #walkingDirection}.
*/
public final void setWalkingDirection(Direction walkingDirection) {
this.walkingDirection = walkingDirection;
}
/**
* @return The running direction of this {@code MobileEntity}.
*/
public Direction getRunningDirection() {
return runningDirection;
}
/**
* Sets the value for {@link #runningDirection}.
*/
public void setRunningDirection(Direction runningDirection) {
this.runningDirection = runningDirection;
}
/**
* @return {@code true} if this {@code MobileEntity} is teleporting, {@code false} otherwise.
*/
public final boolean isTeleporting() {
return teleporting;
}
/**
* @return The {@link Animation} to perform this cycle.
*/
public final Animation getAnimation() {
return animation;
}
/**
* @return The {@link Position} to face this cycle.
*/
public final Position getFacePosition() {
return facePosition;
}
/**
* @return The chat to forcibly display this cycle.
*/
public final String getForceChat() {
return forceChat;
}
/**
* @return The {@link Graphic} to perform this cycle..
*/
public final Graphic getGraphic() {
return graphic;
}
/**
* @return The {@code MobileEntity} to interact with this cycle.
*/
public final int getInteractionIndex() {
return interactionIndex;
}
/**
* @return The primary {@link Hit} to display this cycle.
*/
public final Hit getPrimaryHit() {
return primaryHit;
}
/**
* @return The secondary {@link Hit} to display this cycle.
*/
public final Hit getSecondaryHit() {
return secondaryHit;
}
/**
* @return The {@link WalkingQueue} assigned to this {@code MobileEntity}.
*/
public WalkingQueue getWalkingQueue() {
return walkingQueue;
}
/**
* @return The {@link SkillSet} for this {@code MobileEntity}.
*/
public SkillSet getSkills() {
return skills;
}
/**
* @return The combat level of this {@code MobileEntity}.
*/
public int getCombatLevel() {
return skills.getCombatLevel();
}
/**
* @return The {@link Entity} currently being interacted with.
*/
public Optional<Entity> getInteractingWith() {
return interactingWith;
}
}
| WalkingQueue instance is now protected
| src/main/java/io/luna/game/model/mobile/MobileEntity.java | WalkingQueue instance is now protected |
|
Java | mpl-2.0 | 768e1690e33bd9fb64a3b47a6c658e1a058c2fb3 | 0 | BrightSpots/rcv | /*
* Ranked Choice Voting Universal Tabulator
* Copyright (c) 2017-2019 Bright Spots Developers.
*
* 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/>.
*/
/*
* Purpose:
* Helper class takes tabulation results data as input and generates summary files which
* contains results summary information.
* Currently we support a CSV summary file and a JSON summary file.
*/
package network.brightspots.rcv;
import static java.util.Map.entry;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import javafx.util.Pair;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
class ResultsWriter {
private static final String CDF_CONTEST_ID = "contest-001";
private static final String CDF_ELECTION_ID = "election-001";
private static final String CDF_GPU_ID = "gpu-election";
private static final String CDF_GPU_ID_FORMAT = "gpu-%d";
private static final String CDF_REPORTING_DEVICE_ID = "rd-001";
private static final Map<String, String> candidateCodeToCdfId = new HashMap<>();
// number of rounds needed to elect winner(s)
private int numRounds;
// all precinct Ids which may appear in the output cvrs
private Set<String> precinctIds;
// cache precinct to GpUnitId map
private Map<String, String> GpUnitIds;
// threshold to win
private BigDecimal winningThreshold;
// map from round number to list of candidates eliminated in that round
private Map<Integer, List<String>> roundToEliminatedCandidates;
// map from round number to list of candidates winning in that round
private Map<Integer, List<String>> roundToWinningCandidates;
// configuration file in use for this contest
private ContestConfig config;
// timestampString string to use when generating output file names
private String timestampString;
// TallyTransfer object contains totals votes transferred each round
private TallyTransfers tallyTransfers;
private Map<Integer, BigDecimal> roundToResidualSurplus;
private int numBallots;
static String sequentialSuffixForOutputPath(Integer sequentialTabulationNumber) {
return sequentialTabulationNumber != null ? "_" + sequentialTabulationNumber : "";
}
static String getOutputFilePath(
String outputDirectory,
String outputType,
String timestampString,
Integer sequentialTabulationNumber) {
String fileName =
String.format(
"%s_%s%s",
timestampString, outputType, sequentialSuffixForOutputPath(sequentialTabulationNumber));
return Paths.get(outputDirectory, fileName).toAbsolutePath().toString();
}
static String sanitizeStringForOutput(String s) {
return s.replaceAll("[^a-zA-Z0-9_\\-.]", "_");
}
private static void generateJsonFile(String path, Map<String, Object> json) throws IOException {
// mapper converts java objects to json
ObjectMapper mapper = new ObjectMapper();
// set mapper to order keys alphabetically for more legible output
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
// create a module to contain a serializer for BigDecimal serialization
SimpleModule module = new SimpleModule();
module.addSerializer(BigDecimal.class, new ToStringSerializer());
// attach serializer to mapper
mapper.registerModule(module);
// jsonWriter writes those object to disk
ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
File outFile = new File(path);
try {
jsonWriter.writeValue(outFile, json);
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s\n"
+ "Please check the file path and permissions!", path, exception.toString());
throw exception;
}
}
private static String generateCvrSnapshotID(String cvrID, Integer round) {
return round != null && round > 0
? String.format("ballot-%s-round-%d", cvrID, round)
: String.format("ballot-%s", cvrID);
}
private static String getCdfIdForCandidateCode(String code) {
String id = candidateCodeToCdfId.get(code);
if (id == null) {
id =
code.startsWith("cs-")
? code
: String.format("cs-%s", sanitizeStringForOutput(code).toLowerCase());
candidateCodeToCdfId.put(code, id);
}
return id;
}
// purpose: Instead of a map from rank to list of candidates, we need a sorted list of candidates
// with the ranks they were given. (Ordinarily a candidate will have only a single rank, but they
// could have multiple ranks if the ballot duplicates the candidate, i.e. assigns them multiple
// ranks.
// We sort by the lowest (best) rank, then alphabetically by name.
private static List<Map.Entry<String, List<Integer>>> getCandidatesWithRanksList(
Map<Integer, Set<String>> rankToCandidateIDs) {
Map<String, List<Integer>> candidateIdToRanks = new HashMap<>();
// first group the ranks by candidate
for (int rank : rankToCandidateIDs.keySet()) {
for (String candidateId : rankToCandidateIDs.get(rank)) {
candidateIdToRanks.computeIfAbsent(candidateId, k -> new LinkedList<>());
candidateIdToRanks.get(candidateId).add(rank);
}
}
// we want the ranks for a given candidate in ascending order
for (List<Integer> list : candidateIdToRanks.values()) {
Collections.sort(list);
}
List<Map.Entry<String, List<Integer>>> sortedCandidatesWithRanks =
new LinkedList<>(candidateIdToRanks.entrySet());
// and now we sort the list of candidates with ranks
sortedCandidatesWithRanks.sort(
(firstObject, secondObject) -> {
int ret;
Integer firstRank = firstObject.getValue().get(0);
Integer secondRank = secondObject.getValue().get(0);
if (!firstRank.equals(secondRank)) {
ret = firstRank.compareTo(secondRank);
} else {
ret = firstObject.getKey().compareTo(secondObject.getKey());
}
return ret;
});
return sortedCandidatesWithRanks;
}
ResultsWriter setRoundToResidualSurplus(Map<Integer, BigDecimal> roundToResidualSurplus) {
this.roundToResidualSurplus = roundToResidualSurplus;
return this;
}
// function: setTallyTransfers
// purpose: setter for tally transfer object used when generating json summary output
// param: TallyTransfer object
ResultsWriter setTallyTransfers(TallyTransfers tallyTransfers) {
this.tallyTransfers = tallyTransfers;
return this;
}
ResultsWriter setNumBallots(int numBallots) {
this.numBallots = numBallots;
return this;
}
// function: setNumRounds
// purpose: setter for total number of rounds
// param: numRounds total number of rounds
ResultsWriter setNumRounds(int numRounds) {
this.numRounds = numRounds;
return this;
}
// function: setWinningThreshold
// purpose: setter for winning threshold
// param: threshold to win
ResultsWriter setWinningThreshold(BigDecimal threshold) {
this.winningThreshold = threshold;
return this;
}
// function: setPrecinctIds
// purpose: setter for precinctIds
ResultsWriter setPrecinctIds(Set<String> precinctIds) {
this.precinctIds = precinctIds;
return this;
}
// function: setCandidatesToRoundEliminated
// purpose: setter for candidatesToRoundEliminated object
// param: candidatesToRoundEliminated map of candidateID to round in which they were eliminated
ResultsWriter setCandidatesToRoundEliminated(Map<String, Integer> candidatesToRoundEliminated) {
// roundToEliminatedCandidates is the inverse of candidatesToRoundEliminated map
// so we can look up who got eliminated for each round
roundToEliminatedCandidates = new HashMap<>();
// candidate is used for indexing over all candidates in candidatesToRoundEliminated
for (String candidate : candidatesToRoundEliminated.keySet()) {
// round is the current candidate's round of elimination
int round = candidatesToRoundEliminated.get(candidate);
roundToEliminatedCandidates.computeIfAbsent(round, k -> new LinkedList<>());
roundToEliminatedCandidates.get(round).add(candidate);
}
return this;
}
// function: setWinnerToRound
// purpose: setter for the winning candidates
// param: map from winning candidate name to the round in which they won
ResultsWriter setWinnerToRound(Map<String, Integer> winnerToRound) {
// very similar to the logic in setCandidatesToRoundEliminated above
roundToWinningCandidates = new HashMap<>();
for (String candidate : winnerToRound.keySet()) {
int round = winnerToRound.get(candidate);
roundToWinningCandidates.computeIfAbsent(round, k -> new LinkedList<>());
roundToWinningCandidates.get(round).add(candidate);
}
return this;
}
// function: setContestConfig
// purpose: setter for ContestConfig object
// param: config the ContestConfig object to use when writing results
ResultsWriter setContestConfig(ContestConfig config) {
this.config = config;
return this;
}
// function: setTimestampString
// purpose: setter for timestampString string used for creating output file names
// param: timestampString string to use for creating output file names
ResultsWriter setTimestampString(String timestampString) {
this.timestampString = timestampString;
return this;
}
// function: generatePrecinctSummarySpreadsheet
// purpose: creates a summary spreadsheet for the votes in a particular precinct
// param: roundTallies is map from precinct to the round-by-round vote count in the precinct
void generatePrecinctSummarySpreadsheets(
Map<String, Map<Integer, Map<String, BigDecimal>>> precinctRoundTallies) throws IOException {
Set<String> filenames = new HashSet<>();
for (String precinct : precinctRoundTallies.keySet()) {
// precinctFileString is a unique filesystem-safe string which can be used for creating
// the precinct output filename
String precinctFileString = getPrecinctFileString(precinct, filenames);
// filename for output
String outputFileName =
String.format("%s_%s_precinct_summary", this.timestampString, precinctFileString);
// full path for output
String outputPath =
Paths.get(config.getOutputDirectory(), outputFileName).toAbsolutePath().toString();
generateSummarySpreadsheet(precinctRoundTallies.get(precinct), precinct, outputPath);
// generate json output
generateSummaryJson(precinctRoundTallies.get(precinct), precinct, outputPath);
}
}
// function: generateSummarySpreadsheet
// purpose: creates a summary spreadsheet .csv file
// param: roundTallies is the round-by-count count of votes per candidate
// param: precinct indicates which precinct we're reporting results for (null means all)
// param: outputPath is the full path of the file to save
// file access: write / create
private void generateSummarySpreadsheet(
Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath)
throws IOException {
String csvPath = outputPath + ".csv";
Logger.log(Level.INFO, "Generating summary spreadsheets: %s", csvPath);
// Get all candidates sorted by their first round tally. This determines the display order.
// container for firstRoundTally
Map<String, BigDecimal> firstRoundTally = roundTallies.get(1);
// candidates sorted by first round tally
List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally);
// totalActiveVotesPerRound is a map of round to active votes in each round
Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>();
// round indexes over all rounds plus final results round
for (int round = 1; round <= numRounds; round++) {
// tally is map of candidate to tally for the current round
Map<String, BigDecimal> tallies = roundTallies.get(round);
// total will contain total votes for all candidates in this round
// this is used for calculating other derived data
BigDecimal total = BigDecimal.ZERO;
// tally indexes over all tallies for the current round
for (BigDecimal tally : tallies.values()) {
total = total.add(tally);
}
totalActiveVotesPerRound.put(round, total);
}
// csvPrinter will be used to write output to csv file
CSVPrinter csvPrinter;
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath));
csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s\n"
+ "Please check the file path and permissions!", csvPath, exception.toString());
throw exception;
}
// print contest info
addHeaderRows(csvPrinter, precinct);
// add a row header for the round column labels
csvPrinter.print("Rounds");
// round indexes over all rounds
for (int round = 1; round <= numRounds; round++) {
// label string will have the actual text which goes in the cell
String label = String.format("Round %d", round);
// cell for round label
csvPrinter.print(label);
}
csvPrinter.println();
// actions don't make sense in individual precinct results
if (precinct == null || precinct.isEmpty()) {
addActionRows(csvPrinter);
}
// For each candidate: for each round: output total votes
// candidate indexes over all candidates
for (String candidate : sortedCandidates) {
// show each candidate row with their totals for each round
// text for the candidate name
String candidateDisplayName = config.getNameForCandidateCode(candidate);
csvPrinter.print(candidateDisplayName);
// round indexes over all rounds
for (int round = 1; round <= numRounds; round++) {
// vote tally this round
BigDecimal thisRoundTally = roundTallies.get(round).get(candidate);
// not all candidates may have a tally in every round
if (thisRoundTally == null) {
thisRoundTally = BigDecimal.ZERO;
}
// total votes cell
csvPrinter.print(thisRoundTally.toString());
}
// advance to next line
csvPrinter.println();
}
// row for the inactive CVR counts
// inactive CVR header cell
csvPrinter.print("Inactive ballots");
// round indexes through all rounds
for (int round = 1; round <= numRounds; round++) {
// Exhausted/inactive count is the difference between the total ballots and the total votes
// still active or counting as residual surplus votes in the current round.
BigDecimal thisRoundInactive =
new BigDecimal(numBallots)
.subtract(totalActiveVotesPerRound.get(round))
.subtract(roundToResidualSurplus.get(round));
// total votes cell
csvPrinter.print(thisRoundInactive.toString());
}
csvPrinter.println();
// row for residual surplus (if needed)
// We check if we accumulated any residual surplus over the course of the tabulation by testing
// whether the value in the final round is positive.
if (roundToResidualSurplus.get(numRounds).signum() == 1) {
csvPrinter.print("Residual surplus");
for (int round = 1; round <= numRounds; round++) {
csvPrinter.print(roundToResidualSurplus.get(round).toString());
}
csvPrinter.println();
}
// write xls to disk
try {
// output stream is used to write data to disk
csvPrinter.flush();
csvPrinter.close();
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString());
throw exception;
}
}
// function: addActionRows
// "action" rows describe which candidates were eliminated or elected
// purpose: output rows to csv file describing which actions were taken in each round
// param: csvPrinter object for writing csv file
private void addActionRows(CSVPrinter csvPrinter) throws IOException {
// print eliminated candidates in first action row
csvPrinter.print("Eliminated");
// for each round print any candidates who were eliminated
for (int round = 1; round <= numRounds; round++) {
// list of all candidates eliminated in this round
List<String> eliminated = roundToEliminatedCandidates.get(round);
if (eliminated != null && eliminated.size() > 0) {
addActionRowCandidates(eliminated, csvPrinter);
} else {
csvPrinter.print("");
}
}
csvPrinter.println();
// print elected candidates in second action row
csvPrinter.print("Elected");
// for each round print any candidates who were elected
for (int round = 1; round <= numRounds; round++) {
// list of all candidates eliminated in this round
List<String> winners = roundToWinningCandidates.get(round);
if (winners != null && winners.size() > 0) {
addActionRowCandidates(winners, csvPrinter);
} else {
csvPrinter.print("");
}
}
csvPrinter.println();
}
// function: addActionRowCandidates
// purpose: add the given candidate(s) names to the csv file next cell
// param: candidates list of candidate names to add to the next cell
// param: csvPrinter object for output to csv file
private void addActionRowCandidates(List<String> candidates, CSVPrinter csvPrinter)
throws IOException {
List<String> candidateDisplayNames = new ArrayList<>();
// build list of display names
for (String candidate : candidates) {
candidateDisplayNames.add(config.getNameForCandidateCode(candidate));
}
// concatenate them using semi-colon for display in a single cell
String candidateCellText = String.join("; ", candidateDisplayNames);
// print the candidate name list
csvPrinter.print(candidateCellText);
}
// function: addHeaderRows
// purpose: add arbitrary header rows and cell to the top of the visualizer spreadsheet
private void addHeaderRows(CSVPrinter csvPrinter, String precinct) throws IOException {
csvPrinter.printRecord("Contest", config.getContestName());
csvPrinter.printRecord("Jurisdiction", config.getContestJurisdiction());
csvPrinter.printRecord("Office", config.getContestOffice());
csvPrinter.printRecord("Date", config.getContestDate());
List<String> winners = new LinkedList<>();
List<Integer> winningRounds = new ArrayList<>(roundToWinningCandidates.keySet());
Collections.sort(winningRounds); // make sure we list them in order of election
for (int round : winningRounds) {
for (String candidateCode : roundToWinningCandidates.get(round)) {
winners.add(config.getNameForCandidateCode(candidateCode));
}
}
csvPrinter.printRecord("Winner(s)", String.join(", ", winners));
csvPrinter.printRecord("Threshold", winningThreshold.toString());
if (precinct != null && !precinct.isEmpty()) {
csvPrinter.printRecord("Precinct", precinct);
}
csvPrinter.println();
}
// function: sortCandidatesByTally
// purpose: given a map of candidates to tally return a list of all input candidates
// sorted from highest tally to lowest
// param: tally map of candidateID to tally
// return: list of all input candidates sorted from highest tally to lowest
private List<String> sortCandidatesByTally(Map<String, BigDecimal> tally) {
// entries will contain all the input tally entries in sorted order
List<Map.Entry<String, BigDecimal>> entries = new ArrayList<>(tally.entrySet());
// anonymous custom comparator will sort undeclared write in candidates to last place
entries.sort(
(firstObject, secondObject) -> {
// result of the comparison
int ret;
if (firstObject.getKey().equals(config.getUndeclaredWriteInLabel())) {
ret = 1;
} else if (secondObject.getKey().equals(config.getUndeclaredWriteInLabel())) {
ret = -1;
} else {
ret = (secondObject.getValue()).compareTo(firstObject.getValue());
}
return ret;
});
// container list for the final results
List<String> sortedCandidates = new LinkedList<>();
// index over all entries
for (Map.Entry<String, BigDecimal> entry : entries) {
sortedCandidates.add(entry.getKey());
}
return sortedCandidates;
}
// function: getPrecinctFileString
// purpose: return a unique, valid string for this precinct's output spreadsheet filename
// param: precinct is the name of the precinct
// param: filenames is the set of filenames we've already generated
// return: the new filename
private String getPrecinctFileString(String precinct, Set<String> filenames) {
// sanitized is the precinct name with all special characters converted to underscores
String sanitized = sanitizeStringForOutput(precinct);
// filename is the string that we'll eventually return
String filename = sanitized;
// appendNumber is used to find a unique filename (in practice this really shouldn't be
// necessary because different precinct names shouldn't have the same sanitized name, but we're
// doing it here to be safe)
int appendNumber = 2;
while (filenames.contains(filename)) {
filename = sanitized + "_" + appendNumber++;
}
filenames.add(filename);
return filename;
}
// function: generateOverallSummaryFiles
// purpose: creates a summary spreadsheet and JSON for the full contest
// param: roundTallies is the round-by-round count of votes per candidate
void generateOverallSummaryFiles(Map<Integer, Map<String, BigDecimal>> roundTallies)
throws IOException {
String outputPath =
getOutputFilePath(
config.getOutputDirectory(),
"summary",
timestampString,
config.isSequentialMultiSeatEnabled()
? config.getSequentialWinners().size() + 1
: null);
// generate the spreadsheet
generateSummarySpreadsheet(roundTallies, null, outputPath);
// generate json output
generateSummaryJson(roundTallies, null, outputPath);
}
// create NIST Common Data Format CVR json
void generateCdfJson(List<CastVoteRecord> castVoteRecords)
throws IOException, RoundSnapshotDataMissingException {
// generate GpUnitIds for precincts (identify election jurisdiction and precincts)
GpUnitIds = generateGpUnitIds();
HashMap<String, Object> outputJson = new HashMap<>();
String outputPath =
getOutputFilePath(
config.getOutputDirectory(),
"cvr_cdf",
timestampString,
config.isSequentialMultiSeatEnabled()
? config.getSequentialWinners().size() + 1
: null)
+ ".json";
Logger.log(Level.INFO, "Generating CVR CDF JSON file: %s...", outputPath);
outputJson.put("CVR", generateCdfMapForCvrs(castVoteRecords));
outputJson.put("Election", new Map[]{generateCdfMapForElection()});
outputJson.put(
"GeneratedDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));
outputJson.put("GpUnit", generateCdfMapForGpUnits());
outputJson.put("ReportGeneratingDeviceIds", new String[]{CDF_REPORTING_DEVICE_ID});
outputJson.put(
"ReportingDevice",
new Map[]{
Map.ofEntries(
entry("@id", CDF_REPORTING_DEVICE_ID),
entry("@type", "CVR.ReportingDevice"),
entry("Application", "RCVRC Tabulator"),
entry("Manufacturer", "Bright Spots"))
});
outputJson.put("Version", "1.0.0");
outputJson.put("@type", "CVR.CastVoteRecordReport");
generateJsonFile(outputPath, outputJson);
}
// generate map of GpUnitIds
// we map from precinctId => GpUnitId
// as lookups will be done from precinctId during cvr creation
private Map<String, String> generateGpUnitIds() {
Map<String, String> GpUnitIdToPrecinctId = new HashMap<>();
int GpUnitIdIndex = 0;
// for every precinctId add an entry
for (String precinctId : precinctIds) {
GpUnitIdToPrecinctId.put(precinctId, String.format(CDF_GPU_ID_FORMAT, ++GpUnitIdIndex));
}
return GpUnitIdToPrecinctId;
}
// generates json containing precinct IDs
private List<Map<String, Object>> generateCdfMapForGpUnits() {
// create the GpUnit map
List<Map<String, Object>> GpUnitMaps = new LinkedList<>();
// and add the election-scope entry for the election jurisdiction
GpUnitMaps.add(
Map.ofEntries(
entry("@id", CDF_GPU_ID),
entry("Type", "other"),
entry("OtherType", "Election Scope Jurisdiction"),
entry("Name", config.getContestJurisdiction()),
entry("@type", "CVR.GpUnit")));
// generate GpUnit entries
for (Entry<String, String> entry : GpUnitIds.entrySet()) {
GpUnitMaps.add(
Map.ofEntries(
entry("@id", entry.getValue()),
entry("Type", "precinct"),
entry("Name", entry.getKey()),
entry("@type", "CVR.GpUnit")));
}
return GpUnitMaps;
}
// purpose: helper method for generateCdfJson to compile the data for all the CVR snapshots
private List<Map<String, Object>> generateCdfMapForCvrs(List<CastVoteRecord> castVoteRecords)
throws RoundSnapshotDataMissingException {
List<Map<String, Object>> cvrMaps = new LinkedList<>();
for (CastVoteRecord cvr : castVoteRecords) {
List<Map<String, Object>> cvrSnapshots = new LinkedList<>();
cvrSnapshots.add(generateCvrSnapshotMap(cvr, null, null));
String sanitizedId = sanitizeStringForOutput(cvr.getID());
// copy most recent round snapshot data to subsequent rounds
// until more snapshot data is available
List<Pair<String, BigDecimal>> previousRoundSnapshotData = null;
for (int round = 1; round <= numRounds; round++) {
List<Pair<String, BigDecimal>> currentRoundSnapshotData =
cvr.getCdfSnapshotData().get(round);
if (currentRoundSnapshotData == null) {
if (previousRoundSnapshotData == null) {
throw new RoundSnapshotDataMissingException(sanitizedId);
}
currentRoundSnapshotData = previousRoundSnapshotData;
}
cvrSnapshots.add(generateCvrSnapshotMap(cvr, round, currentRoundSnapshotData));
previousRoundSnapshotData = currentRoundSnapshotData;
}
// create new cvr map entry
Map<String, Object> cvrMap = new HashMap<>();
cvrMap.put("BallotPrePrintedId", sanitizedId);
cvrMap.put("CurrentSnapshotId", generateCvrSnapshotID(sanitizedId, numRounds));
cvrMap.put("CVRSnapshot", cvrSnapshots);
cvrMap.put("ElectionId", CDF_ELECTION_ID);
cvrMap.put("@type", "CVR.CVR");
// if using precincts add GpUnitId for cvr precinct
if (config.isTabulateByPrecinctEnabled()) {
String GpUnitId = GpUnitIds.get(cvr.getPrecinct());
cvrMap.put("BallotStyleUnitId", GpUnitId);
}
cvrMaps.add(cvrMap);
}
return cvrMaps;
}
// purpose: helper for generateCdfMapForCvrs to handle a single CVR in a single round
private Map<String, Object> generateCvrSnapshotMap(
CastVoteRecord cvr, Integer round, List<Pair<String, BigDecimal>> currentRoundSnapshotData) {
List<Map<String, Object>> selectionMapList = new LinkedList<>();
List<Map.Entry<String, List<Integer>>> candidatesWithRanksList =
getCandidatesWithRanksList(cvr.rankToCandidateIDs);
for (Map.Entry<String, List<Integer>> candidateWithRanks : candidatesWithRanksList) {
String candidateCode = candidateWithRanks.getKey();
String isAllocable = "unknown";
BigDecimal numberVotes = BigDecimal.ONE;
if (currentRoundSnapshotData != null) {
// scanning the list isn't actually expensive because it will almost always be very short
for (Pair<String, BigDecimal> allocation : currentRoundSnapshotData) {
if (allocation.getKey().equals(candidateCode)) {
isAllocable = "yes";
numberVotes = allocation.getValue();
break;
}
}
// didn't find an allocation, i.e. this ballot didn't contribute all or part of a vote to
// this candidate in this round
if (isAllocable.equals("unknown")) {
isAllocable = "no";
// not sure what numberVotes should be in this situation
}
}
String fractionalVotes = null;
if (!numberVotes.equals(BigDecimal.ONE)) {
BigDecimal remainder = numberVotes.remainder(BigDecimal.ONE);
if (remainder.signum() == 1) {
fractionalVotes = remainder.toString().substring(1); // remove the 0 before the decimal
}
}
List<Map<String, Object>> selectionPositionMapList = new LinkedList<>();
for (int rank : candidateWithRanks.getValue()) {
Map<String, Object> selectionPositionMap = new HashMap<>();
selectionPositionMap.put("HasIndication", "yes");
selectionPositionMap.put("IsAllocable", isAllocable);
selectionPositionMap.put("NumberVotes", numberVotes.intValue());
selectionPositionMap.put("Rank", rank);
selectionPositionMap.put("@type", "CVR.SelectionPosition");
if (fractionalVotes != null) {
selectionPositionMap.put("FractionalVotes", fractionalVotes);
}
selectionPositionMapList.add(selectionPositionMap);
if (isAllocable.equals("yes")) {
// If there are duplicate rankings for the candidate on this ballot, only the first one
// can be allocable.
isAllocable = "no";
}
}
selectionMapList.add(
Map.ofEntries(
entry("ContestSelectionId", getCdfIdForCandidateCode(candidateCode)),
entry("SelectionPosition", selectionPositionMapList),
entry("@type", "CVR.CVRContestSelection")));
}
Map<String, Object> contestMap =
Map.ofEntries(
entry("ContestId", CDF_CONTEST_ID),
entry("CVRContestSelection", selectionMapList),
entry("@type", "CVR.CVRContest"));
return Map.ofEntries(
entry("@id", generateCvrSnapshotID(sanitizeStringForOutput(cvr.getID()), round)),
entry("CVRContest", new Map[]{contestMap}),
entry("Type", round != null ? "interpreted" : "original"),
entry("@type", "CVR.CVRSnapshot"));
}
private Map<String, Object> generateCdfMapForElection() {
HashMap<String, Object> electionMap = new HashMap<>();
List<Map<String, Object>> contestSelections = new LinkedList<>();
List<String> candidateCodes = new LinkedList<>(config.getCandidateCodeList());
Collections.sort(candidateCodes);
for (String candidateCode : candidateCodes) {
Map<String, String> codeMap =
Map.ofEntries(
entry("@type", "CVR.Code"),
entry("Type", "other"),
entry("OtherType", "vendor-label"),
entry("Value", config.getNameForCandidateCode(candidateCode)));
contestSelections.add(
Map.ofEntries(
entry("@id", getCdfIdForCandidateCode(candidateCode)),
entry("@type", "CVR.ContestSelection"),
entry("Code", new Map[]{codeMap})));
}
Map<String, Object> contestJson =
Map.ofEntries(
entry("@id", CDF_CONTEST_ID),
entry("ContestSelection", contestSelections),
entry("@type", "CVR.CandidateContest"));
electionMap.put("@id", CDF_ELECTION_ID);
electionMap.put("Contest", new Map[]{contestJson});
electionMap.put("ElectionScopeId", CDF_GPU_ID);
electionMap.put("@type", "CVR.Election");
return electionMap;
}
// function: generateSummaryJson
// purpose: create summary json data for use in visualizer, unit tests and other tools
// param: outputPath where to write json file
// param: roundTallies all tally information
// file access: write to outputPath
private void generateSummaryJson(
Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath)
throws IOException {
String jsonPath = outputPath + ".json";
Logger.log(Level.INFO, "Generating summary JSON file: %s", jsonPath);
// root outputJson dict will have two entries:
// results - vote totals, transfers, and candidates elected / eliminated
// config - global config into
HashMap<String, Object> outputJson = new HashMap<>();
// config will contain contest configuration info
HashMap<String, Object> configData = new HashMap<>();
// add config header info
configData.put("contest", config.getContestName());
configData.put("jurisdiction", config.getContestJurisdiction());
configData.put("office", config.getContestOffice());
configData.put("date", config.getContestDate());
configData.put("threshold", winningThreshold);
if (precinct != null && !precinct.isEmpty()) {
configData.put("precinct", precinct);
}
// results will be a list of round data objects
ArrayList<Object> results = new ArrayList<>();
// for each round create objects for json serialization
for (int round = 1; round <= numRounds; round++) {
// container for all json data this round:
HashMap<String, Object> roundData = new HashMap<>();
// add round number (this is implied by the ordering but for debugging we are explicit)
roundData.put("round", round);
// add actions if this is not a precinct summary
if (precinct == null || precinct.isEmpty()) {
// actions is a list of one or more action objects
ArrayList<Object> actions = new ArrayList<>();
addActionObjects("elected", roundToWinningCandidates.get(round), round, actions);
// add any elimination actions
addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions);
// add action objects
roundData.put("tallyResults", actions);
}
// add tally object
roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round)));
// add roundData to results list
results.add(roundData);
}
// add config data to root object
outputJson.put("config", configData);
// add results to root object
outputJson.put("results", results);
// write results to disk
generateJsonFile(jsonPath, outputJson);
}
private Map<String, BigDecimal> updateCandidateNamesInTally(Map<String, BigDecimal> tally) {
Map<String, BigDecimal> newTally = new HashMap<>();
for (String key : tally.keySet()) {
newTally.put(config.getNameForCandidateCode(key), tally.get(key));
}
return newTally;
}
// function: addActionObjects
// purpose: adds action objects to input action list representing all actions applied this round
// each action will have a type followed by a list of 0 or more vote transfers
// (sometimes there is no vote transfer if a candidate had no votes to transfer)
// param: actionType is this an elimination or election action
// param: candidates list of all candidates action is applied to
// param: round which this action occurred
// param: actions list to add new action objects to
private void addActionObjects(
String actionType, List<String> candidates, int round, ArrayList<Object> actions) {
// check for valid candidates:
// "drop undeclared write-in" may result in no one actually being eliminated
if (candidates != null && candidates.size() > 0) {
// transfers contains all vote transfers for this round
// we add one to the round since transfers are currently stored under the round AFTER
// the tallies which triggered them
Map<String, Map<String, BigDecimal>> roundTransfers =
tallyTransfers.getTransfersForRound(round + 1);
// candidate iterates over all candidates who had this action applied to them
for (String candidate : candidates) {
// for each candidate create an action object
HashMap<String, Object> action = new HashMap<>();
// add the specified action type
action.put(actionType, config.getNameForCandidateCode(candidate));
// check if there are any transfers
if (roundTransfers != null) {
Map<String, BigDecimal> transfersFromCandidate = roundTransfers.get(candidate);
if (transfersFromCandidate != null) {
// We want to replace candidate IDs with names here, too.
Map<String, BigDecimal> translatedTransfers = new HashMap<>();
for (String candidateId : transfersFromCandidate.keySet()) {
// candidateName will be null for special values like "exhausted"
String candidateName = config.getNameForCandidateCode(candidateId);
translatedTransfers.put(
candidateName != null ? candidateName : candidateId,
transfersFromCandidate.get(candidateId));
}
action.put("transfers", translatedTransfers);
}
}
if (!action.containsKey("transfers")) {
// add an empty map
action.put("transfers", new HashMap<String, BigDecimal>());
}
// add the action object to list
actions.add(action);
}
}
}
// Exception class used when we're unexpectedly missing snapshot data for a cast vote record
// during CDF JSON generation. If this happens, there's a bug in the tabulation code.
static class RoundSnapshotDataMissingException extends Exception {
private final String cvrId;
RoundSnapshotDataMissingException(String cvrId) {
this.cvrId = cvrId;
}
String getCvrId() {
return cvrId;
}
}
}
| src/main/java/network/brightspots/rcv/ResultsWriter.java | /*
* Ranked Choice Voting Universal Tabulator
* Copyright (c) 2017-2019 Bright Spots Developers.
*
* 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/>.
*/
/*
* Purpose:
* Helper class takes tabulation results data as input and generates summary files which
* contains results summary information.
* Currently we support a CSV summary file and a JSON summary file.
*/
package network.brightspots.rcv;
import static java.util.Map.entry;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import javafx.util.Pair;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
class ResultsWriter {
private static final String CDF_CONTEST_ID = "contest-001";
private static final String CDF_ELECTION_ID = "election-001";
private static final String CDF_GPU_ID = "gpu-election";
private static final String CDF_GPU_ID_FORMAT = "gpu-%d";
private static final String CDF_REPORTING_DEVICE_ID = "rd-001";
private static final Map<String, String> candidateCodeToCdfId = new HashMap<>();
// number of rounds needed to elect winner(s)
private int numRounds;
// all precinct Ids which may appear in the output cvrs
private Set<String> precinctIds;
// cache precinct to GpUnitId map
private Map<String, String> GpUnitIds;
// threshold to win
private BigDecimal winningThreshold;
// map from round number to list of candidates eliminated in that round
private Map<Integer, List<String>> roundToEliminatedCandidates;
// map from round number to list of candidates winning in that round
private Map<Integer, List<String>> roundToWinningCandidates;
// configuration file in use for this contest
private ContestConfig config;
// timestampString string to use when generating output file names
private String timestampString;
// TallyTransfer object contains totals votes transferred each round
private TallyTransfers tallyTransfers;
private Map<Integer, BigDecimal> roundToResidualSurplus;
private int numBallots;
static String sequentialSuffixForOutputPath(Integer sequentialTabulationNumber) {
return sequentialTabulationNumber != null ? "_" + sequentialTabulationNumber : "";
}
static String getOutputFilePath(
String outputDirectory,
String outputType,
String timestampString,
Integer sequentialTabulationNumber) {
String fileName =
String.format(
"%s_%s%s",
timestampString, outputType, sequentialSuffixForOutputPath(sequentialTabulationNumber));
return Paths.get(outputDirectory, fileName).toAbsolutePath().toString();
}
static String sanitizeStringForOutput(String s) {
return s.replaceAll("[^a-zA-Z0-9_\\-.]", "_");
}
private static void generateJsonFile(String path, Map<String, Object> json) throws IOException {
// mapper converts java objects to json
ObjectMapper mapper = new ObjectMapper();
// set mapper to order keys alphabetically for more legible output
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
// create a module to contain a serializer for BigDecimal serialization
SimpleModule module = new SimpleModule();
module.addSerializer(BigDecimal.class, new ToStringSerializer());
// attach serializer to mapper
mapper.registerModule(module);
// jsonWriter writes those object to disk
ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
File outFile = new File(path);
try {
jsonWriter.writeValue(outFile, json);
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s\n"
+ "Please check the file path and permissions!", path, exception.toString());
throw exception;
}
}
private static String generateCvrSnapshotID(String cvrID, Integer round) {
return round != null && round > 0
? String.format("ballot-%s-round-%d", cvrID, round)
: String.format("ballot-%s", cvrID);
}
private static String getCdfIdForCandidateCode(String code) {
String id = candidateCodeToCdfId.get(code);
if (id == null) {
id =
code.startsWith("cs-")
? code
: String.format("cs-%s", sanitizeStringForOutput(code).toLowerCase());
candidateCodeToCdfId.put(code, id);
}
return id;
}
// purpose: Instead of a map from rank to list of candidates, we need a sorted list of candidates
// with the ranks they were given. (Ordinarily a candidate will have only a single rank, but they
// could have multiple ranks if the ballot duplicates the candidate, i.e. assigns them multiple
// ranks.
// We sort by the lowest (best) rank, then alphabetically by name.
private static List<Map.Entry<String, List<Integer>>> getCandidatesWithRanksList(
Map<Integer, Set<String>> rankToCandidateIDs) {
Map<String, List<Integer>> candidateIdToRanks = new HashMap<>();
// first group the ranks by candidate
for (int rank : rankToCandidateIDs.keySet()) {
for (String candidateId : rankToCandidateIDs.get(rank)) {
candidateIdToRanks.computeIfAbsent(candidateId, k -> new LinkedList<>());
candidateIdToRanks.get(candidateId).add(rank);
}
}
// we want the ranks for a given candidate in ascending order
for (List<Integer> list : candidateIdToRanks.values()) {
Collections.sort(list);
}
List<Map.Entry<String, List<Integer>>> sortedCandidatesWithRanks =
new LinkedList<>(candidateIdToRanks.entrySet());
// and now we sort the list of candidates with ranks
sortedCandidatesWithRanks.sort(
(firstObject, secondObject) -> {
int ret;
Integer firstRank = firstObject.getValue().get(0);
Integer secondRank = secondObject.getValue().get(0);
if (!firstRank.equals(secondRank)) {
ret = firstRank.compareTo(secondRank);
} else {
ret = firstObject.getKey().compareTo(secondObject.getKey());
}
return ret;
});
return sortedCandidatesWithRanks;
}
ResultsWriter setRoundToResidualSurplus(Map<Integer, BigDecimal> roundToResidualSurplus) {
this.roundToResidualSurplus = roundToResidualSurplus;
return this;
}
// function: setTallyTransfers
// purpose: setter for tally transfer object used when generating json summary output
// param: TallyTransfer object
ResultsWriter setTallyTransfers(TallyTransfers tallyTransfers) {
this.tallyTransfers = tallyTransfers;
return this;
}
ResultsWriter setNumBallots(int numBallots) {
this.numBallots = numBallots;
return this;
}
// function: setNumRounds
// purpose: setter for total number of rounds
// param: numRounds total number of rounds
ResultsWriter setNumRounds(int numRounds) {
this.numRounds = numRounds;
return this;
}
// function: setWinningThreshold
// purpose: setter for winning threshold
// param: threshold to win
ResultsWriter setWinningThreshold(BigDecimal threshold) {
this.winningThreshold = threshold;
return this;
}
// function: setPrecinctIds
// purpose: setter for precinctIds
ResultsWriter setPrecinctIds(Set<String> precinctIds) {
this.precinctIds = precinctIds;
return this;
}
// function: setCandidatesToRoundEliminated
// purpose: setter for candidatesToRoundEliminated object
// param: candidatesToRoundEliminated map of candidateID to round in which they were eliminated
ResultsWriter setCandidatesToRoundEliminated(Map<String, Integer> candidatesToRoundEliminated) {
// roundToEliminatedCandidates is the inverse of candidatesToRoundEliminated map
// so we can look up who got eliminated for each round
roundToEliminatedCandidates = new HashMap<>();
// candidate is used for indexing over all candidates in candidatesToRoundEliminated
for (String candidate : candidatesToRoundEliminated.keySet()) {
// round is the current candidate's round of elimination
int round = candidatesToRoundEliminated.get(candidate);
roundToEliminatedCandidates.computeIfAbsent(round, k -> new LinkedList<>());
roundToEliminatedCandidates.get(round).add(candidate);
}
return this;
}
// function: setWinnerToRound
// purpose: setter for the winning candidates
// param: map from winning candidate name to the round in which they won
ResultsWriter setWinnerToRound(Map<String, Integer> winnerToRound) {
// very similar to the logic in setCandidatesToRoundEliminated above
roundToWinningCandidates = new HashMap<>();
for (String candidate : winnerToRound.keySet()) {
int round = winnerToRound.get(candidate);
roundToWinningCandidates.computeIfAbsent(round, k -> new LinkedList<>());
roundToWinningCandidates.get(round).add(candidate);
}
return this;
}
// function: setContestConfig
// purpose: setter for ContestConfig object
// param: config the ContestConfig object to use when writing results
ResultsWriter setContestConfig(ContestConfig config) {
this.config = config;
return this;
}
// function: setTimestampString
// purpose: setter for timestampString string used for creating output file names
// param: timestampString string to use for creating output file names
ResultsWriter setTimestampString(String timestampString) {
this.timestampString = timestampString;
return this;
}
// function: generatePrecinctSummarySpreadsheet
// purpose: creates a summary spreadsheet for the votes in a particular precinct
// param: roundTallies is map from precinct to the round-by-round vote count in the precinct
void generatePrecinctSummarySpreadsheets(
Map<String, Map<Integer, Map<String, BigDecimal>>> precinctRoundTallies) throws IOException {
Set<String> filenames = new HashSet<>();
for (String precinct : precinctRoundTallies.keySet()) {
// precinctFileString is a unique filesystem-safe string which can be used for creating
// the precinct output filename
String precinctFileString = getPrecinctFileString(precinct, filenames);
// filename for output
String outputFileName =
String.format("%s_%s_precinct_summary", this.timestampString, precinctFileString);
// full path for output
String outputPath =
Paths.get(config.getOutputDirectory(), outputFileName).toAbsolutePath().toString();
generateSummarySpreadsheet(precinctRoundTallies.get(precinct), precinct, outputPath);
// generate json output
generateSummaryJson(precinctRoundTallies.get(precinct), precinct, outputPath);
}
}
// function: generateSummarySpreadsheet
// purpose: creates a summary spreadsheet .csv file
// param: roundTallies is the round-by-count count of votes per candidate
// param: precinct indicates which precinct we're reporting results for (null means all)
// param: outputPath is the full path of the file to save
// file access: write / create
private void generateSummarySpreadsheet(
Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath)
throws IOException {
String csvPath = outputPath + ".csv";
Logger.log(Level.INFO, "Generating summary spreadsheets: %s", csvPath);
// Get all candidates sorted by their first round tally. This determines the display order.
// container for firstRoundTally
Map<String, BigDecimal> firstRoundTally = roundTallies.get(1);
// candidates sorted by first round tally
List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally);
// totalActiveVotesPerRound is a map of round to active votes in each round
Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>();
// round indexes over all rounds plus final results round
for (int round = 1; round <= numRounds; round++) {
// tally is map of candidate to tally for the current round
Map<String, BigDecimal> tallies = roundTallies.get(round);
// total will contain total votes for all candidates in this round
// this is used for calculating other derived data
BigDecimal total = BigDecimal.ZERO;
// tally indexes over all tallies for the current round
for (BigDecimal tally : tallies.values()) {
total = total.add(tally);
}
totalActiveVotesPerRound.put(round, total);
}
// csvPrinter will be used to write output to csv file
CSVPrinter csvPrinter;
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath));
csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s\n"
+ "Please check the file path and permissions!", csvPath, exception.toString());
throw exception;
}
// print contest info
addHeaderRows(csvPrinter, precinct);
// add a row header for the round column labels
csvPrinter.print("Rounds");
// round indexes over all rounds
for (int round = 1; round <= numRounds; round++) {
// label string will have the actual text which goes in the cell
String label = String.format("Round %d", round);
// cell for round label
csvPrinter.print(label);
}
csvPrinter.println();
// actions don't make sense in individual precinct results
if (precinct == null || precinct.isEmpty()) {
addActionRows(csvPrinter);
}
// For each candidate: for each round: output total votes
// candidate indexes over all candidates
for (String candidate : sortedCandidates) {
// show each candidate row with their totals for each round
// text for the candidate name
String candidateDisplayName = config.getNameForCandidateCode(candidate);
csvPrinter.print(candidateDisplayName);
// round indexes over all rounds
for (int round = 1; round <= numRounds; round++) {
// vote tally this round
BigDecimal thisRoundTally = roundTallies.get(round).get(candidate);
// not all candidates may have a tally in every round
if (thisRoundTally == null) {
thisRoundTally = BigDecimal.ZERO;
}
// total votes cell
csvPrinter.print(thisRoundTally.toString());
}
// advance to next line
csvPrinter.println();
}
// row for the inactive CVR counts
// inactive CVR header cell
csvPrinter.print("Inactive ballots");
// round indexes through all rounds
for (int round = 1; round <= numRounds; round++) {
// Exhausted/inactive count is the difference between the total ballots and the total votes
// still active or counting as residual surplus votes in the current round.
BigDecimal thisRoundInactive =
new BigDecimal(numBallots)
.subtract(totalActiveVotesPerRound.get(round))
.subtract(roundToResidualSurplus.get(round));
// total votes cell
csvPrinter.print(thisRoundInactive.toString());
}
csvPrinter.println();
// row for residual surplus (if needed)
// We check if we accumulated any residual surplus over the course of the tabulation by testing
// whether the value in the final round is positive.
if (roundToResidualSurplus.get(numRounds).signum() == 1) {
csvPrinter.print("Residual surplus");
for (int round = 1; round <= numRounds; round++) {
csvPrinter.print(roundToResidualSurplus.get(round).toString());
}
csvPrinter.println();
}
// write xls to disk
try {
// output stream is used to write data to disk
csvPrinter.flush();
csvPrinter.close();
} catch (IOException exception) {
Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString());
throw exception;
}
}
// function: addActionRows
// "action" rows describe which candidates were eliminated or elected
// purpose: output rows to csv file describing which actions were taken in each round
// param: csvPrinter object for writing csv file
private void addActionRows(CSVPrinter csvPrinter) throws IOException {
// print eliminated candidates in first action row
csvPrinter.print("Eliminated");
// for each round print any candidates who were eliminated
for (int round = 1; round <= numRounds; round++) {
// list of all candidates eliminated in this round
List<String> eliminated = roundToEliminatedCandidates.get(round);
if (eliminated != null && eliminated.size() > 0) {
addActionRowCandidates(eliminated, csvPrinter);
} else {
csvPrinter.print("");
}
}
csvPrinter.println();
// print elected candidates in second action row
csvPrinter.print("Elected");
// for each round print any candidates who were elected
for (int round = 1; round <= numRounds; round++) {
// list of all candidates eliminated in this round
List<String> winners = roundToWinningCandidates.get(round);
if (winners != null && winners.size() > 0) {
addActionRowCandidates(winners, csvPrinter);
} else {
csvPrinter.print("");
}
}
csvPrinter.println();
}
// function: addActionRowCandidates
// purpose: add the given candidate(s) names to the csv file next cell
// param: candidates list of candidate names to add to the next cell
// param: csvPrinter object for output to csv file
private void addActionRowCandidates(List<String> candidates, CSVPrinter csvPrinter)
throws IOException {
List<String> candidateDisplayNames = new ArrayList<>();
// build list of display names
for (String candidate : candidates) {
candidateDisplayNames.add(config.getNameForCandidateCode(candidate));
}
// concatenate them using semi-colon for display in a single cell
String candidateCellText = String.join("; ", candidateDisplayNames);
// print the candidate name list
csvPrinter.print(candidateCellText);
}
// function: addHeaderRows
// purpose: add arbitrary header rows and cell to the top of the visualizer spreadsheet
private void addHeaderRows(CSVPrinter csvPrinter, String precinct) throws IOException {
csvPrinter.printRecord("Contest", config.getContestName());
csvPrinter.printRecord("Jurisdiction", config.getContestJurisdiction());
csvPrinter.printRecord("Office", config.getContestOffice());
csvPrinter.printRecord("Date", config.getContestDate());
csvPrinter.printRecord("Threshold", winningThreshold.toString());
if (precinct != null && !precinct.isEmpty()) {
csvPrinter.printRecord("Precinct", precinct);
}
csvPrinter.println();
}
// function: sortCandidatesByTally
// purpose: given a map of candidates to tally return a list of all input candidates
// sorted from highest tally to lowest
// param: tally map of candidateID to tally
// return: list of all input candidates sorted from highest tally to lowest
private List<String> sortCandidatesByTally(Map<String, BigDecimal> tally) {
// entries will contain all the input tally entries in sorted order
List<Map.Entry<String, BigDecimal>> entries = new ArrayList<>(tally.entrySet());
// anonymous custom comparator will sort undeclared write in candidates to last place
entries.sort(
(firstObject, secondObject) -> {
// result of the comparison
int ret;
if (firstObject.getKey().equals(config.getUndeclaredWriteInLabel())) {
ret = 1;
} else if (secondObject.getKey().equals(config.getUndeclaredWriteInLabel())) {
ret = -1;
} else {
ret = (secondObject.getValue()).compareTo(firstObject.getValue());
}
return ret;
});
// container list for the final results
List<String> sortedCandidates = new LinkedList<>();
// index over all entries
for (Map.Entry<String, BigDecimal> entry : entries) {
sortedCandidates.add(entry.getKey());
}
return sortedCandidates;
}
// function: getPrecinctFileString
// purpose: return a unique, valid string for this precinct's output spreadsheet filename
// param: precinct is the name of the precinct
// param: filenames is the set of filenames we've already generated
// return: the new filename
private String getPrecinctFileString(String precinct, Set<String> filenames) {
// sanitized is the precinct name with all special characters converted to underscores
String sanitized = sanitizeStringForOutput(precinct);
// filename is the string that we'll eventually return
String filename = sanitized;
// appendNumber is used to find a unique filename (in practice this really shouldn't be
// necessary because different precinct names shouldn't have the same sanitized name, but we're
// doing it here to be safe)
int appendNumber = 2;
while (filenames.contains(filename)) {
filename = sanitized + "_" + appendNumber++;
}
filenames.add(filename);
return filename;
}
// function: generateOverallSummaryFiles
// purpose: creates a summary spreadsheet and JSON for the full contest
// param: roundTallies is the round-by-round count of votes per candidate
void generateOverallSummaryFiles(Map<Integer, Map<String, BigDecimal>> roundTallies)
throws IOException {
String outputPath =
getOutputFilePath(
config.getOutputDirectory(),
"summary",
timestampString,
config.isSequentialMultiSeatEnabled()
? config.getSequentialWinners().size() + 1
: null);
// generate the spreadsheet
generateSummarySpreadsheet(roundTallies, null, outputPath);
// generate json output
generateSummaryJson(roundTallies, null, outputPath);
}
// create NIST Common Data Format CVR json
void generateCdfJson(List<CastVoteRecord> castVoteRecords)
throws IOException, RoundSnapshotDataMissingException {
// generate GpUnitIds for precincts (identify election jurisdiction and precincts)
GpUnitIds = generateGpUnitIds();
HashMap<String, Object> outputJson = new HashMap<>();
String outputPath =
getOutputFilePath(
config.getOutputDirectory(),
"cvr_cdf",
timestampString,
config.isSequentialMultiSeatEnabled()
? config.getSequentialWinners().size() + 1
: null)
+ ".json";
Logger.log(Level.INFO, "Generating CVR CDF JSON file: %s...", outputPath);
outputJson.put("CVR", generateCdfMapForCvrs(castVoteRecords));
outputJson.put("Election", new Map[]{generateCdfMapForElection()});
outputJson.put(
"GeneratedDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));
outputJson.put("GpUnit", generateCdfMapForGpUnits());
outputJson.put("ReportGeneratingDeviceIds", new String[]{CDF_REPORTING_DEVICE_ID});
outputJson.put(
"ReportingDevice",
new Map[]{
Map.ofEntries(
entry("@id", CDF_REPORTING_DEVICE_ID),
entry("@type", "CVR.ReportingDevice"),
entry("Application", "RCVRC Tabulator"),
entry("Manufacturer", "Bright Spots"))
});
outputJson.put("Version", "1.0.0");
outputJson.put("@type", "CVR.CastVoteRecordReport");
generateJsonFile(outputPath, outputJson);
}
// generate map of GpUnitIds
// we map from precinctId => GpUnitId
// as lookups will be done from precinctId during cvr creation
private Map<String, String> generateGpUnitIds() {
Map<String, String> GpUnitIdToPrecinctId = new HashMap<>();
int GpUnitIdIndex = 0;
// for every precinctId add an entry
for (String precinctId : precinctIds) {
GpUnitIdToPrecinctId.put(precinctId, String.format(CDF_GPU_ID_FORMAT, ++GpUnitIdIndex));
}
return GpUnitIdToPrecinctId;
}
// generates json containing precinct IDs
private List<Map<String, Object>> generateCdfMapForGpUnits() {
// create the GpUnit map
List<Map<String, Object>> GpUnitMaps = new LinkedList<>();
// and add the election-scope entry for the election jurisdiction
GpUnitMaps.add(
Map.ofEntries(
entry("@id", CDF_GPU_ID),
entry("Type", "other"),
entry("OtherType", "Election Scope Jurisdiction"),
entry("Name", config.getContestJurisdiction()),
entry("@type", "CVR.GpUnit")));
// generate GpUnit entries
for (Entry<String, String> entry : GpUnitIds.entrySet()) {
GpUnitMaps.add(
Map.ofEntries(
entry("@id", entry.getValue()),
entry("Type", "precinct"),
entry("Name", entry.getKey()),
entry("@type", "CVR.GpUnit")));
}
return GpUnitMaps;
}
// purpose: helper method for generateCdfJson to compile the data for all the CVR snapshots
private List<Map<String, Object>> generateCdfMapForCvrs(List<CastVoteRecord> castVoteRecords)
throws RoundSnapshotDataMissingException {
List<Map<String, Object>> cvrMaps = new LinkedList<>();
for (CastVoteRecord cvr : castVoteRecords) {
List<Map<String, Object>> cvrSnapshots = new LinkedList<>();
cvrSnapshots.add(generateCvrSnapshotMap(cvr, null, null));
String sanitizedId = sanitizeStringForOutput(cvr.getID());
// copy most recent round snapshot data to subsequent rounds
// until more snapshot data is available
List<Pair<String, BigDecimal>> previousRoundSnapshotData = null;
for (int round = 1; round <= numRounds; round++) {
List<Pair<String, BigDecimal>> currentRoundSnapshotData =
cvr.getCdfSnapshotData().get(round);
if (currentRoundSnapshotData == null) {
if (previousRoundSnapshotData == null) {
throw new RoundSnapshotDataMissingException(sanitizedId);
}
currentRoundSnapshotData = previousRoundSnapshotData;
}
cvrSnapshots.add(generateCvrSnapshotMap(cvr, round, currentRoundSnapshotData));
previousRoundSnapshotData = currentRoundSnapshotData;
}
// create new cvr map entry
Map<String, Object> cvrMap = new HashMap<>();
cvrMap.put("BallotPrePrintedId", sanitizedId);
cvrMap.put("CurrentSnapshotId", generateCvrSnapshotID(sanitizedId, numRounds));
cvrMap.put("CVRSnapshot", cvrSnapshots);
cvrMap.put("ElectionId", CDF_ELECTION_ID);
cvrMap.put("@type", "CVR.CVR");
// if using precincts add GpUnitId for cvr precinct
if (config.isTabulateByPrecinctEnabled()) {
String GpUnitId = GpUnitIds.get(cvr.getPrecinct());
cvrMap.put("BallotStyleUnitId", GpUnitId);
}
cvrMaps.add(cvrMap);
}
return cvrMaps;
}
// purpose: helper for generateCdfMapForCvrs to handle a single CVR in a single round
private Map<String, Object> generateCvrSnapshotMap(
CastVoteRecord cvr, Integer round, List<Pair<String, BigDecimal>> currentRoundSnapshotData) {
List<Map<String, Object>> selectionMapList = new LinkedList<>();
List<Map.Entry<String, List<Integer>>> candidatesWithRanksList =
getCandidatesWithRanksList(cvr.rankToCandidateIDs);
for (Map.Entry<String, List<Integer>> candidateWithRanks : candidatesWithRanksList) {
String candidateCode = candidateWithRanks.getKey();
String isAllocable = "unknown";
BigDecimal numberVotes = BigDecimal.ONE;
if (currentRoundSnapshotData != null) {
// scanning the list isn't actually expensive because it will almost always be very short
for (Pair<String, BigDecimal> allocation : currentRoundSnapshotData) {
if (allocation.getKey().equals(candidateCode)) {
isAllocable = "yes";
numberVotes = allocation.getValue();
break;
}
}
// didn't find an allocation, i.e. this ballot didn't contribute all or part of a vote to
// this candidate in this round
if (isAllocable.equals("unknown")) {
isAllocable = "no";
// not sure what numberVotes should be in this situation
}
}
String fractionalVotes = null;
if (!numberVotes.equals(BigDecimal.ONE)) {
BigDecimal remainder = numberVotes.remainder(BigDecimal.ONE);
if (remainder.signum() == 1) {
fractionalVotes = remainder.toString().substring(1); // remove the 0 before the decimal
}
}
List<Map<String, Object>> selectionPositionMapList = new LinkedList<>();
for (int rank : candidateWithRanks.getValue()) {
Map<String, Object> selectionPositionMap = new HashMap<>();
selectionPositionMap.put("HasIndication", "yes");
selectionPositionMap.put("IsAllocable", isAllocable);
selectionPositionMap.put("NumberVotes", numberVotes.intValue());
selectionPositionMap.put("Rank", rank);
selectionPositionMap.put("@type", "CVR.SelectionPosition");
if (fractionalVotes != null) {
selectionPositionMap.put("FractionalVotes", fractionalVotes);
}
selectionPositionMapList.add(selectionPositionMap);
if (isAllocable.equals("yes")) {
// If there are duplicate rankings for the candidate on this ballot, only the first one
// can be allocable.
isAllocable = "no";
}
}
selectionMapList.add(
Map.ofEntries(
entry("ContestSelectionId", getCdfIdForCandidateCode(candidateCode)),
entry("SelectionPosition", selectionPositionMapList),
entry("@type", "CVR.CVRContestSelection")));
}
Map<String, Object> contestMap =
Map.ofEntries(
entry("ContestId", CDF_CONTEST_ID),
entry("CVRContestSelection", selectionMapList),
entry("@type", "CVR.CVRContest"));
return Map.ofEntries(
entry("@id", generateCvrSnapshotID(sanitizeStringForOutput(cvr.getID()), round)),
entry("CVRContest", new Map[]{contestMap}),
entry("Type", round != null ? "interpreted" : "original"),
entry("@type", "CVR.CVRSnapshot"));
}
private Map<String, Object> generateCdfMapForElection() {
HashMap<String, Object> electionMap = new HashMap<>();
List<Map<String, Object>> contestSelections = new LinkedList<>();
List<String> candidateCodes = new LinkedList<>(config.getCandidateCodeList());
Collections.sort(candidateCodes);
for (String candidateCode : candidateCodes) {
Map<String, String> codeMap =
Map.ofEntries(
entry("@type", "CVR.Code"),
entry("Type", "other"),
entry("OtherType", "vendor-label"),
entry("Value", config.getNameForCandidateCode(candidateCode)));
contestSelections.add(
Map.ofEntries(
entry("@id", getCdfIdForCandidateCode(candidateCode)),
entry("@type", "CVR.ContestSelection"),
entry("Code", new Map[]{codeMap})));
}
Map<String, Object> contestJson =
Map.ofEntries(
entry("@id", CDF_CONTEST_ID),
entry("ContestSelection", contestSelections),
entry("@type", "CVR.CandidateContest"));
electionMap.put("@id", CDF_ELECTION_ID);
electionMap.put("Contest", new Map[]{contestJson});
electionMap.put("ElectionScopeId", CDF_GPU_ID);
electionMap.put("@type", "CVR.Election");
return electionMap;
}
// function: generateSummaryJson
// purpose: create summary json data for use in visualizer, unit tests and other tools
// param: outputPath where to write json file
// param: roundTallies all tally information
// file access: write to outputPath
private void generateSummaryJson(
Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath)
throws IOException {
String jsonPath = outputPath + ".json";
Logger.log(Level.INFO, "Generating summary JSON file: %s", jsonPath);
// root outputJson dict will have two entries:
// results - vote totals, transfers, and candidates elected / eliminated
// config - global config into
HashMap<String, Object> outputJson = new HashMap<>();
// config will contain contest configuration info
HashMap<String, Object> configData = new HashMap<>();
// add config header info
configData.put("contest", config.getContestName());
configData.put("jurisdiction", config.getContestJurisdiction());
configData.put("office", config.getContestOffice());
configData.put("date", config.getContestDate());
configData.put("threshold", winningThreshold);
if (precinct != null && !precinct.isEmpty()) {
configData.put("precinct", precinct);
}
// results will be a list of round data objects
ArrayList<Object> results = new ArrayList<>();
// for each round create objects for json serialization
for (int round = 1; round <= numRounds; round++) {
// container for all json data this round:
HashMap<String, Object> roundData = new HashMap<>();
// add round number (this is implied by the ordering but for debugging we are explicit)
roundData.put("round", round);
// add actions if this is not a precinct summary
if (precinct == null || precinct.isEmpty()) {
// actions is a list of one or more action objects
ArrayList<Object> actions = new ArrayList<>();
addActionObjects("elected", roundToWinningCandidates.get(round), round, actions);
// add any elimination actions
addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions);
// add action objects
roundData.put("tallyResults", actions);
}
// add tally object
roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round)));
// add roundData to results list
results.add(roundData);
}
// add config data to root object
outputJson.put("config", configData);
// add results to root object
outputJson.put("results", results);
// write results to disk
generateJsonFile(jsonPath, outputJson);
}
private Map<String, BigDecimal> updateCandidateNamesInTally(Map<String, BigDecimal> tally) {
Map<String, BigDecimal> newTally = new HashMap<>();
for (String key : tally.keySet()) {
newTally.put(config.getNameForCandidateCode(key), tally.get(key));
}
return newTally;
}
// function: addActionObjects
// purpose: adds action objects to input action list representing all actions applied this round
// each action will have a type followed by a list of 0 or more vote transfers
// (sometimes there is no vote transfer if a candidate had no votes to transfer)
// param: actionType is this an elimination or election action
// param: candidates list of all candidates action is applied to
// param: round which this action occurred
// param: actions list to add new action objects to
private void addActionObjects(
String actionType, List<String> candidates, int round, ArrayList<Object> actions) {
// check for valid candidates:
// "drop undeclared write-in" may result in no one actually being eliminated
if (candidates != null && candidates.size() > 0) {
// transfers contains all vote transfers for this round
// we add one to the round since transfers are currently stored under the round AFTER
// the tallies which triggered them
Map<String, Map<String, BigDecimal>> roundTransfers =
tallyTransfers.getTransfersForRound(round + 1);
// candidate iterates over all candidates who had this action applied to them
for (String candidate : candidates) {
// for each candidate create an action object
HashMap<String, Object> action = new HashMap<>();
// add the specified action type
action.put(actionType, config.getNameForCandidateCode(candidate));
// check if there are any transfers
if (roundTransfers != null) {
Map<String, BigDecimal> transfersFromCandidate = roundTransfers.get(candidate);
if (transfersFromCandidate != null) {
// We want to replace candidate IDs with names here, too.
Map<String, BigDecimal> translatedTransfers = new HashMap<>();
for (String candidateId : transfersFromCandidate.keySet()) {
// candidateName will be null for special values like "exhausted"
String candidateName = config.getNameForCandidateCode(candidateId);
translatedTransfers.put(
candidateName != null ? candidateName : candidateId,
transfersFromCandidate.get(candidateId));
}
action.put("transfers", translatedTransfers);
}
}
if (!action.containsKey("transfers")) {
// add an empty map
action.put("transfers", new HashMap<String, BigDecimal>());
}
// add the action object to list
actions.add(action);
}
}
}
// Exception class used when we're unexpectedly missing snapshot data for a cast vote record
// during CDF JSON generation. If this happens, there's a bug in the tabulation code.
static class RoundSnapshotDataMissingException extends Exception {
private final String cvrId;
RoundSnapshotDataMissingException(String cvrId) {
this.cvrId = cvrId;
}
String getCvrId() {
return cvrId;
}
}
}
| add Winner(s) row in CSV output
| src/main/java/network/brightspots/rcv/ResultsWriter.java | add Winner(s) row in CSV output |
|
Java | mpl-2.0 | f2c78451534a31bb7e97a1fb3229184b74e26ca9 | 0 | OnlyInAmerica/BLEMeshChat,OnlyInAmerica/BLEMeshChat | package pro.dbro.ble.transport.ble;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattServer;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import pro.dbro.ble.data.model.DataUtil;
import pro.dbro.ble.protocol.IdentityPacket;
import pro.dbro.ble.protocol.MessagePacket;
import pro.dbro.ble.protocol.Protocol;
import pro.dbro.ble.transport.ConnectionGovernor;
import pro.dbro.ble.transport.ConnectionListener;
import pro.dbro.ble.transport.Transport;
import pro.dbro.ble.ui.activities.LogConsumer;
/**
* Created by davidbrodsky on 10/20/14.
*/
public class BLETransport extends Transport implements ConnectionGovernor, ConnectionListener {
public static final String TAG = "BLETransport";
/** How many items to send for each request for this client's items */
private static final int MESSAGES_PER_RESPONSE = 10;
private static final int IDENTITIES_PER_RESPONSE = 10;
private Context mContext;
private BLECentral mCentral;
private BLEPeripheral mPeripheral;
private LogConsumer mLogger;
/** Outgoing message queues by device key. see {@link #getKeyForDevice(byte[], String)} */
private HashMap<String, ArrayDeque<MessagePacket>> mMessageOutboxes = new HashMap<>();
/** Outgoing identity queues by device key */
private HashMap<String, ArrayDeque<IdentityPacket>> mIdentitiesOutboxes = new HashMap<>();
/** Remote identities by device address */
private HashMap<String, IdentityPacket> mConnectedAddressesToIdentities = new HashMap<>();
// <editor-fold desc="Public API">
public BLETransport(@NonNull Context context, @NonNull IdentityPacket identityPacket, @NonNull Protocol protocol, @NonNull TransportDataProvider dataProvider) {
super(identityPacket, protocol, dataProvider);
mContext = context.getApplicationContext();
init();
}
public void setLogConsumer(LogConsumer logger) {
mLogger = logger;
mCentral.setLogConsumer(logger);
mPeripheral.setLogConsumer(logger);
}
@Override
public void makeAvailable() {
mCentral.start();
mPeripheral.start();
}
@Override
public void sendMessage(MessagePacket messagePacket) {
// TODO If Message is instanceof DirectMessage etc, try to send directly to device
// Note the message should already be stored and will be automatically delivered on next connection
}
@Override
public void makeUnavailable() {
mCentral.stop();
mPeripheral.stop();
}
// </editor-fold desc="Public API">
// <editor-fold desc="Private API">
private void init() {
mCentral = new BLECentral(mContext);
mCentral.setConnectionGovernor(this);
mCentral.setConnectionListener(this);
// These Central requests are executed in order
// Note the local Identity must be first presented to the remote peer
// so that it can calculate which identities to present back
mCentral.addDefaultBLECentralRequest(mIdentityWriteRequest);
mCentral.addDefaultBLECentralRequest(mIdentityReadRequest);
mCentral.addDefaultBLECentralRequest(mMessageReadRequest);
mCentral.addDefaultBLECentralRequest(mMessageWriteRequest);
mPeripheral = new BLEPeripheral(mContext);
mPeripheral.setConnectionGovernor(this);
mPeripheral.setConnectionListener(this);
mPeripheral.addDefaultBLEPeripheralResponse(mMessageReadResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mIdentityReadResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mMessageWriteResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mIdentityWriteResponse);
}
/** ConnectionGovernor */
@Override
public boolean shouldConnectToAddress(String address) {
boolean centralConnectedToPeer = mCentral.getConnectedDeviceAddresses().contains(address);
boolean peripheralConnectedToPeer = mPeripheral.getConnectedDeviceAddresses().contains(address);
boolean mayConnect = !centralConnectedToPeer && !peripheralConnectedToPeer;
if (!mayConnect) {
Log.i("ConnectionGovernor", String.format("Blocking connection to %s. Central Connections: %d (includes peer: %b) Peripheral Connections: %d (includes peer: %b)",
address,
mCentral.getConnectedDeviceAddresses().size(),
centralConnectedToPeer,
mPeripheral.getConnectedDeviceAddresses().size(),
peripheralConnectedToPeer));
}
return mayConnect;
}
/** BLECentralRequests */
BLECentralRequest mMessageReadRequest = new BLECentralRequest(GATT.MESSAGES_READ, BLECentralRequest.RequestType.READ) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
// Consume message from characteristic.getValue()
// If status == GATT_SUCCESS, return false to re-issue this request
// else if status == READ_NOT_PERMITTED, return true
if (characteristic.getValue() == null || characteristic.getValue().length == 0) {
return isCentralRequestComplete(status); // retry if got status success
}
MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(characteristic.getValue());
// Note this isn't the author of the message, but the courier who delivered it to us
IdentityPacket courierIdentity = mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress());
if (mCallback != null) mCallback.receivedMessageFromIdentity(receivedMessagePacket, courierIdentity);
logEvent("Central read message " + receivedMessagePacket.body);
return isCentralRequestComplete(status);
}
};
BLECentralRequest mIdentityReadRequest = new BLECentralRequest(GATT.IDENTITY_READ, BLECentralRequest.RequestType.READ) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
// Consume Identity from characteristic.getValue()
// If status == GATT_SUCCESS, return false to re-issue this request
// else if status == READ_NOT_PERMITTED, return true
if (characteristic.getValue() == null || characteristic.getValue().length == 0) {
return isCentralRequestComplete(status); // retry if got status success
}
IdentityPacket receivedIdentityPacket;
try {
receivedIdentityPacket = mProtocol.deserializeIdentity(characteristic.getValue());
} catch (IllegalArgumentException e) {
Log.w(TAG, String.format("Received malformed Identity from %s, ignoring", remotePeripheral.getDevice().getAddress()));
return true; // Don't try again. TODO Add some retry limit
}
handleIdentityBecameAvailable(remotePeripheral.getDevice().getAddress(), receivedIdentityPacket);
logEvent(String.format("Central read identity %s..", DataUtil.bytesToHex(receivedIdentityPacket.publicKey).substring(0,3)));
return isCentralRequestComplete(status);
}
};
BLECentralRequest mMessageWriteRequest = new BLECentralRequest(GATT.MESSAGES_WRITE, BLECentralRequest.RequestType.WRITE) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
MessagePacket justSent = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
Log.i(TAG, "Handling response after central sent message with body " + (justSent == null ? "null" : justSent.body));
if (justSent == null) {
// No data was available for this request. Mark request complete
logEvent("Central had no message for peer");
return true;
} else {
if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) {
mCallback.sentMessage(getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false), mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress()));
}
logEvent(String.format("Central wrote message %s..", justSent.body));
// If we have more messages to send, indicate request should be repeated
return (getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null);
}
}
@Override
public byte[] getDataToWrite(BluetoothGatt remotePeripheral) {
//return byte[] next_message
MessagePacket forRecipient = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
return (forRecipient == null ) ? null : forRecipient.rawPacket;
}
};
BLECentralRequest mIdentityWriteRequest = new BLECentralRequest(GATT.IDENTITY_WRITE, BLECentralRequest.RequestType.WRITE) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
IdentityPacket justSent = getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false);
if (justSent == null) {
//No data was available for this request. Mark request complete
logEvent("Central had no identity for peer");
return true;
} else {
if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) {
mCallback.sentIdentity(getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false),
mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress()));
}
logEvent(String.format("Central wrote identity %s..", DataUtil.bytesToHex(justSent.publicKey).substring(0,3)));
// If we have more messages to send, indicate request should be repeated
return (getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null);
}
}
@Override
public byte[] getDataToWrite(BluetoothGatt remotePeripheral) {
//return byte[] next_identity
IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
return (forRecipient == null) ? null : forRecipient.rawPacket;
}
};
/** BLEPeripheral Responses */
BLEPeripheralResponse mMessageReadResponse = new BLEPeripheralResponse(GATT.MESSAGES_READ, BLEPeripheralResponse.RequestType.READ) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
try {
// Get messages to send and send first
MessagePacket forRecipient = getNextMessageForDeviceAddress(remoteCentral.getAddress(), true);
if (forRecipient != null) {
boolean haveAnotherMessage = getNextMessageForDeviceAddress(remoteCentral.getAddress(), false) != null;
byte[] payload = forRecipient.rawPacket;
int responseGattStatus = haveAnotherMessage ? BluetoothGatt.GATT_SUCCESS : BluetoothGatt.GATT_READ_NOT_PERMITTED;
boolean responseSent = false;
try {
responseSent = localPeripheral.sendResponse(remoteCentral, requestId, responseGattStatus, 0, payload);
Log.w("SendResponse", "message read " + (responseGattStatus == BluetoothGatt.GATT_SUCCESS ? "" : " READ_NOT_PERMITTED") + " success: " + responseSent);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message read " + (responseGattStatus == BluetoothGatt.GATT_SUCCESS ? "" : " READ_NOT_PERMITTED"));
}
//Log.i(TAG, String.format("Responded to message read request with outgoing status %b. response sent: %b data (%d bytes): %s", responseGattStatus, responseSent, (payload == null || payload.length == 0) ? 0 : payload.length, (payload == null || payload.length == 0) ? "null" : DataUtil.bytesToHex(payload)));
if (responseSent) {
if (mCallback != null)
mCallback.sentMessage(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
logEvent(String.format("Peripheral sent message for peer %s", forRecipient.body));
return payload;
}
} else {
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null);
Log.w("SendResponse", "message read READ_NOT_PERMITTED success: " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message read READ_NOT_PERMITTED");
}
logEvent("Peripheral had no message for peer");
//Log.i(TAG, "Had no messages for peer. Sent READ_NOT_PERMITTED with success " + success);
}
} catch(Exception e) {
logEvent("Peripheral failed to send message");
e.printStackTrace();
}
return null;
}
};
BLEPeripheralResponse mIdentityReadResponse = new BLEPeripheralResponse(GATT.IDENTITY_READ, BLEPeripheralResponse.RequestType.READ) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Get identities to send and send first
IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remoteCentral.getAddress(), true);
if (forRecipient != null) {
// If we don't have a public key for this address, we'll only send one identity (the user's)
byte[] payload = forRecipient.rawPacket;
int responseGattStatus = BluetoothGatt.GATT_SUCCESS;
boolean responseSent = false;
try {
responseSent = localPeripheral.sendResponse(remoteCentral, requestId, responseGattStatus, 0, payload);
Log.w("SendResponse", "identity read success " + responseSent);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity read");
}
//Log.i(TAG, String.format("Responded to identity read request with outgoing status %b. response sent: %b data: %s", responseGattStatus, responseSent, (payload == null || payload.length == 0) ? "null" : DataUtil.bytesToHex(payload)));
if (responseSent && mCallback != null) mCallback.sentIdentity(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
if (responseSent) {
if (mCallback != null)
mCallback.sentIdentity(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
logEvent(String.format("Peripheral sent identity %s...", DataUtil.bytesToHex(forRecipient.publicKey).substring(0,3)));
return payload;
}
} else {
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null);
Log.w("SendResponse", "identity read READ_NOT_PERMITTED " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity read READ_NOT_PERMITTED");
}
logEvent("Peripheral had no identities for peer");
}
return null;
}
};
BLEPeripheralResponse mMessageWriteResponse = new BLEPeripheralResponse(GATT.MESSAGES_WRITE, BLEPeripheralResponse.RequestType.WRITE) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Consume message and send GATT_SUCCESS If valid and response needed
testValueVsCharacteristicValue(value, characteristic);
MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(value);
IdentityPacket courierIdentity = mConnectedAddressesToIdentities.get(remoteCentral.getAddress());
if (mCallback != null) mCallback.receivedMessageFromIdentity(receivedMessagePacket, courierIdentity);
if (responseNeeded) {
// TODO: Response code based on message validation?
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
Log.w("SendResponse", "message write success:" + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message write");
}
}
logEvent(String.format("Peripheral received message %s", receivedMessagePacket.body));
return null;
}
};
BLEPeripheralResponse mIdentityWriteResponse = new BLEPeripheralResponse(GATT.IDENTITY_WRITE, BLEPeripheralResponse.RequestType.WRITE) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Consume Identity and send GATT_SUCCESS if valid and response needed
testValueVsCharacteristicValue(value, characteristic);
if (value == null || value.length == 0) {
Log.i(TAG, "got empty write data");
} else {
Log.i(TAG, "got non-empty write data! length: " + value.length);
IdentityPacket receivedIdentityPacket = mProtocol.deserializeIdentity(value);
handleIdentityBecameAvailable(remoteCentral.getAddress(), receivedIdentityPacket);
logEvent(String.format("Peripheral received identity for %s with key: %s...", receivedIdentityPacket.alias, DataUtil.bytesToHex(receivedIdentityPacket.publicKey).substring(2,6)));
}
if (responseNeeded) {
// TODO: Response code based on message validation?
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
Log.w("SendResponse", "Successful identity write " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity write");
}
}
return null;
}
};
/** ConnectionListener */
@Override
public void connectedTo(String deviceAddress) {
// do nothing. We shouldn't report peer available until we have an Identity for it
}
@Override
public void disconnectedFrom(String deviceAddress) {
IdentityPacket disconnectedIdentityPacket = mConnectedAddressesToIdentities.remove(deviceAddress);
if (disconnectedIdentityPacket != null && mCallback != null) {
Log.i(TAG, "Report disconnect to " + deviceAddress);
mCallback.identityBecameUnavailable(disconnectedIdentityPacket);
} else {
// The reported device address changed since connection. With iOS devices this is common
if (mConnectedAddressesToIdentities.size() == 1) {
// It's safe to assume this is the client that has disconnected
String disconnectedAddress = ((Map.Entry <String, IdentityPacket>) mConnectedAddressesToIdentities.entrySet().toArray()[0]).getKey();
disconnectedFrom(disconnectedAddress);
} else {
Log.i(TAG, "Could not report disconnect to " + deviceAddress);
}
}
}
/** Utility */
@Nullable
private IdentityPacket getNextIdentityForDeviceAddress(String address, boolean removeFromQueue) {
byte[] publicKey = getPublicKeyForDeviceAddress(address);
return getNextIdentityForDevice(publicKey, address, removeFromQueue);
}
@Nullable
private MessagePacket getNextMessageForDeviceAddress(String address, boolean removeFromQueue) {
byte[] publicKey = getPublicKeyForDeviceAddress(address);
return getNextMessageForDevice(publicKey, address, removeFromQueue);
}
@Nullable
private MessagePacket getNextMessageForDevice(@Nullable byte[] publicKey, @NonNull String address, boolean removeFromQueue) {
String deviceKey = getKeyForDevice(publicKey, address);
if (publicKey == null) {
// This is a special case because we have no public key so we can't record delivery of any items
// Therefore we can't rely on mDataProvider.getMessagesForIdentity to not return items that were already sent
// So we'll ensure that we only perform that request once per device address
if (!mMessageOutboxes.containsKey(deviceKey)) {
ArrayDeque<MessagePacket> messagesForRecipient = mDataProvider.getMessagesForIdentity(null, MESSAGES_PER_RESPONSE);
mMessageOutboxes.put(deviceKey, messagesForRecipient);
} else {
// We've already sent our own Identity for this identity-less peer
Log.i(TAG, "Returning null for nextMessage to " + address);
return null;
}
}
else if (!mMessageOutboxes.containsKey(deviceKey) || mMessageOutboxes.get(deviceKey).size() == 0) {
ArrayDeque<MessagePacket> messagesForRecipient = mDataProvider.getMessagesForIdentity(publicKey, MESSAGES_PER_RESPONSE);
mMessageOutboxes.put(deviceKey, messagesForRecipient);
Log.i(TAG, String.format("Got %d messages for pk %s", messagesForRecipient.size(), DataUtil.bytesToHex(publicKey)));
}
if (mMessageOutboxes.get(deviceKey).size() == 0) return null;
return removeFromQueue ? mMessageOutboxes.get(deviceKey).poll() : mMessageOutboxes.get(deviceKey).peek();
}
@Nullable
private IdentityPacket getNextIdentityForDevice(@Nullable byte[] publicKey, String address, boolean removeFromQueue) {
String deviceKey = getKeyForDevice(publicKey, address);
if (publicKey == null) {
Log.i(TAG, "Getting identity response for no-identity peer at " + address);
// This is a special case because we have no public key so we can't record delivery of any items
// Therefore we can't rely on mDataProvider.getIdentitiesForIdentity to not return items that were already sent
// So we'll ensure that we only perform that request once per device address
if (!mIdentitiesOutboxes.containsKey(deviceKey)) {
ArrayDeque<IdentityPacket> identitiesForRecipient = mDataProvider.getIdentitiesForIdentity(null, IDENTITIES_PER_RESPONSE);
mIdentitiesOutboxes.put(deviceKey, identitiesForRecipient);
} else {
// We've already sent our own Identity for this identity-less peer
Log.i(TAG, "Returning null for nextIdentity to " + address);
return null;
}
}
else if (!mIdentitiesOutboxes.containsKey(deviceKey) || mIdentitiesOutboxes.get(deviceKey).size() == 0) {
// We have a public key for this peer. Proceed as normal
ArrayDeque<IdentityPacket> identitiesForRecipient = mDataProvider.getIdentitiesForIdentity(publicKey, IDENTITIES_PER_RESPONSE);
mIdentitiesOutboxes.put(deviceKey, identitiesForRecipient);
}
if (mIdentitiesOutboxes.get(deviceKey).size() == 0) return null;
return removeFromQueue ? mIdentitiesOutboxes.get(deviceKey).poll() : mIdentitiesOutboxes.get(deviceKey).peek();
}
private byte[] getPublicKeyForDeviceAddress(String address) {
byte[] publicKey = null;
if (mConnectedAddressesToIdentities.containsKey(address)) publicKey = mConnectedAddressesToIdentities.get(address).publicKey;
if (publicKey == null) {
// No public key on file, perform naive message send for now
Log.w(TAG, String.format("Don't have identity on file for device %s.", address));
}
return publicKey;
}
private boolean isCentralRequestComplete(int gattStatus) {
switch(gattStatus) {
case BluetoothGatt.GATT_READ_NOT_PERMITTED:
case BluetoothGatt.GATT_FAILURE:
return true; // request complete
case BluetoothGatt.GATT_SUCCESS:
return false; // peripheral reports more data available
default:
Log.w(TAG, String.format("Got unexpected GATT status %d", gattStatus));
return true;
}
}
private void testValueVsCharacteristicValue(byte[] value, BluetoothGattCharacteristic characteristic) {
if (value != null && characteristic.getValue() != null) {
Log.i(TAG, "are value and characteristic.getValue equal: " + Arrays.equals(value, characteristic.getValue()));
} else if (value != null) {
Log.i(TAG, "characteristic.getValue null, but value not null");
} else if(characteristic.getValue() != null) {
Log.i(TAG, "value is null but characterisitc.getValue not null");
}
}
/**
* Return a key used for {@link #mIdentitiesOutboxes} and {@link #mMessageOutboxes} using
* a string representation of the public key or device address if public key is null
*/
private String getKeyForDevice(@Nullable byte[] publicKey, @Nullable String deviceAddress) {
if (publicKey != null) return DataUtil.bytesToHex(publicKey);
return deviceAddress;
}
private void logEvent(String event) {
if (mLogger != null) {
mLogger.onLogEvent(event);
} else {
Log.i(TAG, event);
}
}
private void handleIdentityBecameAvailable(String fromAddress, IdentityPacket receivedIdentityPacket) {
if (!mConnectedAddressesToIdentities.containsKey(fromAddress)) {
mConnectedAddressesToIdentities.put(fromAddress, receivedIdentityPacket);
Log.i(TAG, "Got identity for " + fromAddress);
if (mCallback != null) mCallback.identityBecameAvailable(receivedIdentityPacket);
}
}
// </editor-fold desc="Private API">
}
| app/src/main/java/pro/dbro/ble/transport/ble/BLETransport.java | package pro.dbro.ble.transport.ble;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattServer;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import pro.dbro.ble.data.model.DataUtil;
import pro.dbro.ble.protocol.IdentityPacket;
import pro.dbro.ble.protocol.MessagePacket;
import pro.dbro.ble.protocol.Protocol;
import pro.dbro.ble.transport.ConnectionGovernor;
import pro.dbro.ble.transport.ConnectionListener;
import pro.dbro.ble.transport.Transport;
import pro.dbro.ble.ui.activities.LogConsumer;
/**
* Created by davidbrodsky on 10/20/14.
*/
public class BLETransport extends Transport implements ConnectionGovernor, ConnectionListener {
public static final String TAG = "BLETransport";
/** How many items to send for each request for this client's items */
private static final int MESSAGES_PER_RESPONSE = 10;
private static final int IDENTITIES_PER_RESPONSE = 10;
private Context mContext;
private BLECentral mCentral;
private BLEPeripheral mPeripheral;
private LogConsumer mLogger;
/** Outgoing message queues by device key. see {@link #getKeyForDevice(byte[], String)} */
private HashMap<String, ArrayDeque<MessagePacket>> mMessageOutboxes = new HashMap<>();
/** Outgoing identity queues by device key */
private HashMap<String, ArrayDeque<IdentityPacket>> mIdentitiesOutboxes = new HashMap<>();
/** Remote identities by device address */
private HashMap<String, IdentityPacket> mConnectedAddressesToIdentities = new HashMap<>();
// <editor-fold desc="Public API">
public BLETransport(@NonNull Context context, @NonNull IdentityPacket identityPacket, @NonNull Protocol protocol, @NonNull TransportDataProvider dataProvider) {
super(identityPacket, protocol, dataProvider);
mContext = context.getApplicationContext();
init();
}
public void setLogConsumer(LogConsumer logger) {
mLogger = logger;
mCentral.setLogConsumer(logger);
mPeripheral.setLogConsumer(logger);
}
@Override
public void makeAvailable() {
mCentral.start();
mPeripheral.start();
}
@Override
public void sendMessage(MessagePacket messagePacket) {
// TODO If Message is instanceof DirectMessage etc, try to send directly to device
// Note the message should already be stored and will be automatically delivered on next connection
}
@Override
public void makeUnavailable() {
mCentral.stop();
mPeripheral.stop();
}
// </editor-fold desc="Public API">
// <editor-fold desc="Private API">
private void init() {
mCentral = new BLECentral(mContext);
mCentral.setConnectionGovernor(this);
mCentral.setConnectionListener(this);
// These Central requests are executed in order
// Note the local Identity must be first presented to the remote peer
// so that it can calculate which identities to present back
mCentral.addDefaultBLECentralRequest(mIdentityWriteRequest);
mCentral.addDefaultBLECentralRequest(mIdentityReadRequest);
mCentral.addDefaultBLECentralRequest(mMessageReadRequest);
mCentral.addDefaultBLECentralRequest(mMessageWriteRequest);
mPeripheral = new BLEPeripheral(mContext);
mPeripheral.setConnectionGovernor(this);
mPeripheral.setConnectionListener(this);
mPeripheral.addDefaultBLEPeripheralResponse(mMessageReadResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mIdentityReadResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mMessageWriteResponse);
mPeripheral.addDefaultBLEPeripheralResponse(mIdentityWriteResponse);
}
/** ConnectionGovernor */
@Override
public boolean shouldConnectToAddress(String address) {
boolean centralConnectedToPeer = mCentral.getConnectedDeviceAddresses().contains(address);
boolean peripheralConnectedToPeer = mPeripheral.getConnectedDeviceAddresses().contains(address);
boolean mayConnect = !centralConnectedToPeer && !peripheralConnectedToPeer;
if (!mayConnect) {
Log.i("ConnectionGovernor", String.format("Blocking connection to %s. Central Connections: %d (includes peer: %b) Peripheral Connections: %d (includes peer: %b)",
address,
mCentral.getConnectedDeviceAddresses().size(),
centralConnectedToPeer,
mPeripheral.getConnectedDeviceAddresses().size(),
peripheralConnectedToPeer));
}
return mayConnect;
}
/** BLECentralRequests */
BLECentralRequest mMessageReadRequest = new BLECentralRequest(GATT.MESSAGES_READ, BLECentralRequest.RequestType.READ) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
// Consume message from characteristic.getValue()
// If status == GATT_SUCCESS, return false to re-issue this request
// else if status == READ_NOT_PERMITTED, return true
if (characteristic.getValue() == null || characteristic.getValue().length == 0) {
return isCentralRequestComplete(status); // retry if got status success
}
MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(characteristic.getValue());
// Note this isn't the author of the message, but the courier who delivered it to us
IdentityPacket courierIdentity = mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress());
if (mCallback != null) mCallback.receivedMessageFromIdentity(receivedMessagePacket, courierIdentity);
logEvent("Central read message " + receivedMessagePacket.body);
return isCentralRequestComplete(status);
}
};
BLECentralRequest mIdentityReadRequest = new BLECentralRequest(GATT.IDENTITY_READ, BLECentralRequest.RequestType.READ) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
// Consume Identity from characteristic.getValue()
// If status == GATT_SUCCESS, return false to re-issue this request
// else if status == READ_NOT_PERMITTED, return true
if (characteristic.getValue() == null || characteristic.getValue().length == 0) {
return isCentralRequestComplete(status); // retry if got status success
}
IdentityPacket receivedIdentityPacket;
try {
receivedIdentityPacket = mProtocol.deserializeIdentity(characteristic.getValue());
} catch (IllegalArgumentException e) {
Log.w(TAG, String.format("Received malformed Identity from %s, ignoring", remotePeripheral.getDevice().getAddress()));
return true; // Don't try again. TODO Add some retry limit
}
handleIdentityBecameAvailable(remotePeripheral.getDevice().getAddress(), receivedIdentityPacket);
logEvent(String.format("Central read identity %s..", DataUtil.bytesToHex(receivedIdentityPacket.publicKey).substring(0,3)));
return isCentralRequestComplete(status);
}
};
BLECentralRequest mMessageWriteRequest = new BLECentralRequest(GATT.MESSAGES_WRITE, BLECentralRequest.RequestType.WRITE) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
MessagePacket justSent = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
Log.i(TAG, "Handling response after central sent message with body " + (justSent == null ? "null" : justSent.body));
if (justSent == null) {
// No data was available for this request. Mark request complete
logEvent("Central had no message for peer");
return true;
} else {
if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) {
mCallback.sentMessage(getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false), mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress()));
}
logEvent(String.format("Central wrote message %s..", justSent.body));
// If we have more messages to send, indicate request should be repeated
return (getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null);
}
}
@Override
public byte[] getDataToWrite(BluetoothGatt remotePeripheral) {
//return byte[] next_message
MessagePacket forRecipient = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
return (forRecipient == null ) ? null : forRecipient.rawPacket;
}
};
BLECentralRequest mIdentityWriteRequest = new BLECentralRequest(GATT.IDENTITY_WRITE, BLECentralRequest.RequestType.WRITE) {
@Override
public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) {
IdentityPacket justSent = getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false);
if (justSent == null) {
//No data was available for this request. Mark request complete
logEvent("Central had no identity for peer");
return true;
} else {
if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) {
mCallback.sentIdentity(getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false),
mConnectedAddressesToIdentities.get(remotePeripheral.getDevice().getAddress()));
}
logEvent(String.format("Central wrote identity %s..", DataUtil.bytesToHex(justSent.publicKey).substring(0,3)));
// If we have more messages to send, indicate request should be repeated
return (getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null);
}
}
@Override
public byte[] getDataToWrite(BluetoothGatt remotePeripheral) {
//return byte[] next_identity
IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), true);
return (forRecipient == null) ? null : forRecipient.rawPacket;
}
};
/** BLEPeripheral Responses */
BLEPeripheralResponse mMessageReadResponse = new BLEPeripheralResponse(GATT.MESSAGES_READ, BLEPeripheralResponse.RequestType.READ) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
try {
// Get messages to send and send first
MessagePacket forRecipient = getNextMessageForDeviceAddress(remoteCentral.getAddress(), true);
if (forRecipient != null) {
boolean haveAnotherMessage = getNextMessageForDeviceAddress(remoteCentral.getAddress(), false) != null;
byte[] payload = forRecipient.rawPacket;
int responseGattStatus = haveAnotherMessage ? BluetoothGatt.GATT_SUCCESS : BluetoothGatt.GATT_READ_NOT_PERMITTED;
boolean responseSent = false;
try {
responseSent = localPeripheral.sendResponse(remoteCentral, requestId, responseGattStatus, 0, payload);
Log.w("SendResponse", "message read " + (responseGattStatus == BluetoothGatt.GATT_SUCCESS ? "" : " READ_NOT_PERMITTED") + " success: " + responseSent);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message read " + (responseGattStatus == BluetoothGatt.GATT_SUCCESS ? "" : " READ_NOT_PERMITTED"));
}
//Log.i(TAG, String.format("Responded to message read request with outgoing status %b. response sent: %b data (%d bytes): %s", responseGattStatus, responseSent, (payload == null || payload.length == 0) ? 0 : payload.length, (payload == null || payload.length == 0) ? "null" : DataUtil.bytesToHex(payload)));
if (responseSent) {
if (mCallback != null)
mCallback.sentMessage(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
logEvent(String.format("Peripheral sent message for peer %s", forRecipient.body));
return payload;
}
} else {
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null);
Log.w("SendResponse", "message read READ_NOT_PERMITTED success: " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message read READ_NOT_PERMITTED");
}
logEvent("Peripheral had no message for peer");
//Log.i(TAG, "Had no messages for peer. Sent READ_NOT_PERMITTED with success " + success);
}
} catch(Exception e) {
logEvent("Peripheral failed to send message");
e.printStackTrace();
}
return null;
}
};
BLEPeripheralResponse mIdentityReadResponse = new BLEPeripheralResponse(GATT.IDENTITY_READ, BLEPeripheralResponse.RequestType.READ) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Get identities to send and send first
IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remoteCentral.getAddress(), true);
if (forRecipient != null) {
// If we don't have a public key for this address, we'll only send one identity (the user's)
byte[] payload = forRecipient.rawPacket;
int responseGattStatus = BluetoothGatt.GATT_SUCCESS;
boolean responseSent = false;
try {
responseSent = localPeripheral.sendResponse(remoteCentral, requestId, responseGattStatus, 0, payload);
Log.w("SendResponse", "identity read success " + responseSent);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity read");
}
//Log.i(TAG, String.format("Responded to identity read request with outgoing status %b. response sent: %b data: %s", responseGattStatus, responseSent, (payload == null || payload.length == 0) ? "null" : DataUtil.bytesToHex(payload)));
if (responseSent && mCallback != null) mCallback.sentIdentity(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
if (responseSent) {
if (mCallback != null)
mCallback.sentIdentity(forRecipient, mConnectedAddressesToIdentities.get(remoteCentral.getAddress()));
logEvent(String.format("Peripheral sent identity %s...", DataUtil.bytesToHex(forRecipient.publicKey).substring(0,3)));
return payload;
}
} else {
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null);
Log.w("SendResponse", "identity read READ_NOT_PERMITTED " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity read READ_NOT_PERMITTED");
}
logEvent("Peripheral had no identities for peer");
}
return null;
}
};
BLEPeripheralResponse mMessageWriteResponse = new BLEPeripheralResponse(GATT.MESSAGES_WRITE, BLEPeripheralResponse.RequestType.WRITE) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Consume message and send GATT_SUCCESS If valid and response needed
testValueVsCharacteristicValue(value, characteristic);
MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(value);
IdentityPacket courierIdentity = mConnectedAddressesToIdentities.get(remoteCentral.getAddress());
if (mCallback != null) mCallback.receivedMessageFromIdentity(receivedMessagePacket, courierIdentity);
if (responseNeeded) {
// TODO: Response code based on message validation?
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
Log.w("SendResponse", "message write success:" + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on message write");
}
}
logEvent(String.format("Peripheral received message %s", receivedMessagePacket.body));
return null;
}
};
BLEPeripheralResponse mIdentityWriteResponse = new BLEPeripheralResponse(GATT.IDENTITY_WRITE, BLEPeripheralResponse.RequestType.WRITE) {
@Override
public byte[] respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, byte[] value) {
// Consume Identity and send GATT_SUCCESS if valid and response needed
testValueVsCharacteristicValue(value, characteristic);
if (value == null || value.length == 0) {
Log.i(TAG, "got empty write data");
} else {
Log.i(TAG, "got non-empty write data! length: " + value.length);
IdentityPacket receivedIdentityPacket = mProtocol.deserializeIdentity(value);
handleIdentityBecameAvailable(remoteCentral.getAddress(), receivedIdentityPacket);
logEvent(String.format("Peripheral received identity for %s with key: %s...", receivedIdentityPacket.alias, DataUtil.bytesToHex(receivedIdentityPacket.publicKey).substring(2,6)));
}
if (responseNeeded) {
// TODO: Response code based on message validation?
try {
boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
Log.w("SendResponse", "Successful identity write " + success);
} catch (NullPointerException e) {
// On Nexus 5 possibly an issue in the Broadcom IBluetoothGatt implementation
Log.w("SendResponse", "NPE on identity write");
}
}
return null;
}
};
/** ConnectionListener */
@Override
public void connectedTo(String deviceAddress) {
// do nothing. We shouldn't report peer available until we have an Identity for it
}
@Override
public void disconnectedFrom(String deviceAddress) {
IdentityPacket disconnectedIdentityPacket = mConnectedAddressesToIdentities.remove(deviceAddress);
if (disconnectedIdentityPacket != null && mCallback != null) {
Log.i(TAG, "Report disconnect to " + deviceAddress);
mCallback.identityBecameUnavailable(disconnectedIdentityPacket);
} else {
// The reported device address changed since connection. With iOS devices this is common
if (mConnectedAddressesToIdentities.size() == 1) {
// It's safe to assume this is the client that has disconnected
String disconnectedAddress = ((Map.Entry <String, IdentityPacket>) mConnectedAddressesToIdentities.entrySet().toArray()[0]).getKey();
disconnectedFrom(disconnectedAddress);
} else {
Log.i(TAG, "Could not report disconnect to " + deviceAddress);
}
}
}
/** Utility */
@Nullable
private IdentityPacket getNextIdentityForDeviceAddress(String address, boolean removeFromQueue) {
byte[] publicKey = getPublicKeyForDeviceAddress(address);
return getNextIdentityForDevice(publicKey, address, removeFromQueue);
}
@Nullable
private MessagePacket getNextMessageForDeviceAddress(String address, boolean removeFromQueue) {
byte[] publicKey = getPublicKeyForDeviceAddress(address);
return getNextMessageForDevice(publicKey, address, removeFromQueue);
}
@Nullable
private MessagePacket getNextMessageForDevice(@Nullable byte[] publicKey, @NonNull String address, boolean removeFromQueue) {
String deviceKey = getKeyForDevice(publicKey, address);
if (publicKey == null) {
// This is a special case because we have no public key so we can't record delivery of any items
// Therefore we can't rely on mDataProvider.getMessagesForIdentity to not return items that were already sent
// So we'll ensure that we only perform that request once per device address
if (!mMessageOutboxes.containsKey(deviceKey)) {
ArrayDeque<MessagePacket> messagesForRecipient = mDataProvider.getMessagesForIdentity(null, IDENTITIES_PER_RESPONSE);
mMessageOutboxes.put(deviceKey, messagesForRecipient);
} else {
// We've already sent our own Identity for this identity-less peer
Log.i(TAG, "Returning null for nextMessage to " + address);
return null;
}
}
else if (!mMessageOutboxes.containsKey(deviceKey) || mMessageOutboxes.get(deviceKey).size() == 0) {
ArrayDeque<MessagePacket> messagesForRecipient = mDataProvider.getMessagesForIdentity(publicKey, MESSAGES_PER_RESPONSE);
mMessageOutboxes.put(deviceKey, messagesForRecipient);
Log.i(TAG, String.format("Got %d messages for pk %s", messagesForRecipient.size(), DataUtil.bytesToHex(publicKey)));
}
if (mMessageOutboxes.get(deviceKey).size() == 0) return null;
return removeFromQueue ? mMessageOutboxes.get(deviceKey).poll() : mMessageOutboxes.get(deviceKey).peek();
}
@Nullable
private IdentityPacket getNextIdentityForDevice(@Nullable byte[] publicKey, String address, boolean removeFromQueue) {
String deviceKey = getKeyForDevice(publicKey, address);
if (publicKey == null) {
Log.i(TAG, "Getting identity response for no-identity peer at " + address);
// This is a special case because we have no public key so we can't record delivery of any items
// Therefore we can't rely on mDataProvider.getIdentitiesForIdentity to not return items that were already sent
// So we'll ensure that we only perform that request once per device address
if (!mIdentitiesOutboxes.containsKey(deviceKey)) {
ArrayDeque<IdentityPacket> identitiesForRecipient = mDataProvider.getIdentitiesForIdentity(null, IDENTITIES_PER_RESPONSE);
mIdentitiesOutboxes.put(deviceKey, identitiesForRecipient);
} else {
// We've already sent our own Identity for this identity-less peer
Log.i(TAG, "Returning null for nextIdentity to " + address);
return null;
}
}
else if (!mIdentitiesOutboxes.containsKey(deviceKey) || mIdentitiesOutboxes.get(deviceKey).size() == 0) {
// We have a public key for this peer. Proceed as normal
ArrayDeque<IdentityPacket> identitiesForRecipient = mDataProvider.getIdentitiesForIdentity(publicKey, IDENTITIES_PER_RESPONSE);
mIdentitiesOutboxes.put(deviceKey, identitiesForRecipient);
}
if (mIdentitiesOutboxes.get(deviceKey).size() == 0) return null;
return removeFromQueue ? mIdentitiesOutboxes.get(deviceKey).poll() : mIdentitiesOutboxes.get(deviceKey).peek();
}
private byte[] getPublicKeyForDeviceAddress(String address) {
byte[] publicKey = null;
if (mConnectedAddressesToIdentities.containsKey(address)) publicKey = mConnectedAddressesToIdentities.get(address).publicKey;
if (publicKey == null) {
// No public key on file, perform naive message send for now
Log.w(TAG, String.format("Don't have identity on file for device %s.", address));
}
return publicKey;
}
private boolean isCentralRequestComplete(int gattStatus) {
switch(gattStatus) {
case BluetoothGatt.GATT_READ_NOT_PERMITTED:
case BluetoothGatt.GATT_FAILURE:
return true; // request complete
case BluetoothGatt.GATT_SUCCESS:
return false; // peripheral reports more data available
default:
Log.w(TAG, String.format("Got unexpected GATT status %d", gattStatus));
return true;
}
}
private void testValueVsCharacteristicValue(byte[] value, BluetoothGattCharacteristic characteristic) {
if (value != null && characteristic.getValue() != null) {
Log.i(TAG, "are value and characteristic.getValue equal: " + Arrays.equals(value, characteristic.getValue()));
} else if (value != null) {
Log.i(TAG, "characteristic.getValue null, but value not null");
} else if(characteristic.getValue() != null) {
Log.i(TAG, "value is null but characterisitc.getValue not null");
}
}
/**
* Return a key used for {@link #mIdentitiesOutboxes} and {@link #mMessageOutboxes} using
* a string representation of the public key or device address if public key is null
*/
private String getKeyForDevice(@Nullable byte[] publicKey, @Nullable String deviceAddress) {
if (publicKey != null) return DataUtil.bytesToHex(publicKey);
return deviceAddress;
}
private void logEvent(String event) {
if (mLogger != null) {
mLogger.onLogEvent(event);
} else {
Log.i(TAG, event);
}
}
private void handleIdentityBecameAvailable(String fromAddress, IdentityPacket receivedIdentityPacket) {
if (!mConnectedAddressesToIdentities.containsKey(fromAddress)) {
mConnectedAddressesToIdentities.put(fromAddress, receivedIdentityPacket);
Log.i(TAG, "Got identity for " + fromAddress);
if (mCallback != null) mCallback.identityBecameAvailable(receivedIdentityPacket);
}
}
// </editor-fold desc="Private API">
}
| constant mixup
used IDENTITIES_PER_RESPONSE where MESSAGES_PER_RESPONSE wanted
| app/src/main/java/pro/dbro/ble/transport/ble/BLETransport.java | constant mixup |
|
Java | lgpl-2.1 | 98bef17a66c433113c759c019f5d4198b497053b | 0 | cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl | /*
Copyright (c) 2006, 2010-2011, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.io.internal.read.sif;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.io.internal.read.AbstractNetworkReader;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyTableEntry;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Reader for graphs in the interactions file format. Given the filename,
* provides the graph and attributes objects constructed from the file.
*/
public class SIFNetworkReader extends AbstractNetworkReader {
private static final Logger logger = LoggerFactory.getLogger(SIFNetworkReader.class);
private static final String TAB = "\t";
private String delimiter = " "; // single space
private final CyEventHelper eventHelper;
private final CyLayoutAlgorithmManager layouts;
private final StringBuilder edgeNameBuilder = new StringBuilder();
private TaskMonitor parentTaskMonitor;
public SIFNetworkReader(InputStream is, CyLayoutAlgorithmManager layouts,
CyNetworkViewFactory cyNetworkViewFactory, CyNetworkFactory cyNetworkFactory,
final CyEventHelper eventHelper) {
super(is, cyNetworkViewFactory, cyNetworkFactory);
this.layouts = layouts;
this.eventHelper = eventHelper;
}
@Override
public void run(TaskMonitor tm) throws IOException {
try {
readInput(tm);
} finally {
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
}
}
private void readInput(TaskMonitor tm) throws IOException {
this.parentTaskMonitor = tm;
tm.setProgress(0.0);
String line;
final BufferedReader br =
new BufferedReader(new InputStreamReader(inputStream), 128*1024);
Map<String, CyNode> nMap = new HashMap<String, CyNode>(10000);
CyNetwork network = cyNetworkFactory.createNetwork();
final CyTable nodeTable = network.getDefaultNodeTable();
final CyTable edgeTable = network.getDefaultEdgeTable();
tm.setProgress(0.1);
// Generate bundled event to avoid too many events problem.
final String firstLine = br.readLine();
if (firstLine.contains(TAB))
delimiter = TAB;
createEdge(new Interaction(firstLine.trim(), delimiter), network, nMap);
tm.setProgress(0.15);
tm.setStatusMessage("Processing the interactions...");
int numInteractionsRead = 0;
while ((line = br.readLine()) != null) {
if (cancelled) {
// Cancel called. Clean up the garbage.
nMap.clear();
nMap = null;
network = null;
br.close();
return;
}
if (line.trim().length() <= 0)
continue;
try {
final Interaction itr = new Interaction(line, delimiter);
createEdge(itr, network, nMap);
} catch (Exception e) {
// Simply ignore invalid lines.
continue;
}
if ( (++numInteractionsRead % 1000) == 0 )
tm.setStatusMessage("Processed " + numInteractionsRead + " interactions so far.");
}
br.close();
tm.setStatusMessage("Processed " + numInteractionsRead + " interactions in total.");
nMap.clear();
nMap = null;
this.cyNetworks = new CyNetwork[] {network};
tm.setProgress(1.0);
logger.debug("SIF file loaded: ID = " + network.getSUID());
}
private void createEdge(final Interaction itr, final CyNetwork network, final Map<String, CyNode> nMap) {
CyNode sourceNode = nMap.get(itr.getSource());
if (sourceNode == null) {
sourceNode = network.addNode();
network.getRow(sourceNode).set(CyTableEntry.NAME, itr.getSource());
nMap.put(itr.getSource(), sourceNode);
}
for (final String target : itr.getTargets()) {
CyNode targetNode = nMap.get(target);
if (targetNode == null) {
targetNode = network.addNode();
network.getRow(targetNode).set(CyTableEntry.NAME, target);
nMap.put(target, targetNode);
}
final CyEdge edge = network.addEdge(sourceNode, targetNode, true);
network.getRow(edge).set(CyTableEntry.NAME, getEdgeName(itr,target));
network.getRow(edge).set(CyEdge.INTERACTION, itr.getType());
}
}
private String getEdgeName(Interaction itr, String target) {
edgeNameBuilder.delete(0,edgeNameBuilder.length());
edgeNameBuilder.append(itr.getSource());
edgeNameBuilder.append(" (");
edgeNameBuilder.append(itr.getType());
edgeNameBuilder.append(") ");
edgeNameBuilder.append(target);
return edgeNameBuilder.toString();
}
@Override
public CyNetworkView buildCyNetworkView(CyNetwork network) {
final CyNetworkView view = cyNetworkViewFactory.createNetworkView(network);
final CyLayoutAlgorithm layout = layouts.getDefaultLayout();
layout.setNetworkView(view);
// Force to run this task here to avoid concurrency problem.
TaskIterator itr = layout.createTaskIterator();
Task nextTask = itr.next();
try {
nextTask.run(parentTaskMonitor);
} catch (Exception e) {
throw new RuntimeException("Could not finish layout", e);
}
return view;
}
}
| io-impl/impl/src/main/java/org/cytoscape/io/internal/read/sif/SIFNetworkReader.java | /*
Copyright (c) 2006, 2010-2011, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.io.internal.read.sif;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.io.internal.read.AbstractNetworkReader;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyTableEntry;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Reader for graphs in the interactions file format. Given the filename,
* provides the graph and attributes objects constructed from the file.
*/
public class SIFNetworkReader extends AbstractNetworkReader {
private static final Logger logger = LoggerFactory.getLogger(SIFNetworkReader.class);
private static final String TAB = "\t";
private String delimiter = " "; // single space
private final CyEventHelper eventHelper;
private final CyLayoutAlgorithmManager layouts;
private final StringBuilder edgeNameBuilder = new StringBuilder();
private TaskMonitor parentTaskMonitor;
public SIFNetworkReader(InputStream is, CyLayoutAlgorithmManager layouts,
CyNetworkViewFactory cyNetworkViewFactory, CyNetworkFactory cyNetworkFactory,
final CyEventHelper eventHelper) {
super(is, cyNetworkViewFactory, cyNetworkFactory);
this.layouts = layouts;
this.eventHelper = eventHelper;
}
@Override
public void run(TaskMonitor tm) throws IOException {
try {
readInput(tm);
} finally {
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
}
}
private void readInput(TaskMonitor tm) throws IOException {
this.parentTaskMonitor = tm;
tm.setProgress(0.0);
String line;
final BufferedReader br =
new BufferedReader(new InputStreamReader(inputStream), 128*1024);
Map<String, CyNode> nMap = new HashMap<String, CyNode>(10000);
CyNetwork network = cyNetworkFactory.createNetwork();
final CyTable nodeTable = network.getDefaultNodeTable();
final CyTable edgeTable = network.getDefaultEdgeTable();
tm.setProgress(0.1);
// Generate bundled event to avoid too many events problem.
final String firstLine = br.readLine();
if (firstLine.contains(TAB))
delimiter = TAB;
createEdge(new Interaction(firstLine.trim(), delimiter), network, nMap);
tm.setProgress(0.15);
tm.setStatusMessage("Processing the interactions...");
while ((line = br.readLine()) != null) {
if (cancelled) {
// Cancel called. Clean up the garbage.
nMap.clear();
nMap = null;
network = null;
br.close();
return;
}
if (line.trim().length() <= 0)
continue;
try {
final Interaction itr = new Interaction(line, delimiter);
createEdge(itr, network, nMap);
} catch (Exception e) {
// Simply ignore invalid lines.
continue;
}
}
br.close();
// tm.setStatusMessage("Network data loaded from data source.\nCreating Cytoscape network...");
nMap.clear();
nMap = null;
this.cyNetworks = new CyNetwork[] {network};
tm.setProgress(1.0);
logger.debug("SIF file loaded: ID = " + network.getSUID());
}
private void createEdge(final Interaction itr, final CyNetwork network, final Map<String, CyNode> nMap) {
CyNode sourceNode = nMap.get(itr.getSource());
if (sourceNode == null) {
sourceNode = network.addNode();
network.getRow(sourceNode).set(CyTableEntry.NAME, itr.getSource());
nMap.put(itr.getSource(), sourceNode);
}
for (final String target : itr.getTargets()) {
CyNode targetNode = nMap.get(target);
if (targetNode == null) {
targetNode = network.addNode();
network.getRow(targetNode).set(CyTableEntry.NAME, target);
nMap.put(target, targetNode);
}
final CyEdge edge = network.addEdge(sourceNode, targetNode, true);
network.getRow(edge).set(CyTableEntry.NAME, getEdgeName(itr,target));
network.getRow(edge).set(CyEdge.INTERACTION, itr.getType());
}
}
private String getEdgeName(Interaction itr, String target) {
edgeNameBuilder.delete(0,edgeNameBuilder.length());
edgeNameBuilder.append(itr.getSource());
edgeNameBuilder.append(" (");
edgeNameBuilder.append(itr.getType());
edgeNameBuilder.append(") ");
edgeNameBuilder.append(target);
return edgeNameBuilder.toString();
}
@Override
public CyNetworkView buildCyNetworkView(CyNetwork network) {
final CyNetworkView view = cyNetworkViewFactory.createNetworkView(network);
final CyLayoutAlgorithm layout = layouts.getDefaultLayout();
layout.setNetworkView(view);
// Force to run this task here to avoid concurrency problem.
TaskIterator itr = layout.createTaskIterator();
Task nextTask = itr.next();
try {
nextTask.run(parentTaskMonitor);
} catch (Exception e) {
throw new RuntimeException("Could not finish layout", e);
}
return view;
}
}
| added some status update messages for SIF reader task
| io-impl/impl/src/main/java/org/cytoscape/io/internal/read/sif/SIFNetworkReader.java | added some status update messages for SIF reader task |
|
Java | apache-2.0 | 5ff3dabf63bbcf49667416c76aa60edde8b1e775 | 0 | gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa | package uk.ac.ebi.gxa.netcdf.reader;
import junit.framework.TestCase;
import uk.ac.ebi.microarray.atlas.model.AtlasCount;
import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
/**
* This class tests functionality of AtlasNetCDFDAO
*
* @author Rober Petryszak
* @date 13-Sep-2010
*/
public class TestNetCDFDAO extends TestCase {
private File netCDFRepoLocation;
private AtlasNetCDFDAO atlasNetCDFDAO;
private Long geneId;
private String experimentId;
private String ef;
private String efv;
private float minPValue;
private Long designElementIdForMinPValue;
private String efvInMoreThanOneProxy;
private String efvInMoreThanOneProxy1;
Set<Long> geneIds;
private String proxyId;
private final static DecimalFormat pValFormat = new DecimalFormat("0.#######");
private Set<String> proxyIds = new HashSet<String>();
@Override
protected void setUp() throws Exception {
super.setUp();
geneId = 153070209l; // human brca1
experimentId = "411512559"; // E-MTAB-25
proxyId = "411512559_153069949.nc";
ef = "cell_type";
efv = "germ cell";
minPValue = 0.8996214f;
efvInMoreThanOneProxy = "CD4+ T cell";
efvInMoreThanOneProxy1 = "CD8+ T cell";
designElementIdForMinPValue = 153085549l;
netCDFRepoLocation = new File("target" + File.separator + "test-classes");
atlasNetCDFDAO = new AtlasNetCDFDAO();
atlasNetCDFDAO.setAtlasNetCDFRepo(netCDFRepoLocation);
geneIds = new HashSet<Long>();
geneIds.add(geneId);
proxyIds.add(proxyId);
proxyIds.add("411512559_221532256.nc");
proxyIds.add("411512559_222525156.nc");
}
public void testFindFirstProxyForGenes() throws IOException {
NetCDFProxy proxy = atlasNetCDFDAO.findFirstProxyForGenes(experimentId, geneIds);
assertNotNull(proxy);
assertTrue(proxyIds.contains(proxy.getId()));
}
public void testGetGeneIds() throws IOException {
Set<Long> allGeneIds = atlasNetCDFDAO.getGeneIds(experimentId);
assertNotNull(allGeneIds);
assertNotSame(allGeneIds.size(), 0);
assertTrue(allGeneIds.contains(geneId));
}
public void testGetProxyIdToDesignElements() throws IOException {
Map<String, List<Long>> proxyIdToDesignElements = atlasNetCDFDAO.getProxyIdToDesignElements(experimentId);
for (String proxyIdentifier : proxyIdToDesignElements.keySet()) {
List<Long> deIds = proxyIdToDesignElements.get(proxyIdentifier);
assertNotNull(deIds);
assertNotSame(deIds.size(), 0);
if (proxyId.equals(proxyIdentifier)) {
assertTrue(deIds.contains(designElementIdForMinPValue));
}
}
}
public void testGetUniqueFactorValues() throws IOException {
List<String> uniqueFVs = atlasNetCDFDAO.getUniqueFactorValues(experimentId, ef);
assertNotNull(uniqueFVs);
assertNotSame(uniqueFVs.size(), 0);
assertTrue(uniqueFVs.contains(efv));
}
public void testGetFactorValues() throws IOException {
List<String> fvs = atlasNetCDFDAO.getFactorValues(proxyId, ef);
assertNotNull(fvs);
assertNotSame(fvs.size(), 0);
assertTrue(fvs.contains(efv));
}
public void testGetFactorValuesForExperiment() throws IOException {
Map<String, List<String>> proxyIdToFvs = atlasNetCDFDAO.getFactorValuesForExperiment(experimentId, ef);
List<String> fvs = proxyIdToFvs.get(proxyId);
assertNotNull(fvs);
assertNotSame(fvs.size(), 0);
assertTrue(fvs.contains(efv));
HashSet efvsAcrossMoreThanOneProxy = null;
for (String proxyId : proxyIdToFvs.keySet()) {
List<String> efvs = proxyIdToFvs.get(proxyId);
if (efvsAcrossMoreThanOneProxy == null) {
efvsAcrossMoreThanOneProxy = new HashSet(efvs);
} else {
efvsAcrossMoreThanOneProxy.retainAll(efvs);
}
}
assertNotSame(efvsAcrossMoreThanOneProxy.size(), 2);
assert (efvsAcrossMoreThanOneProxy.contains(efvInMoreThanOneProxy));
assert (efvsAcrossMoreThanOneProxy.contains(efvInMoreThanOneProxy1));
}
public void testGetProxyIdToArrayDesignId() throws IOException {
Map<String, Long> proxyIdToArrayDesignIds = atlasNetCDFDAO.getProxyIdToArrayDesignId(experimentId);
for (String proxyIdentifier : proxyIdToArrayDesignIds.keySet()) {
Long arrayDesignId = proxyIdToArrayDesignIds.get(proxyIdentifier);
assertNotNull(arrayDesignId);
assertNotSame(arrayDesignId, 0);
}
}
public void testGetExpressionAnalyticsByGeneID() throws IOException {
try {
Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA =
atlasNetCDFDAO.getExpressionAnalysesForGeneIds(geneIds, experimentId);
// check the returned data
assertNotNull(geneIdsToEfToEfvToEA.get(geneId));
assertNotNull(geneIdsToEfToEfvToEA.get(geneId).get(ef));
ExpressionAnalysis ea = geneIdsToEfToEfvToEA.get(geneId).get(ef).get(efv);
assertNotNull(ea);
assertNotNull("Got null for design element ID", ea.getDesignElementID());
assertNotNull("Got null for experiment ID", ea.getExperimentID());
assertNotNull("Got null for ef name", ea.getEfName());
assertNotNull("Got null for efv name", ea.getEfvName());
assertNotNull("Got null for ef id", ea.getEfId());
assertNotNull("Got null for efv id", ea.getEfvId());
assertNotNull("Got null for pvalue", ea.getPValAdjusted());
assertNotNull("Got null for tstat", ea.getTStatistic());
assertNotNull("Got null for proxyid", ea.getProxyId());
assertNotNull("Got null for design element index", ea.getDesignElementIndex());
System.out.println("Got expression analysis for gene id: " + geneId + " \n" + ea.toString());
assertEquals(Long.valueOf(ea.getDesignElementID()), designElementIdForMinPValue);
assertEquals(pValFormat.format(ea.getPValAdjusted()), pValFormat.format(minPValue));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
/**
* Test the NetCDF equivalent of the following query based on data in a2_expressionanalytics. Essentially
* for a given experimenId, the query finds the min pValue for each ef/efv combination and the counts the number
* of genes that have that ef-efv-min pvalue combination:
* <p/>
* SELECT
* ea.experimentid,
* p.name AS property,
* pv.name AS propertyvalue,
* CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn,
* min(ea.pvaladj),
* COUNT(DISTINCT(g.geneid)) AS genes,
* min(p.propertyid) AS propertyid,
* min(pv.propertyvalueid) AS propertyvalueid
* <p/>
* FROM a2_expressionanalytics ea
* JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid
* JOIN a2_property p ON p.propertyid=pv.propertyid
* JOIN a2_designelement de ON de.designelementid=ea.designelementid
* JOIN a2_gene g ON g.geneid=de.geneid;
* WHERE ea.experimentid=?
* <p/>
* GROUP BY ea.experimentid, p.name, pv.name,
* CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END;
*/
public void testGetAtlasCountsByExperimentID() {
try {
Set<Long> geneIds = atlasNetCDFDAO.getGeneIds(experimentId);
Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA =
atlasNetCDFDAO.getExpressionAnalysesForGeneIds(geneIds, experimentId);
Map<String, Map<String, AtlasCount>> efToEfvToAtlasCount = new HashMap<String, Map<String, AtlasCount>>();
for (Long geneId : geneIdsToEfToEfvToEA.keySet()) {
Map<String, Map<String, ExpressionAnalysis>> efToEfvToEA =
geneIdsToEfToEfvToEA.get(geneId);
for (String ef : efToEfvToEA.keySet()) {
Map<String, ExpressionAnalysis> efvToEA = efToEfvToEA.get(ef);
for (String efv : efvToEA.keySet()) {
ExpressionAnalysis bestEA = efvToEA.get(efv);
if (bestEA != null) {
Map<String, AtlasCount> efvToAtlasCount = efToEfvToAtlasCount.get(ef);
if (efvToAtlasCount == null) {
efvToAtlasCount = new HashMap<String, AtlasCount>();
}
AtlasCount ac = efvToAtlasCount.get(efv);
if (ac == null) {
ac = new AtlasCount();
}
ac.setProperty(ef);
ac.setPropertyValue(efv);
ac.setGeneCount(ac.getGeneCount() + 1);
ac.setUpOrDown(bestEA.getTStatistic() < 0 ? "-1" : "+1");
efvToAtlasCount.put(efv, ac);
efToEfvToAtlasCount.put(ef, efvToAtlasCount);
}
}
}
}
List<AtlasCount> atlasCounts = new ArrayList<AtlasCount>();
for (String ef : efToEfvToAtlasCount.keySet()) {
Map<String, AtlasCount> efvToAtlasCount = efToEfvToAtlasCount.get(ef);
for (String efv : efvToAtlasCount.keySet()) {
atlasCounts.add(efvToAtlasCount.get(efv));
}
}
// check the returned data
assertNotSame("Zero atlas counts returned", atlasCounts.size(), 0);
for (AtlasCount atlas : atlasCounts) {
assertNotNull(atlas);
assertNotNull("Got null property", atlas.getProperty());
assertNotSame("Got null property value", atlas.getPropertyValue());
assertNotNull("Got null updn" + atlas.getUpOrDown());
assertNotNull("Got 0 gene count" + atlas.getGeneCount());
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| netcdf-reader/src/test/java/uk/ac/ebi/gxa/netcdf/reader/TestNetCDFDAO.java | package uk.ac.ebi.gxa.netcdf.reader;
import junit.framework.TestCase;
import uk.ac.ebi.microarray.atlas.model.AtlasCount;
import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
/**
* This class tests functionality of AtlasNetCDFDAO
*
* @author Rober Petryszak
* @date 13-Sep-2010
*/
public class TestNetCDFDAO extends TestCase {
private File netCDFRepoLocation;
private AtlasNetCDFDAO atlasNetCDFDAO;
private Long geneId;
private String experimentId;
private String ef;
private String efv;
private float minPValue;
private Long designElementIdForMinPValue;
private String efvInMoreThanOneProxy;
private String efvInMoreThanOneProxy1;
Set<Long> geneIds;
private String proxyId;
private final static DecimalFormat pValFormat = new DecimalFormat("0.#######");
@Override
protected void setUp() throws Exception {
super.setUp();
geneId = 153070209l; // human brca1
experimentId = "411512559"; // E-MTAB-25
proxyId = "411512559_153069949.nc";
ef = "cell_type";
efv = "germ cell";
minPValue = 0.8996214f;
efvInMoreThanOneProxy = "CD4+ T cell";
efvInMoreThanOneProxy1 = "CD8+ T cell";
designElementIdForMinPValue = 153085549l;
netCDFRepoLocation = new File("target" + File.separator + "test-classes");
atlasNetCDFDAO = new AtlasNetCDFDAO();
atlasNetCDFDAO.setAtlasNetCDFRepo(netCDFRepoLocation);
geneIds = new HashSet<Long>();
geneIds.add(geneId);
}
public void testFindFirstProxyForGenes() throws IOException {
NetCDFProxy proxy = atlasNetCDFDAO.findFirstProxyForGenes(experimentId, geneIds);
assertEquals(proxy.getId(), proxyId);
}
public void testGetGeneIds() throws IOException {
Set<Long> allGeneIds = atlasNetCDFDAO.getGeneIds(experimentId);
assertNotNull(allGeneIds);
assertNotSame(allGeneIds.size(), 0);
assertTrue(allGeneIds.contains(geneId));
}
public void testGetProxyIdToDesignElements() throws IOException {
Map<String, List<Long>> proxyIdToDesignElements = atlasNetCDFDAO.getProxyIdToDesignElements(experimentId);
for (String proxyIdentifier : proxyIdToDesignElements.keySet()) {
List<Long> deIds = proxyIdToDesignElements.get(proxyIdentifier);
assertNotNull(deIds);
assertNotSame(deIds.size(), 0);
if (proxyId.equals(proxyIdentifier)) {
assertTrue(deIds.contains(designElementIdForMinPValue));
}
}
}
public void testGetUniqueFactorValues() throws IOException {
List<String> uniqueFVs = atlasNetCDFDAO.getUniqueFactorValues(experimentId, ef);
assertNotNull(uniqueFVs);
assertNotSame(uniqueFVs.size(), 0);
assertTrue(uniqueFVs.contains(efv));
}
public void testGetFactorValues() throws IOException {
List<String> fvs = atlasNetCDFDAO.getFactorValues(proxyId, ef);
assertNotNull(fvs);
assertNotSame(fvs.size(), 0);
assertTrue(fvs.contains(efv));
}
public void testGetFactorValuesForExperiment() throws IOException {
Map<String, List<String>> proxyIdToFvs = atlasNetCDFDAO.getFactorValuesForExperiment(experimentId, ef);
List<String> fvs = proxyIdToFvs.get(proxyId);
assertNotNull(fvs);
assertNotSame(fvs.size(), 0);
assertTrue(fvs.contains(efv));
HashSet efvsAcrossMoreThanOneProxy = null;
for (String proxyId : proxyIdToFvs.keySet()) {
List<String> efvs = proxyIdToFvs.get(proxyId);
if (efvsAcrossMoreThanOneProxy == null) {
efvsAcrossMoreThanOneProxy = new HashSet(efvs);
} else {
efvsAcrossMoreThanOneProxy.retainAll(efvs);
}
}
assertNotSame(efvsAcrossMoreThanOneProxy.size(), 2);
assert (efvsAcrossMoreThanOneProxy.contains(efvInMoreThanOneProxy));
assert (efvsAcrossMoreThanOneProxy.contains(efvInMoreThanOneProxy1));
}
public void testGetProxyIdToArrayDesignId() throws IOException {
Map<String, Long> proxyIdToArrayDesignIds = atlasNetCDFDAO.getProxyIdToArrayDesignId(experimentId);
for (String proxyIdentifier : proxyIdToArrayDesignIds.keySet()) {
Long arrayDesignId = proxyIdToArrayDesignIds.get(proxyIdentifier);
assertNotNull(arrayDesignId);
assertNotSame(arrayDesignId, 0);
}
}
public void testGetExpressionAnalyticsByGeneID() throws IOException {
try {
Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA =
atlasNetCDFDAO.getExpressionAnalysesForGeneIds(geneIds, experimentId);
// check the returned data
assertNotNull(geneIdsToEfToEfvToEA.get(geneId));
assertNotNull(geneIdsToEfToEfvToEA.get(geneId).get(ef));
ExpressionAnalysis ea = geneIdsToEfToEfvToEA.get(geneId).get(ef).get(efv);
assertNotNull(ea);
assertNotNull("Got null for design element ID", ea.getDesignElementID());
assertNotNull("Got null for experiment ID", ea.getExperimentID());
assertNotNull("Got null for ef name", ea.getEfName());
assertNotNull("Got null for efv name", ea.getEfvName());
assertNotNull("Got null for ef id", ea.getEfId());
assertNotNull("Got null for efv id", ea.getEfvId());
assertNotNull("Got null for pvalue", ea.getPValAdjusted());
assertNotNull("Got null for tstat", ea.getTStatistic());
assertNotNull("Got null for proxyid", ea.getProxyId());
assertNotNull("Got null for design element index", ea.getDesignElementIndex());
System.out.println("Got expression analysis for gene id: " + geneId + " \n" + ea.toString());
assertEquals(Long.valueOf(ea.getDesignElementID()), designElementIdForMinPValue);
assertEquals(pValFormat.format(ea.getPValAdjusted()), pValFormat.format(minPValue));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
/**
* Test the NetCDF equivalent of the following query based on data in a2_expressionanalytics. Essentially
* for a given experimenId, the query finds the min pValue for each ef/efv combination and the counts the number
* of genes that have that ef-efv-min pvalue combination:
* <p/>
* SELECT
* ea.experimentid,
* p.name AS property,
* pv.name AS propertyvalue,
* CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn,
* min(ea.pvaladj),
* COUNT(DISTINCT(g.geneid)) AS genes,
* min(p.propertyid) AS propertyid,
* min(pv.propertyvalueid) AS propertyvalueid
* <p/>
* FROM a2_expressionanalytics ea
* JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid
* JOIN a2_property p ON p.propertyid=pv.propertyid
* JOIN a2_designelement de ON de.designelementid=ea.designelementid
* JOIN a2_gene g ON g.geneid=de.geneid;
* WHERE ea.experimentid=?
* <p/>
* GROUP BY ea.experimentid, p.name, pv.name,
* CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END;
*/
public void testGetAtlasCountsByExperimentID() {
try {
Set<Long> geneIds = atlasNetCDFDAO.getGeneIds(experimentId);
Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA =
atlasNetCDFDAO.getExpressionAnalysesForGeneIds(geneIds, experimentId);
Map<String, Map<String, AtlasCount>> efToEfvToAtlasCount = new HashMap<String, Map<String, AtlasCount>>();
for (Long geneId : geneIdsToEfToEfvToEA.keySet()) {
Map<String, Map<String, ExpressionAnalysis>> efToEfvToEA =
geneIdsToEfToEfvToEA.get(geneId);
for (String ef : efToEfvToEA.keySet()) {
Map<String, ExpressionAnalysis> efvToEA = efToEfvToEA.get(ef);
for (String efv : efvToEA.keySet()) {
ExpressionAnalysis bestEA = efvToEA.get(efv);
if (bestEA != null) {
Map<String, AtlasCount> efvToAtlasCount = efToEfvToAtlasCount.get(ef);
if (efvToAtlasCount == null) {
efvToAtlasCount = new HashMap<String, AtlasCount>();
}
AtlasCount ac = efvToAtlasCount.get(efv);
if (ac == null) {
ac = new AtlasCount();
}
ac.setProperty(ef);
ac.setPropertyValue(efv);
ac.setGeneCount(ac.getGeneCount() + 1);
ac.setUpOrDown(bestEA.getTStatistic() < 0 ? "-1" : "+1");
efvToAtlasCount.put(efv, ac);
efToEfvToAtlasCount.put(ef, efvToAtlasCount);
}
}
}
}
List<AtlasCount> atlasCounts = new ArrayList<AtlasCount>();
for (String ef : efToEfvToAtlasCount.keySet()) {
Map<String, AtlasCount> efvToAtlasCount = efToEfvToAtlasCount.get(ef);
for (String efv : efvToAtlasCount.keySet()) {
atlasCounts.add(efvToAtlasCount.get(efv));
}
}
// check the returned data
assertNotSame("Zero atlas counts returned", atlasCounts.size(), 0);
for (AtlasCount atlas : atlasCounts) {
assertNotNull(atlas);
assertNotNull("Got null property", atlas.getProperty());
assertNotSame("Got null property value", atlas.getPropertyValue());
assertNotNull("Got null updn" + atlas.getUpOrDown());
assertNotNull("Got 0 gene count" + atlas.getGeneCount());
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| Modified testFindFirstProxyForGenes()
git-svn-id: 410459702e6123a874d92574e1336b0959d85891@14006 2913f559-6b04-0410-9a09-c530ee9f5186
| netcdf-reader/src/test/java/uk/ac/ebi/gxa/netcdf/reader/TestNetCDFDAO.java | Modified testFindFirstProxyForGenes() |
|
Java | apache-2.0 | 1ce63a9530c7af7372e70e7ffd827b61b8beff68 | 0 | ahb0327/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,caot/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,jexp/idea2,Lekanich/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,amith01994/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,holmes/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,slisson/intellij-community,samthor/intellij-community,jagguli/intellij-community,holmes/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,kdwink/intellij-community,slisson/intellij-community,kool79/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,xfournet/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,xfournet/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,signed/intellij-community,nicolargo/intellij-community,semonte/intellij-community,apixandru/intellij-community,robovm/robovm-studio,adedayo/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,jexp/idea2,ryano144/intellij-community,semonte/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,caot/intellij-community,dslomov/intellij-community,allotria/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,joewalnes/idea-community,blademainer/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,robovm/robovm-studio,retomerz/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,adedayo/intellij-community,slisson/intellij-community,da1z/intellij-community,retomerz/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,asedunov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,allotria/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,holmes/intellij-community,ryano144/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,da1z/intellij-community,caot/intellij-community,asedunov/intellij-community,ryano144/intellij-community,hurricup/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ryano144/intellij-community,da1z/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,consulo/consulo,SerCeMan/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,jexp/idea2,MER-GROUP/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,apixandru/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,consulo/consulo,muntasirsyed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,allotria/intellij-community,slisson/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,caot/intellij-community,holmes/intellij-community,kool79/intellij-community,supersven/intellij-community,fitermay/intellij-community,blademainer/intellij-community,caot/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,izonder/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,consulo/consulo,TangHao1987/intellij-community,slisson/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,kdwink/intellij-community,hurricup/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,asedunov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,da1z/intellij-community,petteyg/intellij-community,fitermay/intellij-community,fitermay/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,signed/intellij-community,fnouama/intellij-community,ibinti/intellij-community,kdwink/intellij-community,blademainer/intellij-community,jagguli/intellij-community,clumsy/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,signed/intellij-community,da1z/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,kool79/intellij-community,samthor/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,izonder/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,signed/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ernestp/consulo,lucafavatella/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,slisson/intellij-community,supersven/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,samthor/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,jexp/idea2,blademainer/intellij-community,jagguli/intellij-community,dslomov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ibinti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,vladmm/intellij-community,samthor/intellij-community,amith01994/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,FHannes/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,holmes/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ernestp/consulo,gnuhub/intellij-community,allotria/intellij-community,ernestp/consulo,gnuhub/intellij-community,diorcety/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,izonder/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,signed/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,semonte/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,izonder/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,caot/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,hurricup/intellij-community,diorcety/intellij-community,da1z/intellij-community,consulo/consulo,kdwink/intellij-community,blademainer/intellij-community,joewalnes/idea-community,blademainer/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,holmes/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,blademainer/intellij-community,consulo/consulo,izonder/intellij-community,lucafavatella/intellij-community,signed/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,jexp/idea2,FHannes/intellij-community,samthor/intellij-community,allotria/intellij-community,nicolargo/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,xfournet/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,supersven/intellij-community,retomerz/intellij-community,signed/intellij-community,joewalnes/idea-community,apixandru/intellij-community,supersven/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,robovm/robovm-studio,izonder/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,FHannes/intellij-community,apixandru/intellij-community,caot/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,slisson/intellij-community,holmes/intellij-community,caot/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ibinti/intellij-community,diorcety/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,jexp/idea2,samthor/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,da1z/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,allotria/intellij-community,samthor/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,fitermay/intellij-community,robovm/robovm-studio,kdwink/intellij-community,clumsy/intellij-community,adedayo/intellij-community,caot/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,fitermay/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,caot/intellij-community,joewalnes/idea-community,robovm/robovm-studio,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,ryano144/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,Lekanich/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ernestp/consulo,nicolargo/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,orekyuu/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,jexp/idea2,akosyakov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,semonte/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,izonder/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,diorcety/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,retomerz/intellij-community,diorcety/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,suncycheng/intellij-community,semonte/intellij-community,joewalnes/idea-community,fnouama/intellij-community,orekyuu/intellij-community,samthor/intellij-community,signed/intellij-community,diorcety/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fnouama/intellij-community,retomerz/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,kool79/intellij-community,diorcety/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,supersven/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,Distrotech/intellij-community,semonte/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,holmes/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ernestp/consulo,clumsy/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,asedunov/intellij-community,asedunov/intellij-community | /*
* Copyright 2000-2007 JetBrains s.r.o.
* 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.jetbrains.plugins.groovy.lang.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrAdditiveExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrMultiplicativeExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrPowerExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrShiftExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.logical.*;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.regex.GrRegexExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.relational.GrEqualityExprImpl;
import org.jetbrains.plugins.groovy.refactoring.GroovyVariableUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
*/
public class PsiImplUtil {
private static final Logger LOG = Logger.getInstance("org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil");
public static GrExpression replaceExpression(GrExpression oldExpr, GrExpression newExpr) throws IncorrectOperationException {
if (oldExpr.getParent() == null ||
oldExpr.getParent().getNode() == null) {
throw new IncorrectOperationException();
}
// Remove unnecessary parentheses
if (oldExpr.getParent() instanceof GrParenthesizedExpr &&
newExpr instanceof GrReferenceExpression){
return ((GrExpression) oldExpr.getParent()).replaceWithExpression(newExpr);
}
// check priorities
GroovyElementFactory factory = GroovyElementFactory.getInstance(oldExpr.getProject());
if (oldExpr.getParent() instanceof GrExpression) {
GrExpression parentExpr = (GrExpression) oldExpr.getParent();
// todo fix me!
if (getExprPriorityLevel(parentExpr) >= getExprPriorityLevel(newExpr) &&
getExprPriorityLevel(newExpr) != 0) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
}
ASTNode parentNode = oldExpr.getParent().getNode();
ASTNode newNode = newExpr.getNode();
parentNode.replaceChild(oldExpr.getNode(), newNode);
if (!(newNode.getPsi() instanceof GrExpression)){
throw new IncorrectOperationException();
}
return ((GrExpression) newNode.getPsi());
}
public static void shortenReferences(GroovyPsiElement element) {
doShorten(element);
}
private static void doShorten(PsiElement element) {
PsiElement child = element.getFirstChild();
while (child != null) {
if (child instanceof GrReferenceElement) {
final GrCodeReferenceElement ref = (GrCodeReferenceElement) child;
if (ref.getQualifier() != null) {
final PsiElement resolved = ref.resolve();
if (resolved instanceof PsiClass) {
ref.setQualifier(null);
try {
ref.bindToElement(resolved);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
}
doShorten(child);
child = child.getNextSibling();
}
}
public static SearchScope getUseScope(GrMember member) {
if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
return new LocalSearchScope(member.getContainingFile()); //todo: what does GLS say?
}
return member.getManager().getSearchHelper().getUseScope(member);
}
public static PsiNamedElement[] getMethodVariants(GrReferenceElement methodReference) {
final GroovyResolveResult[] results = methodReference.getSameNameVariants(); //will ignore argument types
List<PsiNamedElement> elements = new ArrayList<PsiNamedElement>();
for (GroovyResolveResult result : results) {
final PsiElement element = result.getElement();
if (element instanceof PsiNamedElement) elements.add((PsiNamedElement) element);
}
return elements.toArray(new PsiNamedElement[elements.size()]);
}
public static GrExpression getRuntimeQualifier(GrReferenceExpression refExpr) {
GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier == null) {
GrClosableBlock closure = PsiTreeUtil.getParentOfType(refExpr, GrClosableBlock.class);
while (closure != null) {
GrExpression funExpr = null;
PsiElement parent = closure.getParent();
if (parent instanceof GrApplicationStatement) {
funExpr = ((GrApplicationStatement) parent).getFunExpression();
} else if (parent instanceof GrMethodCallExpression) {
funExpr = ((GrMethodCallExpression) parent).getInvokedExpression();
}
if (funExpr instanceof GrReferenceExpression) {
qualifier = ((GrReferenceExpression) funExpr).getQualifierExpression();
if (qualifier != null) break;
} else break;
closure = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class);
}
}
return qualifier;
}
public static void removeVariable(GrVariable variable) throws IncorrectOperationException {
final GrVariableDeclaration varDecl = (GrVariableDeclaration) variable.getParent();
final List<GrVariable> variables = Arrays.asList(varDecl.getVariables());
if (!variables.contains(variable)) {
throw new IncorrectOperationException();
}
final ASTNode varDeclNode = varDecl.getNode();
final PsiElement parent = varDecl.getParent();
final ASTNode owner = parent.getNode();
if (variables.size() == 1 && owner != null) {
GroovyVariableUtil.cleanAroundDeclarationBeforeRemove(varDecl);
owner.removeChild(varDeclNode);
reformatCode(parent);
return;
}
GroovyVariableUtil.cleanAroundVariableBeforeRemove(variable);
final ASTNode varNode = variable.getNode();
if (varNode != null) {
varDeclNode.removeChild(varNode);
}
reformatCode(varDecl);
}
public static PsiElement realPrevious(PsiElement previousLeaf) {
while (previousLeaf != null &&
(previousLeaf instanceof PsiWhiteSpace ||
previousLeaf instanceof PsiComment ||
previousLeaf instanceof PsiErrorElement)) {
previousLeaf = previousLeaf.getPrevSibling();
}
return previousLeaf;
}
public static PsiElement realNext(PsiElement nextLeaf) {
while (nextLeaf != null &&
(nextLeaf instanceof PsiWhiteSpace ||
nextLeaf instanceof PsiComment ||
nextLeaf instanceof PsiErrorElement)) {
nextLeaf = nextLeaf.getNextSibling();
}
return nextLeaf;
}
public static void reformatCode(final PsiElement element) {
final TextRange textRange = element.getTextRange();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
CodeStyleManager.getInstance(element.getProject()).reformatText(element.getContainingFile(),
textRange.getStartOffset(), textRange.getEndOffset());
} catch (IncorrectOperationException e) {
e.printStackTrace();
}
}
});
}
/**
* Returns priiority level of expression
* @param expr
* @return
*/
public static int getExprPriorityLevel(GrExpression expr){
int priority = 0;
if (expr instanceof GrNewExpression) priority = 1;
if (expr instanceof GrPostfixExpression) priority = 5;
if (expr instanceof GrUnaryExpression ||
expr instanceof GrTypeCastExpression) priority = 6;
if (expr instanceof GrPowerExprImpl) priority = 7;
if (expr instanceof GrMultiplicativeExprImpl) priority = 8;
if (expr instanceof GrAdditiveExprImpl) priority = 9;
if (expr instanceof GrShiftExprImpl) priority = 10;
if (expr instanceof GrRelationalExpression) priority = 11;
if (expr instanceof GrEqualityExprImpl) priority = 12;
if (expr instanceof GrRegexExprImpl) priority = 13;
if (expr instanceof GrAndExprImpl) priority = 14;
if (expr instanceof GrExclusiveOrExprImpl) priority = 15;
if (expr instanceof GrInclusiveOrExprImpl) priority = 16;
if (expr instanceof GrLogicalAndExprImpl) priority = 17;
if (expr instanceof GrLogicalOrExprImpl) priority = 18;
if (expr instanceof GrConditionalExpression) priority = 19;
if (expr instanceof GrAssignmentExpression) priority = 20;
return -priority;
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/PsiImplUtil.java | /*
* Copyright 2000-2007 JetBrains s.r.o.
* 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.jetbrains.plugins.groovy.lang.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrAdditiveExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrMultiplicativeExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrPowerExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.arithmetic.GrShiftExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.logical.*;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.regex.GrRegexExprImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.relational.GrEqualityExprImpl;
import org.jetbrains.plugins.groovy.refactoring.GroovyVariableUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
*/
public class PsiImplUtil {
private static final Logger LOG = Logger.getInstance("org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil");
public static GrExpression replaceExpression(GrExpression oldExpr, GrExpression newExpr) throws IncorrectOperationException {
if (oldExpr.getParent() == null ||
oldExpr.getParent().getNode() == null) {
throw new IncorrectOperationException();
}
// Remove unnecessary parentheses
if (oldExpr.getParent() instanceof GrParenthesizedExpr &&
newExpr instanceof GrReferenceExpression){
return ((GrExpression) oldExpr.getParent()).replaceWithExpression(newExpr);
}
// check priorities
GroovyElementFactory factory = GroovyElementFactory.getInstance(oldExpr.getProject());
if (oldExpr.getParent() instanceof GrExpression) {
GrExpression parentExpr = (GrExpression) oldExpr.getParent();
// todo fix me!
if (getExprPriorityLevel(parentExpr) >= getExprPriorityLevel(newExpr) && getExprPriorityLevel(parentExpr) != 0) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
}
ASTNode parentNode = oldExpr.getParent().getNode();
ASTNode newNode = newExpr.getNode();
parentNode.replaceChild(oldExpr.getNode(), newNode);
if (!(newNode.getPsi() instanceof GrExpression)){
throw new IncorrectOperationException();
}
return ((GrExpression) newNode.getPsi());
}
public static void shortenReferences(GroovyPsiElement element) {
doShorten(element);
}
private static void doShorten(PsiElement element) {
PsiElement child = element.getFirstChild();
while (child != null) {
if (child instanceof GrReferenceElement) {
final GrCodeReferenceElement ref = (GrCodeReferenceElement) child;
if (ref.getQualifier() != null) {
final PsiElement resolved = ref.resolve();
if (resolved instanceof PsiClass) {
ref.setQualifier(null);
try {
ref.bindToElement(resolved);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
}
doShorten(child);
child = child.getNextSibling();
}
}
public static SearchScope getUseScope(GrMember member) {
if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
return new LocalSearchScope(member.getContainingFile()); //todo: what does GLS say?
}
return member.getManager().getSearchHelper().getUseScope(member);
}
public static PsiNamedElement[] getMethodVariants(GrReferenceElement methodReference) {
final GroovyResolveResult[] results = methodReference.getSameNameVariants(); //will ignore argument types
List<PsiNamedElement> elements = new ArrayList<PsiNamedElement>();
for (GroovyResolveResult result : results) {
final PsiElement element = result.getElement();
if (element instanceof PsiNamedElement) elements.add((PsiNamedElement) element);
}
return elements.toArray(new PsiNamedElement[elements.size()]);
}
public static GrExpression getRuntimeQualifier(GrReferenceExpression refExpr) {
GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier == null) {
GrClosableBlock closure = PsiTreeUtil.getParentOfType(refExpr, GrClosableBlock.class);
while (closure != null) {
GrExpression funExpr = null;
PsiElement parent = closure.getParent();
if (parent instanceof GrApplicationStatement) {
funExpr = ((GrApplicationStatement) parent).getFunExpression();
} else if (parent instanceof GrMethodCallExpression) {
funExpr = ((GrMethodCallExpression) parent).getInvokedExpression();
}
if (funExpr instanceof GrReferenceExpression) {
qualifier = ((GrReferenceExpression) funExpr).getQualifierExpression();
if (qualifier != null) break;
} else break;
closure = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class);
}
}
return qualifier;
}
public static void removeVariable(GrVariable variable) throws IncorrectOperationException {
final GrVariableDeclaration varDecl = (GrVariableDeclaration) variable.getParent();
final List<GrVariable> variables = Arrays.asList(varDecl.getVariables());
if (!variables.contains(variable)) {
throw new IncorrectOperationException();
}
final ASTNode varDeclNode = varDecl.getNode();
final PsiElement parent = varDecl.getParent();
final ASTNode owner = parent.getNode();
if (variables.size() == 1 && owner != null) {
GroovyVariableUtil.cleanAroundDeclarationBeforeRemove(varDecl);
owner.removeChild(varDeclNode);
reformatCode(parent);
return;
}
GroovyVariableUtil.cleanAroundVariableBeforeRemove(variable);
final ASTNode varNode = variable.getNode();
if (varNode != null) {
varDeclNode.removeChild(varNode);
}
reformatCode(varDecl);
}
public static PsiElement realPrevious(PsiElement previousLeaf) {
while (previousLeaf != null &&
(previousLeaf instanceof PsiWhiteSpace ||
previousLeaf instanceof PsiComment ||
previousLeaf instanceof PsiErrorElement)) {
previousLeaf = previousLeaf.getPrevSibling();
}
return previousLeaf;
}
public static PsiElement realNext(PsiElement nextLeaf) {
while (nextLeaf != null &&
(nextLeaf instanceof PsiWhiteSpace ||
nextLeaf instanceof PsiComment ||
nextLeaf instanceof PsiErrorElement)) {
nextLeaf = nextLeaf.getNextSibling();
}
return nextLeaf;
}
public static void reformatCode(final PsiElement element) {
final TextRange textRange = element.getTextRange();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
CodeStyleManager.getInstance(element.getProject()).reformatText(element.getContainingFile(),
textRange.getStartOffset(), textRange.getEndOffset());
} catch (IncorrectOperationException e) {
e.printStackTrace();
}
}
});
}
/**
* Returns priiority level of expression
* @param expr
* @return
*/
public static int getExprPriorityLevel(GrExpression expr){
int priority = 0;
if (expr instanceof GrNewExpression) priority = 1;
if (expr instanceof GrPostfixExpression) priority = 5;
if (expr instanceof GrUnaryExpression ||
expr instanceof GrTypeCastExpression) priority = 6;
if (expr instanceof GrPowerExprImpl) priority = 7;
if (expr instanceof GrMultiplicativeExprImpl) priority = 8;
if (expr instanceof GrAdditiveExprImpl) priority = 9;
if (expr instanceof GrShiftExprImpl) priority = 10;
if (expr instanceof GrRelationalExpression) priority = 11;
if (expr instanceof GrEqualityExprImpl) priority = 12;
if (expr instanceof GrRegexExprImpl) priority = 13;
if (expr instanceof GrAndExprImpl) priority = 14;
if (expr instanceof GrExclusiveOrExprImpl) priority = 15;
if (expr instanceof GrInclusiveOrExprImpl) priority = 16;
if (expr instanceof GrLogicalAndExprImpl) priority = 17;
if (expr instanceof GrLogicalOrExprImpl) priority = 18;
if (expr instanceof GrConditionalExpression) priority = 19;
if (expr instanceof GrAssignmentExpression) priority = 20;
return -priority;
}
}
| cleanup | plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/PsiImplUtil.java | cleanup |
|
Java | apache-2.0 | 57285955d470c2f601d4549880a4fc4eb3ebfde0 | 0 | solidfire/solidfire-sdk-java,solidfire/solidfire-sdk-java | /*
* Copyright © 2014-2016 NetApp, Inc. 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.
*/
/*
* DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
*/
package com.solidfire.element.api;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
/**
* PendingNode
* A "pending node" is one that has not yet joined the cluster.
* It can be added to a cluster using the AddNode method.
**/
public class PendingNode implements Serializable {
public static final long serialVersionUID = -930850330231659742L;
@SerializedName("pendingNodeID") private Long pendingNodeID;
@SerializedName("assignedNodeID") private Long assignedNodeID;
@SerializedName("name") private String name;
@SerializedName("compatible") private Boolean compatible;
@SerializedName("platformInfo") private Platform platformInfo;
@SerializedName("cip") private String cip;
@SerializedName("cipi") private String cipi;
@SerializedName("mip") private String mip;
@SerializedName("mipi") private String mipi;
@SerializedName("sip") private String sip;
@SerializedName("sipi") private String sipi;
@SerializedName("softwareVersion") private String softwareVersion;
@SerializedName("uuid") private java.util.UUID uuid;
// empty constructor
@Since("7.0")
public PendingNode() {}
// parameterized constructor
@Since("7.0")
public PendingNode(
Long pendingNodeID,
Long assignedNodeID,
String name,
Boolean compatible,
Platform platformInfo,
String cip,
String cipi,
String mip,
String mipi,
String sip,
String sipi,
String softwareVersion,
java.util.UUID uuid
)
{
this.pendingNodeID = pendingNodeID;
this.assignedNodeID = assignedNodeID;
this.name = name;
this.compatible = compatible;
this.platformInfo = platformInfo;
this.cip = cip;
this.cipi = cipi;
this.mip = mip;
this.mipi = mipi;
this.sip = sip;
this.sipi = sipi;
this.softwareVersion = softwareVersion;
this.uuid = uuid;
}
/**
**/
public Long getPendingNodeID() { return this.pendingNodeID; }
public void setPendingNodeID(Long pendingNodeID) {
this.pendingNodeID = pendingNodeID;
}
/**
**/
public Long getAssignedNodeID() { return this.assignedNodeID; }
public void setAssignedNodeID(Long assignedNodeID) {
this.assignedNodeID = assignedNodeID;
}
/**
* The host name for this node.
**/
public String getName() { return this.name; }
public void setName(String name) {
this.name = name;
}
/**
**/
public Boolean getCompatible() { return this.compatible; }
public void setCompatible(Boolean compatible) {
this.compatible = compatible;
}
/**
* Information about the platform this node is.
**/
public Platform getPlatformInfo() { return this.platformInfo; }
public void setPlatformInfo(Platform platformInfo) {
this.platformInfo = platformInfo;
}
/**
* IP address used for both intra- and inter-cluster communication.
**/
public String getCip() { return this.cip; }
public void setCip(String cip) {
this.cip = cip;
}
/**
* The machine's name for the "cip" interface.
**/
public String getCipi() { return this.cipi; }
public void setCipi(String cipi) {
this.cipi = cipi;
}
/**
* IP address used for cluster management (hosting the API and web site).
**/
public String getMip() { return this.mip; }
public void setMip(String mip) {
this.mip = mip;
}
/**
* The machine's name for the "mip" interface.
**/
public String getMipi() { return this.mipi; }
public void setMipi(String mipi) {
this.mipi = mipi;
}
/**
* IP address used for iSCSI traffic.
**/
public String getSip() { return this.sip; }
public void setSip(String sip) {
this.sip = sip;
}
/**
* The machine's name for the "sip" interface.
**/
public String getSipi() { return this.sipi; }
public void setSipi(String sipi) {
this.sipi = sipi;
}
/**
* The version of SolidFire software this node is currently running.
**/
public String getSoftwareVersion() { return this.softwareVersion; }
public void setSoftwareVersion(String softwareVersion) {
this.softwareVersion = softwareVersion;
}
/**
* UUID of node.
**/
public java.util.UUID getUuid() { return this.uuid; }
public void setUuid(java.util.UUID uuid) {
this.uuid = uuid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PendingNode that = (PendingNode) o;
return
Objects.equals(pendingNodeID, that.pendingNodeID) &&
Objects.equals(assignedNodeID, that.assignedNodeID) &&
Objects.equals(name, that.name) &&
Objects.equals(compatible, that.compatible) &&
Objects.equals(platformInfo, that.platformInfo) &&
Objects.equals(cip, that.cip) &&
Objects.equals(cipi, that.cipi) &&
Objects.equals(mip, that.mip) &&
Objects.equals(mipi, that.mipi) &&
Objects.equals(sip, that.sip) &&
Objects.equals(sipi, that.sipi) &&
Objects.equals(softwareVersion, that.softwareVersion) &&
Objects.equals(uuid, that.uuid);
}
@Override
public int hashCode() {
return Objects.hash( pendingNodeID,assignedNodeID,name,compatible,platformInfo,cip,cipi,mip,mipi,sip,sipi,softwareVersion,uuid );
}
public java.util.Map<String, Object> toMap() {
java.util.Map<String, Object> map = new HashMap<>();
map.put("pendingNodeID", pendingNodeID);
map.put("assignedNodeID", assignedNodeID);
map.put("name", name);
map.put("compatible", compatible);
map.put("platformInfo", platformInfo);
map.put("cip", cip);
map.put("cipi", cipi);
map.put("mip", mip);
map.put("mipi", mipi);
map.put("sip", sip);
map.put("sipi", sipi);
map.put("softwareVersion", softwareVersion);
map.put("uuid", uuid);
return map;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "{ " );
sb.append(" pendingNodeID : ").append(pendingNodeID).append(",");
sb.append(" assignedNodeID : ").append(assignedNodeID).append(",");
sb.append(" name : ").append(name).append(",");
sb.append(" compatible : ").append(compatible).append(",");
sb.append(" platformInfo : ").append(platformInfo).append(",");
sb.append(" cip : ").append(cip).append(",");
sb.append(" cipi : ").append(cipi).append(",");
sb.append(" mip : ").append(mip).append(",");
sb.append(" mipi : ").append(mipi).append(",");
sb.append(" sip : ").append(sip).append(",");
sb.append(" sipi : ").append(sipi).append(",");
sb.append(" softwareVersion : ").append(softwareVersion).append(",");
sb.append(" uuid : ").append(uuid).append(",");
sb.append( " }" );
if(sb.lastIndexOf(", }") != -1)
sb.deleteCharAt(sb.lastIndexOf(", }"));
return sb.toString();
}
public static Builder builder() {
return new Builder();
}
public final Builder asBuilder() {
return new Builder().buildFrom(this);
}
public static class Builder {
private Long pendingNodeID;
private Long assignedNodeID;
private String name;
private Boolean compatible;
private Platform platformInfo;
private String cip;
private String cipi;
private String mip;
private String mipi;
private String sip;
private String sipi;
private String softwareVersion;
private java.util.UUID uuid;
private Builder() { }
public PendingNode build() {
return new PendingNode (
this.pendingNodeID,
this.assignedNodeID,
this.name,
this.compatible,
this.platformInfo,
this.cip,
this.cipi,
this.mip,
this.mipi,
this.sip,
this.sipi,
this.softwareVersion,
this.uuid);
}
private PendingNode.Builder buildFrom(final PendingNode req) {
this.pendingNodeID = req.pendingNodeID;
this.assignedNodeID = req.assignedNodeID;
this.name = req.name;
this.compatible = req.compatible;
this.platformInfo = req.platformInfo;
this.cip = req.cip;
this.cipi = req.cipi;
this.mip = req.mip;
this.mipi = req.mipi;
this.sip = req.sip;
this.sipi = req.sipi;
this.softwareVersion = req.softwareVersion;
this.uuid = req.uuid;
return this;
}
public PendingNode.Builder pendingNodeID(final Long pendingNodeID) {
this.pendingNodeID = pendingNodeID;
return this;
}
public PendingNode.Builder assignedNodeID(final Long assignedNodeID) {
this.assignedNodeID = assignedNodeID;
return this;
}
public PendingNode.Builder name(final String name) {
this.name = name;
return this;
}
public PendingNode.Builder compatible(final Boolean compatible) {
this.compatible = compatible;
return this;
}
public PendingNode.Builder platformInfo(final Platform platformInfo) {
this.platformInfo = platformInfo;
return this;
}
public PendingNode.Builder cip(final String cip) {
this.cip = cip;
return this;
}
public PendingNode.Builder cipi(final String cipi) {
this.cipi = cipi;
return this;
}
public PendingNode.Builder mip(final String mip) {
this.mip = mip;
return this;
}
public PendingNode.Builder mipi(final String mipi) {
this.mipi = mipi;
return this;
}
public PendingNode.Builder sip(final String sip) {
this.sip = sip;
return this;
}
public PendingNode.Builder sipi(final String sipi) {
this.sipi = sipi;
return this;
}
public PendingNode.Builder softwareVersion(final String softwareVersion) {
this.softwareVersion = softwareVersion;
return this;
}
public PendingNode.Builder uuid(final java.util.UUID uuid) {
this.uuid = uuid;
return this;
}
}
}
| src/generated/java/com/solidfire/element/api/PendingNode.java | /*
* Copyright © 2014-2016 NetApp, Inc. 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.
*/
/*
* DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
*/
package com.solidfire.element.api;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
/**
* PendingNode
* A "pending node" is one that has not yet joined the cluster.
* It can be added to a cluster using the AddNode method.
**/
public class PendingNode implements Serializable {
public static final long serialVersionUID = -930850330231659742L;
@SerializedName("pendingNodeID") private Long pendingNodeID;
@SerializedName("AssignedNodeID") private Long assignedNodeID;
@SerializedName("name") private String name;
@SerializedName("compatible") private Boolean compatible;
@SerializedName("platformInfo") private Platform platformInfo;
@SerializedName("cip") private String cip;
@SerializedName("cipi") private String cipi;
@SerializedName("mip") private String mip;
@SerializedName("mipi") private String mipi;
@SerializedName("sip") private String sip;
@SerializedName("sipi") private String sipi;
@SerializedName("softwareVersion") private String softwareVersion;
@SerializedName("uuid") private java.util.UUID uuid;
@SerializedName("assignedNodeID") private Optional<Long> assignedNodeID;
// empty constructor
@Since("7.0")
public PendingNode() {}
// parameterized constructor
@Since("7.0")
public PendingNode(
Long pendingNodeID,
Long assignedNodeID,
String name,
Boolean compatible,
Platform platformInfo,
String cip,
String cipi,
String mip,
String mipi,
String sip,
String sipi,
String softwareVersion,
java.util.UUID uuid,
Optional<Long> assignedNodeID
)
{
this.pendingNodeID = pendingNodeID;
this.assignedNodeID = assignedNodeID;
this.name = name;
this.compatible = compatible;
this.platformInfo = platformInfo;
this.cip = cip;
this.cipi = cipi;
this.mip = mip;
this.mipi = mipi;
this.sip = sip;
this.sipi = sipi;
this.softwareVersion = softwareVersion;
this.uuid = uuid;
this.assignedNodeID = (assignedNodeID == null) ? Optional.<Long>empty() : assignedNodeID;
}
/**
**/
public Long getPendingNodeID() { return this.pendingNodeID; }
public void setPendingNodeID(Long pendingNodeID) {
this.pendingNodeID = pendingNodeID;
}
/**
**/
public Long getAssignedNodeID() { return this.assignedNodeID; }
public void setAssignedNodeID(Long assignedNodeID) {
this.assignedNodeID = assignedNodeID;
}
/**
* The host name for this node.
**/
public String getName() { return this.name; }
public void setName(String name) {
this.name = name;
}
/**
**/
public Boolean getCompatible() { return this.compatible; }
public void setCompatible(Boolean compatible) {
this.compatible = compatible;
}
/**
* Information about the platform this node is.
**/
public Platform getPlatformInfo() { return this.platformInfo; }
public void setPlatformInfo(Platform platformInfo) {
this.platformInfo = platformInfo;
}
/**
* IP address used for both intra- and inter-cluster communication.
**/
public String getCip() { return this.cip; }
public void setCip(String cip) {
this.cip = cip;
}
/**
* The machine's name for the "cip" interface.
**/
public String getCipi() { return this.cipi; }
public void setCipi(String cipi) {
this.cipi = cipi;
}
/**
* IP address used for cluster management (hosting the API and web site).
**/
public String getMip() { return this.mip; }
public void setMip(String mip) {
this.mip = mip;
}
/**
* The machine's name for the "mip" interface.
**/
public String getMipi() { return this.mipi; }
public void setMipi(String mipi) {
this.mipi = mipi;
}
/**
* IP address used for iSCSI traffic.
**/
public String getSip() { return this.sip; }
public void setSip(String sip) {
this.sip = sip;
}
/**
* The machine's name for the "sip" interface.
**/
public String getSipi() { return this.sipi; }
public void setSipi(String sipi) {
this.sipi = sipi;
}
/**
* The version of SolidFire software this node is currently running.
**/
public String getSoftwareVersion() { return this.softwareVersion; }
public void setSoftwareVersion(String softwareVersion) {
this.softwareVersion = softwareVersion;
}
/**
* UUID of node.
**/
public java.util.UUID getUuid() { return this.uuid; }
public void setUuid(java.util.UUID uuid) {
this.uuid = uuid;
}
/**
**/
public Optional<Long> getAssignedNodeID() { return this.assignedNodeID; }
public void setAssignedNodeID(Optional<Long> assignedNodeID) {
this.assignedNodeID = (assignedNodeID == null) ? Optional.<Long>empty() : assignedNodeID;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PendingNode that = (PendingNode) o;
return
Objects.equals(pendingNodeID, that.pendingNodeID) &&
Objects.equals(assignedNodeID, that.assignedNodeID) &&
Objects.equals(name, that.name) &&
Objects.equals(compatible, that.compatible) &&
Objects.equals(platformInfo, that.platformInfo) &&
Objects.equals(cip, that.cip) &&
Objects.equals(cipi, that.cipi) &&
Objects.equals(mip, that.mip) &&
Objects.equals(mipi, that.mipi) &&
Objects.equals(sip, that.sip) &&
Objects.equals(sipi, that.sipi) &&
Objects.equals(softwareVersion, that.softwareVersion) &&
Objects.equals(uuid, that.uuid) &&
Objects.equals(assignedNodeID, that.assignedNodeID);
}
@Override
public int hashCode() {
return Objects.hash( pendingNodeID,assignedNodeID,name,compatible,platformInfo,cip,cipi,mip,mipi,sip,sipi,softwareVersion,uuid,assignedNodeID );
}
public java.util.Map<String, Object> toMap() {
java.util.Map<String, Object> map = new HashMap<>();
map.put("pendingNodeID", pendingNodeID);
map.put("assignedNodeID", assignedNodeID);
map.put("name", name);
map.put("compatible", compatible);
map.put("platformInfo", platformInfo);
map.put("cip", cip);
map.put("cipi", cipi);
map.put("mip", mip);
map.put("mipi", mipi);
map.put("sip", sip);
map.put("sipi", sipi);
map.put("softwareVersion", softwareVersion);
map.put("uuid", uuid);
map.put("assignedNodeID", assignedNodeID);
return map;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "{ " );
sb.append(" pendingNodeID : ").append(pendingNodeID).append(",");
sb.append(" assignedNodeID : ").append(assignedNodeID).append(",");
sb.append(" name : ").append(name).append(",");
sb.append(" compatible : ").append(compatible).append(",");
sb.append(" platformInfo : ").append(platformInfo).append(",");
sb.append(" cip : ").append(cip).append(",");
sb.append(" cipi : ").append(cipi).append(",");
sb.append(" mip : ").append(mip).append(",");
sb.append(" mipi : ").append(mipi).append(",");
sb.append(" sip : ").append(sip).append(",");
sb.append(" sipi : ").append(sipi).append(",");
sb.append(" softwareVersion : ").append(softwareVersion).append(",");
sb.append(" uuid : ").append(uuid).append(",");
if(null != assignedNodeID && assignedNodeID.isPresent()){
sb.append(" assignedNodeID : ").append(assignedNodeID).append(",");
}
sb.append( " }" );
if(sb.lastIndexOf(", }") != -1)
sb.deleteCharAt(sb.lastIndexOf(", }"));
return sb.toString();
}
public static Builder builder() {
return new Builder();
}
public final Builder asBuilder() {
return new Builder().buildFrom(this);
}
public static class Builder {
private Long pendingNodeID;
private Long assignedNodeID;
private String name;
private Boolean compatible;
private Platform platformInfo;
private String cip;
private String cipi;
private String mip;
private String mipi;
private String sip;
private String sipi;
private String softwareVersion;
private java.util.UUID uuid;
private Optional<Long> assignedNodeID;
private Builder() { }
public PendingNode build() {
return new PendingNode (
this.pendingNodeID,
this.assignedNodeID,
this.name,
this.compatible,
this.platformInfo,
this.cip,
this.cipi,
this.mip,
this.mipi,
this.sip,
this.sipi,
this.softwareVersion,
this.uuid,
this.assignedNodeID);
}
private PendingNode.Builder buildFrom(final PendingNode req) {
this.pendingNodeID = req.pendingNodeID;
this.assignedNodeID = req.assignedNodeID;
this.name = req.name;
this.compatible = req.compatible;
this.platformInfo = req.platformInfo;
this.cip = req.cip;
this.cipi = req.cipi;
this.mip = req.mip;
this.mipi = req.mipi;
this.sip = req.sip;
this.sipi = req.sipi;
this.softwareVersion = req.softwareVersion;
this.uuid = req.uuid;
this.assignedNodeID = req.assignedNodeID;
return this;
}
public PendingNode.Builder pendingNodeID(final Long pendingNodeID) {
this.pendingNodeID = pendingNodeID;
return this;
}
public PendingNode.Builder assignedNodeID(final Long assignedNodeID) {
this.assignedNodeID = assignedNodeID;
return this;
}
public PendingNode.Builder name(final String name) {
this.name = name;
return this;
}
public PendingNode.Builder compatible(final Boolean compatible) {
this.compatible = compatible;
return this;
}
public PendingNode.Builder platformInfo(final Platform platformInfo) {
this.platformInfo = platformInfo;
return this;
}
public PendingNode.Builder cip(final String cip) {
this.cip = cip;
return this;
}
public PendingNode.Builder cipi(final String cipi) {
this.cipi = cipi;
return this;
}
public PendingNode.Builder mip(final String mip) {
this.mip = mip;
return this;
}
public PendingNode.Builder mipi(final String mipi) {
this.mipi = mipi;
return this;
}
public PendingNode.Builder sip(final String sip) {
this.sip = sip;
return this;
}
public PendingNode.Builder sipi(final String sipi) {
this.sipi = sipi;
return this;
}
public PendingNode.Builder softwareVersion(final String softwareVersion) {
this.softwareVersion = softwareVersion;
return this;
}
public PendingNode.Builder uuid(final java.util.UUID uuid) {
this.uuid = uuid;
return this;
}
public PendingNode.Builder optionalAssignedNodeID(final Long assignedNodeID) {
this.assignedNodeID = (assignedNodeID == null) ? Optional.<Long>empty() : Optional.of(assignedNodeID);
return this;
}
}
}
| Adding generated files
| src/generated/java/com/solidfire/element/api/PendingNode.java | Adding generated files |
|
Java | apache-2.0 | 01ddfe2049c0046c50b86b57b01acdeb8f579bb8 | 0 | marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api | /*
* Copyright 2012-2018 MarkLogic 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 com.marklogic.client.impl;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.*;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.DatabaseClientFactory.BasicAuthContext;
import com.marklogic.client.DatabaseClientFactory.CertificateAuthContext;
import com.marklogic.client.DatabaseClientFactory.DigestAuthContext;
import com.marklogic.client.DatabaseClientFactory.KerberosAuthContext;
import com.marklogic.client.DatabaseClientFactory.SAMLAuthContext;
import com.marklogic.client.DatabaseClientFactory.SSLHostnameVerifier;
import com.marklogic.client.DatabaseClientFactory.SecurityContext;
import com.marklogic.client.bitemporal.TemporalDescriptor;
import com.marklogic.client.bitemporal.TemporalDocumentManager.ProtectionLevel;
import com.marklogic.client.document.ContentDescriptor;
import com.marklogic.client.document.DocumentDescriptor;
import com.marklogic.client.document.DocumentManager.Metadata;
import com.marklogic.client.document.DocumentPage;
import com.marklogic.client.document.DocumentRecord;
import com.marklogic.client.document.DocumentUriTemplate;
import com.marklogic.client.document.DocumentWriteOperation;
import com.marklogic.client.document.DocumentWriteSet;
import com.marklogic.client.document.ServerTransform;
import com.marklogic.client.eval.EvalResult;
import com.marklogic.client.eval.EvalResultIterator;
import com.marklogic.client.io.BytesHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.io.JacksonParserHandle;
import com.marklogic.client.io.OutputStreamSender;
import com.marklogic.client.io.ReaderHandle;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.io.marker.AbstractReadHandle;
import com.marklogic.client.io.marker.AbstractWriteHandle;
import com.marklogic.client.io.marker.ContentHandle;
import com.marklogic.client.io.marker.CtsQueryWriteHandle;
import com.marklogic.client.io.marker.DocumentMetadataReadHandle;
import com.marklogic.client.io.marker.DocumentMetadataWriteHandle;
import com.marklogic.client.io.marker.DocumentPatchHandle;
import com.marklogic.client.io.marker.SearchReadHandle;
import com.marklogic.client.io.marker.StructureWriteHandle;
import com.marklogic.client.query.DeleteQueryDefinition;
import com.marklogic.client.query.QueryDefinition;
import com.marklogic.client.query.QueryManager.QueryView;
import com.marklogic.client.query.RawCombinedQueryDefinition;
import com.marklogic.client.query.RawCtsQueryDefinition;
import com.marklogic.client.query.RawQueryByExampleDefinition;
import com.marklogic.client.query.RawQueryDefinition;
import com.marklogic.client.query.RawStructuredQueryDefinition;
import com.marklogic.client.query.StringQueryDefinition;
import com.marklogic.client.query.StructuredQueryDefinition;
import com.marklogic.client.query.SuggestDefinition;
import com.marklogic.client.query.ValueQueryDefinition;
import com.marklogic.client.query.ValuesDefinition;
import com.marklogic.client.query.ValuesListDefinition;
import com.marklogic.client.semantics.Capability;
import com.marklogic.client.semantics.GraphManager;
import com.marklogic.client.semantics.GraphPermissions;
import com.marklogic.client.semantics.SPARQLBinding;
import com.marklogic.client.semantics.SPARQLBindings;
import com.marklogic.client.semantics.SPARQLQueryDefinition;
import com.marklogic.client.semantics.SPARQLRuleset;
import com.marklogic.client.util.EditableNamespaceContext;
import com.marklogic.client.util.RequestLogger;
import com.marklogic.client.util.RequestParameters;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.ConnectionPool;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartBody.Part;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.BodyPart;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class OkHttpServices implements RESTServices {
static final private Logger logger = LoggerFactory.getLogger(OkHttpServices.class);
static final public String OKHTTP_LOGGINGINTERCEPTOR_LEVEL = "com.marklogic.client.okhttp.httplogginginterceptor.level";
static final public String OKHTTP_LOGGINGINTERCEPTOR_OUTPUT = "com.marklogic.client.okhttp.httplogginginterceptor.output";
static final private String DOCUMENT_URI_PREFIX = "/documents?uri=";
static final private int DELAY_FLOOR = 125;
static final private int DELAY_CEILING = 2000;
static final private int DELAY_MULTIPLIER = 20;
static final private int DEFAULT_MAX_DELAY = 120000;
static final private int DEFAULT_MIN_RETRY = 8;
private final static MediaType URLENCODED_MIME_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
private final static String UTF8_ID = StandardCharsets.UTF_8.toString();
static final private ConnectionPool connectionPool = new ConnectionPool();
private DatabaseClient databaseClient;
private String database = null;
private HttpUrl baseUri;
private OkHttpClient client;
private boolean released = false;
private String authorizationTokenValue = null;
private Random randRetry = new Random();
private int maxDelay = DEFAULT_MAX_DELAY;
private int minRetry = DEFAULT_MIN_RETRY;
private boolean checkFirstRequest = true;
private Set<Integer> retryStatus = new HashSet<>();
static protected class ThreadState {
boolean isFirstRequest;
ThreadState(boolean value) {
isFirstRequest = value;
}
}
private final ThreadLocal<ThreadState> threadState = new ThreadLocal<ThreadState>() {
@Override
protected ThreadState initialValue() {
return new ThreadState(checkFirstRequest);
}
};
public OkHttpServices() {
retryStatus.add(STATUS_BAD_GATEWAY);
retryStatus.add(STATUS_SERVICE_UNAVAILABLE);
retryStatus.add(STATUS_GATEWAY_TIMEOUT);
}
@Override
public Set<Integer> getRetryStatus() {
return retryStatus;
}
@Override
public int getMaxDelay() {
return maxDelay;
}
@Override
public void setMaxDelay(int maxDelay) {
this.maxDelay = maxDelay;
}
private FailedRequest extractErrorFields(Response response) {
if ( response == null ) return null;
try {
if ( response.code() == STATUS_UNAUTHORIZED ) {
FailedRequest failure = new FailedRequest();
failure.setMessageString("Unauthorized");
failure.setStatusString("Failed Auth");
return failure;
}
String responseBody = getEntity(response.body(), String.class);
InputStream is = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
FailedRequest handler = FailedRequest.getFailedRequest(response.code(), response.header(HEADER_CONTENT_TYPE), is);
if ( handler.getMessage() == null ) {
handler.setMessageString(responseBody);
}
return handler;
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
} finally {
response.close();
}
}
@Override
@Deprecated
public void connect(String host, int port, String database, String user, String password,Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext,
SSLHostnameVerifier verifier) {
connect(host, port, database, user, password, kerberosOptions, authenType, sslContext, null, verifier);
}
@Override
@Deprecated
public void connect(String host, int port, String database, String user, String password,Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext, X509TrustManager trustManager,
SSLHostnameVerifier verifier) {
HostnameVerifier hostnameVerifier = null;
if (verifier == SSLHostnameVerifier.ANY) {
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (verifier == SSLHostnameVerifier.COMMON) {
hostnameVerifier = null;
} else if (verifier == SSLHostnameVerifier.STRICT) {
hostnameVerifier = null;
} else if (verifier != null) {
hostnameVerifier = new SSLHostnameVerifier.HostnameVerifierAdapter(verifier);
}// else {
// throw new IllegalArgumentException(
// "Null SSLContext but non-null SSLHostnameVerifier for client");
//}
connect(host, port, database, user, password, kerberosOptions, authenType, sslContext, trustManager, hostnameVerifier);
}
private void connect(String host, int port, String database, String user, String password, Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext, X509TrustManager trustManager,
HostnameVerifier verifier) {
logger.debug("Connecting to {} at {} as {}", new Object[]{host, port, user});
if (host == null) throw new IllegalArgumentException("No host provided");
this.database = database;
this.baseUri = new HttpUrl.Builder()
.scheme(sslContext == null ? "http" : "https")
.host(host)
.port(port)
.encodedPath("/v1/ping")
.build();
Credentials credentials = new Credentials(user, password);
final Map<String,CachingAuthenticator> authCache = new ConcurrentHashMap<String,CachingAuthenticator>();
if ( authenType == null && sslContext != null ) {
authenType = Authentication.BASIC;
}
CachingAuthenticator authenticator = null;
Interceptor interceptor = null;
if (authenType == null || authenType == Authentication.CERTIFICATE) {
checkFirstRequest = false;
} else if (authenType == Authentication.KERBEROS) {
interceptor = new HTTPKerberosAuthInterceptor(host, kerberosOptions);
checkFirstRequest = false;
} else {
if (user == null) throw new IllegalArgumentException("No user provided");
if (password == null) throw new IllegalArgumentException("No password provided");
if (authenType == Authentication.BASIC) {
interceptor = new HTTPBasicAuthInterceptor(credentials);
checkFirstRequest = false;
} else if (authenType == Authentication.DIGEST) {
authenticator = new DigestAuthenticator(credentials);
interceptor = new AuthenticationCacheInterceptor(authCache);
checkFirstRequest = true;
} else {
throw new MarkLogicInternalException(
"Internal error - unknown authentication type: " + authenType.name());
}
}
OkHttpClient.Builder clientBldr = new OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
// all clients share a single connection pool
.connectionPool(connectionPool)
// cookies are ignored (except when a Transaction is being used)
.cookieJar(CookieJar.NO_COOKIES)
// no timeouts since some of our clients' reads and writes can be massive
.readTimeout(0, TimeUnit.SECONDS)
.writeTimeout(0, TimeUnit.SECONDS);
if (sslContext != null) {
if (trustManager == null) {
clientBldr.sslSocketFactory(sslContext.getSocketFactory());
} else {
clientBldr.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
}
}
if(authenticator != null) clientBldr.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache));
if(interceptor != null) clientBldr.addInterceptor(interceptor);
if ( verifier != null ) {
clientBldr = clientBldr.hostnameVerifier(verifier);
}
Properties props = System.getProperties();
if (props.containsKey(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) {
final boolean useLogger = "LOGGER".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_OUTPUT));
final boolean useStdErr = "STDERR".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_OUTPUT));
HttpLoggingInterceptor networkInterceptor = new HttpLoggingInterceptor(
new HttpLoggingInterceptor.Logger() {
public void log(String message) {
if ( useLogger == true ) {
logger.debug(message);
} else if ( useStdErr == true ) {
System.err.println(message);
} else {
System.out.println(message);
}
}
}
);
if ( "BASIC".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
} else if ( "BODY".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else if ( "HEADERS".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
} else if ( "NONE".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
clientBldr = clientBldr.addNetworkInterceptor(networkInterceptor);
}
if (props.containsKey(MAX_DELAY_PROP)) {
String maxDelayStr = props.getProperty(MAX_DELAY_PROP);
if (maxDelayStr != null && maxDelayStr.length() > 0) {
int max = Integer.parseInt(maxDelayStr);
if (max > 0) {
maxDelay = max * 1000;
}
}
}
if (props.containsKey(MIN_RETRY_PROP)) {
String minRetryStr = props.getProperty(MIN_RETRY_PROP);
if (minRetryStr != null && minRetryStr.length() > 0) {
int min = Integer.parseInt(minRetryStr);
if (min > 0) {
minRetry = min;
}
}
}
this.client = clientBldr.build();
// System.setProperty("javax.net.debug", "all"); // all or ssl
/*
// long-term alternative to isFirstRequest alive
// HttpProtocolParams.setUseExpectContinue(httpParams, false);
// httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);
*/
}
@Override
public void connect(String host, int port, String database, SecurityContext securityContext){
String user = null;
Map<String, String> kerberosOptions = null;
String password = null;
Authentication type = null;
SSLContext sslContext = null;
SSLHostnameVerifier sslVerifier = null;
X509TrustManager trustManager = null;
if (securityContext instanceof BasicAuthContext) {
BasicAuthContext basicContext = (BasicAuthContext) securityContext;
user = basicContext.getUser();
password = basicContext.getPassword();
type = Authentication.BASIC;
if (basicContext.getSSLContext() != null) {
sslContext = basicContext.getSSLContext();
if (basicContext.getTrustManager() != null)
trustManager = basicContext.getTrustManager();
if (basicContext.getSSLHostnameVerifier() != null) {
sslVerifier = basicContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof DigestAuthContext) {
DigestAuthContext digestContext = (DigestAuthContext) securityContext;
user = digestContext.getUser();
password = digestContext.getPassword();
type = Authentication.DIGEST;
if (digestContext.getSSLContext() != null) {
sslContext = digestContext.getSSLContext();
if (digestContext.getTrustManager() != null)
trustManager = digestContext.getTrustManager();
if (digestContext.getSSLHostnameVerifier() != null) {
sslVerifier = digestContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof KerberosAuthContext) {
KerberosAuthContext kerberosContext = (KerberosAuthContext) securityContext;
kerberosOptions = kerberosContext.getKrbOptions();
type = Authentication.KERBEROS;
if (kerberosContext.getSSLContext() != null) {
sslContext = kerberosContext.getSSLContext();
if (kerberosContext.getTrustManager() != null)
trustManager = kerberosContext.getTrustManager();
if (kerberosContext.getSSLHostnameVerifier() != null) {
sslVerifier = kerberosContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof CertificateAuthContext) {
CertificateAuthContext certificateContext = (CertificateAuthContext) securityContext;
type = Authentication.CERTIFICATE;
sslContext = certificateContext.getSSLContext();
if (certificateContext.getTrustManager() != null)
trustManager = certificateContext.getTrustManager();
if (certificateContext.getSSLHostnameVerifier() != null) {
sslVerifier = certificateContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
} else if (securityContext instanceof SAMLAuthContext) {
SAMLAuthContext samlAuthContext = (SAMLAuthContext) securityContext;
type = Authentication.SAML;
sslContext = samlAuthContext.getSSLContext();
authorizationTokenValue = samlAuthContext.getToken();
if (samlAuthContext.getTrustManager() != null)
trustManager = samlAuthContext.getTrustManager();
if (samlAuthContext.getSSLHostnameVerifier() != null) {
sslVerifier = samlAuthContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
} else {
throw new IllegalArgumentException("securityContext must be of type BasicAuthContext, "
+ "DigestAuthContext, KerberosAuthContext, CertificateAuthContext or SAMLAuthContext");
}
HostnameVerifier hostnameVerifier = null;
if (sslVerifier == SSLHostnameVerifier.ANY) {
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (sslVerifier == SSLHostnameVerifier.COMMON || sslVerifier == SSLHostnameVerifier.STRICT) {
hostnameVerifier = null;
} else if (sslVerifier != null) {
hostnameVerifier = new SSLHostnameVerifier.HostnameVerifierAdapter(sslVerifier);
}
connect(host, port, database, user, password, kerberosOptions, type, sslContext, trustManager,
hostnameVerifier);
}
@Override
public DatabaseClient getDatabaseClient() {
return databaseClient;
}
@Override
public void setDatabaseClient(DatabaseClient client) {
this.databaseClient = client;
}
private OkHttpClient getConnection() {
if ( client != null ) {
return client;
} else if ( released ) {
throw new IllegalStateException(
"You cannot use this connected object anymore--connection has already been released");
} else {
throw new MarkLogicInternalException("Cannot proceed--connection is null for unknown reason");
}
}
@Override
public void release() {
if ( client == null ) return;
try {
released = true;
client.dispatcher().executorService().shutdownNow();
} finally {
try {
if ( client.cache() != null ) client.cache().close();
} catch (IOException e) {
throw new MarkLogicIOException(e);
} finally {
client = null;
logger.debug("Releasing connection");
}
}
}
private boolean isFirstRequest() {
return threadState.get().isFirstRequest;
}
private void setFirstRequest(boolean value) {
threadState.get().isFirstRequest = value;
}
private void checkFirstRequest() {
if (checkFirstRequest) setFirstRequest(true);
}
private int makeFirstRequest(int retry) {
return makeFirstRequest(baseUri, "ping", retry);
}
private int makeFirstRequest(HttpUrl requestUri, String path, int retry) {
Response response = sendRequestOnce(setupRequest(requestUri, path, null).head());
int statusCode = response.code();
if (!retryStatus.contains(statusCode)) {
response.close();
return 0;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
return Math.max(retryAfter, calculateDelay(randRetry, retry));
}
private RequestParameters addTemporalProtectionParams(RequestParameters params, String uri, ProtectionLevel level,
String duration, Calendar expiryTime, String archivePath) {
if (params == null)
params = new RequestParameters();
params.add("uri", uri);
params.add("level", level.toString());
if (duration != null)
params.add("duration", duration);
if (expiryTime != null) {
String formattedSystemTime = DatatypeConverter.printDateTime(expiryTime);
params.add("expireTime", formattedSystemTime);
}
if (archivePath != null)
params.add("archivePath", archivePath);
return params;
}
@Override
public String advanceLsqt(RequestLogger reqlog, String temporalCollection, long lag) {
if (logger.isDebugEnabled())
logger.debug("Advancing LSQT in temporal collection {}", temporalCollection);
logRequest(reqlog, "wiped %s document", temporalCollection);
RequestParameters params = new RequestParameters();
params.add("result", "advance-lsqt");
if ( lag > 0 ) params.add("lag", String.valueOf(lag));
Map<String,List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
postResource(reqlog, "temporal/collections/" + temporalCollection,
null, params, null, null, "advanceLsqt", headers);
List<String> values = headers.get(HEADER_ML_LSQT);
if ( values != null && values.size() > 0 ) {
return values.get(0);
} else {
throw new FailedRequestException("Response missing header \"" + HEADER_ML_LSQT + "\"");
}
}
@Override
public void protectDocument(RequestLogger requestLogger, String temporalDocumentURI, Transaction transaction,
RequestParameters extraParams, ProtectionLevel level, String duration,
Calendar expiryTime, String archivePath) {
if (temporalDocumentURI == null)
throw new IllegalArgumentException(
"Document protection for document identifier without uri");
extraParams = addTemporalProtectionParams(extraParams, temporalDocumentURI, level, duration, expiryTime, archivePath);
if (logger.isDebugEnabled())
logger.debug("Protecting {} in transaction {}", temporalDocumentURI, getTransactionId(transaction));
postResource(requestLogger, "documents/protection", transaction, extraParams, null, null, "protect");
}
@Override
public void wipeDocument(RequestLogger reqlog, String temporalDocumentURI, Transaction transaction,
RequestParameters extraParams) {
if (logger.isDebugEnabled())
logger.debug("Wiping {} in transaction {}", temporalDocumentURI, getTransactionId(transaction));
extraParams.add("result", "wiped");
extraParams.add("uri", temporalDocumentURI);
deleteResource(reqlog, "documents", transaction, extraParams, null);
logRequest(reqlog, "wiped %s document", temporalDocumentURI);
}
@Override
public TemporalDescriptor deleteDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document delete for document identifier without uri");
}
logger.debug("Deleting {} in transaction {}", uri, getTransactionId(transaction));
Request.Builder requestBldr = makeDocumentResource(makeDocumentParams(uri,
categories, transaction, extraParams));
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
response.close();
throw new ResourceNotFoundException(
"Could not delete non-existent document");
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to delete document", failure);
}
throw new FailedRequestException(
"Precondition required to delete document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to delete documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to delete document",
failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
Headers responseHeaders = response.headers();
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
logRequest(reqlog, "deleted %s document", uri);
return temporalDesc;
}
@Override
public boolean getDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories,
RequestParameters extraParams,
DocumentMetadataReadHandle metadataHandle,
AbstractReadHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataFormat = null;
String metadataMimetype = null;
if (metadataBase != null) {
metadataFormat = metadataBase.getFormat().toString().toLowerCase();
metadataMimetype = metadataBase.getMimetype();
}
String contentMimetype = null;
if (contentBase != null) {
contentMimetype = contentBase.getMimetype();
}
if (metadataBase != null && contentBase != null) {
return getDocumentImpl(reqlog, desc, transaction, categories,
extraParams, metadataFormat, metadataHandle, contentHandle);
} else if (metadataBase != null) {
return getDocumentImpl(reqlog, desc, transaction, categories,
extraParams, metadataMimetype, metadataHandle);
} else if (contentBase != null) {
return getDocumentImpl(reqlog, desc, transaction, null,
extraParams, contentMimetype, contentHandle);
}
return false;
}
private int getRetryAfterTime(Response response) {
String retryAfterRaw = response.header("Retry-After");
return (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
}
private Response sendRequestOnce(Request.Builder requestBldr) {
return sendRequestOnce(requestBldr.build());
}
private Response sendRequestOnce(Request request) {
try {
return getConnection().newCall(request).execute();
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
private Response sendRequestWithRetry(Request.Builder requestBldr, Function<Request.Builder, Response> doFunction, Consumer<Boolean> resendableConsumer) {
return sendRequestWithRetry(requestBldr, true, doFunction, resendableConsumer);
}
private Response sendRequestWithRetry(
Request.Builder requestBldr, boolean isRetryable, Function<Request.Builder, Response> doFunction, Consumer<Boolean> resendableConsumer
) {
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
/*
* This loop is for retrying the request if the service is unavailable
*/
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try { Thread.sleep(nextDelay);} catch (InterruptedException e) {}
}
/*
* Execute the function which is passed as an argument
* in order to get the Response
*/
response = doFunction.apply(requestBldr);
status = response.code();
if (!isRetryable || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
/*
* If we don't get a service unavailable status or if the request
* is not retryable, we break from the retrying loop and return
* the response
*/
break;
}
/*
* This code will be executed whenever the service is unavailable.
* When the service becomes unavailable, we close the Response
* we got and retry it to try and get a new Response
*/
response.close();
/*
* There are scenarios where we don't want to retry and we just want to
* throw ResourceNotResendableException. In that case, we pass that code from
* the caller through the Consumer and execute it here. In the rest of the
* scenarios, we pass it as null and it is just a no-operation.
*/
if(resendableConsumer != null) resendableConsumer.accept(null);
/*
* Calculate the delay before which we shouldn't retry
*/
nextDelay = Math.max(getRetryAfterTime(response), calculateDelay(randRetry, retry));
}
/*
* If the service is still unavailable after all the retries, we throw a
* FailedRetryException indicating that the service is unavailable.
*/
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
/*
* Once we break from the retry loop, we just return the Response
* back to the caller in order to proceed with the flow
*/
return response;
}
private boolean getDocumentImpl(RequestLogger reqlog,
DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, RequestParameters extraParams,
String mimetype, AbstractReadHandle handle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document read for document identifier without uri");
}
logger.debug("Getting {} in transaction {}", uri, getTransactionId(transaction));
addPointInTimeQueryParam(extraParams, handle);
Request.Builder requestBldr = makeDocumentResource(
makeDocumentParams(uri, categories, transaction, extraParams));
if ( mimetype != null ) {
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
}
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (extraParams != null && extraParams.containsKey("range")) {
requestBldr = requestBldr.header("range", extraParams.get("range").get(0));
}
requestBldr = addVersionHeader(desc, requestBldr, "If-None-Match");
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not read non-existent document",
extractErrorFields(response));
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to read documents",
extractErrorFields(response));
}
if (status == STATUS_NOT_MODIFIED) {
response.close();
return false;
}
if (status != STATUS_OK && status != STATUS_PARTIAL_CONTENT) {
throw new FailedRequestException("read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(
reqlog,
"read %s document from %s transaction with %s mime type and %s metadata categories",
uri, (transaction != null) ? transaction.getTransactionId() : "no",
(mimetype != null) ? mimetype : "no",
stringJoin(categories, ", ", "no"));
HandleImplementation handleBase = HandleAccessor.as(handle);
Headers responseHeaders = response.headers();
if (isExternalDescriptor(desc)) {
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
copyDescriptor(desc, handleBase);
} else {
updateDescriptor(handleBase, responseHeaders);
}
Class as = handleBase.receiveAs();
ResponseBody body = response.body();
Object entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (!InputStream.class.isAssignableFrom(as) && !Reader.class.isAssignableFrom(as))) {
response.close();
}
handleBase.receiveContent((reqlog != null) ? reqlog.copyContent(entity) : entity);
return true;
}
@Override
public DocumentPage getBulkDocuments(RequestLogger reqlog, long serverTimestamp,
Transaction transaction, Set<Metadata> categories,
Format format, RequestParameters extraParams, boolean withContent, String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
boolean hasMetadata = categories != null && categories.size() > 0;
OkHttpResultIterator iterator =
getBulkDocumentsImpl(reqlog, serverTimestamp, transaction, categories, format, extraParams,
withContent, uris);
return new OkHttpDocumentPage(iterator, withContent, hasMetadata);
}
@Override
public DocumentPage getBulkDocuments(RequestLogger reqlog, long serverTimestamp,
QueryDefinition querydef,
long start, long pageLength,
Transaction transaction,
SearchReadHandle searchHandle, QueryView view,
Set<Metadata> categories, Format format, ServerTransform responseTransform,
RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
boolean hasMetadata = categories != null && categories.size() > 0;
boolean hasContent = true;
OkHttpResultIterator iterator =
getBulkDocumentsImpl(reqlog, serverTimestamp, querydef, start, pageLength, transaction,
searchHandle, view, categories, format, responseTransform, extraParams);
return new OkHttpDocumentPage(iterator, hasContent, hasMetadata);
}
private class OkHttpDocumentPage extends BasicPage<DocumentRecord> implements DocumentPage, Iterator<DocumentRecord> {
private OkHttpResultIterator iterator;
private Iterator<DocumentRecord> docRecordIterator;
private boolean hasMetadata;
private boolean hasContent;
OkHttpDocumentPage(OkHttpResultIterator iterator, boolean hasContent, boolean hasMetadata) {
super(
new ArrayList<DocumentRecord>().iterator(),
iterator != null ? iterator.getStart() : 1,
iterator != null ? iterator.getPageSize() : 0,
iterator != null ? iterator.getTotalSize() : 0
);
this.iterator = iterator;
this.hasContent = hasContent;
this.hasMetadata = hasMetadata;
if ( iterator == null ) {
setSize(0);
} else if ( hasContent && hasMetadata ) {
setSize(iterator.getSize() / 2);
} else {
setSize(iterator.getSize());
}
}
@Override
public Iterator<DocumentRecord> iterator() {
return this;
}
@Override
public boolean hasNext() {
if ( iterator == null ) return false;
return iterator.hasNext();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public DocumentRecord next() {
if ( iterator == null ) throw new NoSuchElementException("No documents available");
OkHttpResult result = iterator.next();
DocumentRecord record;
if ( hasContent && hasMetadata ) {
OkHttpResult metadata = result;
OkHttpResult content = iterator.next();
record = new OkHttpDocumentRecord(content, metadata);
} else if ( hasContent ) {
OkHttpResult content = result;
record = new OkHttpDocumentRecord(content);
} else if ( hasMetadata ) {
OkHttpResult metadata = result;
record = new OkHttpDocumentRecord(null, metadata);
} else {
throw new IllegalStateException("Should never have neither content nor metadata");
}
return record;
}
@Override
public <T extends AbstractReadHandle> T nextContent(T contentHandle) {
return next().getContent(contentHandle);
}
@Override
public void close() {
if ( iterator != null ) iterator.close();
}
}
private OkHttpResultIterator getBulkDocumentsImpl(RequestLogger reqlog, long serverTimestamp,
Transaction transaction, Set<Metadata> categories,
Format format, RequestParameters extraParams, boolean withContent,
String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String path = "documents";
RequestParameters params = new RequestParameters();
if ( extraParams != null ) params.putAll(extraParams);
if (serverTimestamp != -1) params.add("timestamp", Long.toString(serverTimestamp));
addCategoryParams(categories, params, withContent);
if (format != null) params.add("format", format.toString().toLowerCase());
for (String uri: uris) {
if ( uri != null && uri.length() > 0 ) {
params.add("uri", uri);
}
}
OkHttpResultIterator iterator = getIteratedResourceImpl(DefaultOkHttpResultIterator.class,
reqlog, path, transaction, params, MIMETYPE_MULTIPART_MIXED);
if ( iterator != null ) {
if ( iterator.getStart() == -1 ) iterator.setStart(1);
if ( iterator.getSize() != -1 ) {
if ( iterator.getPageSize() == -1 ) iterator.setPageSize(iterator.getSize());
if ( iterator.getTotalSize() == -1 ) iterator.setTotalSize(iterator.getSize());
}
}
return iterator;
}
private OkHttpResultIterator getBulkDocumentsImpl(RequestLogger reqlog, long serverTimestamp,
QueryDefinition querydef, long start, long pageLength,
Transaction transaction, SearchReadHandle searchHandle, QueryView view,
Set<Metadata> categories, Format format, ServerTransform responseTransform,
RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
try {
RequestParameters params = new RequestParameters();
if ( extraParams != null ) params.putAll(extraParams);
boolean withContent = true;
addCategoryParams(categories, params, withContent);
if ( searchHandle != null && view != null ) params.add("view", view.toString().toLowerCase());
if ( start > 1 ) params.add("start", Long.toString(start));
if ( pageLength >= 0 ) params.add("pageLength", Long.toString(pageLength));
if (serverTimestamp != -1) params.add("timestamp", Long.toString(serverTimestamp));
addPointInTimeQueryParam(params, searchHandle);
if ( format != null ) params.add("format", format.toString().toLowerCase());
HandleImplementation handleBase = HandleAccessor.as(searchHandle);
if ( format == null && searchHandle != null ) {
if ( Format.XML == handleBase.getFormat() ) {
params.add("format", "xml");
} else if ( Format.JSON == handleBase.getFormat() ) {
params.add("format", "json");
}
}
OkHttpSearchRequest request =
generateSearchRequest(reqlog, querydef, MIMETYPE_MULTIPART_MIXED, transaction, responseTransform, params, null);
Response response = request.getResponse();
if ( response == null ) return null;
MimeMultipart entity = null;
if ( searchHandle != null ) {
updateServerTimestamp(handleBase, response.headers());
ResponseBody body = response.body();
if ( body.contentLength() != 0 ) {
entity = getEntity(body, MimeMultipart.class);
if ( entity != null ) {
List<BodyPart> partList = getPartList(entity);
if ( entity.getCount() > 0 ) {
BodyPart searchResponsePart = entity.getBodyPart(0);
handleBase.receiveContent(getEntity(searchResponsePart, handleBase.receiveAs()));
partList = partList.subList(1, partList.size());
}
Closeable closeable = response;
return makeResults(OkHttpServiceResultIterator.class, reqlog, "read", "resource", partList, response,
closeable);
}
}
}
return makeResults(OkHttpServiceResultIterator.class, reqlog, "read", "resource", response);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private boolean getDocumentImpl(RequestLogger reqlog,
DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, RequestParameters extraParams,
String metadataFormat, DocumentMetadataReadHandle metadataHandle,
AbstractReadHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document read for document identifier without uri");
}
assert metadataHandle != null : "metadataHandle is null";
assert contentHandle != null : "contentHandle is null";
logger.debug("Getting multipart for {} in transaction {}", uri, getTransactionId(transaction));
addPointInTimeQueryParam(extraParams, contentHandle);
RequestParameters docParams = makeDocumentParams(uri, categories, transaction, extraParams, true);
docParams.add("format", metadataFormat);
Request.Builder requestBldr = makeDocumentResource(docParams);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
requestBldr = addVersionHeader(desc, requestBldr, "If-None-Match");
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.addHeader(HEADER_ACCEPT, multipartMixedWithBoundary()).get());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not read non-existent document",
extractErrorFields(response));
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to read documents",
extractErrorFields(response));
}
if (status == STATUS_NOT_MODIFIED) {
response.close();
return false;
}
if (status != STATUS_OK) {
throw new FailedRequestException("read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(
reqlog,
"read %s document from %s transaction with %s metadata categories and content",
uri, (transaction != null) ? transaction.getTransactionId() : "no", stringJoin(categories, ", ", "no"));
try {
ResponseBody body = response.body();
MimeMultipart entity = body.contentLength() != 0 ?
getEntity(body, MimeMultipart.class) : null;
if (entity == null) return false;
int partCount = entity.getCount();
if (partCount == 0) return false;
List<BodyPart> partList = getPartList(entity);
if (partCount != 2) {
throw new FailedRequestException("read expected 2 parts but got " + partCount + " parts",
extractErrorFields(response));
}
HandleImplementation metadataBase = HandleAccessor.as(metadataHandle);
HandleImplementation contentBase = HandleAccessor.as(contentHandle);
BodyPart contentPart = partList.get(1);
Headers responseHeaders = response.headers();
if (isExternalDescriptor(desc)) {
updateVersion(desc, responseHeaders);
updateFormat(desc, responseHeaders);
updateMimetype(desc, getHeaderMimetype(getHeader(contentPart, HEADER_CONTENT_TYPE)));
updateLength(desc, getHeaderLength(getHeader(contentPart, HEADER_CONTENT_LENGTH)));
copyDescriptor(desc, contentBase);
} else {
updateDescriptor(contentBase, responseHeaders);
}
metadataBase.receiveContent(getEntity(partList.get(0),
metadataBase.receiveAs()));
Object contentEntity = getEntity(contentPart, contentBase.receiveAs());
contentBase.receiveContent((reqlog != null) ? reqlog.copyContent(contentEntity) : contentEntity);
response.close();
return true;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public DocumentDescriptor head(RequestLogger reqlog, String uri,
Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
Response response = headImpl(reqlog, uri, transaction, makeDocumentResource(makeDocumentParams(uri,
null, transaction, null)));
// 404
if (response == null) return null;
Headers responseHeaders = response.headers();
response.close();
logRequest(reqlog, "checked %s document from %s transaction", uri,
(transaction != null) ? transaction.getTransactionId() : "no");
DocumentDescriptorImpl desc = new DocumentDescriptorImpl(uri, false);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
return desc;
}
@Override
public boolean exists(String uri) throws ForbiddenUserException, FailedRequestException {
return headImpl(null, uri, null, setupRequest(uri, null)) == null ? false : true;
}
private Response headImpl(RequestLogger reqlog, String uri,
Transaction transaction, Request.Builder requestBldr) {
if (uri == null) {
throw new IllegalArgumentException(
"Existence check for document identifier without uri");
}
logger.debug("Requesting head for {} in transaction {}", uri, getTransactionId(transaction));
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doHeadFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.head().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doHeadFunction, null);
int status = response.code();
if (status != STATUS_OK) {
if (status == STATUS_NOT_FOUND) {
response.close();
return null;
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to check the existence of documents",
extractErrorFields(response));
} else {
throw new FailedRequestException(
"Document existence check failed: "
+ getReasonPhrase(response),
extractErrorFields(response));
}
}
return response;
}
@Override
public TemporalDescriptor putDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories,
RequestParameters extraParams,
DocumentMetadataWriteHandle metadataHandle,
AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if (desc.getUri() == null) {
throw new IllegalArgumentException(
"Document write for document identifier without uri");
}
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataMimetype = null;
if (metadataBase != null) {
metadataMimetype = metadataBase.getMimetype();
}
Format descFormat = desc.getFormat();
String contentMimetype = (descFormat != null && descFormat != Format.UNKNOWN) ? desc.getMimetype() : null;
if (contentMimetype == null && contentBase != null) {
Format contentFormat = contentBase.getFormat();
if (descFormat != null && descFormat != contentFormat) {
contentMimetype = descFormat.getDefaultMimetype();
} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {
contentMimetype = contentBase.getMimetype();
}
}
if (metadataBase != null && contentBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, categories,
extraParams, metadataMimetype, metadataHandle,
contentMimetype, contentHandle);
} else if (metadataBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, categories, false,
extraParams, metadataMimetype, metadataHandle);
} else if (contentBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, null, true,
extraParams, contentMimetype, contentHandle);
}
throw new IllegalArgumentException("Either metadataHandle or contentHandle must not be null");
}
@Override
public DocumentDescriptorImpl postDocument(RequestLogger reqlog, DocumentUriTemplate template,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams,
DocumentMetadataWriteHandle metadataHandle, AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
DocumentDescriptorImpl desc = new DocumentDescriptorImpl(false);
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataMimetype = null;
if (metadataBase != null) {
metadataMimetype = metadataBase.getMimetype();
}
Format templateFormat = template.getFormat();
String contentMimetype = (templateFormat != null && templateFormat != Format.UNKNOWN) ?
template.getMimetype() : null;
if (contentMimetype == null && contentBase != null) {
Format contentFormat = contentBase.getFormat();
if (templateFormat != null && templateFormat != contentFormat) {
contentMimetype = templateFormat.getDefaultMimetype();
desc.setFormat(templateFormat);
} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {
contentMimetype = contentBase.getMimetype();
desc.setFormat(contentFormat);
}
}
desc.setMimetype(contentMimetype);
if (extraParams == null) extraParams = new RequestParameters();
String extension = template.getExtension();
if (extension != null) extraParams.add("extension", extension);
String directory = template.getDirectory();
if (directory != null) extraParams.add("directory", directory);
if (metadataBase != null && contentBase != null) {
putPostDocumentImpl(reqlog, "post", desc, transaction, categories, extraParams,
metadataMimetype, metadataHandle, contentMimetype, contentHandle);
} else if (contentBase != null) {
putPostDocumentImpl(reqlog, "post", desc, transaction, null, true, extraParams,
contentMimetype, contentHandle);
}
return desc;
}
private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, boolean isOnContent, RequestParameters extraParams,
String mimetype, AbstractWriteHandle handle)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
HandleImplementation handleBase = HandleAccessor.as(handle);
logger.debug("Sending {} document in transaction {}",
(uri != null) ? uri : "new", getTransactionId(transaction));
logRequest(
reqlog,
"writing %s document from %s transaction with %s mime type and %s metadata categories",
(uri != null) ? uri : "new",
(transaction != null) ? transaction.getTransactionId() : "no",
(mimetype != null) ? mimetype : "no",
stringJoin(categories, ", ", "no"));
Request.Builder requestBldr = makeDocumentResource(
makeDocumentParams(
uri, categories, transaction, extraParams, isOnContent
));
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE,
(mimetype != null) ? mimetype : MIMETYPE_WILDCARD);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (uri != null) {
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
}
if ("patch".equals(method)) {
requestBldr = requestBldr.header("X-HTTP-Method-Override", "PATCH");
method = "post";
}
boolean isResendable = handleBase.isResendable();
Response response = null;
int status = -1;
Headers responseHeaders = null;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
Object value = handleBase.sendContent();
if (value == null) {
throw new IllegalArgumentException(
"Document write with null value for " + ((uri != null) ? uri : "new document"));
}
if (isFirstRequest() && !isResendable && isStreaming(value)) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if (value instanceof OutputStreamSender) {
StreamingOutputImpl sentStream =
new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType);
requestBldr =
("put".equals(method)) ?
requestBldr.put(sentStream) :
requestBldr.post(sentStream);
} else {
Object sentObj = (reqlog != null) ?
reqlog.copyContent(value) : value;
requestBldr =
("put".equals(method)) ?
requestBldr.put(new ObjectRequestBody(sentObj, mediaType)) :
requestBldr.post(new ObjectRequestBody(sentObj, mediaType));
}
response = sendRequestOnce(requestBldr);
status = response.code();
responseHeaders = response.headers();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " +
((uri != null) ? uri : "new document"));
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not write non-existent document",
extractErrorFields(response));
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to write document", failure);
}
throw new FailedRequestException(
"Precondition required to write document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to write documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to write document", failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status == -1) {
throw new FailedRequestException("write failed: Unknown Reason", extractErrorFields(response));
}
if (status != STATUS_CREATED && status != STATUS_NO_CONTENT) {
throw new FailedRequestException("write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
if (uri == null) {
String location = response.header("Location");
if (location != null) {
int offset = location.indexOf(DOCUMENT_URI_PREFIX);
if (offset == -1) {
throw new MarkLogicInternalException(
"document create produced invalid location: " + location);
}
uri = location.substring(offset + DOCUMENT_URI_PREFIX.length());
if (uri == null) {
throw new MarkLogicInternalException(
"document create produced location without uri: " + location);
}
desc.setUri(uri);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
}
}
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
return temporalDesc;
}
private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams,
String metadataMimetype, DocumentMetadataWriteHandle metadataHandle, String contentMimetype,
AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ResourceNotResendableException,ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
logger.debug("Sending {} multipart document in transaction {}",
(uri != null) ? uri : "new", getTransactionId(transaction));
logRequest(
reqlog,
"writing %s document from %s transaction with %s metadata categories and content",
(uri != null) ? uri : "new",
(transaction != null) ? transaction.getTransactionId() : "no",
stringJoin(categories, ", ", "no"));
RequestParameters docParams =
makeDocumentParams(uri, categories, transaction, extraParams, true);
Request.Builder requestBldr = makeDocumentResource(docParams)
.addHeader(HEADER_ACCEPT, MIMETYPE_MULTIPART_MIXED);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (uri != null) {
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
}
Response response = null;
int status = -1;
Headers responseHeaders = null;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog,
new String[] { metadataMimetype, contentMimetype },
new AbstractWriteHandle[] { metadataHandle, contentHandle });
if (isFirstRequest() && hasStreamingPart) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
requestBldr = ("put".equals(method)) ? requestBldr.put(multiPart.build()) : requestBldr.post(multiPart.build());
response = sendRequestOnce(requestBldr);
status = response.code();
responseHeaders = response.headers();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " +
((uri != null) ? uri : "new document"));
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
response.close();
throw new ResourceNotFoundException(
"Could not write non-existent document");
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to write document", failure);
}
throw new FailedRequestException(
"Precondition required to write document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to write documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to write document", failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status != STATUS_CREATED && status != STATUS_NO_CONTENT) {
throw new FailedRequestException("write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
if (uri == null) {
String location = response.header("Location");
if (location != null) {
int offset = location.indexOf(DOCUMENT_URI_PREFIX);
if (offset == -1) {
throw new MarkLogicInternalException(
"document create produced invalid location: " + location);
}
uri = location.substring(offset + DOCUMENT_URI_PREFIX.length());
if (uri == null) {
throw new MarkLogicInternalException(
"document create produced location without uri: " + location);
}
desc.setUri(uri);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
}
}
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
return temporalDesc;
}
@Override
public void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, boolean isOnContent, DocumentPatchHandle patchHandle)
throws ResourceNotFoundException, ResourceNotResendableException,ForbiddenUserException, FailedRequestException
{
patchDocument(reqlog, desc, transaction, categories, isOnContent, null, null, patchHandle);
}
@Override
public void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, boolean isOnContent, RequestParameters extraParams, String sourceDocumentURI,
DocumentPatchHandle patchHandle)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
HandleImplementation patchBase = HandleAccessor.checkHandle(patchHandle, "patch");
if(sourceDocumentURI != null)
extraParams.add("source-document", sourceDocumentURI);
putPostDocumentImpl(reqlog, "patch", desc, transaction, categories, isOnContent, extraParams, patchBase.getMimetype(),
patchHandle);
}
@Override
public Transaction openTransaction(String name, int timeLimit) throws ForbiddenUserException, FailedRequestException {
logger.debug("Opening transaction");
RequestParameters transParams = new RequestParameters();
if ( name != null || timeLimit > 0 ) {
if ( name != null ) transParams.add("name", name);
if ( timeLimit > 0 ) transParams.add("timeLimit", String.valueOf(timeLimit));
}
Request.Builder requestBldr = setupRequest("transactions", transParams);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.post(RequestBody.create(null, "")));
}
};
Response response = sendRequestWithRetry(requestBldr, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to open transactions", extractErrorFields(response));
}
if (status != STATUS_SEE_OTHER) {
throw new FailedRequestException("transaction open failed: " +
getReasonPhrase(response), extractErrorFields(response));
}
String location = response.headers().get("Location");
String hostId = null;
List<ClientCookie> cookies = new ArrayList<>();
for ( String setCookie : response.headers(HEADER_SET_COOKIE) ) {
ClientCookie cookie = ClientCookie.parse(requestBldr.build().url(), setCookie);
cookies.add(cookie);
if ( "HostId".equalsIgnoreCase(cookie.getName()) ) {
hostId = cookie.getValue();
}
}
response.close();
if (location == null) throw new MarkLogicInternalException("transaction open failed to provide location");
if (!location.contains("/")) {
throw new MarkLogicInternalException("transaction open produced invalid location: " + location);
}
String transactionId = location.substring(location.lastIndexOf("/") + 1);
return new TransactionImpl(this, transactionId, cookies);
}
@Override
public void commitTransaction(Transaction transaction) throws ForbiddenUserException, FailedRequestException {
completeTransaction(transaction, "commit");
}
@Override
public void rollbackTransaction(Transaction transaction) throws ForbiddenUserException, FailedRequestException {
completeTransaction(transaction, "rollback");
}
private void completeTransaction(Transaction transaction, String result)
throws ForbiddenUserException, FailedRequestException
{
if (result == null) {
throw new MarkLogicInternalException(
"transaction completion without operation");
}
if (transaction == null) {
throw new MarkLogicInternalException(
"transaction completion without id: " + result);
}
logger.debug("Completing transaction {} with {}", transaction.getTransactionId(), result);
RequestParameters transParams = new RequestParameters();
transParams.add("result", result);
Request.Builder requestBldr = setupRequest("transactions/" + transaction.getTransactionId(), transParams);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.post(RequestBody.create(null, "")).build());
}
};
Response response = sendRequestWithRetry(requestBldr, false, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to complete transaction with "
+ result, extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("transaction " + result
+ " failed: " + getReasonPhrase(response),
extractErrorFields(response));
}
response.close();
}
private void addCategoryParams(Set<Metadata> categories, RequestParameters params,
boolean withContent)
{
if (withContent && categories == null || categories.size() == 0) {
params.add("category", "content");
} else {
if (withContent) params.add("category", "content");
if (categories.contains(Metadata.ALL)) {
params.add("category", "metadata");
} else {
for (Metadata category : categories) {
params.add("category", category.name().toLowerCase());
}
}
}
}
private RequestParameters makeDocumentParams(String uri,
Set<Metadata> categories, Transaction transaction,
RequestParameters extraParams) {
return makeDocumentParams(uri, categories, transaction, extraParams,
false);
}
private RequestParameters makeDocumentParams(String uri, Set<Metadata> categories, Transaction transaction,
RequestParameters extraParams, boolean withContent)
{
RequestParameters docParams = new RequestParameters();
if (extraParams != null && extraParams.size() > 0) {
for ( Map.Entry<String, List<String>> entry : extraParams.entrySet() ) {
for ( String value : entry.getValue() ) {
String extraKey = entry.getKey();
if ( !"range".equalsIgnoreCase(extraKey) ) {
docParams.add(extraKey, value);
}
}
}
}
if ( uri != null ) docParams.add("uri", uri);
if (categories == null || categories.size() == 0) {
docParams.add("category", "content");
} else {
if (withContent) {
docParams.add("category", "content");
}
if (categories.contains(Metadata.ALL)) {
docParams.add("category", "metadata");
} else {
for (Metadata category : categories) {
docParams.add("category", category.toString().toLowerCase());
}
}
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
return docParams;
}
private Request.Builder makeDocumentResource(RequestParameters queryParams) {
return setupRequest("documents", queryParams);
}
private boolean isExternalDescriptor(ContentDescriptor desc) {
return desc != null && desc instanceof DocumentDescriptorImpl
&& !((DocumentDescriptorImpl) desc).isInternal();
}
private void updateDescriptor(ContentDescriptor desc,
Headers headers) {
if (desc == null || headers == null) return;
updateFormat(desc, headers);
updateMimetype(desc, headers);
updateLength(desc, headers);
updateServerTimestamp(desc, headers);
}
private TemporalDescriptor updateTemporalSystemTime(DocumentDescriptor desc,
Headers headers)
{
if (headers == null) return null;
DocumentDescriptorImpl temporalDescriptor;
if ( desc instanceof DocumentDescriptorImpl ) {
temporalDescriptor = (DocumentDescriptorImpl) desc;
} else {
temporalDescriptor = new DocumentDescriptorImpl(desc.getUri(), false);
}
temporalDescriptor.setTemporalSystemTime(headers.get(HEADER_X_MARKLOGIC_SYSTEM_TIME));
return temporalDescriptor;
}
private void copyDescriptor(DocumentDescriptor desc,
HandleImplementation handleBase) {
if (handleBase == null) return;
if (desc.getFormat() != null) handleBase.setFormat(desc.getFormat());
if (desc.getMimetype() != null) handleBase.setMimetype(desc.getMimetype());
handleBase.setByteLength(desc.getByteLength());
}
private void updateFormat(ContentDescriptor descriptor,
Headers headers) {
updateFormat(descriptor, getHeaderFormat(headers));
}
private void updateFormat(ContentDescriptor descriptor, Format format) {
if (format != null) {
descriptor.setFormat(format);
}
}
private Format getHeaderFormat(Headers headers) {
String format = headers.get(HEADER_VND_MARKLOGIC_DOCUMENT_FORMAT);
if (format != null) {
return Format.valueOf(format.toUpperCase());
}
return null;
}
private Format getHeaderFormat(BodyPart part) {
String contentDisposition = getHeader(part, HEADER_CONTENT_DISPOSITION);
String formatRegex = ".* format=(text|binary|xml|json).*";
String format = getHeader(part, HEADER_VND_MARKLOGIC_DOCUMENT_FORMAT);
String contentType = getHeader(part, HEADER_CONTENT_TYPE);
if ( format != null && format.length() > 0 ) {
return Format.valueOf(format.toUpperCase());
} else if ( contentDisposition != null && contentDisposition.matches(formatRegex) ) {
format = contentDisposition.replaceFirst("^.*" + formatRegex + ".*$", "$1");
return Format.valueOf(format.toUpperCase());
} else if ( contentType != null && contentType.length() > 0 ) {
return Format.getFromMimetype(contentType);
}
return null;
}
private void updateMimetype(ContentDescriptor descriptor,
Headers headers) {
updateMimetype(descriptor, getHeaderMimetype(headers.get(HEADER_CONTENT_TYPE)));
}
private void updateMimetype(ContentDescriptor descriptor, String mimetype) {
if (mimetype != null) {
descriptor.setMimetype(mimetype);
}
}
private String getHeader(Map<String, List<String>> headers, String name) {
List<String> values = headers.get(name);
if ( values != null && values.size() > 0 ) {
return values.get(0);
}
return null;
}
private static String getHeader(BodyPart part, String name) {
if ( part == null ) throw new MarkLogicInternalException("part must not be null");
try {
String[] values = part.getHeader(name);
if ( values != null && values.length > 0 ) {
return values[0];
}
return null;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private String getHeaderMimetype(String contentType) {
if (contentType != null) {
String mimetype = contentType.contains(";")
? contentType.substring(0, contentType.indexOf(";"))
: contentType;
// TODO: if "; charset=foo" set character set
if (mimetype != null && mimetype.length() > 0) {
return mimetype;
}
}
return null;
}
private void updateLength(ContentDescriptor descriptor,
Headers headers) {
updateLength(descriptor, getHeaderLength(headers.get(HEADER_CONTENT_LENGTH)));
}
private void updateLength(ContentDescriptor descriptor, long length) {
descriptor.setByteLength(length);
}
private void updateServerTimestamp(ContentDescriptor descriptor,
Headers headers) {
updateServerTimestamp(descriptor, getHeaderServerTimestamp(headers));
}
private long getHeaderServerTimestamp(Headers headers) {
String timestamp = headers.get(HEADER_ML_EFFECTIVE_TIMESTAMP);
if (timestamp != null && timestamp.length() > 0) {
return Long.parseLong(timestamp);
}
return -1;
}
private void updateServerTimestamp(ContentDescriptor descriptor, long timestamp) {
if ( descriptor instanceof HandleImplementation ) {
if ( descriptor != null && timestamp != -1 ) {
((HandleImplementation) descriptor).setResponseServerTimestamp(timestamp);
}
}
}
private long getHeaderLength(String length) {
if (length != null) {
return Long.parseLong(length);
}
return ContentDescriptor.UNKNOWN_LENGTH;
}
private String getHeaderUri(BodyPart part) {
try {
if ( part != null ) {
return part.getFileName();
}
// if it's not found, just return null
return null;
} catch(MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private void updateVersion(DocumentDescriptor descriptor, Headers headers) {
long version = DocumentDescriptor.UNKNOWN_VERSION;
String value = headers.get(HEADER_ETAG);
if (value != null && value.length() > 0) {
// trim the double quotes
version = Long.parseLong(value.substring(1, value.length() - 1));
}
descriptor.setVersion(version);
}
private Request.Builder addVersionHeader(DocumentDescriptor desc, Request.Builder requestBldr, String name) {
if ( desc != null &&
desc instanceof DocumentDescriptorImpl &&
!((DocumentDescriptorImpl) desc).isInternal())
{
long version = desc.getVersion();
if (version != DocumentDescriptor.UNKNOWN_VERSION) {
return requestBldr.header(name, "\"" + String.valueOf(version) + "\"");
}
}
return requestBldr;
}
@Override
public <T extends SearchReadHandle> T search(RequestLogger reqlog, T searchHandle,
QueryDefinition queryDef, long start, long len, QueryView view,
Transaction transaction, String forestName)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if (start > 1) {
params.add("start", Long.toString(start));
}
if (len > 0) {
params.add("pageLength", Long.toString(len));
}
if (view != null && view != QueryView.DEFAULT) {
if (view == QueryView.ALL) {
params.add("view", "all");
} else if (view == QueryView.RESULTS) {
params.add("view", "results");
} else if (view == QueryView.FACETS) {
params.add("view", "facets");
} else if (view == QueryView.METADATA) {
params.add("view", "metadata");
}
}
addPointInTimeQueryParam(params, searchHandle);
@SuppressWarnings("rawtypes")
HandleImplementation searchBase = HandleAccessor.checkHandle(searchHandle, "search");
Format searchFormat = searchBase.getFormat();
switch(searchFormat) {
case UNKNOWN:
searchFormat = Format.XML;
break;
case JSON:
case XML:
break;
default:
throw new UnsupportedOperationException("Only XML and JSON search results are possible.");
}
String mimetype = searchFormat.getDefaultMimetype();
OkHttpSearchRequest request = generateSearchRequest(reqlog, queryDef, mimetype, transaction, null, params, forestName);
Response response = request.getResponse();
if ( response == null ) return null;
Class<?> as = searchBase.receiveAs();
ResponseBody body = response.body();
Object entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
searchBase.receiveContent(entity);
updateDescriptor(searchBase, response.headers());
logRequest( reqlog,
"searched starting at %s with length %s in %s transaction with %s mime type",
start, len, getTransactionId(transaction), mimetype);
return searchHandle;
}
private OkHttpSearchRequest generateSearchRequest(RequestLogger reqlog, QueryDefinition queryDef,
String mimetype, Transaction transaction, ServerTransform responseTransform,
RequestParameters params, String forestName)
{
if ( params == null ) params = new RequestParameters();
if ( forestName != null ) params.add("forest-name", forestName);
return new OkHttpSearchRequest(reqlog, queryDef, mimetype, transaction, responseTransform, params);
}
private class OkHttpSearchRequest {
RequestLogger reqlog;
QueryDefinition queryDef;
String mimetype;
RequestParameters params;
ServerTransform responseTransform;
Transaction transaction;
Request.Builder requestBldr = null;
String structure = null;
HandleImplementation baseHandle = null;
OkHttpSearchRequest(RequestLogger reqlog, QueryDefinition queryDef, String mimetype,
Transaction transaction, ServerTransform responseTransform, RequestParameters params) {
this.reqlog = reqlog;
this.queryDef = queryDef;
this.mimetype = mimetype;
this.transaction = transaction;
this.responseTransform = responseTransform;
this.params = params != null ? params : new RequestParameters();
addParams();
init();
}
void addParams() {
String directory = queryDef.getDirectory();
if (directory != null) {
params.add("directory", directory);
}
params.add("collection", queryDef.getCollections());
String optionsName = queryDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
params.add("options", optionsName);
}
ServerTransform transform = queryDef.getResponseTransform();
if (transform != null) {
if (responseTransform != null) {
if ( ! transform.getName().equals(responseTransform.getName()) ) {
throw new IllegalStateException("QueryDefinition transform and DocumentManager transform have different names (" +
transform.getName() + ", " + responseTransform.getName() + ")");
}
logger.warn("QueryDefinition and DocumentManager both specify a ServerTransform--using params from QueryDefinition");
}
transform.merge(params);
} else if (responseTransform != null) {
responseTransform.merge(params);
}
if (transaction != null) {
params.add("txid", transaction.getTransactionId());
}
}
void init() {
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
params.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition) {
structure = ((StructuredQueryDefinition) queryDef).serialize();
if (logger.isDebugEnabled()) {
String qtextMessage = text == null ? "" : " and string query \"" + text + "\"";
logger.debug("Searching for structure {}{}", structure, qtextMessage);
}
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof RawQueryDefinition || queryDef instanceof RawCtsQueryDefinition) {
logger.debug("Raw search");
if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "search");
} else if (queryDef instanceof RawCtsQueryDefinition) {
CtsQueryWriteHandle handle = ((RawCtsQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "search");
}
Format payloadFormat = getStructuredQueryFormat(baseHandle);
String payloadMimetype = getMimetypeWithDefaultXML(payloadFormat, baseHandle);
String path = (queryDef instanceof RawQueryByExampleDefinition) ?
"qbe" : "search";
requestBldr = setupRequest(path, params);
if ( payloadMimetype != null ) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, payloadMimetype);
}
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof CombinedQueryDefinition) {
structure = ((CombinedQueryDefinition) queryDef).serialize();
logger.debug("Searching for combined query {}", structure);
requestBldr = setupRequest("search", params);
requestBldr = requestBldr
.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML)
.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof StringQueryDefinition) {
logger.debug("Searching for string [{}]", text);
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof DeleteQueryDefinition) {
logger.debug("Searching for deletes");
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else {
throw new UnsupportedOperationException("Cannot search with "
+ queryDef.getClass().getName());
}
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
}
Response getResponse() {
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
if (queryDef instanceof StructuredQueryDefinition && ! (queryDef instanceof RawQueryDefinition)) {
response = doPost(reqlog, requestBldr, structure);
} else if (queryDef instanceof CombinedQueryDefinition) {
response = doPost(reqlog, requestBldr, structure);
} else if (queryDef instanceof DeleteQueryDefinition) {
response = doGet(requestBldr);
} else if (queryDef instanceof RawQueryDefinition) {
response = doPost(reqlog, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof RawCtsQueryDefinition) {
response = doPost(reqlog, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof StringQueryDefinition) {
response = doGet(requestBldr);
} else {
throw new UnsupportedOperationException("Cannot search with "
+ queryDef.getClass().getName());
}
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
response.close();
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
response.close();
return null;
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
return response;
}
}
private Format getStructuredQueryFormat(HandleImplementation baseHandle) {
Format payloadFormat = baseHandle.getFormat();
if (payloadFormat == Format.UNKNOWN) {
payloadFormat = null;
} else if (payloadFormat != Format.XML && payloadFormat != Format.JSON) {
throw new IllegalArgumentException(
"Cannot perform raw search for format "+payloadFormat.name());
}
return payloadFormat;
}
private String getMimetypeWithDefaultXML(Format payloadFormat, HandleImplementation baseHandle) {
String payloadMimetype = baseHandle.getMimetype();
if (payloadFormat != null) {
if (payloadMimetype == null) {
payloadMimetype = payloadFormat.getDefaultMimetype();
}
} else if (payloadMimetype == null) {
payloadMimetype = MIMETYPE_APPLICATION_XML;
}
return payloadMimetype;
}
@Override
public void deleteSearch(RequestLogger reqlog, DeleteQueryDefinition queryDef,
Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if (queryDef.getDirectory() != null) {
params.add("directory", queryDef.getDirectory());
}
params.add("collection", queryDef.getCollections());
if (transaction != null) {
params.add("txid", transaction.getTransactionId());
}
Request.Builder requestBldr = setupRequest("search", params);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete",
extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(
reqlog,
"deleted search results in %s transaction",
getTransactionId(transaction));
}
@Override
public void delete(RequestLogger logger, Transaction transaction, String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
for ( String uri : uris ) {
params.add("uri", uri);
}
deleteResource(logger, "documents", transaction, params, null);
}
@Override
public <T> T values(Class<T> as, ValuesDefinition valDef, String mimetype,
long start, long pageLength, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
String optionsName = valDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
docParams.add("options", optionsName);
}
if (valDef.getAggregate() != null) {
docParams.add("aggregate", valDef.getAggregate());
}
if (valDef.getAggregatePath() != null) {
docParams.add("aggregatePath",
valDef.getAggregatePath());
}
if (valDef.getView() != null) {
docParams.add("view", valDef.getView());
}
if (valDef.getDirection() != null) {
if (valDef.getDirection() == ValuesDefinition.Direction.ASCENDING) {
docParams.add("direction", "ascending");
} else {
docParams.add("direction", "descending");
}
}
if (valDef.getFrequency() != null) {
if (valDef.getFrequency() == ValuesDefinition.Frequency.FRAGMENT) {
docParams.add("frequency", "fragment");
} else {
docParams.add("frequency", "item");
}
}
if (start > 0) {
docParams.add("start", Long.toString(start));
if (pageLength > 0) {
docParams.add("pageLength", Long.toString(pageLength));
}
}
HandleImplementation baseHandle = null;
if (valDef.getQueryDefinition() != null) {
ValueQueryDefinition queryDef = valDef.getQueryDefinition();
if (optionsName == null) {
optionsName = queryDef.getOptionsName();
if (optionsName != null) {
docParams.add("options", optionsName);
}
} else if (queryDef.getOptionsName() != null) {
if (!queryDef.getOptionsName().equals(optionsName)) {
logger.warn("values definition options take precedence over query definition options");
}
}
if (queryDef.getCollections().length > 0) {
logger.warn("collections scope ignored for values query");
}
if (queryDef.getDirectory() != null) {
logger.warn("directory scope ignored for values query");
}
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
docParams.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition ) {
String structure = ((StructuredQueryDefinition) queryDef)
.serialize();
if (structure != null) {
docParams.add("structuredQuery", structure);
}
} else if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "values");
} else if (queryDef instanceof RawCtsQueryDefinition) {
CtsQueryWriteHandle handle = ((RawCtsQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "values");
} else if (queryDef instanceof StringQueryDefinition) {
} else {
logger.warn("unsupported query definition: {}", queryDef.getClass().getName());
}
ServerTransform transform = queryDef.getResponseTransform();
if (transform != null) {
transform.merge(docParams);
}
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "values";
if (valDef.getName() != null) {
uri += "/" + valDef.getName();
}
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
final HandleImplementation tempBaseHandle = baseHandle;
Function<Request.Builder, Response> doFunction = (baseHandle == null) ?
new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
} :
new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(null, funcBuilder.header(HEADER_CONTENT_TYPE, tempBaseHandle.getMimetype()),
tempBaseHandle.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public <T> T valuesList(Class<T> as, ValuesListDefinition valDef,
String mimetype, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
String optionsName = valDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
docParams.add("options", optionsName);
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "values";
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public <T> T optionsList(Class<T> as, String mimetype, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "config/query";
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
// namespaces, search options etc.
@Override
public <T> T getValue(RequestLogger reqlog, String type, String key,
boolean isNullable, String mimetype, Class<T> as)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getValue(reqlog, type, key, null, isNullable, mimetype, as);
}
@Override
public <T> T getValue(RequestLogger reqlog, String type, String key, Transaction transaction,
boolean isNullable, String mimetype, Class<T> as)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
logger.debug("Getting {}/{}", type, key);
Request.Builder requestBldr = setupRequest(type + "/" + key, null, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status != STATUS_OK) {
if (status == STATUS_NOT_FOUND) {
response.close();
if (!isNullable) {
throw new ResourceNotFoundException("Could not get " + type + "/" + key);
}
return null;
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to read "
+ type, extractErrorFields(response));
} else {
throw new FailedRequestException(type + " read failed: "
+ getReasonPhrase(response),
extractErrorFields(response));
}
}
logRequest(reqlog, "read %s value with %s key and %s mime type", type,
key, (mimetype != null) ? mimetype : null);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
@Override
public <T> T getValues(RequestLogger reqlog, String type, String mimetype, Class<T> as)
throws ForbiddenUserException, FailedRequestException
{
return getValues(reqlog, type, null, mimetype, as);
}
@Override
public <T> T getValues(RequestLogger reqlog, String type, RequestParameters extraParams,
String mimetype, Class<T> as)
throws ForbiddenUserException, FailedRequestException
{
logger.debug("Getting {}", type);
Request.Builder requestBldr = setupRequest(type, extraParams).header(HEADER_ACCEPT, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to read "
+ type, extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException(type + " read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(reqlog, "read %s values with %s mime type", type,
(mimetype != null) ? mimetype : null);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
@Override
public void postValue(RequestLogger reqlog, String type, String key,
String mimetype, Object value)
throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Posting {}/{}", type, key);
putPostValueImpl(reqlog, "post", type, key, null, mimetype, value, STATUS_CREATED);
}
@Override
public void postValue(RequestLogger reqlog, String type, String key,
RequestParameters extraParams)
throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Posting {}/{}", type, key);
putPostValueImpl(reqlog, "post", type, key, extraParams, null, null, STATUS_NO_CONTENT);
}
@Override
public void putValue(RequestLogger reqlog, String type, String key,
String mimetype, Object value)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Putting {}/{}", type, key);
putPostValueImpl(reqlog, "put", type, key, null, mimetype, value, STATUS_NO_CONTENT, STATUS_CREATED);
}
@Override
public void putValue(RequestLogger reqlog, String type, String key,
RequestParameters extraParams, String mimetype, Object value)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Putting {}/{}", type, key);
putPostValueImpl(reqlog, "put", type, key, extraParams, mimetype, value, STATUS_NO_CONTENT);
}
private void putPostValueImpl(RequestLogger reqlog, String method,
String type, String key, RequestParameters extraParams,
String mimetype, Object value,
int... expectedStatuses) {
if (key != null) {
logRequest(reqlog, "writing %s value with %s key and %s mime type",
type, key, (mimetype != null) ? mimetype : null);
} else {
logRequest(reqlog, "writing %s values with %s mime type", type,
(mimetype != null) ? mimetype : null);
}
HandleImplementation handle = (value instanceof HandleImplementation) ?
(HandleImplementation) value : null;
MediaType mediaType = makeType(mimetype);
String connectPath = null;
Request.Builder requestBldr = null;
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
Object nextValue = (handle != null) ? handle.sendContent() : value;
RequestBody sentValue = null;
if (nextValue instanceof OutputStreamSender) {
sentValue = new StreamingOutputImpl(
(OutputStreamSender) nextValue, reqlog, mediaType);
} else {
if (reqlog != null && retry == 0) {
sentValue = new ObjectRequestBody(reqlog.copyContent(nextValue), mediaType);
} else {
sentValue = new ObjectRequestBody(nextValue, mediaType);
}
}
boolean isStreaming = (isFirstRequest() || handle == null) ? isStreaming(sentValue) : false;
boolean isResendable = (handle == null) ? !isStreaming : handle.isResendable();
if (isFirstRequest() && !isResendable && isStreaming) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
if ("put".equals(method)) {
if (requestBldr == null) {
connectPath = (key != null) ? type + "/" + key : type;
Request.Builder resource = setupRequest(connectPath, extraParams);
requestBldr = (mimetype == null) ?
resource : resource.header(HEADER_CONTENT_TYPE, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
}
response = (sentValue == null) ?
sendRequestOnce(requestBldr.put(null).build()) :
sendRequestOnce(requestBldr.put(sentValue).build());
} else if ("post".equals(method)) {
if (requestBldr == null) {
connectPath = type;
Request.Builder resource = setupRequest(connectPath, extraParams);
requestBldr = (mimetype == null) ?
resource : resource.header(HEADER_CONTENT_TYPE, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
}
response = (sentValue == null) ?
sendRequestOnce(requestBldr.post(RequestBody.create(null, "")).build()) :
sendRequestOnce(requestBldr.post(sentValue).build());
} else {
throw new MarkLogicInternalException("unknown method type "
+ method);
}
status = response.code();
if (!retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + connectPath);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to write "
+ type, extractErrorFields(response));
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(type + " not found for write",
extractErrorFields(response));
}
boolean statusOk = false;
for (int expectedStatus : expectedStatuses) {
statusOk = statusOk || (status == expectedStatus);
if (statusOk) {
break;
}
}
if (!statusOk) {
throw new FailedRequestException(type + " write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
}
@Override
public void deleteValue(RequestLogger reqlog, String type, String key)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
logger.debug("Deleting {}/{}", type, key);
Request.Builder requestBldr = setupRequest(type + "/" + key, null);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete "
+ type, extractErrorFields(response));
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(type + " not found for delete",
extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(reqlog, "deleted %s value with %s key", type, key);
}
@Override
public void deleteValues(RequestLogger reqlog, String type)
throws ForbiddenUserException, FailedRequestException
{
logger.debug("Deleting {}", type);
Request.Builder requestBldr = setupRequest(type, null);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete "
+ type, extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(reqlog, "deleted %s values", type);
}
@Override
public <R extends UrisReadHandle> R uris(RequestLogger reqlog, Transaction transaction,
QueryDefinition qdef, long start, long pageLength, String forestName, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if ( forestName != null ) params.add("forest-name", forestName);
if (start > 1) params.add("start", Long.toString(start));
if (pageLength >= 1) params.add("pageLength", Long.toString(pageLength));
if (qdef.getDirectory() != null) params.add("directory", qdef.getDirectory());
if (qdef.getCollections() != null ) {
for ( String collection : qdef.getCollections() ) {
params.add("collection", collection);
}
}
if (qdef.getOptionsName()!= null && qdef.getOptionsName().length() > 0) {
params.add("options", qdef.getOptionsName());
}
if (qdef instanceof RawQueryByExampleDefinition) {
throw new UnsupportedOperationException("Cannot search with RawQueryByExampleDefinition");
} else if (qdef instanceof RawQueryDefinition) {
logger.debug("Raw uris query");
StructureWriteHandle input = ((RawQueryDefinition) qdef).getHandle();
return postResource(reqlog, "internal/uris", transaction, params, input, output);
} else {
String text = null;
if (qdef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) qdef).getCriteria();
}
String qtextMessage = "";
if (text != null) {
params.add("q", text);
qtextMessage = " and string query \"" + text + "\"";
}
if (qdef instanceof RawCtsQueryDefinition) {
String structure = qdef instanceof RawQueryDefinitionImpl.CtsQuery ? ((RawQueryDefinitionImpl.CtsQuery) qdef).serialize() : "";
logger.debug("Query uris with raw cts query {}{}", structure, qtextMessage);
CtsQueryWriteHandle input = ((RawCtsQueryDefinition) qdef).getHandle();
return postResource(reqlog, "internal/uris", transaction, params, input, output);
} else if (qdef instanceof StructuredQueryDefinition) {
String structure = ((StructuredQueryDefinition) qdef).serialize();
logger.debug("Query uris with structured query {}{}", structure, qtextMessage);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof RawStructuredQueryDefinition) {
String structure = ((RawStructuredQueryDefinition) qdef).serialize();
logger.debug("Query uris with raw structured query {}{}", structure, qtextMessage);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof CombinedQueryDefinition) {
String structure = ((CombinedQueryDefinition) qdef).serialize();
logger.debug("Query uris with combined query {}", structure);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof StringQueryDefinition) {
logger.debug("Query uris with string query \"{}\"", text);
} else {
throw new UnsupportedOperationException("Cannot query uris with " +
qdef.getClass().getName());
}
return getResource(reqlog, "internal/uris", transaction, params, output);
}
}
@Override
public <R extends AbstractReadHandle> R getResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
addPointInTimeQueryParam(params, output);
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String mimetype = outputBase.getMimetype();
Class as = outputBase.receiveAs();
Request.Builder requestBldr = makeGetWebResource(path, params, mimetype);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
checkStatus(response, status, "read", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
updateDescriptor(outputBase, response.headers());
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "read", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public RESTServiceResultIterator getIteratedResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, String... mimetypes)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getIteratedResourceImpl(OkHttpServiceResultIterator.class, reqlog, path, transaction, params, mimetypes);
}
private <U extends OkHttpResultIterator> U getIteratedResourceImpl(Class<U> clazz, RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, String... mimetypes)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if (transaction != null) params.add("txid", transaction.getTransactionId());
Request.Builder requestBldr = makeGetWebResource(path, params, null);
requestBldr = setupRequest(requestBldr, null, null);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
requestBldr = requestBldr.header(HEADER_ACCEPT, multipartMixedWithBoundary());
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
checkStatus(response, status, "read", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "read", "resource", response);
}
@Override
public <R extends AbstractReadHandle> R putResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String inputMimetype = inputBase.getMimetype();
boolean isResendable = inputBase.isResendable();
String outputMimeType = null;
Class as = null;
if (outputBase != null) {
outputMimeType = outputBase.getMimetype();
as = outputBase.receiveAs();
}
Request.Builder requestBldr = makePutWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, outputMimeType);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = (resendable) -> {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
};
Function<Request.Builder, Response> doPutFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPut(reqlog, funcBuilder, inputBase.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPutFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, "write", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "write", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R putResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if (input == null || input.length == 0) {
throw new IllegalArgumentException("input not specified for multipart");
}
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String outputMimetype = outputBase.getMimetype();
Class as = outputBase.receiveAs();
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, input);
Request.Builder requestBldr = makePutWebResource(path, params);
requestBldr = setupRequest(requestBldr, multiPart, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPut(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "write", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "write", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, output, "apply");
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output, String operation)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, output, operation, null);
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output, String operation,
Map<String,List<String>> responseHeaders)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String inputMimetype = null;
if(inputBase != null) {
inputMimetype = inputBase.getMimetype();
if ( inputMimetype == null &&
( Format.JSON == inputBase.getFormat() ||
Format.XML == inputBase.getFormat() ) )
{
inputMimetype = inputBase.getFormat().getDefaultMimetype();
}
}
String outputMimetype = outputBase == null ? null : outputBase.getMimetype();
boolean isResendable = inputBase == null ? true : inputBase.isResendable();
Class as = outputBase == null ? null : outputBase.receiveAs();
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = new Consumer<Boolean>() {
public void accept(Boolean resendable) {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException("Cannot retry request for " + path);
}
}
};
final Object value = inputBase == null ? null :inputBase.sendContent();
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(reqlog, funcBuilder, value);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPostFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, operation, "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if ( responseHeaders != null ) {
// add all the headers from the OkHttp Headers object to the caller-provided map
responseHeaders.putAll( response.headers().toMultimap() );
}
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, operation, "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R postResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, null, output);
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R postResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, Map<String, List<String>>[] requestHeaders, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output, "read");
String outputMimetype = outputBase != null ? outputBase.getMimetype() : null;
Class as = outputBase != null ? outputBase.receiveAs() : null;
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, null, input, requestHeaders);
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, multiPart, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPost(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "apply", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public void postBulkDocuments(
RequestLogger reqlog, DocumentWriteSet writeSet,
ServerTransform transform, Transaction transaction, Format defaultFormat)
throws ForbiddenUserException, FailedRequestException
{
postBulkDocuments(reqlog, writeSet, transform, transaction, defaultFormat, null, null);
}
@Override
public <R extends AbstractReadHandle> R postBulkDocuments(
RequestLogger reqlog, DocumentWriteSet writeSet,
ServerTransform transform, Transaction transaction, Format defaultFormat, R output,
String temporalCollection)
throws ForbiddenUserException, FailedRequestException
{
List<AbstractWriteHandle> writeHandles = new ArrayList<AbstractWriteHandle>();
List<RequestParameters> headerList = new ArrayList<RequestParameters>();
for ( DocumentWriteOperation write : writeSet ) {
String temporalDocumentURI = write.getTemporalDocumentURI();
HandleImplementation metadata = HandleAccessor.checkHandle(write.getMetadata(), "write");
HandleImplementation content = HandleAccessor.checkHandle(write.getContent(), "write");
String contentDispositionTemporal = "";
if (temporalDocumentURI != null) {
// escape any quotes or back-slashes in the uri
temporalDocumentURI = escapeContentDispositionFilename(temporalDocumentURI);
contentDispositionTemporal = "; temporal-document="+temporalDocumentURI;
}
if ( write.getOperationType() == DocumentWriteOperation.OperationType.DISABLE_METADATA_DEFAULT ) {
RequestParameters headers = new RequestParameters();
headers.add(HEADER_CONTENT_TYPE, metadata.getMimetype());
headers.add(HEADER_CONTENT_DISPOSITION, DISPOSITION_TYPE_INLINE + "; category=metadata" + contentDispositionTemporal);
headerList.add(headers);
writeHandles.add(write.getMetadata());
} else if ( metadata != null ) {
RequestParameters headers = new RequestParameters();
headers.add(HEADER_CONTENT_TYPE, metadata.getMimetype());
if ( write.getOperationType() == DocumentWriteOperation.OperationType.METADATA_DEFAULT ) {
headers.add(HEADER_CONTENT_DISPOSITION, DISPOSITION_TYPE_INLINE + "; category=metadata" + contentDispositionTemporal);
} else {
String disposition = DISPOSITION_TYPE_ATTACHMENT + "; " +
DISPOSITION_PARAM_FILENAME + "=" + escapeContentDispositionFilename(write.getUri()) +
"; category=metadata" + contentDispositionTemporal;
headers.add(HEADER_CONTENT_DISPOSITION, disposition);
}
headerList.add(headers);
writeHandles.add(write.getMetadata());
}
if ( content != null ) {
RequestParameters headers = new RequestParameters();
String mimeType = content.getMimetype();
if ( mimeType == null && defaultFormat != null ) {
mimeType = defaultFormat.getDefaultMimetype();
}
headers.add(HEADER_CONTENT_TYPE, mimeType);
String disposition = DISPOSITION_TYPE_ATTACHMENT + "; " +
DISPOSITION_PARAM_FILENAME + "=" + escapeContentDispositionFilename(write.getUri()) + contentDispositionTemporal;
headers.add(HEADER_CONTENT_DISPOSITION, disposition);
headerList.add(headers);
writeHandles.add(write.getContent());
}
}
RequestParameters params = new RequestParameters();
if ( transform != null ) {
transform.merge(params);
}
if ( temporalCollection != null ) params.add("temporal-collection", temporalCollection);
return postResource(reqlog, "documents", transaction, params,
(AbstractWriteHandle[]) writeHandles.toArray(new AbstractWriteHandle[0]),
(RequestParameters[]) headerList.toArray(new RequestParameters[0]),
output);
}
// TODO: See what other escaping we need to do for filenames
private String escapeContentDispositionFilename(String str) {
if ( str == null ) return null;
// escape any quotes or back-slashes
return "\"" + str.replace("\"", "\\\"").replace("\\", "\\\\") + "\"";
}
public class OkHttpEvalResultIterator implements EvalResultIterator {
private OkHttpResultIterator iterator;
OkHttpEvalResultIterator(OkHttpResultIterator iterator) {
this.iterator = iterator;
}
@Override
public Iterator<EvalResult> iterator() {
return this;
}
@Override
public boolean hasNext() {
if ( iterator == null ) return false;
return iterator.hasNext();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public EvalResult next() {
if ( iterator == null ) throw new NoSuchElementException("No results available");
OkHttpResult jerseyResult = iterator.next();
EvalResult result = new OkHttpEvalResult(jerseyResult);
return result;
}
@Override
public void close() {
if ( iterator != null ) iterator.close();
}
}
public class OkHttpEvalResult implements EvalResult {
private OkHttpResult content;
public OkHttpEvalResult(OkHttpResult content) {
this.content = content;
}
@Override
public Format getFormat() {
return content.getFormat();
}
@Override
public EvalResult.Type getType() {
String contentType = content.getHeader(HEADER_CONTENT_TYPE);
String xPrimitive = content.getHeader(HEADER_X_PRIMITIVE);
if ( contentType != null ) {
if ( MIMETYPE_APPLICATION_JSON.equals(contentType) ) {
if ( "null-node()".equals(xPrimitive) ) {
return EvalResult.Type.NULL;
} else {
return EvalResult.Type.JSON;
}
} else if ( MIMETYPE_TEXT_JSON.equals(contentType) ) {
return EvalResult.Type.JSON;
} else if ( MIMETYPE_APPLICATION_XML.equals(contentType) ) {
return EvalResult.Type.XML;
} else if ( MIMETYPE_TEXT_XML.equals(contentType) ) {
return EvalResult.Type.XML;
} else if ( "application/x-unknown-content-type".equals(contentType) && "binary()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
} else if ( "application/octet-stream".equals(contentType) && "node()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
}
}
if ( xPrimitive == null ) {
return EvalResult.Type.OTHER;
} else if ( "string".equals(xPrimitive) || "untypedAtomic".equals(xPrimitive) ) {
return EvalResult.Type.STRING;
} else if ( "boolean".equals(xPrimitive) ) {
return EvalResult.Type.BOOLEAN;
} else if ( "attribute()".equals(xPrimitive) ) {
return EvalResult.Type.ATTRIBUTE;
} else if ( "comment()".equals(xPrimitive) ) {
return EvalResult.Type.COMMENT;
} else if ( "processing-instruction()".equals(xPrimitive) ) {
return EvalResult.Type.PROCESSINGINSTRUCTION;
} else if ( "text()".equals(xPrimitive) ) {
return EvalResult.Type.TEXTNODE;
} else if ( "binary()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
} else if ( "duration".equals(xPrimitive) ) {
return EvalResult.Type.DURATION;
} else if ( "date".equals(xPrimitive) ) {
return EvalResult.Type.DATE;
} else if ( "anyURI".equals(xPrimitive) ) {
return EvalResult.Type.ANYURI;
} else if ( "hexBinary".equals(xPrimitive) ) {
return EvalResult.Type.HEXBINARY;
} else if ( "base64Binary".equals(xPrimitive) ) {
return EvalResult.Type.BASE64BINARY;
} else if ( "dateTime".equals(xPrimitive) ) {
return EvalResult.Type.DATETIME;
} else if ( "decimal".equals(xPrimitive) ) {
return EvalResult.Type.DECIMAL;
} else if ( "double".equals(xPrimitive) ) {
return EvalResult.Type.DOUBLE;
} else if ( "float".equals(xPrimitive) ) {
return EvalResult.Type.FLOAT;
} else if ( "gDay".equals(xPrimitive) ) {
return EvalResult.Type.GDAY;
} else if ( "gMonth".equals(xPrimitive) ) {
return EvalResult.Type.GMONTH;
} else if ( "gMonthDay".equals(xPrimitive) ) {
return EvalResult.Type.GMONTHDAY;
} else if ( "gYear".equals(xPrimitive) ) {
return EvalResult.Type.GYEAR;
} else if ( "gYearMonth".equals(xPrimitive) ) {
return EvalResult.Type.GYEARMONTH;
} else if ( "integer".equals(xPrimitive) ) {
return EvalResult.Type.INTEGER;
} else if ( "QName".equals(xPrimitive) ) {
return EvalResult.Type.QNAME;
} else if ( "time".equals(xPrimitive) ) {
return EvalResult.Type.TIME;
}
return EvalResult.Type.OTHER;
}
@Override
public <H extends AbstractReadHandle> H get(H handle) {
if ( getType() == EvalResult.Type.NULL && handle instanceof StringHandle ) {
return (H) ((StringHandle) handle).with(null);
} else if ( getType() == EvalResult.Type.NULL && handle instanceof BytesHandle ) {
return (H) ((BytesHandle) handle).with(null);
} else {
return content.getContent(handle);
}
}
@Override
public <T> T getAs(Class<T> clazz) {
if ( getType() == EvalResult.Type.NULL ) return null;
if (clazz == null) throw new IllegalArgumentException("clazz cannot be null");
ContentHandle<T> readHandle = DatabaseClientFactory.getHandleRegistry().makeHandle(clazz);
if ( readHandle == null ) return null;
readHandle = get(readHandle);
if ( readHandle == null ) return null;
return readHandle.get();
}
@Override
public String getString() {
if ( getType() == EvalResult.Type.NULL ) {
return null;
} else {
return content.getContentAs(String.class);
}
}
@Override
public Number getNumber() {
if ( getType() == EvalResult.Type.DECIMAL ) return new BigDecimal(getString());
else if ( getType() == EvalResult.Type.DOUBLE ) return Double.valueOf(getString());
else if ( getType() == EvalResult.Type.FLOAT ) return Float.valueOf(getString());
// MarkLogic integers can be much larger than Java integers, so we'll use Long instead
else if ( getType() == EvalResult.Type.INTEGER ) return Long.valueOf(getString());
else return new BigDecimal(getString());
}
@Override
public Boolean getBoolean() {
return Boolean.valueOf(getString());
}
}
@Override
public EvalResultIterator postEvalInvoke(
RequestLogger reqlog, String code, String modulePath,
ServerEvaluationCallImpl.Context context,
Map<String, Object> variables, EditableNamespaceContext namespaces,
Transaction transaction)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
String formUrlEncodedPayload;
String path;
RequestParameters params = new RequestParameters();
try {
StringBuffer sb = new StringBuffer();
if ( context == ServerEvaluationCallImpl.Context.ADHOC_XQUERY ) {
path = "eval";
sb.append("xquery=");
sb.append(URLEncoder.encode(code, "UTF-8"));
} else if ( context == ServerEvaluationCallImpl.Context.ADHOC_JAVASCRIPT ) {
path = "eval";
sb.append("javascript=");
sb.append(URLEncoder.encode(code, "UTF-8"));
} else if ( context == ServerEvaluationCallImpl.Context.INVOKE ) {
path = "invoke";
sb.append("module=");
sb.append(URLEncoder.encode(modulePath, "UTF-8"));
} else {
throw new IllegalStateException("Invalid eval context: " + context);
}
if ( variables != null && variables.size() > 0 ) {
int i=0;
for ( String name : variables.keySet() ) {
String namespace = "";
String localname = name;
if ( namespaces != null ) {
for ( String prefix : namespaces.keySet() ) {
if ( name != null && prefix != null && name.startsWith(prefix + ":") ) {
localname = name.substring(prefix.length() + 1);
namespace = namespaces.get(prefix);
}
}
}
// set the variable namespace
sb.append("&evn" + i + "=");
sb.append(URLEncoder.encode(namespace, "UTF-8"));
// set the variable localname
sb.append("&evl" + i + "=");
sb.append(URLEncoder.encode(localname, "UTF-8"));
String value;
String type = null;
Object valueObject = variables.get(name);
if ( valueObject == null ) {
value = "null";
type = "null-node()";
} else if ( valueObject instanceof JacksonHandle ||
valueObject instanceof JacksonParserHandle )
{
JsonNode jsonNode = null;
if ( valueObject instanceof JacksonHandle ) {
jsonNode = ((JacksonHandle) valueObject).get();
} else if ( valueObject instanceof JacksonParserHandle ) {
jsonNode = ((JacksonParserHandle) valueObject).get().readValueAs(JsonNode.class);
}
value = jsonNode.toString();
type = getJsonType(jsonNode);
} else if ( valueObject instanceof AbstractWriteHandle ) {
value = HandleAccessor.contentAsString((AbstractWriteHandle) valueObject);
HandleImplementation valueBase = HandleAccessor.as((AbstractWriteHandle) valueObject);
Format format = valueBase.getFormat();
//TODO: figure out what type should be
// I see element() and document-node() are two valid types
if ( format == Format.XML ) {
type = "document-node()";
} else if ( format == Format.JSON ) {
try ( JacksonParserHandle handle = new JacksonParserHandle() ) {
JsonNode jsonNode = handle.getMapper().readTree(value);
type = getJsonType(jsonNode);
}
} else if ( format == Format.TEXT ) {
/* Comment next line until 32608 is resolved
type = "text()";
// until then, use the following line */
type = "xs:untypedAtomic";
} else if ( format == Format.BINARY ) {
throw new UnsupportedOperationException("Binary format is not supported for variables");
} else {
throw new UnsupportedOperationException("Undefined format is not supported for variables. " +
"Please set the format on your handle for variable " + name + ".");
}
} else if ( valueObject instanceof String ||
valueObject instanceof Boolean ||
valueObject instanceof Number )
{
value = valueObject.toString();
// when we send type "xs:untypedAtomic" via XDBC, the server attempts to intelligently decide
// how to cast the type
type = "xs:untypedAtomic";
} else {
throw new IllegalArgumentException("Variable with name=" +
name + " is of unsupported type" +
valueObject.getClass() + ". Supported types are String, Boolean, Number, " +
"or AbstractWriteHandle");
}
// set the variable value
sb.append("&evv" + i + "=");
sb.append(URLEncoder.encode(value, "UTF-8"));
// set the variable type
sb.append("&evt" + i + "=" + type);
i++;
}
}
formUrlEncodedPayload = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
StringHandle input = new StringHandle(formUrlEncodedPayload)
.withMimetype("application/x-www-form-urlencoded");
return new OkHttpEvalResultIterator( postIteratedResourceImpl(DefaultOkHttpResultIterator.class,
reqlog, path, transaction, params, input) );
}
private String getJsonType(JsonNode jsonNode) {
if ( jsonNode instanceof ArrayNode ) {
return "json:array";
} else if ( jsonNode instanceof ObjectNode ) {
return "json:object";
} else {
throw new IllegalArgumentException("When using JacksonHandle or " +
"JacksonParserHandle with ServerEvaluationCall the content must be " +
"a valid array or object");
}
}
@Override
public RESTServiceResultIterator postIteratedResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, AbstractWriteHandle input,
String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postIteratedResourceImpl(OkHttpServiceResultIterator.class,
reqlog, path, transaction, params, input, outputMimetypes);
}
private <U extends OkHttpResultIterator> U postIteratedResourceImpl(
Class<U> clazz, final RequestLogger reqlog,
final String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
String inputMimetype = inputBase.getMimetype();
boolean isResendable = inputBase.isResendable();
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, null);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = new Consumer<Boolean>() {
public void accept(Boolean resendable) {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
}
};
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(reqlog, funcBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()),
inputBase.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPostFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "apply", "resource", response);
}
@Override
public <W extends AbstractWriteHandle> RESTServiceResultIterator postIteratedResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postIteratedResourceImpl(OkHttpServiceResultIterator.class,
reqlog, path, transaction, params, input, outputMimetypes);
}
private <W extends AbstractWriteHandle, U extends OkHttpResultIterator> U postIteratedResourceImpl(
Class<U> clazz, RequestLogger reqlog, String path, Transaction transaction,
RequestParameters params, W[] input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, input);
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(
requestBldr,
multiPart,
multipartMixedWithBoundary());
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPost(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "apply", "resource", response);
}
@Override
public <R extends AbstractReadHandle> R deleteResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String outputMimeType = null;
Class as = null;
if (outputBase != null) {
outputMimeType = outputBase.getMimetype();
as = outputBase.receiveAs();
}
Request.Builder requestBldr = makeDeleteWebResource(path, params);
requestBldr = setupRequest(requestBldr, null, outputMimeType);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doDelete(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
checkStatus(response, status, "delete", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "delete", "resource",
response, as));
} else {
response.close();
}
return output;
}
private Request.Builder makeGetWebResource(String path,
RequestParameters params, Object mimetype) {
if (path == null) throw new IllegalArgumentException("Read with null path");
logger.debug(String.format("Getting %s as %s", path, mimetype));
return setupRequest(path, params);
}
private Response doGet(Request.Builder requestBldr) {
requestBldr = requestBldr.get();
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makePutWebResource(String path,
RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Write with null path");
logger.debug("Putting {}", path);
return setupRequest(path, params);
}
private Response doPut(RequestLogger reqlog, Request.Builder requestBldr, Object value) {
if (value == null) throw new IllegalArgumentException("Resource write with null value");
if (isFirstRequest() && isStreaming(value)) makeFirstRequest(0);
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if (value instanceof OutputStreamSender) {
requestBldr = requestBldr.put(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
requestBldr = requestBldr.put(new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
requestBldr = requestBldr.put(new ObjectRequestBody(value, mediaType));
}
}
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Response doPut(Request.Builder requestBldr,
MultipartBody.Builder multiPart, boolean hasStreamingPart) {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(0);
requestBldr = requestBldr.put(multiPart.build());
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makePostWebResource(String path, RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Apply with null path");
logger.debug("Posting {}", path);
return setupRequest(path, params);
}
private Response doPost(RequestLogger reqlog, Request.Builder requestBldr, Object value) {
if (isFirstRequest() && isStreaming(value)) {
makeFirstRequest(0);
}
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if(value == null) {
requestBldr = requestBldr.post(new ObjectRequestBody(null, null));
} else if (value instanceof OutputStreamSender) {
requestBldr = requestBldr
.post(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
requestBldr = requestBldr.post(new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
requestBldr = requestBldr.post(new ObjectRequestBody(value, mediaType));
}
}
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Response doPost(Request.Builder requestBldr,
MultipartBody.Builder multiPart, boolean hasStreamingPart) {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(0);
Response response = sendRequestOnce(requestBldr.post(multiPart.build()));
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makeDeleteWebResource(String path, RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Delete with null path");
logger.debug("Deleting {}", path);
return setupRequest(path, params);
}
private Response doDelete(Request.Builder requestBldr) {
Response response = sendRequestOnce(requestBldr.delete().build());
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private void addPointInTimeQueryParam(RequestParameters params, Object outputHandle) {
HandleImplementation handleBase = HandleAccessor.as(outputHandle);
if ( params != null && handleBase != null &&
handleBase.getPointInTimeQueryTimestamp() != -1 )
{
logger.trace("param timestamp=[" + handleBase.getPointInTimeQueryTimestamp() + "]");
params.add("timestamp", Long.toString(handleBase.getPointInTimeQueryTimestamp()));
}
}
private Request.Builder addTransactionScopedCookies(Request.Builder requestBldr, Transaction transaction) {
if ( transaction != null && transaction.getCookies() != null ) {
if ( requestBldr == null ) {
throw new MarkLogicInternalException("no requestBldr available to get the URI");
}
requestBldr = addCookies(
requestBldr, transaction.getCookies(), ((TransactionImpl) transaction).getCreatedTimestamp()
);
}
return requestBldr;
}
private Request.Builder addCookies(Request.Builder requestBldr, List<ClientCookie> cookies, Calendar creation) {
HttpUrl uri = requestBldr.build().url();
for (ClientCookie cookie : cookies) {
// don't forward the cookie if it requires https and we're not using https
if ( cookie.isSecure() && ! uri.isHttps() ) {
continue;
}
// don't forward the cookie if it requires a path and we're using a different path
if ( cookie.getPath() != null ) {
String path = uri.encodedPath();
if ( path == null || ! path.startsWith(cookie.getPath()) ) {
continue;
}
}
// don't forward the cookie if it requires a domain and we're using a different domain
if ( cookie.getDomain() != null ) {
if ( uri.host() == null || ! uri.host().equals(cookie.getDomain()) ) {
continue;
}
}
// don't forward the cookie if it has 0 for max age
if ( cookie.getMaxAge() == 0 ) {
continue;
}
// TODO: determine if we need handling for MIN_VALUE
// else if ( cookie.getMaxAge() == Integer.MIN_VALUE ) {
// don't forward the cookie if it has a max age and we're past the max age
if ( creation != null && cookie.getMaxAge() > 0 ) {
int currentAge = (int) TimeUnit.MILLISECONDS.toSeconds(
System.currentTimeMillis() - creation.getTimeInMillis()
);
if ( currentAge > cookie.getMaxAge() ) {
logger.warn(
cookie.getName()+" cookie expired after "+cookie.getMaxAge()+" seconds: "+cookie.getValue()
);
continue;
}
}
requestBldr = requestBldr.addHeader(HEADER_COOKIE, cookie.toString());
}
return requestBldr;
}
private Request.Builder addTelemetryAgentId(Request.Builder requestBldr) {
if ( requestBldr == null ) throw new MarkLogicInternalException("no requestBldr available to set ML-Agent-ID header");
return requestBldr.header("ML-Agent-ID", "java");
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, W[] input)
{
return addParts(multiPart, reqlog, null, input, null);
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, String[] mimetypes, W[] input)
{
return addParts(multiPart, reqlog, null, input, null);
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, String[] mimetypes,
W[] input, Map<String, List<String>>[] headers)
{
if (mimetypes != null && mimetypes.length != input.length) {
throw new IllegalArgumentException(
"Mismatch between count of mimetypes and input");
}
if (headers != null && headers.length != input.length) {
throw new IllegalArgumentException(
"Mismatch between count of headers and input");
}
multiPart.setType(MediaType.parse(MIMETYPE_MULTIPART_MIXED));
boolean hasStreamingPart = false;
for (int i = 0; i < input.length; i++) {
AbstractWriteHandle handle = input[i];
HandleImplementation handleBase = HandleAccessor.checkHandle(
handle, "write");
if (!hasStreamingPart) {
hasStreamingPart = !handleBase.isResendable();
}
Object value = handleBase.sendContent();
String inputMimetype = null;
if ( mimetypes != null ) inputMimetype = mimetypes[i];
if ( inputMimetype == null && headers != null ) {
inputMimetype = getHeaderMimetype(getHeader(headers[i], HEADER_CONTENT_TYPE));
}
if ( inputMimetype == null ) inputMimetype = handleBase.getMimetype();
MediaType mediaType = (inputMimetype != null)
? MediaType.parse(inputMimetype)
: MediaType.parse(MIMETYPE_WILDCARD);
Headers.Builder partHeaders = new Headers.Builder();
if ( headers != null ) {
for ( String key : headers[i].keySet() ) {
// OkHttp wants me to skip the Content-Type header
if ( HEADER_CONTENT_TYPE.equalsIgnoreCase(key) ) continue;
for ( String headerValue : headers[i].get(key) ) {
partHeaders.add(key, headerValue);
}
}
}
Part bodyPart = null;
if (value instanceof OutputStreamSender) {
bodyPart = Part.create(partHeaders.build(), new StreamingOutputImpl(
(OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(value, mediaType));
}
}
multiPart = multiPart.addPart(bodyPart);
}
return hasStreamingPart;
}
private String multipartMixedWithBoundary() {
return MIMETYPE_MULTIPART_MIXED + "; boundary=" + UUID.randomUUID().toString();
}
private Request.Builder setupRequest(HttpUrl requestUri, String path, RequestParameters params) {
if ( path == null ) throw new IllegalArgumentException("path cannot be null");
if ( path.startsWith("/") ) path = path.substring(1);
HttpUrl.Builder uri = requestUri.resolve(path).newBuilder();
if ( params != null ) {
for ( String key : params.keySet() ) {
for ( String value : params.get(key) ) {
uri.addQueryParameter(key, value);
}
}
}
if ( database != null && ! path.startsWith("config/") ) {
uri.addQueryParameter("database", database);
}
Request.Builder request = new Request.Builder()
.url(uri.build());
if(authorizationTokenValue!=null && authorizationTokenValue.length()!=0) {
String samlHeaderValue = HEADER_AUTHORIZATION + ": " + AUTHORIZATION_TYPE_SAML+ " "+ AUTHORIZATION_PARAM_TOKEN + "=" + authorizationTokenValue;
request = request.header(HEADER_AUTHORIZATION, samlHeaderValue);
}
return request;
}
private Request.Builder setupRequest(String path, RequestParameters params) {
return setupRequest(baseUri, path, params);
}
private Request.Builder setupRequest(Request.Builder requestBldr,
Object inputMimetype, Object outputMimetype) {
if (inputMimetype == null) {
} else if (inputMimetype instanceof String) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, (String) inputMimetype);
} else if (inputMimetype instanceof MediaType) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, inputMimetype.toString());
} else if (inputMimetype instanceof MultipartBody.Builder) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_MULTIPART_MIXED);
logger.debug("Sending multipart for {}", requestBldr.build().url().encodedPath());
} else {
throw new IllegalArgumentException(
"Unknown input mimetype specifier "
+ inputMimetype.getClass().getName());
}
if (outputMimetype == null) {
} else if (outputMimetype instanceof String) {
requestBldr = requestBldr.header(HEADER_ACCEPT, (String) outputMimetype);
} else if (outputMimetype instanceof MediaType) {
requestBldr = requestBldr.header(HEADER_ACCEPT, outputMimetype.toString());
} else {
throw new IllegalArgumentException(
"Unknown output mimetype specifier "
+ outputMimetype.getClass().getName());
}
return requestBldr;
}
private Request.Builder setupRequest(String path, RequestParameters params, Object inputMimetype,
Object outputMimetype)
{
return setupRequest(setupRequest(path, params), inputMimetype, outputMimetype);
}
private void checkStatus(Response response, int status, String operation, String entityType,
String path, ResponseStatus expected)
{
if (!expected.isExpected(status)) {
FailedRequest failure = extractErrorFields(response);
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException("Could not " + operation
+ " " + entityType + " at " + path,
failure);
}
if ("RESTAPI-CONTENTNOVERSION".equals(failure.getMessageCode())) {
throw new FailedRequestException("Content version required to " +
operation + " " + entityType + " at " + path, failure);
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to "
+ operation + " " + entityType + " at " + path,
failure);
}
throw new FailedRequestException("failed to " + operation + " "
+ entityType + " at " + path + ": "
+ getReasonPhrase(response), failure);
}
}
private <T> T makeResult(RequestLogger reqlog, String operation,
String entityType, Response response, Class<T> as) {
if (as == null) {
return null;
}
logRequest(reqlog, "%s for %s", operation, entityType);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
private <U extends OkHttpResultIterator> U makeResults(
Class<U> clazz, RequestLogger reqlog,
String operation, String entityType, Response response) {
if ( response == null ) return null;
ResponseBody body = response.body();
MimeMultipart entity = body.contentLength() != 0 ?
getEntity(body, MimeMultipart.class) : null;
List<BodyPart> partList = getPartList(entity);
Closeable closeable = response;
return makeResults(clazz, reqlog, operation, entityType, partList, response, closeable);
}
private <U extends OkHttpResultIterator> U makeResults(
Class<U> clazz, RequestLogger reqlog,
String operation, String entityType, List<BodyPart> partList, Response response,
Closeable closeable) {
logRequest(reqlog, "%s for %s", operation, entityType);
if ( response == null ) return null;
try {
java.lang.reflect.Constructor<U> constructor =
clazz.getConstructor(OkHttpServices.class, RequestLogger.class, List.class, Closeable.class);
OkHttpResultIterator result = constructor.newInstance(this, reqlog, partList, closeable);
Headers headers = response.headers();
if (headers.get(HEADER_VND_MARKLOGIC_START) != null) {
result.setStart(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_START)));
}
if (headers.get(HEADER_VND_MARKLOGIC_PAGELENGTH) != null) {
result.setPageSize(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_PAGELENGTH)));
}
if (headers.get(HEADER_VND_MARKLOGIC_RESULT_ESTIMATE) != null) {
result.setTotalSize(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_RESULT_ESTIMATE)));
}
return (U) result;
} catch (Throwable t) {
throw new MarkLogicInternalException("Error instantiating " + clazz.getName(), t);
}
}
private boolean isStreaming(Object value) {
return !(value instanceof String || value instanceof byte[] || value instanceof File);
}
private void logRequest(RequestLogger reqlog, String message,
Object... params) {
if (reqlog == null) return;
PrintStream out = reqlog.getPrintStream();
if (out == null) return;
if (params == null || params.length == 0) {
out.println(message);
} else {
out.format(message, params);
out.println();
}
}
private String stringJoin(Collection collection, String separator,
String defaultValue) {
if (collection == null || collection.size() == 0) return defaultValue;
StringBuilder builder = null;
for (Object value : collection) {
if (builder == null) {
builder = new StringBuilder();
} else {
builder.append(separator);
}
builder.append(value);
}
return (builder != null) ? builder.toString() : null;
}
private int calculateDelay(Random rand, int i) {
int min =
(i > 6) ? DELAY_CEILING :
(i == 0) ? DELAY_FLOOR :
DELAY_FLOOR + (1 << i) * DELAY_MULTIPLIER;
int range =
(i > 6) ? DELAY_FLOOR :
(i == 0) ? 2 * DELAY_MULTIPLIER :
(i == 6) ? DELAY_CEILING - min :
(1 << i) * DELAY_MULTIPLIER;
return min + randRetry.nextInt(range);
}
public class OkHttpResult {
private RequestLogger reqlog;
private BodyPart part;
private boolean extractedHeaders = false;
private String uri;
private RequestParameters headers = new RequestParameters();
private Format format;
private String mimetype;
private long length;
public OkHttpResult(RequestLogger reqlog, BodyPart part) {
this.reqlog = reqlog;
this.part = part;
}
public <R extends AbstractReadHandle> R getContent(R handle) {
if (part == null) throw new IllegalStateException("Content already retrieved");
HandleImplementation handleBase = HandleAccessor.as(handle);
extractHeaders();
updateFormat(handleBase, format);
updateMimetype(handleBase, mimetype);
updateLength(handleBase, length);
try {
Object contentEntity = getEntity(part, handleBase.receiveAs());
handleBase.receiveContent((reqlog != null) ? reqlog.copyContent(contentEntity) : contentEntity);
return handle;
} finally {
part = null;
reqlog = null;
}
}
public <T> T getContentAs(Class<T> clazz) {
ContentHandle<T> readHandle = DatabaseClientFactory.getHandleRegistry().makeHandle(clazz);
readHandle = getContent(readHandle);
if ( readHandle == null ) return null;
return readHandle.get();
}
public String getUri() {
extractHeaders();
return uri;
}
public Format getFormat() {
extractHeaders();
return format;
}
public String getMimetype() {
extractHeaders();
return mimetype;
}
public long getLength() {
extractHeaders();
return length;
}
public String getHeader(String name) {
extractHeaders();
List<String> values = headers.get(name);
if ( values != null && values.size() > 0 ) {
return values.get(0);
}
return null;
}
public Map<String,List<String>> getHeaders() {
extractHeaders();
return headers.getMap();
}
private void extractHeaders() {
if (part == null || extractedHeaders) return;
try {
for ( Enumeration<Header> e = part.getAllHeaders(); e.hasMoreElements(); ) {
Header header = e.nextElement();
headers.put(header.getName(), header.getValue());
}
format = getHeaderFormat(part);
mimetype = getHeaderMimetype(OkHttpServices.getHeader(part, HEADER_CONTENT_TYPE));
length = getHeaderLength(OkHttpServices.getHeader(part, HEADER_CONTENT_LENGTH));
uri = getHeaderUri(part);
extractedHeaders = true;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
}
public class OkHttpServiceResult extends OkHttpResult implements RESTServices.RESTServiceResult {
public OkHttpServiceResult(RequestLogger reqlog, BodyPart part) {
super(reqlog, part);
}
}
public class OkHttpResultIterator<T extends OkHttpResult> {
private RequestLogger reqlog;
private Iterator<BodyPart> partQueue;
private Class<T> clazz;
private long start = -1;
private long size = -1;
private long pageSize = -1;
private long totalSize = -1;
private Closeable closeable;
public OkHttpResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Class<T> clazz, Closeable closeable) {
this.clazz = clazz;
this.reqlog = reqlog;
if (partList != null && partList.size() > 0) {
this.size = partList.size();
this.partQueue = new ConcurrentLinkedQueue<>(
partList).iterator();
} else {
this.size = 0;
}
this.closeable = closeable;
}
public long getStart() {
return start;
}
public OkHttpResultIterator<T> setStart(long start) {
this.start = start;
return this;
}
public long getSize() {
return size;
}
public OkHttpResultIterator<T> setSize(long size) {
this.size = size;
return this;
}
public long getPageSize() {
return pageSize;
}
public OkHttpResultIterator<T> setPageSize(long pageSize) {
this.pageSize = pageSize;
return this;
}
public long getTotalSize() {
return totalSize;
}
public OkHttpResultIterator<T> setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public boolean hasNext() {
if (partQueue == null) return false;
boolean hasNext = partQueue.hasNext();
return hasNext;
}
public T next() {
if (partQueue == null) return null;
try {
java.lang.reflect.Constructor<T> constructor =
clazz.getConstructor(OkHttpServices.class, RequestLogger.class, BodyPart.class);
return constructor.newInstance(new OkHttpServices(), reqlog, partQueue.next());
} catch (Throwable t) {
throw new IllegalStateException("Error instantiating " + clazz.getName(), t);
}
}
public void remove() {
if (partQueue == null) return;
partQueue.remove();
if (!partQueue.hasNext()) close();
}
public void close() {
partQueue = null;
reqlog = null;
if ( closeable != null ) {
try {
closeable.close();
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
}
}
public class OkHttpServiceResultIterator
extends OkHttpResultIterator<OkHttpServiceResult>
implements RESTServiceResultIterator
{
public OkHttpServiceResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Closeable closeable) {
super(reqlog, partList, OkHttpServiceResult.class, closeable);
}
}
public class DefaultOkHttpResultIterator
extends OkHttpResultIterator<OkHttpResult>
implements Iterator<OkHttpResult>
{
public DefaultOkHttpResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Closeable closeable) {
super(reqlog, partList, OkHttpResult.class, closeable);
}
}
public class OkHttpDocumentRecord implements DocumentRecord {
private OkHttpResult content;
private OkHttpResult metadata;
public OkHttpDocumentRecord(OkHttpResult content, OkHttpResult metadata) {
this.content = content;
this.metadata = metadata;
}
public OkHttpDocumentRecord(OkHttpResult content) {
this.content = content;
}
@Override
public String getUri() {
if ( content == null && metadata != null ) {
return metadata.getUri();
} else if ( content != null ) {
return content.getUri();
} else {
throw new IllegalStateException("Missing both content and metadata!");
}
}
@Override
public Format getFormat() {
return content.getFormat();
}
@Override
public String getMimetype() {
return content.getMimetype();
}
@Override
public <T extends DocumentMetadataReadHandle> T getMetadata(T metadataHandle) {
if ( metadata == null ) {
throw new IllegalStateException("getMetadata called when no metadata is available");
}
return metadata.getContent(metadataHandle);
}
@Override
public <T> T getMetadataAs(Class<T> as) {
if ( as == null ) {
throw new IllegalStateException("getMetadataAs cannot accept null");
}
return metadata.getContentAs(as);
}
@Override
public <T extends AbstractReadHandle> T getContent(T contentHandle) {
if ( content == null ) {
throw new IllegalStateException("getContent called when no content is available");
}
return content.getContent(contentHandle);
}
@Override
public <T> T getContentAs(Class<T> as) {
if ( as == null ) {
throw new IllegalStateException("getContentAs cannot accept null");
}
return content.getContentAs(as);
}
}
@Override
public OkHttpClient getClientImplementation() {
if (client == null) return null;
return client;
}
public void setClientImplementation(OkHttpClient client) {
this.client = client;
}
@Override
public <T> T suggest(Class<T> as, SuggestDefinition suggestionDef) {
RequestParameters params = new RequestParameters();
String suggestCriteria = suggestionDef.getStringCriteria();
String[] queries = suggestionDef.getQueryStrings();
String optionsName = suggestionDef.getOptionsName();
Integer limit = suggestionDef.getLimit();
Integer cursorPosition = suggestionDef.getCursorPosition();
if (suggestCriteria != null) {
params.add("partial-q", suggestCriteria);
}
if (optionsName != null) {
params.add("options", optionsName);
}
if (limit != null) {
params.add("limit", Long.toString(limit));
}
if (cursorPosition != null) {
params.add("cursor-position", Long.toString(cursorPosition));
}
if (queries != null) {
for (String stringQuery : queries) {
params.add("q", stringQuery);
}
}
Request.Builder requestBldr = null;
requestBldr = setupRequest("suggest", params, null, MIMETYPE_APPLICATION_XML);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to get suggestions",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("Suggest call failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public InputStream match(StructureWriteHandle document,
String[] candidateRules, String mimeType, ServerTransform transform) {
RequestParameters params = new RequestParameters();
HandleImplementation baseHandle = HandleAccessor.checkHandle(document, "match");
if (candidateRules != null) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (transform != null) {
transform.merge(params);
}
Request.Builder requestBldr = null;
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, mimeType);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(null, funcBuilder, baseHandle.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
@Override
public InputStream match(QueryDefinition queryDef,
long start, long pageLength, String[] candidateRules, ServerTransform transform) {
if (queryDef == null) {
throw new IllegalArgumentException("Cannot match null query");
}
RequestParameters params = new RequestParameters();
if (start > 1) {
params.add("start", Long.toString(start));
}
if (pageLength >= 0) {
params.add("pageLength", Long.toString(pageLength));
}
if (transform != null) {
transform.merge(params);
}
if (candidateRules.length > 0) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (queryDef.getOptionsName() != null) {
params.add("options", queryDef.getOptionsName());
}
Request.Builder requestBldr = null;
String structure = null;
HandleImplementation baseHandle = null;
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
params.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition) {
structure = ((StructuredQueryDefinition) queryDef).serialize();
logger.debug("Searching with structured query {}", structure);
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
} else if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "match");
logger.debug("Searching with raw query");
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
} else if (queryDef instanceof StringQueryDefinition) {
logger.debug("Searching with string query [{}]", text);
requestBldr = setupRequest("alert/match", params, null, MIMETYPE_APPLICATION_XML);
} else {
throw new UnsupportedOperationException("Cannot match with "
+ queryDef.getClass().getName());
}
requestBldr = addTelemetryAgentId(requestBldr);
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
if (queryDef instanceof StructuredQueryDefinition) {
response = sendRequestOnce(requestBldr.post(RequestBody.create(mediaType, structure)));
response = doPost(null, requestBldr, structure);
} else if (queryDef instanceof RawQueryDefinition) {
response = doPost(null, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof StringQueryDefinition) {
response = sendRequestOnce(requestBldr.get());
} else {
throw new UnsupportedOperationException("Cannot match with "
+ queryDef.getClass().getName());
}
status = response.code();
if (!retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
response.close();
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
@Override
public InputStream match(String[] docIds, String[] candidateRules, ServerTransform transform) {
RequestParameters params = new RequestParameters();
if (docIds.length > 0) {
for (String docId : docIds) {
params.add("uri", docId);
}
}
if (candidateRules.length > 0) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (transform != null) {
transform.merge(params);
}
Request.Builder requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
private void addGraphUriParam(RequestParameters params, String uri) {
if ( uri == null || uri.equals(GraphManager.DEFAULT_GRAPH) ) {
params.add("default", "");
} else {
params.add("graph", uri);
}
}
private void addPermsParams(RequestParameters params, GraphPermissions permissions) {
if ( permissions != null ) {
for ( Map.Entry<String,Set<Capability>> entry : permissions.entrySet() ) {
if ( entry.getValue() != null ) {
for ( Capability capability : entry.getValue() ) {
params.add("perm:" + entry.getKey(), capability.toString().toLowerCase());
}
}
}
}
}
@Override
public <R extends AbstractReadHandle> R getGraphUris(RequestLogger reqlog, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getResource(reqlog, "graphs", null, null, output);
}
@Override
public <R extends AbstractReadHandle> R readGraph(RequestLogger reqlog, String uri, R output,
Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
return getResource(reqlog, "graphs", transaction, params, output);
}
@Override
public void writeGraph(RequestLogger reqlog, String uri,
AbstractWriteHandle input, GraphPermissions permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
addPermsParams(params, permissions);
putResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void writeGraphs(RequestLogger reqlog, AbstractWriteHandle input, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
putResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void mergeGraph(RequestLogger reqlog, String uri,
AbstractWriteHandle input, GraphPermissions permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
addPermsParams(params, permissions);
postResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void mergeGraphs(RequestLogger reqlog, AbstractWriteHandle input, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
postResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public <R extends AbstractReadHandle> R getPermissions(RequestLogger reqlog, String uri,
R output,Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
return getResource(reqlog, "graphs", transaction, params, output);
}
@Override
public void deletePermissions(RequestLogger reqlog, String uri, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
deleteResource(reqlog, "graphs", transaction, params, null);
}
@Override
public void writePermissions(RequestLogger reqlog, String uri,
AbstractWriteHandle permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
putResource(reqlog, "graphs", transaction, params, permissions, null);
}
@Override
public void mergePermissions(RequestLogger reqlog, String uri,
AbstractWriteHandle permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
postResource(reqlog, "graphs", transaction, params, permissions, null);
}
@Override
public Object deleteGraph(RequestLogger reqlog, String uri, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
return deleteResource(reqlog, "graphs", transaction, params, null);
}
@Override
public void deleteGraphs(RequestLogger reqlog, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
deleteResource(reqlog, "graphs", transaction, null, null);
}
@Override
public <R extends AbstractReadHandle> R getThings(RequestLogger reqlog, String[] iris, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( iris == null ) throw new IllegalArgumentException("iris cannot be null");
RequestParameters params = new RequestParameters();
for ( String iri : iris ) {
params.add("iri", iri);
}
return getResource(reqlog, "graphs/things", null, params, output);
}
@Override
public <R extends AbstractReadHandle> R executeSparql(RequestLogger reqlog,
SPARQLQueryDefinition qdef, R output, long start, long pageLength,
Transaction transaction, boolean isUpdate)
{
if ( qdef == null ) throw new IllegalArgumentException("qdef cannot be null");
if ( output == null ) throw new IllegalArgumentException("output cannot be null");
RequestParameters params = new RequestParameters();
if (start > 1) params.add("start", Long.toString(start));
if (pageLength >= 0) params.add("pageLength", Long.toString(pageLength));
if (qdef.getOptimizeLevel() >= 0) {
params.add("optimize", Integer.toString(qdef.getOptimizeLevel()));
}
if (qdef.getCollections() != null ) {
for ( String collection : qdef.getCollections() ) {
params.add("collection", collection);
}
}
addPermsParams(params, qdef.getUpdatePermissions());
String sparql = qdef.getSparql();
SPARQLBindings bindings = qdef.getBindings();
for ( Map.Entry<String,List<SPARQLBinding>> entry : bindings.entrySet() ) {
String paramName = "bind:" + entry.getKey();
String typeOrLang = "";
for ( SPARQLBinding binding : entry.getValue() ) {
if ( binding.getDatatype() != null ) {
typeOrLang = ":" + binding.getDatatype();
} else if ( binding.getLanguageTag() != null ) {
typeOrLang = "@" + binding.getLanguageTag().toLanguageTag();
}
params.add(paramName + typeOrLang, binding.getValue());
}
}
QueryDefinition constrainingQuery = qdef.getConstrainingQueryDefinition();
StructureWriteHandle input;
if ( constrainingQuery != null ) {
if (qdef.getOptionsName()!= null && qdef.getOptionsName().length() > 0) {
params.add("options", qdef.getOptionsName());
}
if ( constrainingQuery instanceof RawCombinedQueryDefinition ) {
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
(RawCombinedQueryDefinition) constrainingQuery, null, null, sparql);
Format format = combinedQdef.getFormat();
input = new StringHandle(combinedQdef.serialize()).withFormat(format);
} else if ( constrainingQuery instanceof RawStructuredQueryDefinition ) {
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
(RawStructuredQueryDefinition) constrainingQuery, null, null, sparql);
Format format = combinedQdef.getFormat();
input = new StringHandle(combinedQdef.serialize()).withFormat(format);
} else if ( constrainingQuery instanceof StringQueryDefinition ||
constrainingQuery instanceof StructuredQueryDefinition )
{
String stringQuery = constrainingQuery instanceof StringQueryDefinition ?
((StringQueryDefinition) constrainingQuery).getCriteria() : null;
StructuredQueryDefinition structuredQuery =
constrainingQuery instanceof StructuredQueryDefinition ?
(StructuredQueryDefinition) constrainingQuery : null;
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
structuredQuery, null, stringQuery, sparql);
input = new StringHandle(combinedQdef.serialize()).withMimetype(MIMETYPE_APPLICATION_XML);
} else {
throw new IllegalArgumentException(
"Constraining query must be of type SPARQLConstrainingQueryDefinition");
}
} else {
String mimetype = isUpdate ? "application/sparql-update" : "application/sparql-query";
input = new StringHandle(sparql).withMimetype(mimetype);
}
if (qdef.getBaseUri() != null) {
params.add("base", qdef.getBaseUri());
}
if (qdef.getDefaultGraphUris() != null) {
for (String defaultGraphUri : qdef.getDefaultGraphUris()) {
params.add("default-graph-uri", defaultGraphUri);
}
}
if (qdef.getNamedGraphUris() != null) {
for (String namedGraphUri : qdef.getNamedGraphUris()) {
params.add("named-graph-uri", namedGraphUri);
}
}
if (qdef.getUsingGraphUris() != null) {
for (String usingGraphUri : qdef.getUsingGraphUris()) {
params.add("using-graph-uri", usingGraphUri);
}
}
if (qdef.getUsingNamedGraphUris() != null) {
for (String usingNamedGraphUri : qdef.getUsingNamedGraphUris()) {
params.add("using-named-graph-uri", usingNamedGraphUri);
}
}
// rulesets
if (qdef.getRulesets() != null) {
for (SPARQLRuleset ruleset : qdef.getRulesets()) {
params.add("ruleset", ruleset.getName());
}
}
if (qdef.getIncludeDefaultRulesets() != null) {
params.add("default-rulesets", qdef.getIncludeDefaultRulesets() ? "include" : "exclude");
}
return postResource(reqlog, "/graphs/sparql", transaction, params, input, output);
}
private String getTransactionId(Transaction transaction) {
if ( transaction == null ) return null;
return transaction.getTransactionId();
}
private String getReasonPhrase(Response response) {
if ( response.message() == null ) return "";
// strip off the number part of the reason phrase
return response.message().replaceFirst("^\\d+ ", "");
}
private <T> T getEntity(BodyPart part, Class<T> as) {
try {
String contentType = part.getContentType();
return getEntity(ResponseBody.create(MediaType.parse(contentType), part.getSize(),
Okio.buffer(Okio.source(part.getInputStream()))), as);
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private MediaType makeType(String mimetype) {
if ( mimetype == null ) return null;
MediaType type = MediaType.parse(mimetype);
if ( type == null ) throw new IllegalArgumentException("Invalid mime-type: " + mimetype);
return type;
}
private <T> T getEntity(ResponseBody body, Class<T> as) {
try {
if ( as == InputStream.class ) {
return (T) body.byteStream();
} else if ( as == byte[].class ) {
return (T) body.bytes();
} else if ( as == Reader.class ) {
return (T) body.charStream();
} else if ( as == String.class ) {
return (T) body.string();
} else if ( as == MimeMultipart.class ) {
ByteArrayDataSource dataSource = new ByteArrayDataSource(body.byteStream(), body.contentType().toString());
return (T) new MimeMultipart(dataSource);
} else if ( as == File.class ) {
// write out the response body to a temp file in the system temp folder
// then return the path to that file as a File object
String suffix = ".unknown";
boolean isBinary = true;
MediaType mediaType = body.contentType();
if ( mediaType != null ) {
suffix = "." + mediaType.subtype();
for ( String type : new String[] {"json", "xml", "xquery", "sjs", "javascript", "html"} ) {
if ( type.equalsIgnoreCase(mediaType.subtype()) ) {
isBinary = false;
}
}
if ( isBinary == true && "text".equalsIgnoreCase(mediaType.type()) ) {
suffix = ".txt";
isBinary = false;
}
}
Path path = Files.createTempFile("tmp", suffix);
if ( isBinary == true ) {
Files.write(path, body.bytes());
} else {
Writer out = Files.newBufferedWriter(path, Charset.forName("UTF-8"));
try {
out.write(body.string());
} finally {
out.close();
}
}
return (T) path.toFile();
} else {
throw new IllegalArgumentException(
"Handle recieveAs returned " + as + " which is not a supported type. " +
"Try InputStream, Reader, String, byte[], File.");
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private List<BodyPart> getPartList(MimeMultipart multipart) {
try {
if ( multipart == null ) return null;
List<BodyPart> partList = new ArrayList<BodyPart>();
for ( int i = 0; i < multipart.getCount(); i++ ) {
partList.add(multipart.getBodyPart(i));
}
return partList;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private class ObjectRequestBody extends RequestBody {
private Object obj;
private MediaType contentType;
ObjectRequestBody(Object obj, MediaType contentType) {
super();
this.obj = obj;
this.contentType = contentType;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if ( obj instanceof InputStream ) {
sink.writeAll(Okio.source((InputStream) obj));
} else if ( obj instanceof File ) {
try ( Source source = Okio.source((File) obj) ) {
sink.writeAll(source);
}
} else if ( obj instanceof byte[] ) {
sink.write((byte[]) obj);
} else if ( obj instanceof String) {
sink.write(((String) obj).getBytes("UTF-8"));
} else if ( obj == null ) {
} else {
throw new IllegalStateException("Cannot write object of type: " + obj.getClass());
}
}
}
private interface Function<T,R> {
R apply(T t);
}
private interface Consumer<T> {
void accept(T t);
}
// API First Changes
static private class EmptyRequestBody extends RequestBody {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) {
}
}
static class AtomicRequestBody extends RequestBody {
private MediaType contentType;
private String value;
AtomicRequestBody(String value, MediaType contentType) {
super();
this.value = value;
this.contentType = contentType;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(value);
}
}
public class CallRequestImpl implements CallRequest {
private SessionStateImpl session;
private Request.Builder requestBldr;
private RequestBody requestBody;
private boolean hasStreamingPart;
private HttpMethod method;
private String endpoint;
private HttpUrl callBaseUri;
CallRequestImpl(String endpoint, HttpMethod method, SessionState session) {
if (session != null && !(session instanceof SessionStateImpl)) {
throw new IllegalArgumentException("Session state must be implemented by internal class: "+session.getClass().getName());
}
this.endpoint = endpoint;
this.method = method;
this.session = (SessionStateImpl) session;
this.hasStreamingPart = false;
this.callBaseUri = new HttpUrl.Builder()
.scheme(baseUri.scheme())
.host(baseUri.host())
.port(baseUri.port())
.encodedPath("/")
.build();
}
@Override
public CallResponse withEmptyResponse() {
prepareRequestBuilder();
CallResponseImpl responseImpl = new CallResponseImpl();
executeRequest(responseImpl);
return responseImpl;
}
@Override
public SingleCallResponse withDocumentResponse(Format format) {
prepareRequestBuilder();
SingleCallResponseImpl responseImpl = new SingleCallResponseImpl(format);
this.requestBldr = forDocumentResponse(requestBldr, format);
executeRequest(responseImpl);
return responseImpl;
}
@Override
public MultipleCallResponse withMultipartMixedResponse(Format format) {
prepareRequestBuilder();
MultipleCallResponseImpl responseImpl = new MultipleCallResponseImpl(format);
this.requestBldr = forMultipartMixedResponse(requestBldr);
executeRequest(responseImpl);
return responseImpl;
}
@Override
public boolean hasStreamingPart() {
return this.hasStreamingPart;
}
@Override
public SessionState getSession() {
return this.session;
}
@Override
public String getEndpoint() {
return this.endpoint;
}
@Override
public HttpMethod getHttpMethod() {
return this.method;
}
private void prepareRequestBuilder() {
this.requestBldr = setupRequest(callBaseUri, endpoint, null);
if (session != null) {
this.requestBldr = addCookies(this.requestBldr, session.getCookies(), session.getCreatedTimestamp());
// Add the Cookie header for SessionId if we have a session object passed
this.requestBldr.addHeader(HEADER_COOKIE, "SessionID="+session.getSessionId());
}
addHttpMethod();
this.requestBldr.addHeader(HEADER_ERROR_FORMAT, MIMETYPE_APPLICATION_JSON);
}
private void addHttpMethod() {
if(method != null && method == HttpMethod.POST) {
if(requestBody == null) {
throw new IllegalStateException("Request Body is null!");
}
this.requestBldr.post(requestBody);
} else {
throw new IllegalStateException("HTTP method is null or invalid!");
}
}
private void executeRequest(CallResponseImpl responseImpl) {
SessionState session = getSession();
//TODO: Add a telemetry agent if needed
// requestBuilder = addTelemetryAgentId(requestBuilder);
boolean hasStreamingPart = hasStreamingPart();
Consumer<Boolean> resendableConsumer = resendable -> {
if (hasStreamingPart) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + getEndpoint());
}
};
Function<Request.Builder, Response> sendRequestFunction = requestBldr -> {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(callBaseUri, "", 0);
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
};
Response response = sendRequestWithRetry(requestBldr, sendRequestFunction, resendableConsumer);
if(session != null) {
List<ClientCookie> cookies = new ArrayList<>();
for ( String setCookie : response.headers(HEADER_SET_COOKIE) ) {
ClientCookie cookie = ClientCookie.parse(requestBldr.build().url(), setCookie);
cookies.add(cookie);
}
((SessionStateImpl)session).setCookies(cookies);
}
checkStatus(response);
responseImpl.setResponse(response);
}
private void checkStatus(Response response) {
int statusCode = response.code();
if (statusCode >= 300) {
FailedRequest failure = null;
MediaType mediaType = MediaType.parse(response.header(HEADER_CONTENT_TYPE));
if ( "json".equals(mediaType.subtype()) ) {
failure = extractErrorFields(response);
} else if ( statusCode == STATUS_UNAUTHORIZED ) {
failure = new FailedRequest();
failure.setMessageString("Unauthorized");
failure.setStatusString("Failed Auth");
} else if (statusCode == STATUS_NOT_FOUND) {
ResourceNotFoundException ex = failure == null ? new ResourceNotFoundException("Could not " + method + " at " + endpoint) :
new ResourceNotFoundException("Could not " + method + " at " + endpoint, failure);
throw ex;
} else if (statusCode == STATUS_FORBIDDEN) {
ForbiddenUserException ex = failure == null ? new ForbiddenUserException("User is not allowed to " + method + " at " + endpoint) :
new ForbiddenUserException("User is not allowed to " + method + " at " + endpoint, failure);
throw ex;
} else {
failure = new FailedRequest();
failure.setStatusCode(statusCode);
failure.setMessageCode("UNKNOWN");
failure.setMessageString("Server did not respond with an expected Error message.");
failure.setStatusString("UNKNOWN");
}
FailedRequestException ex = failure == null ? new FailedRequestException("failed to " + method + " at " + endpoint + ": "
+ getReasonPhrase(response)) : new FailedRequestException("failed to " + method + " at " + endpoint + ": "
+ getReasonPhrase(response), failure);
throw ex;
}
}
public CallRequest withEmptyRequest() {
requestBody = new EmptyRequestBody();
return this;
}
public CallRequest withAtomicBodyRequest(CallField... params) {
String atomics = Stream.of(params)
.map(param -> encodeParamValue(param))
.filter(param -> param != null)
.collect(Collectors.joining("&"));
requestBody = RequestBody.create(URLENCODED_MIME_TYPE, (atomics == null) ? "" : atomics);
return this;
}
public CallRequest withNodeBodyRequest(CallField... params) {
this.requestBody = makeRequestBody(params);
return this;
}
private RequestBody makeRequestBody(String value) {
if (value == null) {
return new EmptyRequestBody();
}
return new AtomicRequestBody(value, MediaType.parse("text/plain"));
}
private RequestBody makeRequestBody(AbstractWriteHandle document) {
if (document == null) {
return new EmptyRequestBody();
}
HandleImplementation handleBase = HandleAccessor.as(document);
Format format = handleBase.getFormat();
String mimetype = (format == Format.BINARY) ?
"application/x-unknown-content-type" : handleBase.getMimetype();
MediaType mediaType = MediaType.parse(mimetype);
return (document instanceof OutputStreamSender) ?
new StreamingOutputImpl((OutputStreamSender) document, null, mediaType) :
new ObjectRequestBody(HandleAccessor.sendContent(document), mediaType);
}
private RequestBody makeRequestBody(CallField[] params) {
if (params == null || params.length == 0) {
return new EmptyRequestBody();
}
MultipartBody.Builder multiBldr = new MultipartBody.Builder();
multiBldr.setType(MultipartBody.FORM);
Condition hasValue = new Condition();
Condition hasStreamingPartCondition = new Condition();
for (CallField param: params) {
if (param == null) {
continue;
}
final String paramName = param.getParamName();
if (param instanceof SingleAtomicCallField) {
String paramValue = ((SingleAtomicCallField) param).getParamValue();
if (paramValue != null) {
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
}
} else if (param instanceof MultipleAtomicCallField) {
Stream<String> paramValues = ((MultipleAtomicCallField) param).getParamValues();
if (paramValues != null) {
paramValues
.filter(paramValue -> paramValue != null)
.forEachOrdered(paramValue ->
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue))
);
}
} else if (param instanceof SingleNodeCallField) {
AbstractWriteHandle paramValue = ((SingleNodeCallField) param).getParamValue();
if (paramValue != null) {
HandleImplementation handleBase = HandleAccessor.as(paramValue);
if(! handleBase.isResendable()) {
hasStreamingPartCondition.set();
}
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
}
} else if (param instanceof MultipleNodeCallField) {
Stream<? extends AbstractWriteHandle> paramValues = ((MultipleNodeCallField) param).getParamValues();
if (paramValues != null) {
paramValues
.filter(paramValue -> paramValue != null)
.forEachOrdered(paramValue -> {
HandleImplementation handleBase = HandleAccessor.as(paramValue);
if(!handleBase.isResendable()) {
hasStreamingPartCondition.set();
}
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
});
}
} else {
throw new IllegalStateException(
"unknown multipart "+paramName+" param of: "+param.getClass().getName()
);
}
}
if (!hasValue.get()) {
return new EmptyRequestBody();
}
this.hasStreamingPart = hasStreamingPartCondition.get();
return multiBldr.build();
}
}
@Override
public CallRequest makeEmptyRequest(String endpoint, HttpMethod method, SessionState session) {
return new CallRequestImpl(endpoint, method, session).withEmptyRequest();
}
@Override
public CallRequest makeAtomicBodyRequest(String endpoint, HttpMethod method, SessionState session, CallField... params) {
if (params == null || params.length == 0) {
return makeEmptyRequest(endpoint, method, session);
}
return new CallRequestImpl(endpoint, method, session).withAtomicBodyRequest(params);
}
@Override
public CallRequest makeNodeBodyRequest(String endpoint, HttpMethod method, SessionState session, CallField... params) {
if (params == null || params.length == 0) {
return makeEmptyRequest(endpoint, method, session);
}
return new CallRequestImpl(endpoint, method, session).withNodeBodyRequest(params);
}
private String encodeParamValue(String paramName, String value) {
if (value == null) {
return null;
}
try {
return paramName+"="+URLEncoder.encode(value, UTF8_ID);
} catch(UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
}
}
private String encodeParamValue(SingleAtomicCallField param) {
if (param == null) {
return null;
}
return encodeParamValue(param.getParamName(), param.getParamValue());
}
private String encodeParamValue(MultipleAtomicCallField param) {
if (param == null) {
return null;
}
String paramName = param.getParamName();
Stream<String> paramValues = param.getParamValues();
if (paramValues == null) {
return null;
}
String encodedParamValues = paramValues
.map(paramValue -> encodeParamValue(paramName, paramValue))
.filter(paramValue -> (paramValue != null))
.collect(Collectors.joining("&"));
if (encodedParamValues == null || encodedParamValues.length() == 0) {
return null;
}
return encodedParamValues;
}
private String encodeParamValue(CallField param) {
if (param == null) {
return null;
} else if (param instanceof SingleAtomicCallField) {
return encodeParamValue((SingleAtomicCallField) param);
} else if (param instanceof MultipleAtomicCallField) {
return encodeParamValue((MultipleAtomicCallField) param);
}
throw new IllegalStateException(
"could not encode parameter "+param.getParamName()+" of type: "+param.getClass().getName()
);
}
static class CallResponseImpl implements CallResponse {
private boolean isNull = true;
private Response response;
void setResponse(Response response) {
this.response = response;
}
@Override
public boolean isNull() {
return isNull;
}
void setNull(boolean isNull) {
this.isNull = isNull;
}
@Override
public int getStatusCode() {
return response.code();
}
@Override
public String getStatusMsg() {
return response.message();
}
//TODO: Check if this is needed since we are parsing it in the checkStatus(Respose).
//TODO: It might throw a closed exception since the response would be closed. Remove it after some testing
@Override
public String getErrorBody() {
try (ResponseBody errorBody = response.body()) {
if (errorBody.contentLength() > 0) {
MediaType errorType = errorBody.contentType();
if (errorType != null) {
String errorContentType = errorType.toString();
if (errorContentType != null && errorContentType.startsWith("application/") && errorContentType.contains("json")) {
return errorBody.string();
}
}
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
return null;
}
}
static class SingleCallResponseImpl extends CallResponseImpl implements SingleCallResponse, AutoCloseable {
private Format format;
private ResponseBody responseBody;
SingleCallResponseImpl(Format format) {
this.format = format;
}
void setResponse(Response response) {
super.setResponse(response);
setResponseBody(response.body());
}
void setResponseBody(ResponseBody responseBody) {
if (!checkNull(responseBody, format)) {
this.responseBody = responseBody;
setNull(false);
}
}
@Override
public byte[] asBytes() {
try {
if (responseBody == null) {
return null;
}
byte[] value = responseBody.bytes();
closeImpl();
return value;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public InputStream asInputStream() {
return (responseBody == null) ? null : responseBody.byteStream();
}
@Override
public InputStreamHandle asInputStreamHandle() {
return (responseBody == null) ? null : new InputStreamHandle(asInputStream());
}
@Override
public Reader asReader() {
return (responseBody == null) ? null : responseBody.charStream();
}
@Override
public ReaderHandle asReaderHandle() {
return (responseBody == null) ? null : new ReaderHandle(asReader());
}
@Override
public String asString() {
try {
if (responseBody == null) {
return null;
}
String value = responseBody.string();
closeImpl();
return value;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public void close() throws Exception {
if (responseBody != null) {
closeImpl();
}
}
private void closeImpl() {
responseBody.close();
responseBody = null;
}
}
static class MultipleCallResponseImpl extends CallResponseImpl implements MultipleCallResponse {
private Format format;
private MimeMultipart multipart;
MultipleCallResponseImpl(Format format){
this.format = format;
}
void setResponse(Response response) {
try {
super.setResponse(response);
ResponseBody responseBody = response.body();
if (responseBody == null) {
setNull(true);
return;
}
MediaType contentType = responseBody.contentType();
if (contentType == null) {
setNull(true);
return;
}
ByteArrayDataSource dataSource = new ByteArrayDataSource(
responseBody.byteStream(), contentType.toString()
);
setMultipart(new MimeMultipart(dataSource));
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
void setMultipart(MimeMultipart multipart) {
if (!checkNull(multipart, format)) {
this.multipart = multipart;
setNull(false);
}
}
@Override
public Stream<byte[]> asStreamOfBytes() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<byte[]> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToBytes(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public Stream<InputStreamHandle> asStreamOfInputStreamHandle() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<InputStreamHandle> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(new InputStreamHandle(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<InputStream> asStreamOfInputStream() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<InputStream> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(bodyPart.getInputStream());
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<Reader> asStreamOfReader() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<Reader> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToReader(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<ReaderHandle> asStreamOfReaderHandle() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<ReaderHandle> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(new ReaderHandle(NodeConverter.InputStreamToReader(bodyPart.getInputStream())));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<String> asStreamOfString() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<String> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToString(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
}
static protected boolean checkNull(ResponseBody body, Format format) {
if (body != null) {
if (body.contentLength() == 0) {
body.close();
} else {
MediaType actualType = body.contentType();
String defaultType = (format == Format.BINARY) ?
"application/x-unknown-content-type" : format.getDefaultMimetype();
if (actualType == null) {
body.close();
throw new RuntimeException(
"Returned document with unknown mime type instead of "+defaultType
);
} else if (!actualType.toString().startsWith(defaultType)) {
body.close();
throw new RuntimeException(
"Returned document as "+actualType.toString()+" instead of "+defaultType
);
}
return false;
}
}
return true;
}
static protected boolean checkNull(MimeMultipart multipart, Format format) {
if (multipart != null) {
try {
if (multipart.getCount() != 0) {
BodyPart firstPart = multipart.getBodyPart(0);
String actualType = (firstPart == null) ? null : firstPart.getContentType();
String defaultType = (format == Format.BINARY) ?
"application/x-unknown-content-type" : format.getDefaultMimetype();
if (actualType == null || !actualType.startsWith(defaultType)) {
throw new RuntimeException(
"Returned document as "+actualType+" instead of "+defaultType
);
}
return false;
}
} catch (MessagingException e) {
new MarkLogicIOException(e);
}
}
return true;
}
Request.Builder forDocumentResponse(Request.Builder requestBldr, Format format) {
return requestBldr.addHeader(HEADER_ACCEPT, (format == Format.BINARY) ? "application/x-unknown-content-type" : format.getDefaultMimetype());
}
Request.Builder forMultipartMixedResponse(Request.Builder requestBldr) {
return requestBldr.addHeader(HEADER_ACCEPT, multipartMixedWithBoundary());
}
static protected class Condition {
private boolean is = false;
protected boolean get() {
return is;
}
protected void set() {
if (!is)
is = true;
}
}
}
| marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java | /*
* Copyright 2012-2018 MarkLogic 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 com.marklogic.client.impl;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.*;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.DatabaseClientFactory.BasicAuthContext;
import com.marklogic.client.DatabaseClientFactory.CertificateAuthContext;
import com.marklogic.client.DatabaseClientFactory.DigestAuthContext;
import com.marklogic.client.DatabaseClientFactory.KerberosAuthContext;
import com.marklogic.client.DatabaseClientFactory.SAMLAuthContext;
import com.marklogic.client.DatabaseClientFactory.SSLHostnameVerifier;
import com.marklogic.client.DatabaseClientFactory.SecurityContext;
import com.marklogic.client.bitemporal.TemporalDescriptor;
import com.marklogic.client.bitemporal.TemporalDocumentManager.ProtectionLevel;
import com.marklogic.client.document.ContentDescriptor;
import com.marklogic.client.document.DocumentDescriptor;
import com.marklogic.client.document.DocumentManager.Metadata;
import com.marklogic.client.document.DocumentPage;
import com.marklogic.client.document.DocumentRecord;
import com.marklogic.client.document.DocumentUriTemplate;
import com.marklogic.client.document.DocumentWriteOperation;
import com.marklogic.client.document.DocumentWriteSet;
import com.marklogic.client.document.ServerTransform;
import com.marklogic.client.eval.EvalResult;
import com.marklogic.client.eval.EvalResultIterator;
import com.marklogic.client.io.BytesHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.io.JacksonParserHandle;
import com.marklogic.client.io.OutputStreamSender;
import com.marklogic.client.io.ReaderHandle;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.io.marker.AbstractReadHandle;
import com.marklogic.client.io.marker.AbstractWriteHandle;
import com.marklogic.client.io.marker.ContentHandle;
import com.marklogic.client.io.marker.CtsQueryWriteHandle;
import com.marklogic.client.io.marker.DocumentMetadataReadHandle;
import com.marklogic.client.io.marker.DocumentMetadataWriteHandle;
import com.marklogic.client.io.marker.DocumentPatchHandle;
import com.marklogic.client.io.marker.SearchReadHandle;
import com.marklogic.client.io.marker.StructureWriteHandle;
import com.marklogic.client.query.DeleteQueryDefinition;
import com.marklogic.client.query.QueryDefinition;
import com.marklogic.client.query.QueryManager.QueryView;
import com.marklogic.client.query.RawCombinedQueryDefinition;
import com.marklogic.client.query.RawCtsQueryDefinition;
import com.marklogic.client.query.RawQueryByExampleDefinition;
import com.marklogic.client.query.RawQueryDefinition;
import com.marklogic.client.query.RawStructuredQueryDefinition;
import com.marklogic.client.query.StringQueryDefinition;
import com.marklogic.client.query.StructuredQueryDefinition;
import com.marklogic.client.query.SuggestDefinition;
import com.marklogic.client.query.ValueQueryDefinition;
import com.marklogic.client.query.ValuesDefinition;
import com.marklogic.client.query.ValuesListDefinition;
import com.marklogic.client.semantics.Capability;
import com.marklogic.client.semantics.GraphManager;
import com.marklogic.client.semantics.GraphPermissions;
import com.marklogic.client.semantics.SPARQLBinding;
import com.marklogic.client.semantics.SPARQLBindings;
import com.marklogic.client.semantics.SPARQLQueryDefinition;
import com.marklogic.client.semantics.SPARQLRuleset;
import com.marklogic.client.util.EditableNamespaceContext;
import com.marklogic.client.util.RequestLogger;
import com.marklogic.client.util.RequestParameters;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.ConnectionPool;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartBody.Part;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.BodyPart;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class OkHttpServices implements RESTServices {
static final private Logger logger = LoggerFactory.getLogger(OkHttpServices.class);
static final public String OKHTTP_LOGGINGINTERCEPTOR_LEVEL = "com.marklogic.client.okhttp.httplogginginterceptor.level";
static final public String OKHTTP_LOGGINGINTERCEPTOR_OUTPUT = "com.marklogic.client.okhttp.httplogginginterceptor.output";
static final private String DOCUMENT_URI_PREFIX = "/documents?uri=";
static final private int DELAY_FLOOR = 125;
static final private int DELAY_CEILING = 2000;
static final private int DELAY_MULTIPLIER = 20;
static final private int DEFAULT_MAX_DELAY = 120000;
static final private int DEFAULT_MIN_RETRY = 8;
private final static MediaType URLENCODED_MIME_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
private final static String UTF8_ID = StandardCharsets.UTF_8.toString();
static final private ConnectionPool connectionPool = new ConnectionPool();
private DatabaseClient databaseClient;
private String database = null;
private HttpUrl baseUri;
private OkHttpClient client;
private boolean released = false;
private String headerValue = "Authorization";
private Random randRetry = new Random();
private int maxDelay = DEFAULT_MAX_DELAY;
private int minRetry = DEFAULT_MIN_RETRY;
private boolean checkFirstRequest = true;
private Set<Integer> retryStatus = new HashSet<>();
static protected class ThreadState {
boolean isFirstRequest;
ThreadState(boolean value) {
isFirstRequest = value;
}
}
private final ThreadLocal<ThreadState> threadState = new ThreadLocal<ThreadState>() {
@Override
protected ThreadState initialValue() {
return new ThreadState(checkFirstRequest);
}
};
public OkHttpServices() {
retryStatus.add(STATUS_BAD_GATEWAY);
retryStatus.add(STATUS_SERVICE_UNAVAILABLE);
retryStatus.add(STATUS_GATEWAY_TIMEOUT);
}
@Override
public Set<Integer> getRetryStatus() {
return retryStatus;
}
@Override
public int getMaxDelay() {
return maxDelay;
}
@Override
public void setMaxDelay(int maxDelay) {
this.maxDelay = maxDelay;
}
private FailedRequest extractErrorFields(Response response) {
if ( response == null ) return null;
try {
if ( response.code() == STATUS_UNAUTHORIZED ) {
FailedRequest failure = new FailedRequest();
failure.setMessageString("Unauthorized");
failure.setStatusString("Failed Auth");
return failure;
}
String responseBody = getEntity(response.body(), String.class);
InputStream is = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
FailedRequest handler = FailedRequest.getFailedRequest(response.code(), response.header(HEADER_CONTENT_TYPE), is);
if ( handler.getMessage() == null ) {
handler.setMessageString(responseBody);
}
return handler;
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
} finally {
response.close();
}
}
@Override
@Deprecated
public void connect(String host, int port, String database, String user, String password,Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext,
SSLHostnameVerifier verifier) {
connect(host, port, database, user, password, kerberosOptions, authenType, sslContext, null, verifier);
}
@Override
@Deprecated
public void connect(String host, int port, String database, String user, String password,Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext, X509TrustManager trustManager,
SSLHostnameVerifier verifier) {
HostnameVerifier hostnameVerifier = null;
if (verifier == SSLHostnameVerifier.ANY) {
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (verifier == SSLHostnameVerifier.COMMON) {
hostnameVerifier = null;
} else if (verifier == SSLHostnameVerifier.STRICT) {
hostnameVerifier = null;
} else if (verifier != null) {
hostnameVerifier = new SSLHostnameVerifier.HostnameVerifierAdapter(verifier);
}// else {
// throw new IllegalArgumentException(
// "Null SSLContext but non-null SSLHostnameVerifier for client");
//}
connect(host, port, database, user, password, kerberosOptions, authenType, sslContext, trustManager, hostnameVerifier);
}
private void connect(String host, int port, String database, String user, String password, Map<String,String> kerberosOptions,
Authentication authenType, SSLContext sslContext, X509TrustManager trustManager,
HostnameVerifier verifier) {
logger.debug("Connecting to {} at {} as {}", new Object[]{host, port, user});
if (host == null) throw new IllegalArgumentException("No host provided");
this.database = database;
this.baseUri = new HttpUrl.Builder()
.scheme(sslContext == null ? "http" : "https")
.host(host)
.port(port)
.encodedPath("/v1/ping")
.build();
Credentials credentials = new Credentials(user, password);
final Map<String,CachingAuthenticator> authCache = new ConcurrentHashMap<String,CachingAuthenticator>();
if ( authenType == null && sslContext != null ) {
authenType = Authentication.BASIC;
}
CachingAuthenticator authenticator = null;
Interceptor interceptor = null;
if (authenType == null || authenType == Authentication.CERTIFICATE) {
checkFirstRequest = false;
} else if (authenType == Authentication.KERBEROS) {
interceptor = new HTTPKerberosAuthInterceptor(host, kerberosOptions);
checkFirstRequest = false;
} else {
if (user == null) throw new IllegalArgumentException("No user provided");
if (password == null) throw new IllegalArgumentException("No password provided");
if (authenType == Authentication.BASIC) {
interceptor = new HTTPBasicAuthInterceptor(credentials);
checkFirstRequest = false;
} else if (authenType == Authentication.DIGEST) {
authenticator = new DigestAuthenticator(credentials);
interceptor = new AuthenticationCacheInterceptor(authCache);
checkFirstRequest = true;
} else {
throw new MarkLogicInternalException(
"Internal error - unknown authentication type: " + authenType.name());
}
}
OkHttpClient.Builder clientBldr = new OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
// all clients share a single connection pool
.connectionPool(connectionPool)
// cookies are ignored (except when a Transaction is being used)
.cookieJar(CookieJar.NO_COOKIES)
// no timeouts since some of our clients' reads and writes can be massive
.readTimeout(0, TimeUnit.SECONDS)
.writeTimeout(0, TimeUnit.SECONDS);
if (sslContext != null) {
if (trustManager == null) {
clientBldr.sslSocketFactory(sslContext.getSocketFactory());
} else {
clientBldr.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
}
}
if(authenticator != null) clientBldr.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache));
if(interceptor != null) clientBldr.addInterceptor(interceptor);
if ( verifier != null ) {
clientBldr = clientBldr.hostnameVerifier(verifier);
}
Properties props = System.getProperties();
if (props.containsKey(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) {
final boolean useLogger = "LOGGER".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_OUTPUT));
final boolean useStdErr = "STDERR".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_OUTPUT));
HttpLoggingInterceptor networkInterceptor = new HttpLoggingInterceptor(
new HttpLoggingInterceptor.Logger() {
public void log(String message) {
if ( useLogger == true ) {
logger.debug(message);
} else if ( useStdErr == true ) {
System.err.println(message);
} else {
System.out.println(message);
}
}
}
);
if ( "BASIC".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
} else if ( "BODY".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else if ( "HEADERS".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
} else if ( "NONE".equalsIgnoreCase(props.getProperty(OKHTTP_LOGGINGINTERCEPTOR_LEVEL)) ) {
networkInterceptor = networkInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
clientBldr = clientBldr.addNetworkInterceptor(networkInterceptor);
}
if (props.containsKey(MAX_DELAY_PROP)) {
String maxDelayStr = props.getProperty(MAX_DELAY_PROP);
if (maxDelayStr != null && maxDelayStr.length() > 0) {
int max = Integer.parseInt(maxDelayStr);
if (max > 0) {
maxDelay = max * 1000;
}
}
}
if (props.containsKey(MIN_RETRY_PROP)) {
String minRetryStr = props.getProperty(MIN_RETRY_PROP);
if (minRetryStr != null && minRetryStr.length() > 0) {
int min = Integer.parseInt(minRetryStr);
if (min > 0) {
minRetry = min;
}
}
}
this.client = clientBldr.build();
// System.setProperty("javax.net.debug", "all"); // all or ssl
/*
// long-term alternative to isFirstRequest alive
// HttpProtocolParams.setUseExpectContinue(httpParams, false);
// httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);
*/
}
@Override
public void connect(String host, int port, String database, SecurityContext securityContext){
String user = null;
Map<String, String> kerberosOptions = null;
String password = null;
Authentication type = null;
SSLContext sslContext = null;
SSLHostnameVerifier sslVerifier = null;
X509TrustManager trustManager = null;
if (securityContext instanceof BasicAuthContext) {
BasicAuthContext basicContext = (BasicAuthContext) securityContext;
user = basicContext.getUser();
password = basicContext.getPassword();
type = Authentication.BASIC;
if (basicContext.getSSLContext() != null) {
sslContext = basicContext.getSSLContext();
if (basicContext.getTrustManager() != null)
trustManager = basicContext.getTrustManager();
if (basicContext.getSSLHostnameVerifier() != null) {
sslVerifier = basicContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof DigestAuthContext) {
DigestAuthContext digestContext = (DigestAuthContext) securityContext;
user = digestContext.getUser();
password = digestContext.getPassword();
type = Authentication.DIGEST;
if (digestContext.getSSLContext() != null) {
sslContext = digestContext.getSSLContext();
if (digestContext.getTrustManager() != null)
trustManager = digestContext.getTrustManager();
if (digestContext.getSSLHostnameVerifier() != null) {
sslVerifier = digestContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof KerberosAuthContext) {
KerberosAuthContext kerberosContext = (KerberosAuthContext) securityContext;
kerberosOptions = kerberosContext.getKrbOptions();
type = Authentication.KERBEROS;
if (kerberosContext.getSSLContext() != null) {
sslContext = kerberosContext.getSSLContext();
if (kerberosContext.getTrustManager() != null)
trustManager = kerberosContext.getTrustManager();
if (kerberosContext.getSSLHostnameVerifier() != null) {
sslVerifier = kerberosContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
}
} else if (securityContext instanceof CertificateAuthContext) {
CertificateAuthContext certificateContext = (CertificateAuthContext) securityContext;
type = Authentication.CERTIFICATE;
sslContext = certificateContext.getSSLContext();
if (certificateContext.getTrustManager() != null)
trustManager = certificateContext.getTrustManager();
if (certificateContext.getSSLHostnameVerifier() != null) {
sslVerifier = certificateContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
} else if (securityContext instanceof SAMLAuthContext) {
SAMLAuthContext samlAuthContext = (SAMLAuthContext) securityContext;
type = Authentication.SAML;
sslContext = samlAuthContext.getSSLContext();
headerValue = samlAuthContext.getToken();
if (samlAuthContext.getTrustManager() != null)
trustManager = samlAuthContext.getTrustManager();
if (samlAuthContext.getSSLHostnameVerifier() != null) {
sslVerifier = samlAuthContext.getSSLHostnameVerifier();
} else {
sslVerifier = SSLHostnameVerifier.COMMON;
}
} else {
throw new IllegalArgumentException("securityContext must be of type BasicAuthContext, "
+ "DigestAuthContext, KerberosAuthContext, CertificateAuthContext or SAMLAuthContext");
}
HostnameVerifier hostnameVerifier = null;
if (sslVerifier == SSLHostnameVerifier.ANY) {
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (sslVerifier == SSLHostnameVerifier.COMMON || sslVerifier == SSLHostnameVerifier.STRICT) {
hostnameVerifier = null;
} else if (sslVerifier != null) {
hostnameVerifier = new SSLHostnameVerifier.HostnameVerifierAdapter(sslVerifier);
}
connect(host, port, database, user, password, kerberosOptions, type, sslContext, trustManager,
hostnameVerifier);
}
@Override
public DatabaseClient getDatabaseClient() {
return databaseClient;
}
@Override
public void setDatabaseClient(DatabaseClient client) {
this.databaseClient = client;
}
private OkHttpClient getConnection() {
if ( client != null ) {
return client;
} else if ( released ) {
throw new IllegalStateException(
"You cannot use this connected object anymore--connection has already been released");
} else {
throw new MarkLogicInternalException("Cannot proceed--connection is null for unknown reason");
}
}
@Override
public void release() {
if ( client == null ) return;
try {
released = true;
client.dispatcher().executorService().shutdownNow();
} finally {
try {
if ( client.cache() != null ) client.cache().close();
} catch (IOException e) {
throw new MarkLogicIOException(e);
} finally {
client = null;
logger.debug("Releasing connection");
}
}
}
private boolean isFirstRequest() {
return threadState.get().isFirstRequest;
}
private void setFirstRequest(boolean value) {
threadState.get().isFirstRequest = value;
}
private void checkFirstRequest() {
if (checkFirstRequest) setFirstRequest(true);
}
private int makeFirstRequest(int retry) {
return makeFirstRequest(baseUri, "ping", retry);
}
private int makeFirstRequest(HttpUrl requestUri, String path, int retry) {
Response response = sendRequestOnce(setupRequest(requestUri, path, null).head());
int statusCode = response.code();
if (!retryStatus.contains(statusCode)) {
response.close();
return 0;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
return Math.max(retryAfter, calculateDelay(randRetry, retry));
}
private RequestParameters addTemporalProtectionParams(RequestParameters params, String uri, ProtectionLevel level,
String duration, Calendar expiryTime, String archivePath) {
if (params == null)
params = new RequestParameters();
params.add("uri", uri);
params.add("level", level.toString());
if (duration != null)
params.add("duration", duration);
if (expiryTime != null) {
String formattedSystemTime = DatatypeConverter.printDateTime(expiryTime);
params.add("expireTime", formattedSystemTime);
}
if (archivePath != null)
params.add("archivePath", archivePath);
return params;
}
@Override
public String advanceLsqt(RequestLogger reqlog, String temporalCollection, long lag) {
if (logger.isDebugEnabled())
logger.debug("Advancing LSQT in temporal collection {}", temporalCollection);
logRequest(reqlog, "wiped %s document", temporalCollection);
RequestParameters params = new RequestParameters();
params.add("result", "advance-lsqt");
if ( lag > 0 ) params.add("lag", String.valueOf(lag));
Map<String,List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
postResource(reqlog, "temporal/collections/" + temporalCollection,
null, params, null, null, "advanceLsqt", headers);
List<String> values = headers.get(HEADER_ML_LSQT);
if ( values != null && values.size() > 0 ) {
return values.get(0);
} else {
throw new FailedRequestException("Response missing header \"" + HEADER_ML_LSQT + "\"");
}
}
@Override
public void protectDocument(RequestLogger requestLogger, String temporalDocumentURI, Transaction transaction,
RequestParameters extraParams, ProtectionLevel level, String duration,
Calendar expiryTime, String archivePath) {
if (temporalDocumentURI == null)
throw new IllegalArgumentException(
"Document protection for document identifier without uri");
extraParams = addTemporalProtectionParams(extraParams, temporalDocumentURI, level, duration, expiryTime, archivePath);
if (logger.isDebugEnabled())
logger.debug("Protecting {} in transaction {}", temporalDocumentURI, getTransactionId(transaction));
postResource(requestLogger, "documents/protection", transaction, extraParams, null, null, "protect");
}
@Override
public void wipeDocument(RequestLogger reqlog, String temporalDocumentURI, Transaction transaction,
RequestParameters extraParams) {
if (logger.isDebugEnabled())
logger.debug("Wiping {} in transaction {}", temporalDocumentURI, getTransactionId(transaction));
extraParams.add("result", "wiped");
extraParams.add("uri", temporalDocumentURI);
deleteResource(reqlog, "documents", transaction, extraParams, null);
logRequest(reqlog, "wiped %s document", temporalDocumentURI);
}
@Override
public TemporalDescriptor deleteDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document delete for document identifier without uri");
}
logger.debug("Deleting {} in transaction {}", uri, getTransactionId(transaction));
Request.Builder requestBldr = makeDocumentResource(makeDocumentParams(uri,
categories, transaction, extraParams));
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
response.close();
throw new ResourceNotFoundException(
"Could not delete non-existent document");
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to delete document", failure);
}
throw new FailedRequestException(
"Precondition required to delete document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to delete documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to delete document",
failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
Headers responseHeaders = response.headers();
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
logRequest(reqlog, "deleted %s document", uri);
return temporalDesc;
}
@Override
public boolean getDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories,
RequestParameters extraParams,
DocumentMetadataReadHandle metadataHandle,
AbstractReadHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataFormat = null;
String metadataMimetype = null;
if (metadataBase != null) {
metadataFormat = metadataBase.getFormat().toString().toLowerCase();
metadataMimetype = metadataBase.getMimetype();
}
String contentMimetype = null;
if (contentBase != null) {
contentMimetype = contentBase.getMimetype();
}
if (metadataBase != null && contentBase != null) {
return getDocumentImpl(reqlog, desc, transaction, categories,
extraParams, metadataFormat, metadataHandle, contentHandle);
} else if (metadataBase != null) {
return getDocumentImpl(reqlog, desc, transaction, categories,
extraParams, metadataMimetype, metadataHandle);
} else if (contentBase != null) {
return getDocumentImpl(reqlog, desc, transaction, null,
extraParams, contentMimetype, contentHandle);
}
return false;
}
private int getRetryAfterTime(Response response) {
String retryAfterRaw = response.header("Retry-After");
return (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
}
private Response sendRequestOnce(Request.Builder requestBldr) {
return sendRequestOnce(requestBldr.build());
}
private Response sendRequestOnce(Request request) {
try {
return getConnection().newCall(request).execute();
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
private Response sendRequestWithRetry(Request.Builder requestBldr, Function<Request.Builder, Response> doFunction, Consumer<Boolean> resendableConsumer) {
return sendRequestWithRetry(requestBldr, true, doFunction, resendableConsumer);
}
private Response sendRequestWithRetry(
Request.Builder requestBldr, boolean isRetryable, Function<Request.Builder, Response> doFunction, Consumer<Boolean> resendableConsumer
) {
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
/*
* This loop is for retrying the request if the service is unavailable
*/
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try { Thread.sleep(nextDelay);} catch (InterruptedException e) {}
}
/*
* Execute the function which is passed as an argument
* in order to get the Response
*/
response = doFunction.apply(requestBldr);
status = response.code();
if (!isRetryable || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
/*
* If we don't get a service unavailable status or if the request
* is not retryable, we break from the retrying loop and return
* the response
*/
break;
}
/*
* This code will be executed whenever the service is unavailable.
* When the service becomes unavailable, we close the Response
* we got and retry it to try and get a new Response
*/
response.close();
/*
* There are scenarios where we don't want to retry and we just want to
* throw ResourceNotResendableException. In that case, we pass that code from
* the caller through the Consumer and execute it here. In the rest of the
* scenarios, we pass it as null and it is just a no-operation.
*/
if(resendableConsumer != null) resendableConsumer.accept(null);
/*
* Calculate the delay before which we shouldn't retry
*/
nextDelay = Math.max(getRetryAfterTime(response), calculateDelay(randRetry, retry));
}
/*
* If the service is still unavailable after all the retries, we throw a
* FailedRetryException indicating that the service is unavailable.
*/
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
/*
* Once we break from the retry loop, we just return the Response
* back to the caller in order to proceed with the flow
*/
return response;
}
private boolean getDocumentImpl(RequestLogger reqlog,
DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, RequestParameters extraParams,
String mimetype, AbstractReadHandle handle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document read for document identifier without uri");
}
logger.debug("Getting {} in transaction {}", uri, getTransactionId(transaction));
addPointInTimeQueryParam(extraParams, handle);
Request.Builder requestBldr = makeDocumentResource(
makeDocumentParams(uri, categories, transaction, extraParams));
if ( mimetype != null ) {
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
}
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (extraParams != null && extraParams.containsKey("range")) {
requestBldr = requestBldr.header("range", extraParams.get("range").get(0));
}
requestBldr = addVersionHeader(desc, requestBldr, "If-None-Match");
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not read non-existent document",
extractErrorFields(response));
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to read documents",
extractErrorFields(response));
}
if (status == STATUS_NOT_MODIFIED) {
response.close();
return false;
}
if (status != STATUS_OK && status != STATUS_PARTIAL_CONTENT) {
throw new FailedRequestException("read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(
reqlog,
"read %s document from %s transaction with %s mime type and %s metadata categories",
uri, (transaction != null) ? transaction.getTransactionId() : "no",
(mimetype != null) ? mimetype : "no",
stringJoin(categories, ", ", "no"));
HandleImplementation handleBase = HandleAccessor.as(handle);
Headers responseHeaders = response.headers();
if (isExternalDescriptor(desc)) {
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
copyDescriptor(desc, handleBase);
} else {
updateDescriptor(handleBase, responseHeaders);
}
Class as = handleBase.receiveAs();
ResponseBody body = response.body();
Object entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (!InputStream.class.isAssignableFrom(as) && !Reader.class.isAssignableFrom(as))) {
response.close();
}
handleBase.receiveContent((reqlog != null) ? reqlog.copyContent(entity) : entity);
return true;
}
@Override
public DocumentPage getBulkDocuments(RequestLogger reqlog, long serverTimestamp,
Transaction transaction, Set<Metadata> categories,
Format format, RequestParameters extraParams, boolean withContent, String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
boolean hasMetadata = categories != null && categories.size() > 0;
OkHttpResultIterator iterator =
getBulkDocumentsImpl(reqlog, serverTimestamp, transaction, categories, format, extraParams,
withContent, uris);
return new OkHttpDocumentPage(iterator, withContent, hasMetadata);
}
@Override
public DocumentPage getBulkDocuments(RequestLogger reqlog, long serverTimestamp,
QueryDefinition querydef,
long start, long pageLength,
Transaction transaction,
SearchReadHandle searchHandle, QueryView view,
Set<Metadata> categories, Format format, ServerTransform responseTransform,
RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
boolean hasMetadata = categories != null && categories.size() > 0;
boolean hasContent = true;
OkHttpResultIterator iterator =
getBulkDocumentsImpl(reqlog, serverTimestamp, querydef, start, pageLength, transaction,
searchHandle, view, categories, format, responseTransform, extraParams);
return new OkHttpDocumentPage(iterator, hasContent, hasMetadata);
}
private class OkHttpDocumentPage extends BasicPage<DocumentRecord> implements DocumentPage, Iterator<DocumentRecord> {
private OkHttpResultIterator iterator;
private Iterator<DocumentRecord> docRecordIterator;
private boolean hasMetadata;
private boolean hasContent;
OkHttpDocumentPage(OkHttpResultIterator iterator, boolean hasContent, boolean hasMetadata) {
super(
new ArrayList<DocumentRecord>().iterator(),
iterator != null ? iterator.getStart() : 1,
iterator != null ? iterator.getPageSize() : 0,
iterator != null ? iterator.getTotalSize() : 0
);
this.iterator = iterator;
this.hasContent = hasContent;
this.hasMetadata = hasMetadata;
if ( iterator == null ) {
setSize(0);
} else if ( hasContent && hasMetadata ) {
setSize(iterator.getSize() / 2);
} else {
setSize(iterator.getSize());
}
}
@Override
public Iterator<DocumentRecord> iterator() {
return this;
}
@Override
public boolean hasNext() {
if ( iterator == null ) return false;
return iterator.hasNext();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public DocumentRecord next() {
if ( iterator == null ) throw new NoSuchElementException("No documents available");
OkHttpResult result = iterator.next();
DocumentRecord record;
if ( hasContent && hasMetadata ) {
OkHttpResult metadata = result;
OkHttpResult content = iterator.next();
record = new OkHttpDocumentRecord(content, metadata);
} else if ( hasContent ) {
OkHttpResult content = result;
record = new OkHttpDocumentRecord(content);
} else if ( hasMetadata ) {
OkHttpResult metadata = result;
record = new OkHttpDocumentRecord(null, metadata);
} else {
throw new IllegalStateException("Should never have neither content nor metadata");
}
return record;
}
@Override
public <T extends AbstractReadHandle> T nextContent(T contentHandle) {
return next().getContent(contentHandle);
}
@Override
public void close() {
if ( iterator != null ) iterator.close();
}
}
private OkHttpResultIterator getBulkDocumentsImpl(RequestLogger reqlog, long serverTimestamp,
Transaction transaction, Set<Metadata> categories,
Format format, RequestParameters extraParams, boolean withContent,
String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String path = "documents";
RequestParameters params = new RequestParameters();
if ( extraParams != null ) params.putAll(extraParams);
if (serverTimestamp != -1) params.add("timestamp", Long.toString(serverTimestamp));
addCategoryParams(categories, params, withContent);
if (format != null) params.add("format", format.toString().toLowerCase());
for (String uri: uris) {
if ( uri != null && uri.length() > 0 ) {
params.add("uri", uri);
}
}
OkHttpResultIterator iterator = getIteratedResourceImpl(DefaultOkHttpResultIterator.class,
reqlog, path, transaction, params, MIMETYPE_MULTIPART_MIXED);
if ( iterator != null ) {
if ( iterator.getStart() == -1 ) iterator.setStart(1);
if ( iterator.getSize() != -1 ) {
if ( iterator.getPageSize() == -1 ) iterator.setPageSize(iterator.getSize());
if ( iterator.getTotalSize() == -1 ) iterator.setTotalSize(iterator.getSize());
}
}
return iterator;
}
private OkHttpResultIterator getBulkDocumentsImpl(RequestLogger reqlog, long serverTimestamp,
QueryDefinition querydef, long start, long pageLength,
Transaction transaction, SearchReadHandle searchHandle, QueryView view,
Set<Metadata> categories, Format format, ServerTransform responseTransform,
RequestParameters extraParams)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
try {
RequestParameters params = new RequestParameters();
if ( extraParams != null ) params.putAll(extraParams);
boolean withContent = true;
addCategoryParams(categories, params, withContent);
if ( searchHandle != null && view != null ) params.add("view", view.toString().toLowerCase());
if ( start > 1 ) params.add("start", Long.toString(start));
if ( pageLength >= 0 ) params.add("pageLength", Long.toString(pageLength));
if (serverTimestamp != -1) params.add("timestamp", Long.toString(serverTimestamp));
addPointInTimeQueryParam(params, searchHandle);
if ( format != null ) params.add("format", format.toString().toLowerCase());
HandleImplementation handleBase = HandleAccessor.as(searchHandle);
if ( format == null && searchHandle != null ) {
if ( Format.XML == handleBase.getFormat() ) {
params.add("format", "xml");
} else if ( Format.JSON == handleBase.getFormat() ) {
params.add("format", "json");
}
}
OkHttpSearchRequest request =
generateSearchRequest(reqlog, querydef, MIMETYPE_MULTIPART_MIXED, transaction, responseTransform, params, null);
Response response = request.getResponse();
if ( response == null ) return null;
MimeMultipart entity = null;
if ( searchHandle != null ) {
updateServerTimestamp(handleBase, response.headers());
ResponseBody body = response.body();
if ( body.contentLength() != 0 ) {
entity = getEntity(body, MimeMultipart.class);
if ( entity != null ) {
List<BodyPart> partList = getPartList(entity);
if ( entity.getCount() > 0 ) {
BodyPart searchResponsePart = entity.getBodyPart(0);
handleBase.receiveContent(getEntity(searchResponsePart, handleBase.receiveAs()));
partList = partList.subList(1, partList.size());
}
Closeable closeable = response;
return makeResults(OkHttpServiceResultIterator.class, reqlog, "read", "resource", partList, response,
closeable);
}
}
}
return makeResults(OkHttpServiceResultIterator.class, reqlog, "read", "resource", response);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private boolean getDocumentImpl(RequestLogger reqlog,
DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, RequestParameters extraParams,
String metadataFormat, DocumentMetadataReadHandle metadataHandle,
AbstractReadHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
if (uri == null) {
throw new IllegalArgumentException(
"Document read for document identifier without uri");
}
assert metadataHandle != null : "metadataHandle is null";
assert contentHandle != null : "contentHandle is null";
logger.debug("Getting multipart for {} in transaction {}", uri, getTransactionId(transaction));
addPointInTimeQueryParam(extraParams, contentHandle);
RequestParameters docParams = makeDocumentParams(uri, categories, transaction, extraParams, true);
docParams.add("format", metadataFormat);
Request.Builder requestBldr = makeDocumentResource(docParams);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
requestBldr = addVersionHeader(desc, requestBldr, "If-None-Match");
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.addHeader(HEADER_ACCEPT, multipartMixedWithBoundary()).get());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not read non-existent document",
extractErrorFields(response));
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to read documents",
extractErrorFields(response));
}
if (status == STATUS_NOT_MODIFIED) {
response.close();
return false;
}
if (status != STATUS_OK) {
throw new FailedRequestException("read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(
reqlog,
"read %s document from %s transaction with %s metadata categories and content",
uri, (transaction != null) ? transaction.getTransactionId() : "no", stringJoin(categories, ", ", "no"));
try {
ResponseBody body = response.body();
MimeMultipart entity = body.contentLength() != 0 ?
getEntity(body, MimeMultipart.class) : null;
if (entity == null) return false;
int partCount = entity.getCount();
if (partCount == 0) return false;
List<BodyPart> partList = getPartList(entity);
if (partCount != 2) {
throw new FailedRequestException("read expected 2 parts but got " + partCount + " parts",
extractErrorFields(response));
}
HandleImplementation metadataBase = HandleAccessor.as(metadataHandle);
HandleImplementation contentBase = HandleAccessor.as(contentHandle);
BodyPart contentPart = partList.get(1);
Headers responseHeaders = response.headers();
if (isExternalDescriptor(desc)) {
updateVersion(desc, responseHeaders);
updateFormat(desc, responseHeaders);
updateMimetype(desc, getHeaderMimetype(getHeader(contentPart, HEADER_CONTENT_TYPE)));
updateLength(desc, getHeaderLength(getHeader(contentPart, HEADER_CONTENT_LENGTH)));
copyDescriptor(desc, contentBase);
} else {
updateDescriptor(contentBase, responseHeaders);
}
metadataBase.receiveContent(getEntity(partList.get(0),
metadataBase.receiveAs()));
Object contentEntity = getEntity(contentPart, contentBase.receiveAs());
contentBase.receiveContent((reqlog != null) ? reqlog.copyContent(contentEntity) : contentEntity);
response.close();
return true;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public DocumentDescriptor head(RequestLogger reqlog, String uri,
Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
Response response = headImpl(reqlog, uri, transaction, makeDocumentResource(makeDocumentParams(uri,
null, transaction, null)));
// 404
if (response == null) return null;
Headers responseHeaders = response.headers();
response.close();
logRequest(reqlog, "checked %s document from %s transaction", uri,
(transaction != null) ? transaction.getTransactionId() : "no");
DocumentDescriptorImpl desc = new DocumentDescriptorImpl(uri, false);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
return desc;
}
@Override
public boolean exists(String uri) throws ForbiddenUserException, FailedRequestException {
return headImpl(null, uri, null, setupRequest(uri, null)) == null ? false : true;
}
private Response headImpl(RequestLogger reqlog, String uri,
Transaction transaction, Request.Builder requestBldr) {
if (uri == null) {
throw new IllegalArgumentException(
"Existence check for document identifier without uri");
}
logger.debug("Requesting head for {} in transaction {}", uri, getTransactionId(transaction));
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doHeadFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.head().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doHeadFunction, null);
int status = response.code();
if (status != STATUS_OK) {
if (status == STATUS_NOT_FOUND) {
response.close();
return null;
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to check the existence of documents",
extractErrorFields(response));
} else {
throw new FailedRequestException(
"Document existence check failed: "
+ getReasonPhrase(response),
extractErrorFields(response));
}
}
return response;
}
@Override
public TemporalDescriptor putDocument(RequestLogger reqlog, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories,
RequestParameters extraParams,
DocumentMetadataWriteHandle metadataHandle,
AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if (desc.getUri() == null) {
throw new IllegalArgumentException(
"Document write for document identifier without uri");
}
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataMimetype = null;
if (metadataBase != null) {
metadataMimetype = metadataBase.getMimetype();
}
Format descFormat = desc.getFormat();
String contentMimetype = (descFormat != null && descFormat != Format.UNKNOWN) ? desc.getMimetype() : null;
if (contentMimetype == null && contentBase != null) {
Format contentFormat = contentBase.getFormat();
if (descFormat != null && descFormat != contentFormat) {
contentMimetype = descFormat.getDefaultMimetype();
} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {
contentMimetype = contentBase.getMimetype();
}
}
if (metadataBase != null && contentBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, categories,
extraParams, metadataMimetype, metadataHandle,
contentMimetype, contentHandle);
} else if (metadataBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, categories, false,
extraParams, metadataMimetype, metadataHandle);
} else if (contentBase != null) {
return putPostDocumentImpl(reqlog, "put", desc, transaction, null, true,
extraParams, contentMimetype, contentHandle);
}
throw new IllegalArgumentException("Either metadataHandle or contentHandle must not be null");
}
@Override
public DocumentDescriptorImpl postDocument(RequestLogger reqlog, DocumentUriTemplate template,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams,
DocumentMetadataWriteHandle metadataHandle, AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
DocumentDescriptorImpl desc = new DocumentDescriptorImpl(false);
HandleImplementation metadataBase = HandleAccessor.checkHandle(
metadataHandle, "metadata");
HandleImplementation contentBase = HandleAccessor.checkHandle(
contentHandle, "content");
String metadataMimetype = null;
if (metadataBase != null) {
metadataMimetype = metadataBase.getMimetype();
}
Format templateFormat = template.getFormat();
String contentMimetype = (templateFormat != null && templateFormat != Format.UNKNOWN) ?
template.getMimetype() : null;
if (contentMimetype == null && contentBase != null) {
Format contentFormat = contentBase.getFormat();
if (templateFormat != null && templateFormat != contentFormat) {
contentMimetype = templateFormat.getDefaultMimetype();
desc.setFormat(templateFormat);
} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {
contentMimetype = contentBase.getMimetype();
desc.setFormat(contentFormat);
}
}
desc.setMimetype(contentMimetype);
if (extraParams == null) extraParams = new RequestParameters();
String extension = template.getExtension();
if (extension != null) extraParams.add("extension", extension);
String directory = template.getDirectory();
if (directory != null) extraParams.add("directory", directory);
if (metadataBase != null && contentBase != null) {
putPostDocumentImpl(reqlog, "post", desc, transaction, categories, extraParams,
metadataMimetype, metadataHandle, contentMimetype, contentHandle);
} else if (contentBase != null) {
putPostDocumentImpl(reqlog, "post", desc, transaction, null, true, extraParams,
contentMimetype, contentHandle);
}
return desc;
}
private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, boolean isOnContent, RequestParameters extraParams,
String mimetype, AbstractWriteHandle handle)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
HandleImplementation handleBase = HandleAccessor.as(handle);
logger.debug("Sending {} document in transaction {}",
(uri != null) ? uri : "new", getTransactionId(transaction));
logRequest(
reqlog,
"writing %s document from %s transaction with %s mime type and %s metadata categories",
(uri != null) ? uri : "new",
(transaction != null) ? transaction.getTransactionId() : "no",
(mimetype != null) ? mimetype : "no",
stringJoin(categories, ", ", "no"));
Request.Builder requestBldr = makeDocumentResource(
makeDocumentParams(
uri, categories, transaction, extraParams, isOnContent
));
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE,
(mimetype != null) ? mimetype : MIMETYPE_WILDCARD);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (uri != null) {
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
}
if ("patch".equals(method)) {
requestBldr = requestBldr.header("X-HTTP-Method-Override", "PATCH");
method = "post";
}
boolean isResendable = handleBase.isResendable();
Response response = null;
int status = -1;
Headers responseHeaders = null;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
Object value = handleBase.sendContent();
if (value == null) {
throw new IllegalArgumentException(
"Document write with null value for " + ((uri != null) ? uri : "new document"));
}
if (isFirstRequest() && !isResendable && isStreaming(value)) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if (value instanceof OutputStreamSender) {
StreamingOutputImpl sentStream =
new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType);
requestBldr =
("put".equals(method)) ?
requestBldr.put(sentStream) :
requestBldr.post(sentStream);
} else {
Object sentObj = (reqlog != null) ?
reqlog.copyContent(value) : value;
requestBldr =
("put".equals(method)) ?
requestBldr.put(new ObjectRequestBody(sentObj, mediaType)) :
requestBldr.post(new ObjectRequestBody(sentObj, mediaType));
}
response = sendRequestOnce(requestBldr);
status = response.code();
responseHeaders = response.headers();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " +
((uri != null) ? uri : "new document"));
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(
"Could not write non-existent document",
extractErrorFields(response));
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to write document", failure);
}
throw new FailedRequestException(
"Precondition required to write document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to write documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to write document", failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status == -1) {
throw new FailedRequestException("write failed: Unknown Reason", extractErrorFields(response));
}
if (status != STATUS_CREATED && status != STATUS_NO_CONTENT) {
throw new FailedRequestException("write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
if (uri == null) {
String location = response.header("Location");
if (location != null) {
int offset = location.indexOf(DOCUMENT_URI_PREFIX);
if (offset == -1) {
throw new MarkLogicInternalException(
"document create produced invalid location: " + location);
}
uri = location.substring(offset + DOCUMENT_URI_PREFIX.length());
if (uri == null) {
throw new MarkLogicInternalException(
"document create produced location without uri: " + location);
}
desc.setUri(uri);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
}
}
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
return temporalDesc;
}
private TemporalDescriptor putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,
Transaction transaction, Set<Metadata> categories, RequestParameters extraParams,
String metadataMimetype, DocumentMetadataWriteHandle metadataHandle, String contentMimetype,
AbstractWriteHandle contentHandle)
throws ResourceNotFoundException, ResourceNotResendableException,ForbiddenUserException, FailedRequestException
{
String uri = desc.getUri();
logger.debug("Sending {} multipart document in transaction {}",
(uri != null) ? uri : "new", getTransactionId(transaction));
logRequest(
reqlog,
"writing %s document from %s transaction with %s metadata categories and content",
(uri != null) ? uri : "new",
(transaction != null) ? transaction.getTransactionId() : "no",
stringJoin(categories, ", ", "no"));
RequestParameters docParams =
makeDocumentParams(uri, categories, transaction, extraParams, true);
Request.Builder requestBldr = makeDocumentResource(docParams)
.addHeader(HEADER_ACCEPT, MIMETYPE_MULTIPART_MIXED);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
if (uri != null) {
requestBldr = addVersionHeader(desc, requestBldr, "If-Match");
}
Response response = null;
int status = -1;
Headers responseHeaders = null;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog,
new String[] { metadataMimetype, contentMimetype },
new AbstractWriteHandle[] { metadataHandle, contentHandle });
if (isFirstRequest() && hasStreamingPart) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
requestBldr = ("put".equals(method)) ? requestBldr.put(multiPart.build()) : requestBldr.post(multiPart.build());
response = sendRequestOnce(requestBldr);
status = response.code();
responseHeaders = response.headers();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " +
((uri != null) ? uri : "new document"));
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
response.close();
throw new ResourceNotFoundException(
"Could not write non-existent document");
}
if (status == STATUS_PRECONDITION_REQUIRED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTNOVERSION")) {
throw new FailedRequestException(
"Content version required to write document", failure);
}
throw new FailedRequestException(
"Precondition required to write document", failure);
} else if (status == STATUS_FORBIDDEN) {
FailedRequest failure = extractErrorFields(response);
throw new ForbiddenUserException(
"User is not allowed to write documents", failure);
}
if (status == STATUS_PRECONDITION_FAILED) {
FailedRequest failure = extractErrorFields(response);
if (failure.getMessageCode().equals("RESTAPI-CONTENTWRONGVERSION")) {
throw new FailedRequestException(
"Content version must match to write document", failure);
} else if (failure.getMessageCode().equals("RESTAPI-EMPTYBODY")) {
throw new FailedRequestException(
"Empty request body sent to server", failure);
}
throw new FailedRequestException("Precondition Failed", failure);
}
if (status != STATUS_CREATED && status != STATUS_NO_CONTENT) {
throw new FailedRequestException("write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
if (uri == null) {
String location = response.header("Location");
if (location != null) {
int offset = location.indexOf(DOCUMENT_URI_PREFIX);
if (offset == -1) {
throw new MarkLogicInternalException(
"document create produced invalid location: " + location);
}
uri = location.substring(offset + DOCUMENT_URI_PREFIX.length());
if (uri == null) {
throw new MarkLogicInternalException(
"document create produced location without uri: " + location);
}
desc.setUri(uri);
updateVersion(desc, responseHeaders);
updateDescriptor(desc, responseHeaders);
}
}
TemporalDescriptor temporalDesc = updateTemporalSystemTime(desc, responseHeaders);
response.close();
return temporalDesc;
}
@Override
public void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, boolean isOnContent, DocumentPatchHandle patchHandle)
throws ResourceNotFoundException, ResourceNotResendableException,ForbiddenUserException, FailedRequestException
{
patchDocument(reqlog, desc, transaction, categories, isOnContent, null, null, patchHandle);
}
@Override
public void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, Transaction transaction,
Set<Metadata> categories, boolean isOnContent, RequestParameters extraParams, String sourceDocumentURI,
DocumentPatchHandle patchHandle)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
HandleImplementation patchBase = HandleAccessor.checkHandle(patchHandle, "patch");
if(sourceDocumentURI != null)
extraParams.add("source-document", sourceDocumentURI);
putPostDocumentImpl(reqlog, "patch", desc, transaction, categories, isOnContent, extraParams, patchBase.getMimetype(),
patchHandle);
}
@Override
public Transaction openTransaction(String name, int timeLimit) throws ForbiddenUserException, FailedRequestException {
logger.debug("Opening transaction");
RequestParameters transParams = new RequestParameters();
if ( name != null || timeLimit > 0 ) {
if ( name != null ) transParams.add("name", name);
if ( timeLimit > 0 ) transParams.add("timeLimit", String.valueOf(timeLimit));
}
Request.Builder requestBldr = setupRequest("transactions", transParams);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.post(RequestBody.create(null, "")));
}
};
Response response = sendRequestWithRetry(requestBldr, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to open transactions", extractErrorFields(response));
}
if (status != STATUS_SEE_OTHER) {
throw new FailedRequestException("transaction open failed: " +
getReasonPhrase(response), extractErrorFields(response));
}
String location = response.headers().get("Location");
String hostId = null;
List<ClientCookie> cookies = new ArrayList<>();
for ( String setCookie : response.headers(HEADER_SET_COOKIE) ) {
ClientCookie cookie = ClientCookie.parse(requestBldr.build().url(), setCookie);
cookies.add(cookie);
if ( "HostId".equalsIgnoreCase(cookie.getName()) ) {
hostId = cookie.getValue();
}
}
response.close();
if (location == null) throw new MarkLogicInternalException("transaction open failed to provide location");
if (!location.contains("/")) {
throw new MarkLogicInternalException("transaction open produced invalid location: " + location);
}
String transactionId = location.substring(location.lastIndexOf("/") + 1);
return new TransactionImpl(this, transactionId, cookies);
}
@Override
public void commitTransaction(Transaction transaction) throws ForbiddenUserException, FailedRequestException {
completeTransaction(transaction, "commit");
}
@Override
public void rollbackTransaction(Transaction transaction) throws ForbiddenUserException, FailedRequestException {
completeTransaction(transaction, "rollback");
}
private void completeTransaction(Transaction transaction, String result)
throws ForbiddenUserException, FailedRequestException
{
if (result == null) {
throw new MarkLogicInternalException(
"transaction completion without operation");
}
if (transaction == null) {
throw new MarkLogicInternalException(
"transaction completion without id: " + result);
}
logger.debug("Completing transaction {} with {}", transaction.getTransactionId(), result);
RequestParameters transParams = new RequestParameters();
transParams.add("result", result);
Request.Builder requestBldr = setupRequest("transactions/" + transaction.getTransactionId(), transParams);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.post(RequestBody.create(null, "")).build());
}
};
Response response = sendRequestWithRetry(requestBldr, false, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to complete transaction with "
+ result, extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("transaction " + result
+ " failed: " + getReasonPhrase(response),
extractErrorFields(response));
}
response.close();
}
private void addCategoryParams(Set<Metadata> categories, RequestParameters params,
boolean withContent)
{
if (withContent && categories == null || categories.size() == 0) {
params.add("category", "content");
} else {
if (withContent) params.add("category", "content");
if (categories.contains(Metadata.ALL)) {
params.add("category", "metadata");
} else {
for (Metadata category : categories) {
params.add("category", category.name().toLowerCase());
}
}
}
}
private RequestParameters makeDocumentParams(String uri,
Set<Metadata> categories, Transaction transaction,
RequestParameters extraParams) {
return makeDocumentParams(uri, categories, transaction, extraParams,
false);
}
private RequestParameters makeDocumentParams(String uri, Set<Metadata> categories, Transaction transaction,
RequestParameters extraParams, boolean withContent)
{
RequestParameters docParams = new RequestParameters();
if (extraParams != null && extraParams.size() > 0) {
for ( Map.Entry<String, List<String>> entry : extraParams.entrySet() ) {
for ( String value : entry.getValue() ) {
String extraKey = entry.getKey();
if ( !"range".equalsIgnoreCase(extraKey) ) {
docParams.add(extraKey, value);
}
}
}
}
if ( uri != null ) docParams.add("uri", uri);
if (categories == null || categories.size() == 0) {
docParams.add("category", "content");
} else {
if (withContent) {
docParams.add("category", "content");
}
if (categories.contains(Metadata.ALL)) {
docParams.add("category", "metadata");
} else {
for (Metadata category : categories) {
docParams.add("category", category.toString().toLowerCase());
}
}
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
return docParams;
}
private Request.Builder makeDocumentResource(RequestParameters queryParams) {
return setupRequest("documents", queryParams);
}
private boolean isExternalDescriptor(ContentDescriptor desc) {
return desc != null && desc instanceof DocumentDescriptorImpl
&& !((DocumentDescriptorImpl) desc).isInternal();
}
private void updateDescriptor(ContentDescriptor desc,
Headers headers) {
if (desc == null || headers == null) return;
updateFormat(desc, headers);
updateMimetype(desc, headers);
updateLength(desc, headers);
updateServerTimestamp(desc, headers);
}
private TemporalDescriptor updateTemporalSystemTime(DocumentDescriptor desc,
Headers headers)
{
if (headers == null) return null;
DocumentDescriptorImpl temporalDescriptor;
if ( desc instanceof DocumentDescriptorImpl ) {
temporalDescriptor = (DocumentDescriptorImpl) desc;
} else {
temporalDescriptor = new DocumentDescriptorImpl(desc.getUri(), false);
}
temporalDescriptor.setTemporalSystemTime(headers.get(HEADER_X_MARKLOGIC_SYSTEM_TIME));
return temporalDescriptor;
}
private void copyDescriptor(DocumentDescriptor desc,
HandleImplementation handleBase) {
if (handleBase == null) return;
if (desc.getFormat() != null) handleBase.setFormat(desc.getFormat());
if (desc.getMimetype() != null) handleBase.setMimetype(desc.getMimetype());
handleBase.setByteLength(desc.getByteLength());
}
private void updateFormat(ContentDescriptor descriptor,
Headers headers) {
updateFormat(descriptor, getHeaderFormat(headers));
}
private void updateFormat(ContentDescriptor descriptor, Format format) {
if (format != null) {
descriptor.setFormat(format);
}
}
private Format getHeaderFormat(Headers headers) {
String format = headers.get(HEADER_VND_MARKLOGIC_DOCUMENT_FORMAT);
if (format != null) {
return Format.valueOf(format.toUpperCase());
}
return null;
}
private Format getHeaderFormat(BodyPart part) {
String contentDisposition = getHeader(part, HEADER_CONTENT_DISPOSITION);
String formatRegex = ".* format=(text|binary|xml|json).*";
String format = getHeader(part, HEADER_VND_MARKLOGIC_DOCUMENT_FORMAT);
String contentType = getHeader(part, HEADER_CONTENT_TYPE);
if ( format != null && format.length() > 0 ) {
return Format.valueOf(format.toUpperCase());
} else if ( contentDisposition != null && contentDisposition.matches(formatRegex) ) {
format = contentDisposition.replaceFirst("^.*" + formatRegex + ".*$", "$1");
return Format.valueOf(format.toUpperCase());
} else if ( contentType != null && contentType.length() > 0 ) {
return Format.getFromMimetype(contentType);
}
return null;
}
private void updateMimetype(ContentDescriptor descriptor,
Headers headers) {
updateMimetype(descriptor, getHeaderMimetype(headers.get(HEADER_CONTENT_TYPE)));
}
private void updateMimetype(ContentDescriptor descriptor, String mimetype) {
if (mimetype != null) {
descriptor.setMimetype(mimetype);
}
}
private String getHeader(Map<String, List<String>> headers, String name) {
List<String> values = headers.get(name);
if ( values != null && values.size() > 0 ) {
return values.get(0);
}
return null;
}
private static String getHeader(BodyPart part, String name) {
if ( part == null ) throw new MarkLogicInternalException("part must not be null");
try {
String[] values = part.getHeader(name);
if ( values != null && values.length > 0 ) {
return values[0];
}
return null;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private String getHeaderMimetype(String contentType) {
if (contentType != null) {
String mimetype = contentType.contains(";")
? contentType.substring(0, contentType.indexOf(";"))
: contentType;
// TODO: if "; charset=foo" set character set
if (mimetype != null && mimetype.length() > 0) {
return mimetype;
}
}
return null;
}
private void updateLength(ContentDescriptor descriptor,
Headers headers) {
updateLength(descriptor, getHeaderLength(headers.get(HEADER_CONTENT_LENGTH)));
}
private void updateLength(ContentDescriptor descriptor, long length) {
descriptor.setByteLength(length);
}
private void updateServerTimestamp(ContentDescriptor descriptor,
Headers headers) {
updateServerTimestamp(descriptor, getHeaderServerTimestamp(headers));
}
private long getHeaderServerTimestamp(Headers headers) {
String timestamp = headers.get(HEADER_ML_EFFECTIVE_TIMESTAMP);
if (timestamp != null && timestamp.length() > 0) {
return Long.parseLong(timestamp);
}
return -1;
}
private void updateServerTimestamp(ContentDescriptor descriptor, long timestamp) {
if ( descriptor instanceof HandleImplementation ) {
if ( descriptor != null && timestamp != -1 ) {
((HandleImplementation) descriptor).setResponseServerTimestamp(timestamp);
}
}
}
private long getHeaderLength(String length) {
if (length != null) {
return Long.parseLong(length);
}
return ContentDescriptor.UNKNOWN_LENGTH;
}
private String getHeaderUri(BodyPart part) {
try {
if ( part != null ) {
return part.getFileName();
}
// if it's not found, just return null
return null;
} catch(MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private void updateVersion(DocumentDescriptor descriptor, Headers headers) {
long version = DocumentDescriptor.UNKNOWN_VERSION;
String value = headers.get(HEADER_ETAG);
if (value != null && value.length() > 0) {
// trim the double quotes
version = Long.parseLong(value.substring(1, value.length() - 1));
}
descriptor.setVersion(version);
}
private Request.Builder addVersionHeader(DocumentDescriptor desc, Request.Builder requestBldr, String name) {
if ( desc != null &&
desc instanceof DocumentDescriptorImpl &&
!((DocumentDescriptorImpl) desc).isInternal())
{
long version = desc.getVersion();
if (version != DocumentDescriptor.UNKNOWN_VERSION) {
return requestBldr.header(name, "\"" + String.valueOf(version) + "\"");
}
}
return requestBldr;
}
@Override
public <T extends SearchReadHandle> T search(RequestLogger reqlog, T searchHandle,
QueryDefinition queryDef, long start, long len, QueryView view,
Transaction transaction, String forestName)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if (start > 1) {
params.add("start", Long.toString(start));
}
if (len > 0) {
params.add("pageLength", Long.toString(len));
}
if (view != null && view != QueryView.DEFAULT) {
if (view == QueryView.ALL) {
params.add("view", "all");
} else if (view == QueryView.RESULTS) {
params.add("view", "results");
} else if (view == QueryView.FACETS) {
params.add("view", "facets");
} else if (view == QueryView.METADATA) {
params.add("view", "metadata");
}
}
addPointInTimeQueryParam(params, searchHandle);
@SuppressWarnings("rawtypes")
HandleImplementation searchBase = HandleAccessor.checkHandle(searchHandle, "search");
Format searchFormat = searchBase.getFormat();
switch(searchFormat) {
case UNKNOWN:
searchFormat = Format.XML;
break;
case JSON:
case XML:
break;
default:
throw new UnsupportedOperationException("Only XML and JSON search results are possible.");
}
String mimetype = searchFormat.getDefaultMimetype();
OkHttpSearchRequest request = generateSearchRequest(reqlog, queryDef, mimetype, transaction, null, params, forestName);
Response response = request.getResponse();
if ( response == null ) return null;
Class<?> as = searchBase.receiveAs();
ResponseBody body = response.body();
Object entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
searchBase.receiveContent(entity);
updateDescriptor(searchBase, response.headers());
logRequest( reqlog,
"searched starting at %s with length %s in %s transaction with %s mime type",
start, len, getTransactionId(transaction), mimetype);
return searchHandle;
}
private OkHttpSearchRequest generateSearchRequest(RequestLogger reqlog, QueryDefinition queryDef,
String mimetype, Transaction transaction, ServerTransform responseTransform,
RequestParameters params, String forestName)
{
if ( params == null ) params = new RequestParameters();
if ( forestName != null ) params.add("forest-name", forestName);
return new OkHttpSearchRequest(reqlog, queryDef, mimetype, transaction, responseTransform, params);
}
private class OkHttpSearchRequest {
RequestLogger reqlog;
QueryDefinition queryDef;
String mimetype;
RequestParameters params;
ServerTransform responseTransform;
Transaction transaction;
Request.Builder requestBldr = null;
String structure = null;
HandleImplementation baseHandle = null;
OkHttpSearchRequest(RequestLogger reqlog, QueryDefinition queryDef, String mimetype,
Transaction transaction, ServerTransform responseTransform, RequestParameters params) {
this.reqlog = reqlog;
this.queryDef = queryDef;
this.mimetype = mimetype;
this.transaction = transaction;
this.responseTransform = responseTransform;
this.params = params != null ? params : new RequestParameters();
addParams();
init();
}
void addParams() {
String directory = queryDef.getDirectory();
if (directory != null) {
params.add("directory", directory);
}
params.add("collection", queryDef.getCollections());
String optionsName = queryDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
params.add("options", optionsName);
}
ServerTransform transform = queryDef.getResponseTransform();
if (transform != null) {
if (responseTransform != null) {
if ( ! transform.getName().equals(responseTransform.getName()) ) {
throw new IllegalStateException("QueryDefinition transform and DocumentManager transform have different names (" +
transform.getName() + ", " + responseTransform.getName() + ")");
}
logger.warn("QueryDefinition and DocumentManager both specify a ServerTransform--using params from QueryDefinition");
}
transform.merge(params);
} else if (responseTransform != null) {
responseTransform.merge(params);
}
if (transaction != null) {
params.add("txid", transaction.getTransactionId());
}
}
void init() {
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
params.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition) {
structure = ((StructuredQueryDefinition) queryDef).serialize();
if (logger.isDebugEnabled()) {
String qtextMessage = text == null ? "" : " and string query \"" + text + "\"";
logger.debug("Searching for structure {}{}", structure, qtextMessage);
}
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof RawQueryDefinition || queryDef instanceof RawCtsQueryDefinition) {
logger.debug("Raw search");
if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "search");
} else if (queryDef instanceof RawCtsQueryDefinition) {
CtsQueryWriteHandle handle = ((RawCtsQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "search");
}
Format payloadFormat = getStructuredQueryFormat(baseHandle);
String payloadMimetype = getMimetypeWithDefaultXML(payloadFormat, baseHandle);
String path = (queryDef instanceof RawQueryByExampleDefinition) ?
"qbe" : "search";
requestBldr = setupRequest(path, params);
if ( payloadMimetype != null ) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, payloadMimetype);
}
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof CombinedQueryDefinition) {
structure = ((CombinedQueryDefinition) queryDef).serialize();
logger.debug("Searching for combined query {}", structure);
requestBldr = setupRequest("search", params);
requestBldr = requestBldr
.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML)
.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof StringQueryDefinition) {
logger.debug("Searching for string [{}]", text);
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_APPLICATION_XML);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else if (queryDef instanceof DeleteQueryDefinition) {
logger.debug("Searching for deletes");
requestBldr = setupRequest("search", params);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
} else {
throw new UnsupportedOperationException("Cannot search with "
+ queryDef.getClass().getName());
}
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
}
Response getResponse() {
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
if (queryDef instanceof StructuredQueryDefinition && ! (queryDef instanceof RawQueryDefinition)) {
response = doPost(reqlog, requestBldr, structure);
} else if (queryDef instanceof CombinedQueryDefinition) {
response = doPost(reqlog, requestBldr, structure);
} else if (queryDef instanceof DeleteQueryDefinition) {
response = doGet(requestBldr);
} else if (queryDef instanceof RawQueryDefinition) {
response = doPost(reqlog, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof RawCtsQueryDefinition) {
response = doPost(reqlog, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof StringQueryDefinition) {
response = doGet(requestBldr);
} else {
throw new UnsupportedOperationException("Cannot search with "
+ queryDef.getClass().getName());
}
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
response.close();
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_NOT_FOUND) {
response.close();
return null;
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
return response;
}
}
private Format getStructuredQueryFormat(HandleImplementation baseHandle) {
Format payloadFormat = baseHandle.getFormat();
if (payloadFormat == Format.UNKNOWN) {
payloadFormat = null;
} else if (payloadFormat != Format.XML && payloadFormat != Format.JSON) {
throw new IllegalArgumentException(
"Cannot perform raw search for format "+payloadFormat.name());
}
return payloadFormat;
}
private String getMimetypeWithDefaultXML(Format payloadFormat, HandleImplementation baseHandle) {
String payloadMimetype = baseHandle.getMimetype();
if (payloadFormat != null) {
if (payloadMimetype == null) {
payloadMimetype = payloadFormat.getDefaultMimetype();
}
} else if (payloadMimetype == null) {
payloadMimetype = MIMETYPE_APPLICATION_XML;
}
return payloadMimetype;
}
@Override
public void deleteSearch(RequestLogger reqlog, DeleteQueryDefinition queryDef,
Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if (queryDef.getDirectory() != null) {
params.add("directory", queryDef.getDirectory());
}
params.add("collection", queryDef.getCollections());
if (transaction != null) {
params.add("txid", transaction.getTransactionId());
}
Request.Builder requestBldr = setupRequest("search", params);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete",
extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(
reqlog,
"deleted search results in %s transaction",
getTransactionId(transaction));
}
@Override
public void delete(RequestLogger logger, Transaction transaction, String... uris)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
for ( String uri : uris ) {
params.add("uri", uri);
}
deleteResource(logger, "documents", transaction, params, null);
}
@Override
public <T> T values(Class<T> as, ValuesDefinition valDef, String mimetype,
long start, long pageLength, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
String optionsName = valDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
docParams.add("options", optionsName);
}
if (valDef.getAggregate() != null) {
docParams.add("aggregate", valDef.getAggregate());
}
if (valDef.getAggregatePath() != null) {
docParams.add("aggregatePath",
valDef.getAggregatePath());
}
if (valDef.getView() != null) {
docParams.add("view", valDef.getView());
}
if (valDef.getDirection() != null) {
if (valDef.getDirection() == ValuesDefinition.Direction.ASCENDING) {
docParams.add("direction", "ascending");
} else {
docParams.add("direction", "descending");
}
}
if (valDef.getFrequency() != null) {
if (valDef.getFrequency() == ValuesDefinition.Frequency.FRAGMENT) {
docParams.add("frequency", "fragment");
} else {
docParams.add("frequency", "item");
}
}
if (start > 0) {
docParams.add("start", Long.toString(start));
if (pageLength > 0) {
docParams.add("pageLength", Long.toString(pageLength));
}
}
HandleImplementation baseHandle = null;
if (valDef.getQueryDefinition() != null) {
ValueQueryDefinition queryDef = valDef.getQueryDefinition();
if (optionsName == null) {
optionsName = queryDef.getOptionsName();
if (optionsName != null) {
docParams.add("options", optionsName);
}
} else if (queryDef.getOptionsName() != null) {
if (!queryDef.getOptionsName().equals(optionsName)) {
logger.warn("values definition options take precedence over query definition options");
}
}
if (queryDef.getCollections().length > 0) {
logger.warn("collections scope ignored for values query");
}
if (queryDef.getDirectory() != null) {
logger.warn("directory scope ignored for values query");
}
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
docParams.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition ) {
String structure = ((StructuredQueryDefinition) queryDef)
.serialize();
if (structure != null) {
docParams.add("structuredQuery", structure);
}
} else if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "values");
} else if (queryDef instanceof RawCtsQueryDefinition) {
CtsQueryWriteHandle handle = ((RawCtsQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "values");
} else if (queryDef instanceof StringQueryDefinition) {
} else {
logger.warn("unsupported query definition: {}", queryDef.getClass().getName());
}
ServerTransform transform = queryDef.getResponseTransform();
if (transform != null) {
transform.merge(docParams);
}
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "values";
if (valDef.getName() != null) {
uri += "/" + valDef.getName();
}
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
final HandleImplementation tempBaseHandle = baseHandle;
Function<Request.Builder, Response> doFunction = (baseHandle == null) ?
new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
} :
new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(null, funcBuilder.header(HEADER_CONTENT_TYPE, tempBaseHandle.getMimetype()),
tempBaseHandle.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public <T> T valuesList(Class<T> as, ValuesListDefinition valDef,
String mimetype, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
String optionsName = valDef.getOptionsName();
if (optionsName != null && optionsName.length() > 0) {
docParams.add("options", optionsName);
}
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "values";
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public <T> T optionsList(Class<T> as, String mimetype, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters docParams = new RequestParameters();
if (transaction != null) {
docParams.add("txid", transaction.getTransactionId());
}
String uri = "config/query";
Request.Builder requestBldr = setupRequest(uri, docParams);
requestBldr = requestBldr.header(HEADER_ACCEPT, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to search",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("search failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
// namespaces, search options etc.
@Override
public <T> T getValue(RequestLogger reqlog, String type, String key,
boolean isNullable, String mimetype, Class<T> as)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getValue(reqlog, type, key, null, isNullable, mimetype, as);
}
@Override
public <T> T getValue(RequestLogger reqlog, String type, String key, Transaction transaction,
boolean isNullable, String mimetype, Class<T> as)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
logger.debug("Getting {}/{}", type, key);
Request.Builder requestBldr = setupRequest(type + "/" + key, null, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
if (status != STATUS_OK) {
if (status == STATUS_NOT_FOUND) {
response.close();
if (!isNullable) {
throw new ResourceNotFoundException("Could not get " + type + "/" + key);
}
return null;
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to read "
+ type, extractErrorFields(response));
} else {
throw new FailedRequestException(type + " read failed: "
+ getReasonPhrase(response),
extractErrorFields(response));
}
}
logRequest(reqlog, "read %s value with %s key and %s mime type", type,
key, (mimetype != null) ? mimetype : null);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
@Override
public <T> T getValues(RequestLogger reqlog, String type, String mimetype, Class<T> as)
throws ForbiddenUserException, FailedRequestException
{
return getValues(reqlog, type, null, mimetype, as);
}
@Override
public <T> T getValues(RequestLogger reqlog, String type, RequestParameters extraParams,
String mimetype, Class<T> as)
throws ForbiddenUserException, FailedRequestException
{
logger.debug("Getting {}", type);
Request.Builder requestBldr = setupRequest(type, extraParams).header(HEADER_ACCEPT, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to read "
+ type, extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException(type + " read failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
logRequest(reqlog, "read %s values with %s mime type", type,
(mimetype != null) ? mimetype : null);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
@Override
public void postValue(RequestLogger reqlog, String type, String key,
String mimetype, Object value)
throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Posting {}/{}", type, key);
putPostValueImpl(reqlog, "post", type, key, null, mimetype, value, STATUS_CREATED);
}
@Override
public void postValue(RequestLogger reqlog, String type, String key,
RequestParameters extraParams)
throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Posting {}/{}", type, key);
putPostValueImpl(reqlog, "post", type, key, extraParams, null, null, STATUS_NO_CONTENT);
}
@Override
public void putValue(RequestLogger reqlog, String type, String key,
String mimetype, Object value)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Putting {}/{}", type, key);
putPostValueImpl(reqlog, "put", type, key, null, mimetype, value, STATUS_NO_CONTENT, STATUS_CREATED);
}
@Override
public void putValue(RequestLogger reqlog, String type, String key,
RequestParameters extraParams, String mimetype, Object value)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
logger.debug("Putting {}/{}", type, key);
putPostValueImpl(reqlog, "put", type, key, extraParams, mimetype, value, STATUS_NO_CONTENT);
}
private void putPostValueImpl(RequestLogger reqlog, String method,
String type, String key, RequestParameters extraParams,
String mimetype, Object value,
int... expectedStatuses) {
if (key != null) {
logRequest(reqlog, "writing %s value with %s key and %s mime type",
type, key, (mimetype != null) ? mimetype : null);
} else {
logRequest(reqlog, "writing %s values with %s mime type", type,
(mimetype != null) ? mimetype : null);
}
HandleImplementation handle = (value instanceof HandleImplementation) ?
(HandleImplementation) value : null;
MediaType mediaType = makeType(mimetype);
String connectPath = null;
Request.Builder requestBldr = null;
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
Object nextValue = (handle != null) ? handle.sendContent() : value;
RequestBody sentValue = null;
if (nextValue instanceof OutputStreamSender) {
sentValue = new StreamingOutputImpl(
(OutputStreamSender) nextValue, reqlog, mediaType);
} else {
if (reqlog != null && retry == 0) {
sentValue = new ObjectRequestBody(reqlog.copyContent(nextValue), mediaType);
} else {
sentValue = new ObjectRequestBody(nextValue, mediaType);
}
}
boolean isStreaming = (isFirstRequest() || handle == null) ? isStreaming(sentValue) : false;
boolean isResendable = (handle == null) ? !isStreaming : handle.isResendable();
if (isFirstRequest() && !isResendable && isStreaming) {
nextDelay = makeFirstRequest(retry);
if (nextDelay != 0) continue;
}
if ("put".equals(method)) {
if (requestBldr == null) {
connectPath = (key != null) ? type + "/" + key : type;
Request.Builder resource = setupRequest(connectPath, extraParams);
requestBldr = (mimetype == null) ?
resource : resource.header(HEADER_CONTENT_TYPE, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
}
response = (sentValue == null) ?
sendRequestOnce(requestBldr.put(null).build()) :
sendRequestOnce(requestBldr.put(sentValue).build());
} else if ("post".equals(method)) {
if (requestBldr == null) {
connectPath = type;
Request.Builder resource = setupRequest(connectPath, extraParams);
requestBldr = (mimetype == null) ?
resource : resource.header(HEADER_CONTENT_TYPE, mimetype);
requestBldr = addTelemetryAgentId(requestBldr);
}
response = (sentValue == null) ?
sendRequestOnce(requestBldr.post(RequestBody.create(null, "")).build()) :
sendRequestOnce(requestBldr.post(sentValue).build());
} else {
throw new MarkLogicInternalException("unknown method type "
+ method);
}
status = response.code();
if (!retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + connectPath);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to write "
+ type, extractErrorFields(response));
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(type + " not found for write",
extractErrorFields(response));
}
boolean statusOk = false;
for (int expectedStatus : expectedStatuses) {
statusOk = statusOk || (status == expectedStatus);
if (statusOk) {
break;
}
}
if (!statusOk) {
throw new FailedRequestException(type + " write failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
}
@Override
public void deleteValue(RequestLogger reqlog, String type, String key)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
logger.debug("Deleting {}/{}", type, key);
Request.Builder requestBldr = setupRequest(type + "/" + key, null);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete "
+ type, extractErrorFields(response));
}
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException(type + " not found for delete",
extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(reqlog, "deleted %s value with %s key", type, key);
}
@Override
public void deleteValues(RequestLogger reqlog, String type)
throws ForbiddenUserException, FailedRequestException
{
logger.debug("Deleting {}", type);
Request.Builder requestBldr = setupRequest(type, null);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.delete().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doDeleteFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to delete "
+ type, extractErrorFields(response));
}
if (status != STATUS_NO_CONTENT) {
throw new FailedRequestException("delete failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
response.close();
logRequest(reqlog, "deleted %s values", type);
}
@Override
public <R extends UrisReadHandle> R uris(RequestLogger reqlog, Transaction transaction,
QueryDefinition qdef, long start, long pageLength, String forestName, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
if ( forestName != null ) params.add("forest-name", forestName);
if (start > 1) params.add("start", Long.toString(start));
if (pageLength >= 1) params.add("pageLength", Long.toString(pageLength));
if (qdef.getDirectory() != null) params.add("directory", qdef.getDirectory());
if (qdef.getCollections() != null ) {
for ( String collection : qdef.getCollections() ) {
params.add("collection", collection);
}
}
if (qdef.getOptionsName()!= null && qdef.getOptionsName().length() > 0) {
params.add("options", qdef.getOptionsName());
}
if (qdef instanceof RawQueryByExampleDefinition) {
throw new UnsupportedOperationException("Cannot search with RawQueryByExampleDefinition");
} else if (qdef instanceof RawQueryDefinition) {
logger.debug("Raw uris query");
StructureWriteHandle input = ((RawQueryDefinition) qdef).getHandle();
return postResource(reqlog, "internal/uris", transaction, params, input, output);
} else {
String text = null;
if (qdef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) qdef).getCriteria();
} else if (qdef instanceof RawCtsQueryDefinition) {
text = ((RawCtsQueryDefinition) qdef).getCriteria();
}
String qtextMessage = "";
if (text != null) {
params.add("q", text);
qtextMessage = " and string query \"" + text + "\"";
}
if (qdef instanceof RawCtsQueryDefinition) {
String structure = qdef instanceof RawQueryDefinitionImpl.CtsQuery ? ((RawQueryDefinitionImpl.CtsQuery) qdef).serialize() : "";
logger.debug("Query uris with raw cts query {}{}", structure, qtextMessage);
CtsQueryWriteHandle input = ((RawCtsQueryDefinition) qdef).getHandle();
return postResource(reqlog, "internal/uris", transaction, params, input, output);
} else if (qdef instanceof StructuredQueryDefinition) {
String structure = ((StructuredQueryDefinition) qdef).serialize();
logger.debug("Query uris with structured query {}{}", structure, qtextMessage);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof RawStructuredQueryDefinition) {
String structure = ((RawStructuredQueryDefinition) qdef).serialize();
logger.debug("Query uris with raw structured query {}{}", structure, qtextMessage);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof CombinedQueryDefinition) {
String structure = ((CombinedQueryDefinition) qdef).serialize();
logger.debug("Query uris with combined query {}", structure);
if (structure != null) {
params.add("structuredQuery", structure);
}
} else if (qdef instanceof StringQueryDefinition) {
logger.debug("Query uris with string query \"{}\"", text);
} else {
throw new UnsupportedOperationException("Cannot query uris with " +
qdef.getClass().getName());
}
return getResource(reqlog, "internal/uris", transaction, params, output);
}
}
@Override
public <R extends AbstractReadHandle> R getResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
addPointInTimeQueryParam(params, output);
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String mimetype = outputBase.getMimetype();
Class as = outputBase.receiveAs();
Request.Builder requestBldr = makeGetWebResource(path, params, mimetype);
requestBldr = setupRequest(requestBldr, null, mimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
checkStatus(response, status, "read", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
updateDescriptor(outputBase, response.headers());
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "read", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public RESTServiceResultIterator getIteratedResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, String... mimetypes)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getIteratedResourceImpl(OkHttpServiceResultIterator.class, reqlog, path, transaction, params, mimetypes);
}
private <U extends OkHttpResultIterator> U getIteratedResourceImpl(Class<U> clazz, RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, String... mimetypes)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if (transaction != null) params.add("txid", transaction.getTransactionId());
Request.Builder requestBldr = makeGetWebResource(path, params, null);
requestBldr = setupRequest(requestBldr, null, null);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
requestBldr = requestBldr.header(HEADER_ACCEPT, multipartMixedWithBoundary());
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doGetFunction, null);
int status = response.code();
checkStatus(response, status, "read", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "read", "resource", response);
}
@Override
public <R extends AbstractReadHandle> R putResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String inputMimetype = inputBase.getMimetype();
boolean isResendable = inputBase.isResendable();
String outputMimeType = null;
Class as = null;
if (outputBase != null) {
outputMimeType = outputBase.getMimetype();
as = outputBase.receiveAs();
}
Request.Builder requestBldr = makePutWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, outputMimeType);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = (resendable) -> {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
};
Function<Request.Builder, Response> doPutFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPut(reqlog, funcBuilder, inputBase.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPutFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, "write", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "write", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R putResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if (input == null || input.length == 0) {
throw new IllegalArgumentException("input not specified for multipart");
}
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String outputMimetype = outputBase.getMimetype();
Class as = outputBase.receiveAs();
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, input);
Request.Builder requestBldr = makePutWebResource(path, params);
requestBldr = setupRequest(requestBldr, multiPart, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPut(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "write", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "write", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, output, "apply");
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output, String operation)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, output, operation, null);
}
@Override
public <R extends AbstractReadHandle> R postResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, R output, String operation,
Map<String,List<String>> responseHeaders)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String inputMimetype = null;
if(inputBase != null) {
inputMimetype = inputBase.getMimetype();
if ( inputMimetype == null &&
( Format.JSON == inputBase.getFormat() ||
Format.XML == inputBase.getFormat() ) )
{
inputMimetype = inputBase.getFormat().getDefaultMimetype();
}
}
String outputMimetype = outputBase == null ? null : outputBase.getMimetype();
boolean isResendable = inputBase == null ? true : inputBase.isResendable();
Class as = outputBase == null ? null : outputBase.receiveAs();
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = new Consumer<Boolean>() {
public void accept(Boolean resendable) {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException("Cannot retry request for " + path);
}
}
};
final Object value = inputBase == null ? null :inputBase.sendContent();
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(reqlog, funcBuilder, value);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPostFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, operation, "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if ( responseHeaders != null ) {
// add all the headers from the OkHttp Headers object to the caller-provided map
responseHeaders.putAll( response.headers().toMultimap() );
}
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, operation, "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R postResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postResource(reqlog, path, transaction, params, input, null, output);
}
@Override
public <R extends AbstractReadHandle, W extends AbstractWriteHandle> R postResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, Map<String, List<String>>[] requestHeaders, R output)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output, "read");
String outputMimetype = outputBase != null ? outputBase.getMimetype() : null;
Class as = outputBase != null ? outputBase.receiveAs() : null;
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, null, input, requestHeaders);
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, multiPart, outputMimetype);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPost(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "apply", "resource",
response, as));
} else {
response.close();
}
return output;
}
@Override
public void postBulkDocuments(
RequestLogger reqlog, DocumentWriteSet writeSet,
ServerTransform transform, Transaction transaction, Format defaultFormat)
throws ForbiddenUserException, FailedRequestException
{
postBulkDocuments(reqlog, writeSet, transform, transaction, defaultFormat, null, null);
}
@Override
public <R extends AbstractReadHandle> R postBulkDocuments(
RequestLogger reqlog, DocumentWriteSet writeSet,
ServerTransform transform, Transaction transaction, Format defaultFormat, R output,
String temporalCollection)
throws ForbiddenUserException, FailedRequestException
{
List<AbstractWriteHandle> writeHandles = new ArrayList<AbstractWriteHandle>();
List<RequestParameters> headerList = new ArrayList<RequestParameters>();
for ( DocumentWriteOperation write : writeSet ) {
String temporalDocumentURI = write.getTemporalDocumentURI();
HandleImplementation metadata = HandleAccessor.checkHandle(write.getMetadata(), "write");
HandleImplementation content = HandleAccessor.checkHandle(write.getContent(), "write");
String contentDispositionTemporal = "";
if (temporalDocumentURI != null) {
// escape any quotes or back-slashes in the uri
temporalDocumentURI = escapeContentDispositionFilename(temporalDocumentURI);
contentDispositionTemporal = "; temporal-document="+temporalDocumentURI;
}
if ( write.getOperationType() == DocumentWriteOperation.OperationType.DISABLE_METADATA_DEFAULT ) {
RequestParameters headers = new RequestParameters();
headers.add(HEADER_CONTENT_TYPE, metadata.getMimetype());
headers.add(HEADER_CONTENT_DISPOSITION, DISPOSITION_TYPE_INLINE + "; category=metadata" + contentDispositionTemporal);
headerList.add(headers);
writeHandles.add(write.getMetadata());
} else if ( metadata != null ) {
RequestParameters headers = new RequestParameters();
headers.add(HEADER_CONTENT_TYPE, metadata.getMimetype());
if ( write.getOperationType() == DocumentWriteOperation.OperationType.METADATA_DEFAULT ) {
headers.add(HEADER_CONTENT_DISPOSITION, DISPOSITION_TYPE_INLINE + "; category=metadata" + contentDispositionTemporal);
} else {
String disposition = DISPOSITION_TYPE_ATTACHMENT + "; " +
DISPOSITION_PARAM_FILENAME + "=" + escapeContentDispositionFilename(write.getUri()) +
"; category=metadata" + contentDispositionTemporal;
headers.add(HEADER_CONTENT_DISPOSITION, disposition);
}
headerList.add(headers);
writeHandles.add(write.getMetadata());
}
if ( content != null ) {
RequestParameters headers = new RequestParameters();
String mimeType = content.getMimetype();
if ( mimeType == null && defaultFormat != null ) {
mimeType = defaultFormat.getDefaultMimetype();
}
headers.add(HEADER_CONTENT_TYPE, mimeType);
String disposition = DISPOSITION_TYPE_ATTACHMENT + "; " +
DISPOSITION_PARAM_FILENAME + "=" + escapeContentDispositionFilename(write.getUri()) + contentDispositionTemporal;
headers.add(HEADER_CONTENT_DISPOSITION, disposition);
headerList.add(headers);
writeHandles.add(write.getContent());
}
}
RequestParameters params = new RequestParameters();
if ( transform != null ) {
transform.merge(params);
}
if ( temporalCollection != null ) params.add("temporal-collection", temporalCollection);
return postResource(reqlog, "documents", transaction, params,
(AbstractWriteHandle[]) writeHandles.toArray(new AbstractWriteHandle[0]),
(RequestParameters[]) headerList.toArray(new RequestParameters[0]),
output);
}
// TODO: See what other escaping we need to do for filenames
private String escapeContentDispositionFilename(String str) {
if ( str == null ) return null;
// escape any quotes or back-slashes
return "\"" + str.replace("\"", "\\\"").replace("\\", "\\\\") + "\"";
}
public class OkHttpEvalResultIterator implements EvalResultIterator {
private OkHttpResultIterator iterator;
OkHttpEvalResultIterator(OkHttpResultIterator iterator) {
this.iterator = iterator;
}
@Override
public Iterator<EvalResult> iterator() {
return this;
}
@Override
public boolean hasNext() {
if ( iterator == null ) return false;
return iterator.hasNext();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public EvalResult next() {
if ( iterator == null ) throw new NoSuchElementException("No results available");
OkHttpResult jerseyResult = iterator.next();
EvalResult result = new OkHttpEvalResult(jerseyResult);
return result;
}
@Override
public void close() {
if ( iterator != null ) iterator.close();
}
}
public class OkHttpEvalResult implements EvalResult {
private OkHttpResult content;
public OkHttpEvalResult(OkHttpResult content) {
this.content = content;
}
@Override
public Format getFormat() {
return content.getFormat();
}
@Override
public EvalResult.Type getType() {
String contentType = content.getHeader(HEADER_CONTENT_TYPE);
String xPrimitive = content.getHeader(HEADER_X_PRIMITIVE);
if ( contentType != null ) {
if ( MIMETYPE_APPLICATION_JSON.equals(contentType) ) {
if ( "null-node()".equals(xPrimitive) ) {
return EvalResult.Type.NULL;
} else {
return EvalResult.Type.JSON;
}
} else if ( MIMETYPE_TEXT_JSON.equals(contentType) ) {
return EvalResult.Type.JSON;
} else if ( MIMETYPE_APPLICATION_XML.equals(contentType) ) {
return EvalResult.Type.XML;
} else if ( MIMETYPE_TEXT_XML.equals(contentType) ) {
return EvalResult.Type.XML;
} else if ( "application/x-unknown-content-type".equals(contentType) && "binary()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
} else if ( "application/octet-stream".equals(contentType) && "node()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
}
}
if ( xPrimitive == null ) {
return EvalResult.Type.OTHER;
} else if ( "string".equals(xPrimitive) || "untypedAtomic".equals(xPrimitive) ) {
return EvalResult.Type.STRING;
} else if ( "boolean".equals(xPrimitive) ) {
return EvalResult.Type.BOOLEAN;
} else if ( "attribute()".equals(xPrimitive) ) {
return EvalResult.Type.ATTRIBUTE;
} else if ( "comment()".equals(xPrimitive) ) {
return EvalResult.Type.COMMENT;
} else if ( "processing-instruction()".equals(xPrimitive) ) {
return EvalResult.Type.PROCESSINGINSTRUCTION;
} else if ( "text()".equals(xPrimitive) ) {
return EvalResult.Type.TEXTNODE;
} else if ( "binary()".equals(xPrimitive) ) {
return EvalResult.Type.BINARY;
} else if ( "duration".equals(xPrimitive) ) {
return EvalResult.Type.DURATION;
} else if ( "date".equals(xPrimitive) ) {
return EvalResult.Type.DATE;
} else if ( "anyURI".equals(xPrimitive) ) {
return EvalResult.Type.ANYURI;
} else if ( "hexBinary".equals(xPrimitive) ) {
return EvalResult.Type.HEXBINARY;
} else if ( "base64Binary".equals(xPrimitive) ) {
return EvalResult.Type.BASE64BINARY;
} else if ( "dateTime".equals(xPrimitive) ) {
return EvalResult.Type.DATETIME;
} else if ( "decimal".equals(xPrimitive) ) {
return EvalResult.Type.DECIMAL;
} else if ( "double".equals(xPrimitive) ) {
return EvalResult.Type.DOUBLE;
} else if ( "float".equals(xPrimitive) ) {
return EvalResult.Type.FLOAT;
} else if ( "gDay".equals(xPrimitive) ) {
return EvalResult.Type.GDAY;
} else if ( "gMonth".equals(xPrimitive) ) {
return EvalResult.Type.GMONTH;
} else if ( "gMonthDay".equals(xPrimitive) ) {
return EvalResult.Type.GMONTHDAY;
} else if ( "gYear".equals(xPrimitive) ) {
return EvalResult.Type.GYEAR;
} else if ( "gYearMonth".equals(xPrimitive) ) {
return EvalResult.Type.GYEARMONTH;
} else if ( "integer".equals(xPrimitive) ) {
return EvalResult.Type.INTEGER;
} else if ( "QName".equals(xPrimitive) ) {
return EvalResult.Type.QNAME;
} else if ( "time".equals(xPrimitive) ) {
return EvalResult.Type.TIME;
}
return EvalResult.Type.OTHER;
}
@Override
public <H extends AbstractReadHandle> H get(H handle) {
if ( getType() == EvalResult.Type.NULL && handle instanceof StringHandle ) {
return (H) ((StringHandle) handle).with(null);
} else if ( getType() == EvalResult.Type.NULL && handle instanceof BytesHandle ) {
return (H) ((BytesHandle) handle).with(null);
} else {
return content.getContent(handle);
}
}
@Override
public <T> T getAs(Class<T> clazz) {
if ( getType() == EvalResult.Type.NULL ) return null;
if (clazz == null) throw new IllegalArgumentException("clazz cannot be null");
ContentHandle<T> readHandle = DatabaseClientFactory.getHandleRegistry().makeHandle(clazz);
if ( readHandle == null ) return null;
readHandle = get(readHandle);
if ( readHandle == null ) return null;
return readHandle.get();
}
@Override
public String getString() {
if ( getType() == EvalResult.Type.NULL ) {
return null;
} else {
return content.getContentAs(String.class);
}
}
@Override
public Number getNumber() {
if ( getType() == EvalResult.Type.DECIMAL ) return new BigDecimal(getString());
else if ( getType() == EvalResult.Type.DOUBLE ) return Double.valueOf(getString());
else if ( getType() == EvalResult.Type.FLOAT ) return Float.valueOf(getString());
// MarkLogic integers can be much larger than Java integers, so we'll use Long instead
else if ( getType() == EvalResult.Type.INTEGER ) return Long.valueOf(getString());
else return new BigDecimal(getString());
}
@Override
public Boolean getBoolean() {
return Boolean.valueOf(getString());
}
}
@Override
public EvalResultIterator postEvalInvoke(
RequestLogger reqlog, String code, String modulePath,
ServerEvaluationCallImpl.Context context,
Map<String, Object> variables, EditableNamespaceContext namespaces,
Transaction transaction)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
String formUrlEncodedPayload;
String path;
RequestParameters params = new RequestParameters();
try {
StringBuffer sb = new StringBuffer();
if ( context == ServerEvaluationCallImpl.Context.ADHOC_XQUERY ) {
path = "eval";
sb.append("xquery=");
sb.append(URLEncoder.encode(code, "UTF-8"));
} else if ( context == ServerEvaluationCallImpl.Context.ADHOC_JAVASCRIPT ) {
path = "eval";
sb.append("javascript=");
sb.append(URLEncoder.encode(code, "UTF-8"));
} else if ( context == ServerEvaluationCallImpl.Context.INVOKE ) {
path = "invoke";
sb.append("module=");
sb.append(URLEncoder.encode(modulePath, "UTF-8"));
} else {
throw new IllegalStateException("Invalid eval context: " + context);
}
if ( variables != null && variables.size() > 0 ) {
int i=0;
for ( String name : variables.keySet() ) {
String namespace = "";
String localname = name;
if ( namespaces != null ) {
for ( String prefix : namespaces.keySet() ) {
if ( name != null && prefix != null && name.startsWith(prefix + ":") ) {
localname = name.substring(prefix.length() + 1);
namespace = namespaces.get(prefix);
}
}
}
// set the variable namespace
sb.append("&evn" + i + "=");
sb.append(URLEncoder.encode(namespace, "UTF-8"));
// set the variable localname
sb.append("&evl" + i + "=");
sb.append(URLEncoder.encode(localname, "UTF-8"));
String value;
String type = null;
Object valueObject = variables.get(name);
if ( valueObject == null ) {
value = "null";
type = "null-node()";
} else if ( valueObject instanceof JacksonHandle ||
valueObject instanceof JacksonParserHandle )
{
JsonNode jsonNode = null;
if ( valueObject instanceof JacksonHandle ) {
jsonNode = ((JacksonHandle) valueObject).get();
} else if ( valueObject instanceof JacksonParserHandle ) {
jsonNode = ((JacksonParserHandle) valueObject).get().readValueAs(JsonNode.class);
}
value = jsonNode.toString();
type = getJsonType(jsonNode);
} else if ( valueObject instanceof AbstractWriteHandle ) {
value = HandleAccessor.contentAsString((AbstractWriteHandle) valueObject);
HandleImplementation valueBase = HandleAccessor.as((AbstractWriteHandle) valueObject);
Format format = valueBase.getFormat();
//TODO: figure out what type should be
// I see element() and document-node() are two valid types
if ( format == Format.XML ) {
type = "document-node()";
} else if ( format == Format.JSON ) {
try ( JacksonParserHandle handle = new JacksonParserHandle() ) {
JsonNode jsonNode = handle.getMapper().readTree(value);
type = getJsonType(jsonNode);
}
} else if ( format == Format.TEXT ) {
/* Comment next line until 32608 is resolved
type = "text()";
// until then, use the following line */
type = "xs:untypedAtomic";
} else if ( format == Format.BINARY ) {
throw new UnsupportedOperationException("Binary format is not supported for variables");
} else {
throw new UnsupportedOperationException("Undefined format is not supported for variables. " +
"Please set the format on your handle for variable " + name + ".");
}
} else if ( valueObject instanceof String ||
valueObject instanceof Boolean ||
valueObject instanceof Number )
{
value = valueObject.toString();
// when we send type "xs:untypedAtomic" via XDBC, the server attempts to intelligently decide
// how to cast the type
type = "xs:untypedAtomic";
} else {
throw new IllegalArgumentException("Variable with name=" +
name + " is of unsupported type" +
valueObject.getClass() + ". Supported types are String, Boolean, Number, " +
"or AbstractWriteHandle");
}
// set the variable value
sb.append("&evv" + i + "=");
sb.append(URLEncoder.encode(value, "UTF-8"));
// set the variable type
sb.append("&evt" + i + "=" + type);
i++;
}
}
formUrlEncodedPayload = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
StringHandle input = new StringHandle(formUrlEncodedPayload)
.withMimetype("application/x-www-form-urlencoded");
return new OkHttpEvalResultIterator( postIteratedResourceImpl(DefaultOkHttpResultIterator.class,
reqlog, path, transaction, params, input) );
}
private String getJsonType(JsonNode jsonNode) {
if ( jsonNode instanceof ArrayNode ) {
return "json:array";
} else if ( jsonNode instanceof ObjectNode ) {
return "json:object";
} else {
throw new IllegalArgumentException("When using JacksonHandle or " +
"JacksonParserHandle with ServerEvaluationCall the content must be " +
"a valid array or object");
}
}
@Override
public RESTServiceResultIterator postIteratedResource(RequestLogger reqlog,
String path, Transaction transaction, RequestParameters params, AbstractWriteHandle input,
String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postIteratedResourceImpl(OkHttpServiceResultIterator.class,
reqlog, path, transaction, params, input, outputMimetypes);
}
private <U extends OkHttpResultIterator> U postIteratedResourceImpl(
Class<U> clazz, final RequestLogger reqlog,
final String path, Transaction transaction, RequestParameters params,
AbstractWriteHandle input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation inputBase = HandleAccessor.checkHandle(input,
"write");
String inputMimetype = inputBase.getMimetype();
boolean isResendable = inputBase.isResendable();
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(requestBldr, inputMimetype, null);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Consumer<Boolean> resendableConsumer = new Consumer<Boolean>() {
public void accept(Boolean resendable) {
if (!isResendable) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
}
};
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(reqlog, funcBuilder.header(HEADER_ACCEPT, multipartMixedWithBoundary()),
inputBase.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doPostFunction, resendableConsumer);
int status = response.code();
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "apply", "resource", response);
}
@Override
public <W extends AbstractWriteHandle> RESTServiceResultIterator postIteratedResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
W[] input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
return postIteratedResourceImpl(OkHttpServiceResultIterator.class,
reqlog, path, transaction, params, input, outputMimetypes);
}
private <W extends AbstractWriteHandle, U extends OkHttpResultIterator> U postIteratedResourceImpl(
Class<U> clazz, RequestLogger reqlog, String path, Transaction transaction,
RequestParameters params, W[] input, String... outputMimetypes)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
MultipartBody.Builder multiPart = new MultipartBody.Builder();
boolean hasStreamingPart = addParts(multiPart, reqlog, input);
Request.Builder requestBldr = makePostWebResource(path, params);
requestBldr = setupRequest(
requestBldr,
multiPart,
multipartMixedWithBoundary());
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
response = doPost(requestBldr, multiPart, hasStreamingPart);
status = response.code();
if (transaction != null || !retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
response.close();
if (hasStreamingPart) {
throw new ResourceNotResendableException(
"Cannot retry request for " + path);
}
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
checkStatus(response, status, "apply", "resource", path,
ResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);
return makeResults(clazz, reqlog, "apply", "resource", response);
}
@Override
public <R extends AbstractReadHandle> R deleteResource(
RequestLogger reqlog, String path, Transaction transaction, RequestParameters params,
R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( params == null ) params = new RequestParameters();
if ( transaction != null ) params.add("txid", transaction.getTransactionId());
HandleImplementation outputBase = HandleAccessor.checkHandle(output,
"read");
String outputMimeType = null;
Class as = null;
if (outputBase != null) {
outputMimeType = outputBase.getMimetype();
as = outputBase.receiveAs();
}
Request.Builder requestBldr = makeDeleteWebResource(path, params);
requestBldr = setupRequest(requestBldr, null, outputMimeType);
requestBldr = addTransactionScopedCookies(requestBldr, transaction);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doDeleteFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doDelete(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, (transaction == null), doDeleteFunction, null);
int status = response.code();
checkStatus(response, status, "delete", "resource", path,
ResponseStatus.OK_OR_NO_CONTENT);
if (as != null) {
outputBase.receiveContent(makeResult(reqlog, "delete", "resource",
response, as));
} else {
response.close();
}
return output;
}
private Request.Builder makeGetWebResource(String path,
RequestParameters params, Object mimetype) {
if (path == null) throw new IllegalArgumentException("Read with null path");
logger.debug(String.format("Getting %s as %s", path, mimetype));
return setupRequest(path, params);
}
private Response doGet(Request.Builder requestBldr) {
requestBldr = requestBldr.get();
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makePutWebResource(String path,
RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Write with null path");
logger.debug("Putting {}", path);
return setupRequest(path, params);
}
private Response doPut(RequestLogger reqlog, Request.Builder requestBldr, Object value) {
if (value == null) throw new IllegalArgumentException("Resource write with null value");
if (isFirstRequest() && isStreaming(value)) makeFirstRequest(0);
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if (value instanceof OutputStreamSender) {
requestBldr = requestBldr.put(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
requestBldr = requestBldr.put(new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
requestBldr = requestBldr.put(new ObjectRequestBody(value, mediaType));
}
}
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Response doPut(Request.Builder requestBldr,
MultipartBody.Builder multiPart, boolean hasStreamingPart) {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(0);
requestBldr = requestBldr.put(multiPart.build());
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makePostWebResource(String path, RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Apply with null path");
logger.debug("Posting {}", path);
return setupRequest(path, params);
}
private Response doPost(RequestLogger reqlog, Request.Builder requestBldr, Object value) {
if (isFirstRequest() && isStreaming(value)) {
makeFirstRequest(0);
}
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
if(value == null) {
requestBldr = requestBldr.post(new ObjectRequestBody(null, null));
} else if (value instanceof OutputStreamSender) {
requestBldr = requestBldr
.post(new StreamingOutputImpl((OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
requestBldr = requestBldr.post(new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
requestBldr = requestBldr.post(new ObjectRequestBody(value, mediaType));
}
}
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Response doPost(Request.Builder requestBldr,
MultipartBody.Builder multiPart, boolean hasStreamingPart) {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(0);
Response response = sendRequestOnce(requestBldr.post(multiPart.build()));
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private Request.Builder makeDeleteWebResource(String path, RequestParameters params) {
if (path == null) throw new IllegalArgumentException("Delete with null path");
logger.debug("Deleting {}", path);
return setupRequest(path, params);
}
private Response doDelete(Request.Builder requestBldr) {
Response response = sendRequestOnce(requestBldr.delete().build());
if (isFirstRequest()) setFirstRequest(false);
return response;
}
private void addPointInTimeQueryParam(RequestParameters params, Object outputHandle) {
HandleImplementation handleBase = HandleAccessor.as(outputHandle);
if ( params != null && handleBase != null &&
handleBase.getPointInTimeQueryTimestamp() != -1 )
{
logger.trace("param timestamp=[" + handleBase.getPointInTimeQueryTimestamp() + "]");
params.add("timestamp", Long.toString(handleBase.getPointInTimeQueryTimestamp()));
}
}
private Request.Builder addTransactionScopedCookies(Request.Builder requestBldr, Transaction transaction) {
if ( transaction != null && transaction.getCookies() != null ) {
if ( requestBldr == null ) {
throw new MarkLogicInternalException("no requestBldr available to get the URI");
}
requestBldr = addCookies(
requestBldr, transaction.getCookies(), ((TransactionImpl) transaction).getCreatedTimestamp()
);
}
return requestBldr;
}
private Request.Builder addCookies(Request.Builder requestBldr, List<ClientCookie> cookies, Calendar creation) {
HttpUrl uri = requestBldr.build().url();
for (ClientCookie cookie : cookies) {
// don't forward the cookie if it requires https and we're not using https
if ( cookie.isSecure() && ! uri.isHttps() ) {
continue;
}
// don't forward the cookie if it requires a path and we're using a different path
if ( cookie.getPath() != null ) {
String path = uri.encodedPath();
if ( path == null || ! path.startsWith(cookie.getPath()) ) {
continue;
}
}
// don't forward the cookie if it requires a domain and we're using a different domain
if ( cookie.getDomain() != null ) {
if ( uri.host() == null || ! uri.host().equals(cookie.getDomain()) ) {
continue;
}
}
// don't forward the cookie if it has 0 for max age
if ( cookie.getMaxAge() == 0 ) {
continue;
}
// TODO: determine if we need handling for MIN_VALUE
// else if ( cookie.getMaxAge() == Integer.MIN_VALUE ) {
// don't forward the cookie if it has a max age and we're past the max age
if ( creation != null && cookie.getMaxAge() > 0 ) {
int currentAge = (int) TimeUnit.MILLISECONDS.toSeconds(
System.currentTimeMillis() - creation.getTimeInMillis()
);
if ( currentAge > cookie.getMaxAge() ) {
logger.warn(
cookie.getName()+" cookie expired after "+cookie.getMaxAge()+" seconds: "+cookie.getValue()
);
continue;
}
}
requestBldr = requestBldr.addHeader(HEADER_COOKIE, cookie.toString());
}
return requestBldr;
}
private Request.Builder addTelemetryAgentId(Request.Builder requestBldr) {
if ( requestBldr == null ) throw new MarkLogicInternalException("no requestBldr available to set ML-Agent-ID header");
return requestBldr.header("ML-Agent-ID", "java");
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, W[] input)
{
return addParts(multiPart, reqlog, null, input, null);
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, String[] mimetypes, W[] input)
{
return addParts(multiPart, reqlog, null, input, null);
}
private <W extends AbstractWriteHandle> boolean addParts(
MultipartBody.Builder multiPart, RequestLogger reqlog, String[] mimetypes,
W[] input, Map<String, List<String>>[] headers)
{
if (mimetypes != null && mimetypes.length != input.length) {
throw new IllegalArgumentException(
"Mismatch between count of mimetypes and input");
}
if (headers != null && headers.length != input.length) {
throw new IllegalArgumentException(
"Mismatch between count of headers and input");
}
multiPart.setType(MediaType.parse(MIMETYPE_MULTIPART_MIXED));
boolean hasStreamingPart = false;
for (int i = 0; i < input.length; i++) {
AbstractWriteHandle handle = input[i];
HandleImplementation handleBase = HandleAccessor.checkHandle(
handle, "write");
if (!hasStreamingPart) {
hasStreamingPart = !handleBase.isResendable();
}
Object value = handleBase.sendContent();
String inputMimetype = null;
if ( mimetypes != null ) inputMimetype = mimetypes[i];
if ( inputMimetype == null && headers != null ) {
inputMimetype = getHeaderMimetype(getHeader(headers[i], HEADER_CONTENT_TYPE));
}
if ( inputMimetype == null ) inputMimetype = handleBase.getMimetype();
MediaType mediaType = (inputMimetype != null)
? MediaType.parse(inputMimetype)
: MediaType.parse(MIMETYPE_WILDCARD);
Headers.Builder partHeaders = new Headers.Builder();
if ( headers != null ) {
for ( String key : headers[i].keySet() ) {
// OkHttp wants me to skip the Content-Type header
if ( HEADER_CONTENT_TYPE.equalsIgnoreCase(key) ) continue;
for ( String headerValue : headers[i].get(key) ) {
partHeaders.add(key, headerValue);
}
}
}
Part bodyPart = null;
if (value instanceof OutputStreamSender) {
bodyPart = Part.create(partHeaders.build(), new StreamingOutputImpl(
(OutputStreamSender) value, reqlog, mediaType));
} else {
if (reqlog != null) {
bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(reqlog.copyContent(value), mediaType));
} else {
bodyPart = Part.create(partHeaders.build(), new ObjectRequestBody(value, mediaType));
}
}
multiPart = multiPart.addPart(bodyPart);
}
return hasStreamingPart;
}
private String multipartMixedWithBoundary() {
return MIMETYPE_MULTIPART_MIXED + "; boundary=" + UUID.randomUUID().toString();
}
private Request.Builder setupRequest(HttpUrl requestUri, String path, RequestParameters params) {
if ( path == null ) throw new IllegalArgumentException("path cannot be null");
if ( path.startsWith("/") ) path = path.substring(1);
HttpUrl.Builder uri = requestUri.resolve(path).newBuilder();
if ( params != null ) {
for ( String key : params.keySet() ) {
for ( String value : params.get(key) ) {
uri.addQueryParameter(key, value);
}
}
}
if ( database != null && ! path.startsWith("config/") ) {
uri.addQueryParameter("database", database);
}
Request.Builder request = new Request.Builder()
.url(uri.build());
if(headerValue!=null && headerValue.length()!=0) {
String samlHeaderValue = "Authorization: SAML token="+ headerValue;
request = request.header(HEADER_AUTHORIZATION, samlHeaderValue);
}
return request;
}
private Request.Builder setupRequest(String path, RequestParameters params) {
return setupRequest(baseUri, path, params);
}
private Request.Builder setupRequest(Request.Builder requestBldr,
Object inputMimetype, Object outputMimetype) {
if (inputMimetype == null) {
} else if (inputMimetype instanceof String) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, (String) inputMimetype);
} else if (inputMimetype instanceof MediaType) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, inputMimetype.toString());
} else if (inputMimetype instanceof MultipartBody.Builder) {
requestBldr = requestBldr.header(HEADER_CONTENT_TYPE, MIMETYPE_MULTIPART_MIXED);
logger.debug("Sending multipart for {}", requestBldr.build().url().encodedPath());
} else {
throw new IllegalArgumentException(
"Unknown input mimetype specifier "
+ inputMimetype.getClass().getName());
}
if (outputMimetype == null) {
} else if (outputMimetype instanceof String) {
requestBldr = requestBldr.header(HEADER_ACCEPT, (String) outputMimetype);
} else if (outputMimetype instanceof MediaType) {
requestBldr = requestBldr.header(HEADER_ACCEPT, outputMimetype.toString());
} else {
throw new IllegalArgumentException(
"Unknown output mimetype specifier "
+ outputMimetype.getClass().getName());
}
return requestBldr;
}
private Request.Builder setupRequest(String path, RequestParameters params, Object inputMimetype,
Object outputMimetype)
{
return setupRequest(setupRequest(path, params), inputMimetype, outputMimetype);
}
private void checkStatus(Response response, int status, String operation, String entityType,
String path, ResponseStatus expected)
{
if (!expected.isExpected(status)) {
FailedRequest failure = extractErrorFields(response);
if (status == STATUS_NOT_FOUND) {
throw new ResourceNotFoundException("Could not " + operation
+ " " + entityType + " at " + path,
failure);
}
if ("RESTAPI-CONTENTNOVERSION".equals(failure.getMessageCode())) {
throw new FailedRequestException("Content version required to " +
operation + " " + entityType + " at " + path, failure);
} else if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to "
+ operation + " " + entityType + " at " + path,
failure);
}
throw new FailedRequestException("failed to " + operation + " "
+ entityType + " at " + path + ": "
+ getReasonPhrase(response), failure);
}
}
private <T> T makeResult(RequestLogger reqlog, String operation,
String entityType, Response response, Class<T> as) {
if (as == null) {
return null;
}
logRequest(reqlog, "%s for %s", operation, entityType);
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return (reqlog != null) ? reqlog.copyContent(entity) : entity;
}
private <U extends OkHttpResultIterator> U makeResults(
Class<U> clazz, RequestLogger reqlog,
String operation, String entityType, Response response) {
if ( response == null ) return null;
ResponseBody body = response.body();
MimeMultipart entity = body.contentLength() != 0 ?
getEntity(body, MimeMultipart.class) : null;
List<BodyPart> partList = getPartList(entity);
Closeable closeable = response;
return makeResults(clazz, reqlog, operation, entityType, partList, response, closeable);
}
private <U extends OkHttpResultIterator> U makeResults(
Class<U> clazz, RequestLogger reqlog,
String operation, String entityType, List<BodyPart> partList, Response response,
Closeable closeable) {
logRequest(reqlog, "%s for %s", operation, entityType);
if ( response == null ) return null;
try {
java.lang.reflect.Constructor<U> constructor =
clazz.getConstructor(OkHttpServices.class, RequestLogger.class, List.class, Closeable.class);
OkHttpResultIterator result = constructor.newInstance(this, reqlog, partList, closeable);
Headers headers = response.headers();
if (headers.get(HEADER_VND_MARKLOGIC_START) != null) {
result.setStart(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_START)));
}
if (headers.get(HEADER_VND_MARKLOGIC_PAGELENGTH) != null) {
result.setPageSize(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_PAGELENGTH)));
}
if (headers.get(HEADER_VND_MARKLOGIC_RESULT_ESTIMATE) != null) {
result.setTotalSize(Long.parseLong(headers.get(HEADER_VND_MARKLOGIC_RESULT_ESTIMATE)));
}
return (U) result;
} catch (Throwable t) {
throw new MarkLogicInternalException("Error instantiating " + clazz.getName(), t);
}
}
private boolean isStreaming(Object value) {
return !(value instanceof String || value instanceof byte[] || value instanceof File);
}
private void logRequest(RequestLogger reqlog, String message,
Object... params) {
if (reqlog == null) return;
PrintStream out = reqlog.getPrintStream();
if (out == null) return;
if (params == null || params.length == 0) {
out.println(message);
} else {
out.format(message, params);
out.println();
}
}
private String stringJoin(Collection collection, String separator,
String defaultValue) {
if (collection == null || collection.size() == 0) return defaultValue;
StringBuilder builder = null;
for (Object value : collection) {
if (builder == null) {
builder = new StringBuilder();
} else {
builder.append(separator);
}
builder.append(value);
}
return (builder != null) ? builder.toString() : null;
}
private int calculateDelay(Random rand, int i) {
int min =
(i > 6) ? DELAY_CEILING :
(i == 0) ? DELAY_FLOOR :
DELAY_FLOOR + (1 << i) * DELAY_MULTIPLIER;
int range =
(i > 6) ? DELAY_FLOOR :
(i == 0) ? 2 * DELAY_MULTIPLIER :
(i == 6) ? DELAY_CEILING - min :
(1 << i) * DELAY_MULTIPLIER;
return min + randRetry.nextInt(range);
}
public class OkHttpResult {
private RequestLogger reqlog;
private BodyPart part;
private boolean extractedHeaders = false;
private String uri;
private RequestParameters headers = new RequestParameters();
private Format format;
private String mimetype;
private long length;
public OkHttpResult(RequestLogger reqlog, BodyPart part) {
this.reqlog = reqlog;
this.part = part;
}
public <R extends AbstractReadHandle> R getContent(R handle) {
if (part == null) throw new IllegalStateException("Content already retrieved");
HandleImplementation handleBase = HandleAccessor.as(handle);
extractHeaders();
updateFormat(handleBase, format);
updateMimetype(handleBase, mimetype);
updateLength(handleBase, length);
try {
Object contentEntity = getEntity(part, handleBase.receiveAs());
handleBase.receiveContent((reqlog != null) ? reqlog.copyContent(contentEntity) : contentEntity);
return handle;
} finally {
part = null;
reqlog = null;
}
}
public <T> T getContentAs(Class<T> clazz) {
ContentHandle<T> readHandle = DatabaseClientFactory.getHandleRegistry().makeHandle(clazz);
readHandle = getContent(readHandle);
if ( readHandle == null ) return null;
return readHandle.get();
}
public String getUri() {
extractHeaders();
return uri;
}
public Format getFormat() {
extractHeaders();
return format;
}
public String getMimetype() {
extractHeaders();
return mimetype;
}
public long getLength() {
extractHeaders();
return length;
}
public String getHeader(String name) {
extractHeaders();
List<String> values = headers.get(name);
if ( values != null && values.size() > 0 ) {
return values.get(0);
}
return null;
}
public Map<String,List<String>> getHeaders() {
extractHeaders();
return headers.getMap();
}
private void extractHeaders() {
if (part == null || extractedHeaders) return;
try {
for ( Enumeration<Header> e = part.getAllHeaders(); e.hasMoreElements(); ) {
Header header = e.nextElement();
headers.put(header.getName(), header.getValue());
}
format = getHeaderFormat(part);
mimetype = getHeaderMimetype(OkHttpServices.getHeader(part, HEADER_CONTENT_TYPE));
length = getHeaderLength(OkHttpServices.getHeader(part, HEADER_CONTENT_LENGTH));
uri = getHeaderUri(part);
extractedHeaders = true;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
}
public class OkHttpServiceResult extends OkHttpResult implements RESTServices.RESTServiceResult {
public OkHttpServiceResult(RequestLogger reqlog, BodyPart part) {
super(reqlog, part);
}
}
public class OkHttpResultIterator<T extends OkHttpResult> {
private RequestLogger reqlog;
private Iterator<BodyPart> partQueue;
private Class<T> clazz;
private long start = -1;
private long size = -1;
private long pageSize = -1;
private long totalSize = -1;
private Closeable closeable;
public OkHttpResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Class<T> clazz, Closeable closeable) {
this.clazz = clazz;
this.reqlog = reqlog;
if (partList != null && partList.size() > 0) {
this.size = partList.size();
this.partQueue = new ConcurrentLinkedQueue<>(
partList).iterator();
} else {
this.size = 0;
}
this.closeable = closeable;
}
public long getStart() {
return start;
}
public OkHttpResultIterator<T> setStart(long start) {
this.start = start;
return this;
}
public long getSize() {
return size;
}
public OkHttpResultIterator<T> setSize(long size) {
this.size = size;
return this;
}
public long getPageSize() {
return pageSize;
}
public OkHttpResultIterator<T> setPageSize(long pageSize) {
this.pageSize = pageSize;
return this;
}
public long getTotalSize() {
return totalSize;
}
public OkHttpResultIterator<T> setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public boolean hasNext() {
if (partQueue == null) return false;
boolean hasNext = partQueue.hasNext();
return hasNext;
}
public T next() {
if (partQueue == null) return null;
try {
java.lang.reflect.Constructor<T> constructor =
clazz.getConstructor(OkHttpServices.class, RequestLogger.class, BodyPart.class);
return constructor.newInstance(new OkHttpServices(), reqlog, partQueue.next());
} catch (Throwable t) {
throw new IllegalStateException("Error instantiating " + clazz.getName(), t);
}
}
public void remove() {
if (partQueue == null) return;
partQueue.remove();
if (!partQueue.hasNext()) close();
}
public void close() {
partQueue = null;
reqlog = null;
if ( closeable != null ) {
try {
closeable.close();
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
}
}
public class OkHttpServiceResultIterator
extends OkHttpResultIterator<OkHttpServiceResult>
implements RESTServiceResultIterator
{
public OkHttpServiceResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Closeable closeable) {
super(reqlog, partList, OkHttpServiceResult.class, closeable);
}
}
public class DefaultOkHttpResultIterator
extends OkHttpResultIterator<OkHttpResult>
implements Iterator<OkHttpResult>
{
public DefaultOkHttpResultIterator(RequestLogger reqlog,
List<BodyPart> partList, Closeable closeable) {
super(reqlog, partList, OkHttpResult.class, closeable);
}
}
public class OkHttpDocumentRecord implements DocumentRecord {
private OkHttpResult content;
private OkHttpResult metadata;
public OkHttpDocumentRecord(OkHttpResult content, OkHttpResult metadata) {
this.content = content;
this.metadata = metadata;
}
public OkHttpDocumentRecord(OkHttpResult content) {
this.content = content;
}
@Override
public String getUri() {
if ( content == null && metadata != null ) {
return metadata.getUri();
} else if ( content != null ) {
return content.getUri();
} else {
throw new IllegalStateException("Missing both content and metadata!");
}
}
@Override
public Format getFormat() {
return content.getFormat();
}
@Override
public String getMimetype() {
return content.getMimetype();
}
@Override
public <T extends DocumentMetadataReadHandle> T getMetadata(T metadataHandle) {
if ( metadata == null ) {
throw new IllegalStateException("getMetadata called when no metadata is available");
}
return metadata.getContent(metadataHandle);
}
@Override
public <T> T getMetadataAs(Class<T> as) {
if ( as == null ) {
throw new IllegalStateException("getMetadataAs cannot accept null");
}
return metadata.getContentAs(as);
}
@Override
public <T extends AbstractReadHandle> T getContent(T contentHandle) {
if ( content == null ) {
throw new IllegalStateException("getContent called when no content is available");
}
return content.getContent(contentHandle);
}
@Override
public <T> T getContentAs(Class<T> as) {
if ( as == null ) {
throw new IllegalStateException("getContentAs cannot accept null");
}
return content.getContentAs(as);
}
}
@Override
public OkHttpClient getClientImplementation() {
if (client == null) return null;
return client;
}
public void setClientImplementation(OkHttpClient client) {
this.client = client;
}
@Override
public <T> T suggest(Class<T> as, SuggestDefinition suggestionDef) {
RequestParameters params = new RequestParameters();
String suggestCriteria = suggestionDef.getStringCriteria();
String[] queries = suggestionDef.getQueryStrings();
String optionsName = suggestionDef.getOptionsName();
Integer limit = suggestionDef.getLimit();
Integer cursorPosition = suggestionDef.getCursorPosition();
if (suggestCriteria != null) {
params.add("partial-q", suggestCriteria);
}
if (optionsName != null) {
params.add("options", optionsName);
}
if (limit != null) {
params.add("limit", Long.toString(limit));
}
if (cursorPosition != null) {
params.add("cursor-position", Long.toString(cursorPosition));
}
if (queries != null) {
for (String stringQuery : queries) {
params.add("q", stringQuery);
}
}
Request.Builder requestBldr = null;
requestBldr = setupRequest("suggest", params, null, MIMETYPE_APPLICATION_XML);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return sendRequestOnce(funcBuilder.get().build());
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException(
"User is not allowed to get suggestions",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("Suggest call failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
T entity = body.contentLength() != 0 ? getEntity(body, as) : null;
if (entity == null || (as != InputStream.class && as != Reader.class)) {
response.close();
}
return entity;
}
@Override
public InputStream match(StructureWriteHandle document,
String[] candidateRules, String mimeType, ServerTransform transform) {
RequestParameters params = new RequestParameters();
HandleImplementation baseHandle = HandleAccessor.checkHandle(document, "match");
if (candidateRules != null) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (transform != null) {
transform.merge(params);
}
Request.Builder requestBldr = null;
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, mimeType);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doPostFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doPost(null, funcBuilder, baseHandle.sendContent());
}
};
Response response = sendRequestWithRetry(requestBldr, doPostFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
@Override
public InputStream match(QueryDefinition queryDef,
long start, long pageLength, String[] candidateRules, ServerTransform transform) {
if (queryDef == null) {
throw new IllegalArgumentException("Cannot match null query");
}
RequestParameters params = new RequestParameters();
if (start > 1) {
params.add("start", Long.toString(start));
}
if (pageLength >= 0) {
params.add("pageLength", Long.toString(pageLength));
}
if (transform != null) {
transform.merge(params);
}
if (candidateRules.length > 0) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (queryDef.getOptionsName() != null) {
params.add("options", queryDef.getOptionsName());
}
Request.Builder requestBldr = null;
String structure = null;
HandleImplementation baseHandle = null;
String text = null;
if (queryDef instanceof StringQueryDefinition) {
text = ((StringQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof StructuredQueryDefinition) {
text = ((StructuredQueryDefinition) queryDef).getCriteria();
} else if (queryDef instanceof RawStructuredQueryDefinition) {
text = ((RawStructuredQueryDefinition) queryDef).getCriteria();
}
if (text != null) {
params.add("q", text);
}
if (queryDef instanceof StructuredQueryDefinition) {
structure = ((StructuredQueryDefinition) queryDef).serialize();
logger.debug("Searching with structured query {}", structure);
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
} else if (queryDef instanceof RawQueryDefinition) {
StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();
baseHandle = HandleAccessor.checkHandle(handle, "match");
logger.debug("Searching with raw query");
requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
} else if (queryDef instanceof StringQueryDefinition) {
logger.debug("Searching with string query [{}]", text);
requestBldr = setupRequest("alert/match", params, null, MIMETYPE_APPLICATION_XML);
} else {
throw new UnsupportedOperationException("Cannot match with "
+ queryDef.getClass().getName());
}
requestBldr = addTelemetryAgentId(requestBldr);
MediaType mediaType = makeType(requestBldr.build().header(HEADER_CONTENT_TYPE));
Response response = null;
int status = -1;
long startTime = System.currentTimeMillis();
int nextDelay = 0;
int retry = 0;
for (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {
if (nextDelay > 0) {
try {
Thread.sleep(nextDelay);
} catch (InterruptedException e) {
}
}
if (queryDef instanceof StructuredQueryDefinition) {
response = sendRequestOnce(requestBldr.post(RequestBody.create(mediaType, structure)));
response = doPost(null, requestBldr, structure);
} else if (queryDef instanceof RawQueryDefinition) {
response = doPost(null, requestBldr, baseHandle.sendContent());
} else if (queryDef instanceof StringQueryDefinition) {
response = sendRequestOnce(requestBldr.get());
} else {
throw new UnsupportedOperationException("Cannot match with "
+ queryDef.getClass().getName());
}
status = response.code();
if (!retryStatus.contains(status)) {
if (isFirstRequest()) setFirstRequest(false);
break;
}
String retryAfterRaw = response.header("Retry-After");
int retryAfter = (retryAfterRaw != null) ? Integer.parseInt(retryAfterRaw) : -1;
response.close();
nextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));
}
if (retryStatus.contains(status)) {
checkFirstRequest();
throw new FailedRetryException(
"Service unavailable and maximum retry period elapsed: "+
Math.round((System.currentTimeMillis() - startTime) / 1000)+
" seconds after "+retry+" retries");
}
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
@Override
public InputStream match(String[] docIds, String[] candidateRules, ServerTransform transform) {
RequestParameters params = new RequestParameters();
if (docIds.length > 0) {
for (String docId : docIds) {
params.add("uri", docId);
}
}
if (candidateRules.length > 0) {
for (String candidateRule : candidateRules) {
params.add("rule", candidateRule);
}
}
if (transform != null) {
transform.merge(params);
}
Request.Builder requestBldr = setupRequest("alert/match", params, MIMETYPE_APPLICATION_XML, MIMETYPE_APPLICATION_XML);
requestBldr = addTelemetryAgentId(requestBldr);
Function<Request.Builder, Response> doGetFunction = new Function<Request.Builder, Response>() {
public Response apply(Request.Builder funcBuilder) {
return doGet(funcBuilder);
}
};
Response response = sendRequestWithRetry(requestBldr, doGetFunction, null);
int status = response.code();
if (status == STATUS_FORBIDDEN) {
throw new ForbiddenUserException("User is not allowed to match",
extractErrorFields(response));
}
if (status != STATUS_OK) {
throw new FailedRequestException("match failed: "
+ getReasonPhrase(response), extractErrorFields(response));
}
ResponseBody body = response.body();
InputStream entity = body.contentLength() != 0 ?
getEntity(body, InputStream.class) : null;
if (entity == null) response.close();
return entity;
}
private void addGraphUriParam(RequestParameters params, String uri) {
if ( uri == null || uri.equals(GraphManager.DEFAULT_GRAPH) ) {
params.add("default", "");
} else {
params.add("graph", uri);
}
}
private void addPermsParams(RequestParameters params, GraphPermissions permissions) {
if ( permissions != null ) {
for ( Map.Entry<String,Set<Capability>> entry : permissions.entrySet() ) {
if ( entry.getValue() != null ) {
for ( Capability capability : entry.getValue() ) {
params.add("perm:" + entry.getKey(), capability.toString().toLowerCase());
}
}
}
}
}
@Override
public <R extends AbstractReadHandle> R getGraphUris(RequestLogger reqlog, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
return getResource(reqlog, "graphs", null, null, output);
}
@Override
public <R extends AbstractReadHandle> R readGraph(RequestLogger reqlog, String uri, R output,
Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
return getResource(reqlog, "graphs", transaction, params, output);
}
@Override
public void writeGraph(RequestLogger reqlog, String uri,
AbstractWriteHandle input, GraphPermissions permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
addPermsParams(params, permissions);
putResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void writeGraphs(RequestLogger reqlog, AbstractWriteHandle input, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
putResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void mergeGraph(RequestLogger reqlog, String uri,
AbstractWriteHandle input, GraphPermissions permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
addPermsParams(params, permissions);
postResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public void mergeGraphs(RequestLogger reqlog, AbstractWriteHandle input, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
postResource(reqlog, "graphs", transaction, params, input, null);
}
@Override
public <R extends AbstractReadHandle> R getPermissions(RequestLogger reqlog, String uri,
R output,Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
return getResource(reqlog, "graphs", transaction, params, output);
}
@Override
public void deletePermissions(RequestLogger reqlog, String uri, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
deleteResource(reqlog, "graphs", transaction, params, null);
}
@Override
public void writePermissions(RequestLogger reqlog, String uri,
AbstractWriteHandle permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
putResource(reqlog, "graphs", transaction, params, permissions, null);
}
@Override
public void mergePermissions(RequestLogger reqlog, String uri,
AbstractWriteHandle permissions, Transaction transaction)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
params.add("category", "permissions");
postResource(reqlog, "graphs", transaction, params, permissions, null);
}
@Override
public Object deleteGraph(RequestLogger reqlog, String uri, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
RequestParameters params = new RequestParameters();
addGraphUriParam(params, uri);
return deleteResource(reqlog, "graphs", transaction, params, null);
}
@Override
public void deleteGraphs(RequestLogger reqlog, Transaction transaction)
throws ForbiddenUserException, FailedRequestException
{
deleteResource(reqlog, "graphs", transaction, null, null);
}
@Override
public <R extends AbstractReadHandle> R getThings(RequestLogger reqlog, String[] iris, R output)
throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
{
if ( iris == null ) throw new IllegalArgumentException("iris cannot be null");
RequestParameters params = new RequestParameters();
for ( String iri : iris ) {
params.add("iri", iri);
}
return getResource(reqlog, "graphs/things", null, params, output);
}
@Override
public <R extends AbstractReadHandle> R executeSparql(RequestLogger reqlog,
SPARQLQueryDefinition qdef, R output, long start, long pageLength,
Transaction transaction, boolean isUpdate)
{
if ( qdef == null ) throw new IllegalArgumentException("qdef cannot be null");
if ( output == null ) throw new IllegalArgumentException("output cannot be null");
RequestParameters params = new RequestParameters();
if (start > 1) params.add("start", Long.toString(start));
if (pageLength >= 0) params.add("pageLength", Long.toString(pageLength));
if (qdef.getOptimizeLevel() >= 0) {
params.add("optimize", Integer.toString(qdef.getOptimizeLevel()));
}
if (qdef.getCollections() != null ) {
for ( String collection : qdef.getCollections() ) {
params.add("collection", collection);
}
}
addPermsParams(params, qdef.getUpdatePermissions());
String sparql = qdef.getSparql();
SPARQLBindings bindings = qdef.getBindings();
for ( Map.Entry<String,List<SPARQLBinding>> entry : bindings.entrySet() ) {
String paramName = "bind:" + entry.getKey();
String typeOrLang = "";
for ( SPARQLBinding binding : entry.getValue() ) {
if ( binding.getDatatype() != null ) {
typeOrLang = ":" + binding.getDatatype();
} else if ( binding.getLanguageTag() != null ) {
typeOrLang = "@" + binding.getLanguageTag().toLanguageTag();
}
params.add(paramName + typeOrLang, binding.getValue());
}
}
QueryDefinition constrainingQuery = qdef.getConstrainingQueryDefinition();
StructureWriteHandle input;
if ( constrainingQuery != null ) {
if (qdef.getOptionsName()!= null && qdef.getOptionsName().length() > 0) {
params.add("options", qdef.getOptionsName());
}
if ( constrainingQuery instanceof RawCombinedQueryDefinition ) {
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
(RawCombinedQueryDefinition) constrainingQuery, null, null, sparql);
Format format = combinedQdef.getFormat();
input = new StringHandle(combinedQdef.serialize()).withFormat(format);
} else if ( constrainingQuery instanceof RawStructuredQueryDefinition ) {
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
(RawStructuredQueryDefinition) constrainingQuery, null, null, sparql);
Format format = combinedQdef.getFormat();
input = new StringHandle(combinedQdef.serialize()).withFormat(format);
} else if ( constrainingQuery instanceof StringQueryDefinition ||
constrainingQuery instanceof StructuredQueryDefinition )
{
String stringQuery = constrainingQuery instanceof StringQueryDefinition ?
((StringQueryDefinition) constrainingQuery).getCriteria() : null;
StructuredQueryDefinition structuredQuery =
constrainingQuery instanceof StructuredQueryDefinition ?
(StructuredQueryDefinition) constrainingQuery : null;
CombinedQueryDefinition combinedQdef = new CombinedQueryBuilderImpl().combine(
structuredQuery, null, stringQuery, sparql);
input = new StringHandle(combinedQdef.serialize()).withMimetype(MIMETYPE_APPLICATION_XML);
} else {
throw new IllegalArgumentException(
"Constraining query must be of type SPARQLConstrainingQueryDefinition");
}
} else {
String mimetype = isUpdate ? "application/sparql-update" : "application/sparql-query";
input = new StringHandle(sparql).withMimetype(mimetype);
}
if (qdef.getBaseUri() != null) {
params.add("base", qdef.getBaseUri());
}
if (qdef.getDefaultGraphUris() != null) {
for (String defaultGraphUri : qdef.getDefaultGraphUris()) {
params.add("default-graph-uri", defaultGraphUri);
}
}
if (qdef.getNamedGraphUris() != null) {
for (String namedGraphUri : qdef.getNamedGraphUris()) {
params.add("named-graph-uri", namedGraphUri);
}
}
if (qdef.getUsingGraphUris() != null) {
for (String usingGraphUri : qdef.getUsingGraphUris()) {
params.add("using-graph-uri", usingGraphUri);
}
}
if (qdef.getUsingNamedGraphUris() != null) {
for (String usingNamedGraphUri : qdef.getUsingNamedGraphUris()) {
params.add("using-named-graph-uri", usingNamedGraphUri);
}
}
// rulesets
if (qdef.getRulesets() != null) {
for (SPARQLRuleset ruleset : qdef.getRulesets()) {
params.add("ruleset", ruleset.getName());
}
}
if (qdef.getIncludeDefaultRulesets() != null) {
params.add("default-rulesets", qdef.getIncludeDefaultRulesets() ? "include" : "exclude");
}
return postResource(reqlog, "/graphs/sparql", transaction, params, input, output);
}
private String getTransactionId(Transaction transaction) {
if ( transaction == null ) return null;
return transaction.getTransactionId();
}
private String getReasonPhrase(Response response) {
if ( response.message() == null ) return "";
// strip off the number part of the reason phrase
return response.message().replaceFirst("^\\d+ ", "");
}
private <T> T getEntity(BodyPart part, Class<T> as) {
try {
String contentType = part.getContentType();
return getEntity(ResponseBody.create(MediaType.parse(contentType), part.getSize(),
Okio.buffer(Okio.source(part.getInputStream()))), as);
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private MediaType makeType(String mimetype) {
if ( mimetype == null ) return null;
MediaType type = MediaType.parse(mimetype);
if ( type == null ) throw new IllegalArgumentException("Invalid mime-type: " + mimetype);
return type;
}
private <T> T getEntity(ResponseBody body, Class<T> as) {
try {
if ( as == InputStream.class ) {
return (T) body.byteStream();
} else if ( as == byte[].class ) {
return (T) body.bytes();
} else if ( as == Reader.class ) {
return (T) body.charStream();
} else if ( as == String.class ) {
return (T) body.string();
} else if ( as == MimeMultipart.class ) {
ByteArrayDataSource dataSource = new ByteArrayDataSource(body.byteStream(), body.contentType().toString());
return (T) new MimeMultipart(dataSource);
} else if ( as == File.class ) {
// write out the response body to a temp file in the system temp folder
// then return the path to that file as a File object
String suffix = ".unknown";
boolean isBinary = true;
MediaType mediaType = body.contentType();
if ( mediaType != null ) {
suffix = "." + mediaType.subtype();
for ( String type : new String[] {"json", "xml", "xquery", "sjs", "javascript", "html"} ) {
if ( type.equalsIgnoreCase(mediaType.subtype()) ) {
isBinary = false;
}
}
if ( isBinary == true && "text".equalsIgnoreCase(mediaType.type()) ) {
suffix = ".txt";
isBinary = false;
}
}
Path path = Files.createTempFile("tmp", suffix);
if ( isBinary == true ) {
Files.write(path, body.bytes());
} else {
Writer out = Files.newBufferedWriter(path, Charset.forName("UTF-8"));
try {
out.write(body.string());
} finally {
out.close();
}
}
return (T) path.toFile();
} else {
throw new IllegalArgumentException(
"Handle recieveAs returned " + as + " which is not a supported type. " +
"Try InputStream, Reader, String, byte[], File.");
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private List<BodyPart> getPartList(MimeMultipart multipart) {
try {
if ( multipart == null ) return null;
List<BodyPart> partList = new ArrayList<BodyPart>();
for ( int i = 0; i < multipart.getCount(); i++ ) {
partList.add(multipart.getBodyPart(i));
}
return partList;
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
private class ObjectRequestBody extends RequestBody {
private Object obj;
private MediaType contentType;
ObjectRequestBody(Object obj, MediaType contentType) {
super();
this.obj = obj;
this.contentType = contentType;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if ( obj instanceof InputStream ) {
sink.writeAll(Okio.source((InputStream) obj));
} else if ( obj instanceof File ) {
try ( Source source = Okio.source((File) obj) ) {
sink.writeAll(source);
}
} else if ( obj instanceof byte[] ) {
sink.write((byte[]) obj);
} else if ( obj instanceof String) {
sink.write(((String) obj).getBytes("UTF-8"));
} else if ( obj == null ) {
} else {
throw new IllegalStateException("Cannot write object of type: " + obj.getClass());
}
}
}
private interface Function<T,R> {
R apply(T t);
}
private interface Consumer<T> {
void accept(T t);
}
// API First Changes
static private class EmptyRequestBody extends RequestBody {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) {
}
}
static class AtomicRequestBody extends RequestBody {
private MediaType contentType;
private String value;
AtomicRequestBody(String value, MediaType contentType) {
super();
this.value = value;
this.contentType = contentType;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(value);
}
}
public class CallRequestImpl implements CallRequest {
private SessionStateImpl session;
private Request.Builder requestBldr;
private RequestBody requestBody;
private boolean hasStreamingPart;
private HttpMethod method;
private String endpoint;
private HttpUrl callBaseUri;
CallRequestImpl(String endpoint, HttpMethod method, SessionState session) {
if (session != null && !(session instanceof SessionStateImpl)) {
throw new IllegalArgumentException("Session state must be implemented by internal class: "+session.getClass().getName());
}
this.endpoint = endpoint;
this.method = method;
this.session = (SessionStateImpl) session;
this.hasStreamingPart = false;
this.callBaseUri = new HttpUrl.Builder()
.scheme(baseUri.scheme())
.host(baseUri.host())
.port(baseUri.port())
.encodedPath("/")
.build();
}
@Override
public CallResponse withEmptyResponse() {
prepareRequestBuilder();
CallResponseImpl responseImpl = new CallResponseImpl();
executeRequest(responseImpl);
return responseImpl;
}
@Override
public SingleCallResponse withDocumentResponse(Format format) {
prepareRequestBuilder();
SingleCallResponseImpl responseImpl = new SingleCallResponseImpl(format);
this.requestBldr = forDocumentResponse(requestBldr, format);
executeRequest(responseImpl);
return responseImpl;
}
@Override
public MultipleCallResponse withMultipartMixedResponse(Format format) {
prepareRequestBuilder();
MultipleCallResponseImpl responseImpl = new MultipleCallResponseImpl(format);
this.requestBldr = forMultipartMixedResponse(requestBldr);
executeRequest(responseImpl);
return responseImpl;
}
@Override
public boolean hasStreamingPart() {
return this.hasStreamingPart;
}
@Override
public SessionState getSession() {
return this.session;
}
@Override
public String getEndpoint() {
return this.endpoint;
}
@Override
public HttpMethod getHttpMethod() {
return this.method;
}
private void prepareRequestBuilder() {
this.requestBldr = setupRequest(callBaseUri, endpoint, null);
if (session != null) {
this.requestBldr = addCookies(this.requestBldr, session.getCookies(), session.getCreatedTimestamp());
// Add the Cookie header for SessionId if we have a session object passed
this.requestBldr.addHeader(HEADER_COOKIE, "SessionID="+session.getSessionId());
}
addHttpMethod();
this.requestBldr.addHeader(HEADER_ERROR_FORMAT, MIMETYPE_APPLICATION_JSON);
}
private void addHttpMethod() {
if(method != null && method == HttpMethod.POST) {
if(requestBody == null) {
throw new IllegalStateException("Request Body is null!");
}
this.requestBldr.post(requestBody);
} else {
throw new IllegalStateException("HTTP method is null or invalid!");
}
}
private void executeRequest(CallResponseImpl responseImpl) {
SessionState session = getSession();
//TODO: Add a telemetry agent if needed
// requestBuilder = addTelemetryAgentId(requestBuilder);
boolean hasStreamingPart = hasStreamingPart();
Consumer<Boolean> resendableConsumer = resendable -> {
if (hasStreamingPart) {
checkFirstRequest();
throw new ResourceNotResendableException(
"Cannot retry request for " + getEndpoint());
}
};
Function<Request.Builder, Response> sendRequestFunction = requestBldr -> {
if (isFirstRequest() && hasStreamingPart) makeFirstRequest(callBaseUri, "", 0);
Response response = sendRequestOnce(requestBldr);
if (isFirstRequest()) setFirstRequest(false);
return response;
};
Response response = sendRequestWithRetry(requestBldr, sendRequestFunction, resendableConsumer);
if(session != null) {
List<ClientCookie> cookies = new ArrayList<>();
for ( String setCookie : response.headers(HEADER_SET_COOKIE) ) {
ClientCookie cookie = ClientCookie.parse(requestBldr.build().url(), setCookie);
cookies.add(cookie);
}
((SessionStateImpl)session).setCookies(cookies);
}
checkStatus(response);
responseImpl.setResponse(response);
}
private void checkStatus(Response response) {
int statusCode = response.code();
if (statusCode >= 300) {
FailedRequest failure = null;
MediaType mediaType = MediaType.parse(response.header(HEADER_CONTENT_TYPE));
if ( "json".equals(mediaType.subtype()) ) {
failure = extractErrorFields(response);
} else if ( statusCode == STATUS_UNAUTHORIZED ) {
failure = new FailedRequest();
failure.setMessageString("Unauthorized");
failure.setStatusString("Failed Auth");
} else if (statusCode == STATUS_NOT_FOUND) {
ResourceNotFoundException ex = failure == null ? new ResourceNotFoundException("Could not " + method + " at " + endpoint) :
new ResourceNotFoundException("Could not " + method + " at " + endpoint, failure);
throw ex;
} else if (statusCode == STATUS_FORBIDDEN) {
ForbiddenUserException ex = failure == null ? new ForbiddenUserException("User is not allowed to " + method + " at " + endpoint) :
new ForbiddenUserException("User is not allowed to " + method + " at " + endpoint, failure);
throw ex;
} else {
failure = new FailedRequest();
failure.setStatusCode(statusCode);
failure.setMessageCode("UNKNOWN");
failure.setMessageString("Server did not respond with an expected Error message.");
failure.setStatusString("UNKNOWN");
}
FailedRequestException ex = failure == null ? new FailedRequestException("failed to " + method + " at " + endpoint + ": "
+ getReasonPhrase(response)) : new FailedRequestException("failed to " + method + " at " + endpoint + ": "
+ getReasonPhrase(response), failure);
throw ex;
}
}
public CallRequest withEmptyRequest() {
requestBody = new EmptyRequestBody();
return this;
}
public CallRequest withAtomicBodyRequest(CallField... params) {
String atomics = Stream.of(params)
.map(param -> encodeParamValue(param))
.filter(param -> param != null)
.collect(Collectors.joining("&"));
requestBody = RequestBody.create(URLENCODED_MIME_TYPE, (atomics == null) ? "" : atomics);
return this;
}
public CallRequest withNodeBodyRequest(CallField... params) {
this.requestBody = makeRequestBody(params);
return this;
}
private RequestBody makeRequestBody(String value) {
if (value == null) {
return new EmptyRequestBody();
}
return new AtomicRequestBody(value, MediaType.parse("text/plain"));
}
private RequestBody makeRequestBody(AbstractWriteHandle document) {
if (document == null) {
return new EmptyRequestBody();
}
HandleImplementation handleBase = HandleAccessor.as(document);
Format format = handleBase.getFormat();
String mimetype = (format == Format.BINARY) ?
"application/x-unknown-content-type" : handleBase.getMimetype();
MediaType mediaType = MediaType.parse(mimetype);
return (document instanceof OutputStreamSender) ?
new StreamingOutputImpl((OutputStreamSender) document, null, mediaType) :
new ObjectRequestBody(HandleAccessor.sendContent(document), mediaType);
}
private RequestBody makeRequestBody(CallField[] params) {
if (params == null || params.length == 0) {
return new EmptyRequestBody();
}
MultipartBody.Builder multiBldr = new MultipartBody.Builder();
multiBldr.setType(MultipartBody.FORM);
Condition hasValue = new Condition();
Condition hasStreamingPartCondition = new Condition();
for (CallField param: params) {
if (param == null) {
continue;
}
final String paramName = param.getParamName();
if (param instanceof SingleAtomicCallField) {
String paramValue = ((SingleAtomicCallField) param).getParamValue();
if (paramValue != null) {
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
}
} else if (param instanceof MultipleAtomicCallField) {
Stream<String> paramValues = ((MultipleAtomicCallField) param).getParamValues();
if (paramValues != null) {
paramValues
.filter(paramValue -> paramValue != null)
.forEachOrdered(paramValue ->
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue))
);
}
} else if (param instanceof SingleNodeCallField) {
AbstractWriteHandle paramValue = ((SingleNodeCallField) param).getParamValue();
if (paramValue != null) {
HandleImplementation handleBase = HandleAccessor.as(paramValue);
if(! handleBase.isResendable()) {
hasStreamingPartCondition.set();
}
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
}
} else if (param instanceof MultipleNodeCallField) {
Stream<? extends AbstractWriteHandle> paramValues = ((MultipleNodeCallField) param).getParamValues();
if (paramValues != null) {
paramValues
.filter(paramValue -> paramValue != null)
.forEachOrdered(paramValue -> {
HandleImplementation handleBase = HandleAccessor.as(paramValue);
if(!handleBase.isResendable()) {
hasStreamingPartCondition.set();
}
hasValue.set();
multiBldr.addFormDataPart(paramName, null, makeRequestBody(paramValue));
});
}
} else {
throw new IllegalStateException(
"unknown multipart "+paramName+" param of: "+param.getClass().getName()
);
}
}
if (!hasValue.get()) {
return new EmptyRequestBody();
}
this.hasStreamingPart = hasStreamingPartCondition.get();
return multiBldr.build();
}
}
@Override
public CallRequest makeEmptyRequest(String endpoint, HttpMethod method, SessionState session) {
return new CallRequestImpl(endpoint, method, session).withEmptyRequest();
}
@Override
public CallRequest makeAtomicBodyRequest(String endpoint, HttpMethod method, SessionState session, CallField... params) {
if (params == null || params.length == 0) {
return makeEmptyRequest(endpoint, method, session);
}
return new CallRequestImpl(endpoint, method, session).withAtomicBodyRequest(params);
}
@Override
public CallRequest makeNodeBodyRequest(String endpoint, HttpMethod method, SessionState session, CallField... params) {
if (params == null || params.length == 0) {
return makeEmptyRequest(endpoint, method, session);
}
return new CallRequestImpl(endpoint, method, session).withNodeBodyRequest(params);
}
private String encodeParamValue(String paramName, String value) {
if (value == null) {
return null;
}
try {
return paramName+"="+URLEncoder.encode(value, UTF8_ID);
} catch(UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 is unsupported", e);
}
}
private String encodeParamValue(SingleAtomicCallField param) {
if (param == null) {
return null;
}
return encodeParamValue(param.getParamName(), param.getParamValue());
}
private String encodeParamValue(MultipleAtomicCallField param) {
if (param == null) {
return null;
}
String paramName = param.getParamName();
Stream<String> paramValues = param.getParamValues();
if (paramValues == null) {
return null;
}
String encodedParamValues = paramValues
.map(paramValue -> encodeParamValue(paramName, paramValue))
.filter(paramValue -> (paramValue != null))
.collect(Collectors.joining("&"));
if (encodedParamValues == null || encodedParamValues.length() == 0) {
return null;
}
return encodedParamValues;
}
private String encodeParamValue(CallField param) {
if (param == null) {
return null;
} else if (param instanceof SingleAtomicCallField) {
return encodeParamValue((SingleAtomicCallField) param);
} else if (param instanceof MultipleAtomicCallField) {
return encodeParamValue((MultipleAtomicCallField) param);
}
throw new IllegalStateException(
"could not encode parameter "+param.getParamName()+" of type: "+param.getClass().getName()
);
}
static class CallResponseImpl implements CallResponse {
private boolean isNull = true;
private Response response;
void setResponse(Response response) {
this.response = response;
}
@Override
public boolean isNull() {
return isNull;
}
void setNull(boolean isNull) {
this.isNull = isNull;
}
@Override
public int getStatusCode() {
return response.code();
}
@Override
public String getStatusMsg() {
return response.message();
}
//TODO: Check if this is needed since we are parsing it in the checkStatus(Respose).
//TODO: It might throw a closed exception since the response would be closed. Remove it after some testing
@Override
public String getErrorBody() {
try (ResponseBody errorBody = response.body()) {
if (errorBody.contentLength() > 0) {
MediaType errorType = errorBody.contentType();
if (errorType != null) {
String errorContentType = errorType.toString();
if (errorContentType != null && errorContentType.startsWith("application/") && errorContentType.contains("json")) {
return errorBody.string();
}
}
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
return null;
}
}
static class SingleCallResponseImpl extends CallResponseImpl implements SingleCallResponse, AutoCloseable {
private Format format;
private ResponseBody responseBody;
SingleCallResponseImpl(Format format) {
this.format = format;
}
void setResponse(Response response) {
super.setResponse(response);
setResponseBody(response.body());
}
void setResponseBody(ResponseBody responseBody) {
if (!checkNull(responseBody, format)) {
this.responseBody = responseBody;
setNull(false);
}
}
@Override
public byte[] asBytes() {
try {
if (responseBody == null) {
return null;
}
byte[] value = responseBody.bytes();
closeImpl();
return value;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public InputStream asInputStream() {
return (responseBody == null) ? null : responseBody.byteStream();
}
@Override
public InputStreamHandle asInputStreamHandle() {
return (responseBody == null) ? null : new InputStreamHandle(asInputStream());
}
@Override
public Reader asReader() {
return (responseBody == null) ? null : responseBody.charStream();
}
@Override
public ReaderHandle asReaderHandle() {
return (responseBody == null) ? null : new ReaderHandle(asReader());
}
@Override
public String asString() {
try {
if (responseBody == null) {
return null;
}
String value = responseBody.string();
closeImpl();
return value;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public void close() throws Exception {
if (responseBody != null) {
closeImpl();
}
}
private void closeImpl() {
responseBody.close();
responseBody = null;
}
}
static class MultipleCallResponseImpl extends CallResponseImpl implements MultipleCallResponse {
private Format format;
private MimeMultipart multipart;
MultipleCallResponseImpl(Format format){
this.format = format;
}
void setResponse(Response response) {
try {
super.setResponse(response);
ResponseBody responseBody = response.body();
if (responseBody == null) {
setNull(true);
return;
}
MediaType contentType = responseBody.contentType();
if (contentType == null) {
setNull(true);
return;
}
ByteArrayDataSource dataSource = new ByteArrayDataSource(
responseBody.byteStream(), contentType.toString()
);
setMultipart(new MimeMultipart(dataSource));
} catch (IOException e) {
throw new MarkLogicIOException(e);
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
}
}
void setMultipart(MimeMultipart multipart) {
if (!checkNull(multipart, format)) {
this.multipart = multipart;
setNull(false);
}
}
@Override
public Stream<byte[]> asStreamOfBytes() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<byte[]> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToBytes(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public Stream<InputStreamHandle> asStreamOfInputStreamHandle() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<InputStreamHandle> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(new InputStreamHandle(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<InputStream> asStreamOfInputStream() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<InputStream> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(bodyPart.getInputStream());
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<Reader> asStreamOfReader() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<Reader> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToReader(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<ReaderHandle> asStreamOfReaderHandle() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<ReaderHandle> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(new ReaderHandle(NodeConverter.InputStreamToReader(bodyPart.getInputStream())));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Stream<String> asStreamOfString() {
try {
if (multipart == null) {
return Stream.empty();
}
int partCount = multipart.getCount();
Stream.Builder<String> builder = Stream.builder();
for (int i=0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
builder.accept(NodeConverter.InputStreamToString(bodyPart.getInputStream()));
}
return builder.build();
} catch (MessagingException e) {
throw new MarkLogicIOException(e);
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
}
static protected boolean checkNull(ResponseBody body, Format format) {
if (body != null) {
if (body.contentLength() == 0) {
body.close();
} else {
MediaType actualType = body.contentType();
String defaultType = (format == Format.BINARY) ?
"application/x-unknown-content-type" : format.getDefaultMimetype();
if (actualType == null) {
body.close();
throw new RuntimeException(
"Returned document with unknown mime type instead of "+defaultType
);
} else if (!actualType.toString().startsWith(defaultType)) {
body.close();
throw new RuntimeException(
"Returned document as "+actualType.toString()+" instead of "+defaultType
);
}
return false;
}
}
return true;
}
static protected boolean checkNull(MimeMultipart multipart, Format format) {
if (multipart != null) {
try {
if (multipart.getCount() != 0) {
BodyPart firstPart = multipart.getBodyPart(0);
String actualType = (firstPart == null) ? null : firstPart.getContentType();
String defaultType = (format == Format.BINARY) ?
"application/x-unknown-content-type" : format.getDefaultMimetype();
if (actualType == null || !actualType.startsWith(defaultType)) {
throw new RuntimeException(
"Returned document as "+actualType+" instead of "+defaultType
);
}
return false;
}
} catch (MessagingException e) {
new MarkLogicIOException(e);
}
}
return true;
}
Request.Builder forDocumentResponse(Request.Builder requestBldr, Format format) {
return requestBldr.addHeader(HEADER_ACCEPT, (format == Format.BINARY) ? "application/x-unknown-content-type" : format.getDefaultMimetype());
}
Request.Builder forMultipartMixedResponse(Request.Builder requestBldr) {
return requestBldr.addHeader(HEADER_ACCEPT, multipartMixedWithBoundary());
}
static protected class Condition {
private boolean is = false;
protected boolean get() {
return is;
}
protected void set() {
if (!is)
is = true;
}
}
}
| Added the suggested changes. Also removed some unused imports. | marklogic-client-api/src/main/java/com/marklogic/client/impl/OkHttpServices.java | Added the suggested changes. Also removed some unused imports. |
|
Java | apache-2.0 | 0d1432c967540a577fc166f338cb25159f28a327 | 0 | saikrishna321/java-client,appium/java-client,saikrishna321/java-client,TikhomirovSergey/java-client,saikrishna321/java-client,rafael-chavez/java-client,TikhomirovSergey/java-client,rafael-chavez/java-client,rafael-chavez/java-client,YOU-i-Labs/appium-java-client,TikhomirovSergey/java-client,rafael-chavez/java-client,SrinivasanTarget/java-client,YOU-i-Labs/appium-java-client,saikrishna321/java-client,appium/java-client,SrinivasanTarget/java-client,YOU-i-Labs/appium-java-client,SrinivasanTarget/java-client,YOU-i-Labs/appium-java-client,TikhomirovSergey/java-client,SrinivasanTarget/java-client | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.logging.LoggingPreferences;
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* The main interface to use for testing, which represents an idealised web browser. The methods in
* this class fall into three categories:
* <ul>
* <li>Control of the browser itself</li>
* <li>Selection of {@link WebElement}s</li>
* <li>Debugging aids</li>
* </ul>
* <p>
* Key methods are {@link WebDriver#get(String)}, which is used to load a new web page, and the
* various methods similar to {@link WebDriver#findElement(By)}, which is used to find
* {@link WebElement}s.
* <p>
* Currently, you will need to instantiate implementations of this class directly. It is hoped that
* you write your tests against this interface so that you may "swap in" a more fully featured
* browser when there is a requirement for one.
* <p>
* Note that all methods that use XPath to locate elements will throw a {@link RuntimeException}
* should there be an error thrown by the underlying XPath engine.
*/
public interface WebDriver extends SearchContext {
// Navigation
/**
* Load a new web page in the current browser window. This is done using an HTTP GET operation,
* and the method will block until the load is complete. This will follow redirects issued either
* by the server or as a meta-redirect from within the returned HTML. Should a meta-redirect
* "rest" for any duration of time, it is best to wait until this timeout is over, since should
* the underlying page change whilst your test is executing the results of future calls against
* this interface will be against the freshly loaded page. Synonym for
* {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
*
* @param url The URL to load. It is best to use a fully qualified URL
*/
void get(String url);
/**
* Get a string representing the current URL that the browser is looking at.
*
* @return The URL of the page currently loaded in the browser
*/
String getCurrentUrl();
// General properties
/**
* The title of the current page.
*
* @return The title of the current page, with leading and trailing whitespace stripped, or null
* if one is not already set
*/
String getTitle();
/**
* Find all elements within the current page using the given mechanism.
* This method is affected by the 'implicit wait' times in force at the time of execution. When
* implicitly waiting, this method will return as soon as there are more than 0 items in the
* found collection, or will return an empty list if the timeout is reached.
*
* @param by The locating mechanism to use
* @return A list of all {@link WebElement}s, or an empty list if nothing matches
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
List<WebElement> findElements(By by);
/**
* Find the first {@link WebElement} using the given method.
* This method is affected by the 'implicit wait' times in force at the time of execution.
* The findElement(..) invocation will return a matching row, or try again repeatedly until
* the configured timeout is reached.
*
* findElement should not be used to look for non-present elements, use {@link #findElements(By)}
* and assert zero length response instead.
*
* @param by The locating mechanism
* @return The first matching element on the current page
* @throws NoSuchElementException If no matching elements are found
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
WebElement findElement(By by);
// Misc
/**
* Get the source of the last loaded page. If the page has been modified after loading (for
* example, by Javascript) there is no guarantee that the returned text is that of the modified
* page. Please consult the documentation of the particular driver being used to determine whether
* the returned text reflects the current state of the page or the text last sent by the web
* server. The page source returned is a representation of the underlying DOM: do not expect it to
* be formatted or escaped in the same way as the response sent from the web server. Think of it as
* an artist's impression.
*
* @return The source of the current page
*/
String getPageSource();
/**
* Close the current window, quitting the browser if it's the last window currently open.
*/
void close();
/**
* Quits this driver, closing every associated window.
*/
void quit();
/**
* Return a set of window handles which can be used to iterate over all open windows of this
* WebDriver instance by passing them to {@link #switchTo()}.{@link Options#window()}
*
* @return A set of window handles which can be used to iterate over all open windows.
*/
Set<String> getWindowHandles();
/**
* Return an opaque handle to this window that uniquely identifies it within this driver instance.
* This can be used to switch to this window at a later date
*
* @return the current window handle
*/
String getWindowHandle();
/**
* Send future commands to a different frame or window.
*
* @return A TargetLocator which can be used to select a frame or window
* @see org.openqa.selenium.WebDriver.TargetLocator
*/
TargetLocator switchTo();
/**
* An abstraction allowing the driver to access the browser's history and to navigate to a given
* URL.
*
* @return A {@link org.openqa.selenium.WebDriver.Navigation} that allows the selection of what to
* do next
*/
Navigation navigate();
/**
* Gets the Option interface
*
* @return An option interface
* @see org.openqa.selenium.WebDriver.Options
*/
Options manage();
/**
* An interface for managing stuff you would do in a browser menu
*/
interface Options {
/**
* Add a specific cookie. If the cookie's domain name is left blank, it is assumed that the
* cookie is meant for the domain of the current document.
*
* @param cookie The cookie to add.
*/
void addCookie(Cookie cookie);
/**
* Delete the named cookie from the current domain. This is equivalent to setting the named
* cookie's expiry date to some time in the past.
*
* @param name The name of the cookie to delete
*/
void deleteCookieNamed(String name);
/**
* Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored.
*
* @param cookie nom nom nom
*/
void deleteCookie(Cookie cookie);
/**
* Delete all the cookies for the current domain.
*/
void deleteAllCookies();
/**
* Get all the cookies for the current domain. This is the equivalent of calling
* "document.cookie" and parsing the result
*
* @return A Set of cookies for the current domain.
*/
Set<Cookie> getCookies();
/**
* Get a cookie with a given name.
*
* @param name the name of the cookie
* @return the cookie, or null if no cookie with the given name is present
*/
Cookie getCookieNamed(String name);
/**
* @return the interface for managing driver timeouts.
*/
Timeouts timeouts();
/**
* @return the interface for controlling IME engines to generate complex-script input.
*/
ImeHandler ime();
/**
* @return the interface for managing the current window.
*/
@Beta
Window window();
/**
* Gets the {@link Logs} interface used to fetch different types of logs.
*
* <p>To set the logging preferences {@link LoggingPreferences}.
*
* @return A Logs interface.
*/
@Beta
Logs logs();
}
/**
* An interface for managing timeout behavior for WebDriver instances.
*/
interface Timeouts {
/**
* Specifies the amount of time the driver should wait when searching for an element if it is
* not immediately present.
* <p>
* When searching for a single element, the driver should poll the page until the element has
* been found, or this timeout expires before throwing a {@link NoSuchElementException}. When
* searching for multiple elements, the driver should poll the page until at least one element
* has been found or this timeout has expired.
* <p>
* Increasing the implicit wait timeout should be used judiciously as it will have an adverse
* effect on test run time, especially when used with slower location strategies like XPath.
*
* @param time The amount of time to wait.
* @param unit The unit of measure for {@code time}.
* @return A self reference.
*/
Timeouts implicitlyWait(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, then the script will be allowed to run
* indefinitely.
*
* @param time The timeout value.
* @param unit The unit of time.
* @return A self reference.
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
*/
Timeouts setScriptTimeout(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for a page load to complete before throwing an error.
* If the timeout is negative, page loads can be indefinite.
*
* @param time The timeout value.
* @param unit The unit of time.
* @return A Timeouts interface.
*/
Timeouts pageLoadTimeout(long time, TimeUnit unit);
}
/**
* Used to locate a given frame or window.
*/
interface TargetLocator {
/**
* Select a frame by its (zero-based) index. Selecting a frame by index is equivalent to the
* JS expression window.frames[index] where "window" is the DOM window represented by the
* current context. Once the frame has been selected, all subsequent calls on the WebDriver
* interface are made to that frame.
*
* @param index (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(int index);
/**
* Select a frame by its name or ID. Frames located by matching name attributes are always given
* precedence over those matched by ID.
*
* @param nameOrId the name of the frame window, the id of the <frame> or <iframe>
* element, or the (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(String nameOrId);
/**
* Select a frame using its previously located {@link WebElement}.
*
* @param frameElement The frame element to switch to.
* @return This driver focused on the given frame.
* @throws NoSuchFrameException If the given element is neither an IFRAME nor a FRAME element.
* @throws StaleElementReferenceException If the WebElement has gone stale.
* @see WebDriver#findElement(By)
*/
WebDriver frame(WebElement frameElement);
/**
* Change focus to the parent context. If the current context is the top level browsing context,
* the context remains unchanged.
*
* @return This driver focused on the parent frame
*/
WebDriver parentFrame();
/**
* Switch the focus of future commands for this driver to the window with the given name/handle.
*
* @param nameOrHandle The name of the window or the handle as returned by
* {@link WebDriver#getWindowHandle()}
* @return This driver focused on the given window
* @throws NoSuchWindowException If the window cannot be found
*/
WebDriver window(String nameOrHandle);
/**
* Selects either the first frame on the page, or the main document when a page contains
* iframes.
*
* @return This driver focused on the top window/first frame.
*/
WebDriver defaultContent();
/**
* Switches to the element that currently has focus within the document currently "switched to",
* or the body element if this cannot be detected. This matches the semantics of calling
* "document.activeElement" in Javascript.
*
* @return The WebElement with focus, or the body element if no element with focus can be
* detected.
*/
WebElement activeElement();
/**
* Switches to the currently active modal dialog for this particular driver instance.
*
* @return A handle to the dialog.
* @throws NoAlertPresentException If the dialog cannot be found
*/
Alert alert();
}
interface Navigation {
/**
* Move back a single "item" in the browser's history.
*/
void back();
/**
* Move a single "item" forward in the browser's history. Does nothing if we are on the latest
* page viewed.
*/
void forward();
/**
* Load a new web page in the current browser window. This is done using an HTTP GET operation,
* and the method will block until the load is complete. This will follow redirects issued
* either by the server or as a meta-redirect from within the returned HTML. Should a
* meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over,
* since should the underlying page change whilst your test is executing the results of future
* calls against this interface will be against the freshly loaded page.
*
* @param url The URL to load. It is best to use a fully qualified URL
*/
void to(String url);
/**
* Overloaded version of {@link #to(String)} that makes it easy to pass in a URL.
*
* @param url URL
*/
void to(URL url);
/**
* Refresh the current page
*/
void refresh();
}
/**
* An interface for managing input methods.
*/
interface ImeHandler {
/**
* All available engines on the machine. To use an engine, it has to be activated.
*
* @return list of available IME engines.
* @throws ImeNotAvailableException if the host does not support IME.
*/
List<String> getAvailableEngines();
/**
* Get the name of the active IME engine. The name string is platform-specific.
*
* @return name of the active IME engine.
* @throws ImeNotAvailableException if the host does not support IME.
*/
String getActiveEngine();
/**
* Indicates whether IME input active at the moment (not if it's available).
*
* @return true if IME input is available and currently active, false otherwise.
* @throws ImeNotAvailableException if the host does not support IME.
*/
boolean isActivated();
/**
* De-activate IME input (turns off the currently activated engine). Note that getActiveEngine
* may still return the name of the engine but isActivated will return false.
*
* @throws ImeNotAvailableException if the host does not support IME.
*/
void deactivate();
/**
* Make an engines that is available (appears on the list returned by getAvailableEngines)
* active. After this call, the only loaded engine on the IME daemon will be this one and the
* input sent using sendKeys will be converted by the engine. Noteh that this is a
* platform-independent method of activating IME (the platform-specific way being using keyboard
* shortcuts).
*
*
* @param engine name of engine to activate.
* @throws ImeNotAvailableException if the host does not support IME.
* @throws ImeActivationFailedException if the engine is not available or if activation failed
* for other reasons.
*/
void activateEngine(String engine);
}
@Beta
interface Window {
/**
* Set the size of the current window. This will change the outer window dimension,
* not just the view port, synonymous to window.resizeTo() in JS.
*
* @param targetSize The target size.
*/
void setSize(Dimension targetSize);
/**
* Set the position of the current window. This is relative to the upper left corner of the
* screen, synonymous to window.moveTo() in JS.
*
* @param targetPosition The target position of the window.
*/
void setPosition(Point targetPosition);
/**
* Get the size of the current window. This will return the outer window dimension, not just
* the view port.
*
* @return The current window size.
*/
Dimension getSize();
/**
* Get the position of the current window, relative to the upper left corner of the screen.
*
* @return The current window position.
*/
Point getPosition();
/**
* Maximizes the current window if it is not already maximized
*/
void maximize();
}
}
| src/main/java/org/openqa/selenium/WebDriver.java | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.logging.LoggingPreferences;
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* The main interface to use for testing, which represents an idealised web browser. The methods in
* this class fall into three categories:
* <ul>
* <li>Control of the browser itself</li>
* <li>Selection of {@link WebElement}s</li>
* <li>Debugging aids</li>
* </ul>
* <p>
* Key methods are {@link WebDriver#get(String)}, which is used to load a new web page, and the
* various methods similar to {@link WebDriver#findElement(By)}, which is used to find
* {@link WebElement}s.
* <p>
* Currently, you will need to instantiate implementations of this class directly. It is hoped that
* you write your tests against this interface so that you may "swap in" a more fully featured
* browser when there is a requirement for one. Given this approach to testing, it is best to start
* writing your tests using the {@link org.openqa.selenium.htmlunit.HtmlUnitDriver} implementation.
* <p>
* Note that all methods that use XPath to locate elements will throw a {@link RuntimeException}
* should there be an error thrown by the underlying XPath engine.
*
* @see org.openqa.selenium.ie.InternetExplorerDriver
* @see org.openqa.selenium.htmlunit.HtmlUnitDriver
*/
public interface WebDriver extends SearchContext {
// Navigation
/**
* Load a new web page in the current browser window. This is done using an HTTP GET operation,
* and the method will block until the load is complete. This will follow redirects issued either
* by the server or as a meta-redirect from within the returned HTML. Should a meta-redirect
* "rest" for any duration of time, it is best to wait until this timeout is over, since should
* the underlying page change whilst your test is executing the results of future calls against
* this interface will be against the freshly loaded page. Synonym for
* {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
*
* @param url The URL to load. It is best to use a fully qualified URL
*/
void get(String url);
/**
* Get a string representing the current URL that the browser is looking at.
*
* @return The URL of the page currently loaded in the browser
*/
String getCurrentUrl();
// General properties
/**
* The title of the current page.
*
* @return The title of the current page, with leading and trailing whitespace stripped, or null
* if one is not already set
*/
String getTitle();
/**
* Find all elements within the current page using the given mechanism.
* This method is affected by the 'implicit wait' times in force at the time of execution. When
* implicitly waiting, this method will return as soon as there are more than 0 items in the
* found collection, or will return an empty list if the timeout is reached.
*
* @param by The locating mechanism to use
* @return A list of all {@link WebElement}s, or an empty list if nothing matches
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
List<WebElement> findElements(By by);
/**
* Find the first {@link WebElement} using the given method.
* This method is affected by the 'implicit wait' times in force at the time of execution.
* The findElement(..) invocation will return a matching row, or try again repeatedly until
* the configured timeout is reached.
*
* findElement should not be used to look for non-present elements, use {@link #findElements(By)}
* and assert zero length response instead.
*
* @param by The locating mechanism
* @return The first matching element on the current page
* @throws NoSuchElementException If no matching elements are found
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
WebElement findElement(By by);
// Misc
/**
* Get the source of the last loaded page. If the page has been modified after loading (for
* example, by Javascript) there is no guarantee that the returned text is that of the modified
* page. Please consult the documentation of the particular driver being used to determine whether
* the returned text reflects the current state of the page or the text last sent by the web
* server. The page source returned is a representation of the underlying DOM: do not expect it to
* be formatted or escaped in the same way as the response sent from the web server. Think of it as
* an artist's impression.
*
* @return The source of the current page
*/
String getPageSource();
/**
* Close the current window, quitting the browser if it's the last window currently open.
*/
void close();
/**
* Quits this driver, closing every associated window.
*/
void quit();
/**
* Return a set of window handles which can be used to iterate over all open windows of this
* WebDriver instance by passing them to {@link #switchTo()}.{@link Options#window()}
*
* @return A set of window handles which can be used to iterate over all open windows.
*/
Set<String> getWindowHandles();
/**
* Return an opaque handle to this window that uniquely identifies it within this driver instance.
* This can be used to switch to this window at a later date
*
* @return the current window handle
*/
String getWindowHandle();
/**
* Send future commands to a different frame or window.
*
* @return A TargetLocator which can be used to select a frame or window
* @see org.openqa.selenium.WebDriver.TargetLocator
*/
TargetLocator switchTo();
/**
* An abstraction allowing the driver to access the browser's history and to navigate to a given
* URL.
*
* @return A {@link org.openqa.selenium.WebDriver.Navigation} that allows the selection of what to
* do next
*/
Navigation navigate();
/**
* Gets the Option interface
*
* @return An option interface
* @see org.openqa.selenium.WebDriver.Options
*/
Options manage();
/**
* An interface for managing stuff you would do in a browser menu
*/
interface Options {
/**
* Add a specific cookie. If the cookie's domain name is left blank, it is assumed that the
* cookie is meant for the domain of the current document.
*
* @param cookie The cookie to add.
*/
void addCookie(Cookie cookie);
/**
* Delete the named cookie from the current domain. This is equivalent to setting the named
* cookie's expiry date to some time in the past.
*
* @param name The name of the cookie to delete
*/
void deleteCookieNamed(String name);
/**
* Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored.
*
* @param cookie nom nom nom
*/
void deleteCookie(Cookie cookie);
/**
* Delete all the cookies for the current domain.
*/
void deleteAllCookies();
/**
* Get all the cookies for the current domain. This is the equivalent of calling
* "document.cookie" and parsing the result
*
* @return A Set of cookies for the current domain.
*/
Set<Cookie> getCookies();
/**
* Get a cookie with a given name.
*
* @param name the name of the cookie
* @return the cookie, or null if no cookie with the given name is present
*/
Cookie getCookieNamed(String name);
/**
* @return the interface for managing driver timeouts.
*/
Timeouts timeouts();
/**
* @return the interface for controlling IME engines to generate complex-script input.
*/
ImeHandler ime();
/**
* @return the interface for managing the current window.
*/
@Beta
Window window();
/**
* Gets the {@link Logs} interface used to fetch different types of logs.
*
* <p>To set the logging preferences {@link LoggingPreferences}.
*
* @return A Logs interface.
*/
@Beta
Logs logs();
}
/**
* An interface for managing timeout behavior for WebDriver instances.
*/
interface Timeouts {
/**
* Specifies the amount of time the driver should wait when searching for an element if it is
* not immediately present.
* <p>
* When searching for a single element, the driver should poll the page until the element has
* been found, or this timeout expires before throwing a {@link NoSuchElementException}. When
* searching for multiple elements, the driver should poll the page until at least one element
* has been found or this timeout has expired.
* <p>
* Increasing the implicit wait timeout should be used judiciously as it will have an adverse
* effect on test run time, especially when used with slower location strategies like XPath.
*
* @param time The amount of time to wait.
* @param unit The unit of measure for {@code time}.
* @return A self reference.
*/
Timeouts implicitlyWait(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, then the script will be allowed to run
* indefinitely.
*
* @param time The timeout value.
* @param unit The unit of time.
* @return A self reference.
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
*/
Timeouts setScriptTimeout(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for a page load to complete before throwing an error.
* If the timeout is negative, page loads can be indefinite.
*
* @param time The timeout value.
* @param unit The unit of time.
* @return A Timeouts interface.
*/
Timeouts pageLoadTimeout(long time, TimeUnit unit);
}
/**
* Used to locate a given frame or window.
*/
interface TargetLocator {
/**
* Select a frame by its (zero-based) index. Selecting a frame by index is equivalent to the
* JS expression window.frames[index] where "window" is the DOM window represented by the
* current context. Once the frame has been selected, all subsequent calls on the WebDriver
* interface are made to that frame.
*
* @param index (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(int index);
/**
* Select a frame by its name or ID. Frames located by matching name attributes are always given
* precedence over those matched by ID.
*
* @param nameOrId the name of the frame window, the id of the <frame> or <iframe>
* element, or the (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(String nameOrId);
/**
* Select a frame using its previously located {@link WebElement}.
*
* @param frameElement The frame element to switch to.
* @return This driver focused on the given frame.
* @throws NoSuchFrameException If the given element is neither an IFRAME nor a FRAME element.
* @throws StaleElementReferenceException If the WebElement has gone stale.
* @see WebDriver#findElement(By)
*/
WebDriver frame(WebElement frameElement);
/**
* Change focus to the parent context. If the current context is the top level browsing context,
* the context remains unchanged.
*
* @return This driver focused on the parent frame
*/
WebDriver parentFrame();
/**
* Switch the focus of future commands for this driver to the window with the given name/handle.
*
* @param nameOrHandle The name of the window or the handle as returned by
* {@link WebDriver#getWindowHandle()}
* @return This driver focused on the given window
* @throws NoSuchWindowException If the window cannot be found
*/
WebDriver window(String nameOrHandle);
/**
* Selects either the first frame on the page, or the main document when a page contains
* iframes.
*
* @return This driver focused on the top window/first frame.
*/
WebDriver defaultContent();
/**
* Switches to the element that currently has focus within the document currently "switched to",
* or the body element if this cannot be detected. This matches the semantics of calling
* "document.activeElement" in Javascript.
*
* @return The WebElement with focus, or the body element if no element with focus can be
* detected.
*/
WebElement activeElement();
/**
* Switches to the currently active modal dialog for this particular driver instance.
*
* @return A handle to the dialog.
* @throws NoAlertPresentException If the dialog cannot be found
*/
Alert alert();
}
interface Navigation {
/**
* Move back a single "item" in the browser's history.
*/
void back();
/**
* Move a single "item" forward in the browser's history. Does nothing if we are on the latest
* page viewed.
*/
void forward();
/**
* Load a new web page in the current browser window. This is done using an HTTP GET operation,
* and the method will block until the load is complete. This will follow redirects issued
* either by the server or as a meta-redirect from within the returned HTML. Should a
* meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over,
* since should the underlying page change whilst your test is executing the results of future
* calls against this interface will be against the freshly loaded page.
*
* @param url The URL to load. It is best to use a fully qualified URL
*/
void to(String url);
/**
* Overloaded version of {@link #to(String)} that makes it easy to pass in a URL.
*
* @param url URL
*/
void to(URL url);
/**
* Refresh the current page
*/
void refresh();
}
/**
* An interface for managing input methods.
*/
interface ImeHandler {
/**
* All available engines on the machine. To use an engine, it has to be activated.
*
* @return list of available IME engines.
* @throws ImeNotAvailableException if the host does not support IME.
*/
List<String> getAvailableEngines();
/**
* Get the name of the active IME engine. The name string is platform-specific.
*
* @return name of the active IME engine.
* @throws ImeNotAvailableException if the host does not support IME.
*/
String getActiveEngine();
/**
* Indicates whether IME input active at the moment (not if it's available).
*
* @return true if IME input is available and currently active, false otherwise.
* @throws ImeNotAvailableException if the host does not support IME.
*/
boolean isActivated();
/**
* De-activate IME input (turns off the currently activated engine). Note that getActiveEngine
* may still return the name of the engine but isActivated will return false.
*
* @throws ImeNotAvailableException if the host does not support IME.
*/
void deactivate();
/**
* Make an engines that is available (appears on the list returned by getAvailableEngines)
* active. After this call, the only loaded engine on the IME daemon will be this one and the
* input sent using sendKeys will be converted by the engine. Noteh that this is a
* platform-independent method of activating IME (the platform-specific way being using keyboard
* shortcuts).
*
*
* @param engine name of engine to activate.
* @throws ImeNotAvailableException if the host does not support IME.
* @throws ImeActivationFailedException if the engine is not available or if activation failed
* for other reasons.
*/
void activateEngine(String engine);
}
@Beta
interface Window {
/**
* Set the size of the current window. This will change the outer window dimension,
* not just the view port, synonymous to window.resizeTo() in JS.
*
* @param targetSize The target size.
*/
void setSize(Dimension targetSize);
/**
* Set the position of the current window. This is relative to the upper left corner of the
* screen, synonymous to window.moveTo() in JS.
*
* @param targetPosition The target position of the window.
*/
void setPosition(Point targetPosition);
/**
* Get the size of the current window. This will return the outer window dimension, not just
* the view port.
*
* @return The current window size.
*/
Dimension getSize();
/**
* Get the position of the current window, relative to the upper left corner of the screen.
*
* @return The current window position.
*/
Point getPosition();
/**
* Maximizes the current window if it is not already maximized
*/
void maximize();
}
}
| moar javadoc
| src/main/java/org/openqa/selenium/WebDriver.java | moar javadoc |
|
Java | apache-2.0 | 49611dee16310f5b88db112ca2793226a23adede | 0 | brightchen/apex-core,tweise/incubator-apex-core,tweise/incubator-apex-core,vrozov/incubator-apex-core,tushargosavi/incubator-apex-core,tweise/apex-core,apache/incubator-apex-core,devtagare/incubator-apex-core,aniruddhas/incubator-apex-core,tushargosavi/apex-core,simplifi-it/otterx,MalharJenkins/incubator-apex-core,andyperlitch/incubator-apex-core,tushargosavi/apex-core,ishark/incubator-apex-core,sandeshh/apex-core,sandeshh/incubator-apex-core,vrozov/incubator-apex-core,mattqzhang/apex-core,aniruddhas/incubator-apex-core,simplifi-it/otterx,ishark/incubator-apex-core,vrozov/apex-core,PramodSSImmaneni/apex-core,PramodSSImmaneni/apex-core,apache/incubator-apex-core,mattqzhang/apex-core,PramodSSImmaneni/incubator-apex-core,tweise/apex-core,devtagare/incubator-apex-core,vrozov/apex-core,tushargosavi/incubator-apex-core,tweise/apex-core,sandeshh/apex-core,sandeshh/apex-core,brightchen/apex-core,chinmaykolhatkar/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,apache/incubator-apex-core,devtagare/incubator-apex-core,simplifi-it/otterx,vrozov/apex-core,deepak-narkhede/apex-core,amberarrow/incubator-apex-core,vrozov/incubator-apex-core,MalharJenkins/incubator-apex-core,amberarrow/incubator-apex-core,tweise/incubator-apex-core,PramodSSImmaneni/apex-core,klynchDS/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,mattqzhang/apex-core,ishark/incubator-apex-core,andyperlitch/incubator-apex-core,sandeshh/incubator-apex-core,klynchDS/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,brightchen/incubator-apex-core,brightchen/apex-core,deepak-narkhede/apex-core,mt0803/incubator-apex-core,deepak-narkhede/apex-core,sandeshh/incubator-apex-core,brightchen/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,tushargosavi/incubator-apex-core,mt0803/incubator-apex-core,tushargosavi/apex-core | /*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.codec;
import java.io.*;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.ser.impl.RawSerializer;
import com.malhartech.api.StreamCodec;
import com.malhartech.api.util.ObjectMapperString;
import com.malhartech.common.util.Slice;
import com.malhartech.stram.cli.StramAppLauncher.AppConfig;
/**
*
* @param <T> tuple type
* @author David Yan <[email protected]>
*/
public class JsonStreamCodec<T> implements StreamCodec<T>
{
private ObjectMapper mapper;
public JsonStreamCodec()
{
mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addSerializer(ObjectMapperString.class, new RawSerializer<Object>(Object.class));
module.addSerializer(AppConfig.class, new AppConfigSerializer());
mapper.registerModule(module);
}
@Override
public Object fromByteArray(Slice data)
{
ByteArrayInputStream bis = new ByteArrayInputStream(data.buffer, data.offset, data.length);
try {
return mapper.readValue(bis, Object.class);
}
catch (Exception ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public Slice toByteArray(T o)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mapper.writeValue(bos, o);
byte[] bytes = bos.toByteArray();
return new Slice(bytes, 0, bytes.length);
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public int getPartition(T o)
{
return o.hashCode();
}
}
| engine/src/main/java/com/malhartech/codec/JsonStreamCodec.java | /*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.codec;
import com.malhartech.api.StreamCodec;
import com.malhartech.api.util.ObjectMapperString;
import java.io.*;
import com.malhartech.common.util.Slice;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.ser.impl.RawSerializer;
/**
*
* @param <T> tuple type
* @author David Yan <[email protected]>
*/
public class JsonStreamCodec<T> implements StreamCodec<T>
{
private ObjectMapper mapper;
public JsonStreamCodec()
{
mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addSerializer(ObjectMapperString.class, new RawSerializer<Object>(Object.class));
module.addSerializer(AppConfig.class, new AppConfigSerializer());
mapper.registerModule(module);
}
@Override
public Object fromByteArray(Slice data)
{
ByteArrayInputStream bis = new ByteArrayInputStream(data.buffer, data.offset, data.length);
try {
return mapper.readValue(bis, Object.class);
}
catch (Exception ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public Slice toByteArray(T o)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mapper.writeValue(bos, o);
byte[] bytes = bos.toByteArray();
return new Slice(bytes, 0, bytes.length);
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public int getPartition(T o)
{
return o.hashCode();
}
}
| fixed conflict. | engine/src/main/java/com/malhartech/codec/JsonStreamCodec.java | fixed conflict. |
|
Java | apache-2.0 | fb328b5a84040563ab0a76c29e6891cbec00c0a2 | 0 | kiuby88/jclouds-examples,rackerlabs/jclouds-examples,danbroudy/jclouds-examples,danbroudy/jclouds-examples,cosu/jclouds-examples,kiuby88/jclouds-examples,cosu/jclouds-examples,rackerlabs/jclouds-examples,rackerlabs/jclouds-examples,cosu/jclouds-examples,jclouds/jclouds-examples,danbroudy/jclouds-examples,kiuby88/jclouds-examples | /*
* 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.jclouds.examples.google.computeengine;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;
import static org.jclouds.examples.google.computeengine.Constants.*;
/**
* This example creates a Debian Wheezy server on a f1-micro instance on the
* Google Compute Engine.
*/
public class CreateServer implements Closeable {
private final ComputeService computeService;
/**
* To get a service account and its private key see [TODO: write some
* documentation on the website and put a link to it]
*
* The first argument (args[0]) must be your service account email address
* The second argument (args[1]) must a path to your service account
* private key PEM file (without a password).
*/
public static void main(String[] args) throws IOException {
String key = Files.toString(new File(args[1]), Charset.defaultCharset());
CreateServer createServer = new CreateServer(args[0], key);
try {
createServer.createServer();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
createServer.close();
}
}
public CreateServer(String serviceAccountEmailAddress, String serviceAccountKey) {
// These properties control how often jclouds polls for a status update
Properties overrides = new Properties();
overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
ComputeServiceContext context = ContextBuilder.newBuilder(PROVIDER)
.credentials(serviceAccountEmailAddress, serviceAccountKey)
.overrides(overrides)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
}
/**
* Create a server based on a Template. This method uses Template.hardwareId() and Template.imageId() to
* also demonstrate iterating through Hardware and Images. Alternatively you do the same without iterating
* using the following Template.
*
* Template template = computeService.templateBuilder()
* .locationId(getLocationId())
* .osFamily(OsFamily.CENTOS)
* .osVersionMatches("6")
* .minRam(28*1024)
* .build();
*/
private void createServer() throws RunNodesException, TimeoutException {
System.out.format("Create Server%n");
// TODO: make fromHardware(...) and fromImage(...) work as well. Currently,
// fromHardware chooses a deprecated platform and the call fails, while using
// hardwareId() and fromImage() causes no image to be found.
Template template = computeService.templateBuilder()
.locationId(ZONE)
.hardwareId(getHardware().getId())
.imageId(getImage().getId())
.build();
// This method will continue to poll for the server status and won't
// return until this server is ACTIVE.
// TODO: does GCE also log what's happening during the polling, like for
// Rackspace? If so, add an example for that.
Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, 1, template);
NodeMetadata nodeMetadata = nodes.iterator().next();
String publicAddress = nodeMetadata.getPublicAddresses().iterator().next();
System.out.format(" %s%n", nodeMetadata);
System.out.format(" Instance %s started with IP %s%n", nodeMetadata.getName(), publicAddress);
}
/**
* This method uses the generic ComputeService.listHardwareProfiles() to find the hardware profile.
*
* @return The Hardware for a f1-micro instance.
*/
private Hardware getHardware() {
System.out.format(" Hardware Profiles%n");
Set<? extends Hardware> profiles = computeService.listHardwareProfiles();
Hardware result = null;
for (Hardware profile : profiles) {
System.out.format(" %s%n", profile);
if (profile.getId().equals(ZONE + "/f1-micro")) {
result = profile;
}
}
if (result == null) {
System.err.println("f1-micro flavor not found. Using first flavor found:");
result = profiles.iterator().next();
System.err.format("-> %s%n", result);
}
return result;
}
/**
* This method uses the generic ComputeService.listImages() to find the image.
*
* @return A Debian Wheezy Image
*/
private Image getImage() {
System.out.format(" Images%n");
Set<? extends Image> images = computeService.listImages();
Image result = null;
for (Image image : images) {
System.out.format(" %s%n", image);
if (image.getOperatingSystem().getVersion().equals("debian.7.wheezy")) {
result = image;
}
}
if (result == null) {
System.err.println("Image with Debian Wheezy operating system not found. Using first image found:");
result = images.iterator().next();
System.err.format("-> %s%n", result);
}
return result;
}
/**
* Always close your service when you're done with it.
*/
public void close() throws IOException {
Closeables.close(computeService.getContext(), true);
}
}
| google/src/main/java/org/jclouds/examples/google/computeengine/CreateServer.java | /*
* 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.jclouds.examples.google.computeengine;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;
import static org.jclouds.examples.google.computeengine.Constants.*;
/**
* This example creates a Debian Wheezy server on a f1-micro instance on the
* Google Compute Engine.
*/
public class CreateServer implements Closeable {
private final ComputeService computeService;
/**
* To get a service account and its private key see [TODO: write some
* documentation on the website and put a link to it]
*
* The first argument (args[0]) must be your service account email address
* The second argument (args[1]) must a path to your service account
* private key PEM file (without a password).
*/
public static void main(String[] args) throws IOException {
String key = Files.toString(new File(args[1]), Charset.defaultCharset());
CreateServer createServer = new CreateServer(args[0], key);
try {
createServer.createServer();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
createServer.close();
}
}
public CreateServer(String serviceAccountEmailAddress, String serviceAccountKey) {
// These properties control how often jclouds polls for a status update
Properties overrides = new Properties();
overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
ComputeServiceContext context = ContextBuilder.newBuilder(PROVIDER)
.credentials(serviceAccountEmailAddress, serviceAccountKey)
.overrides(overrides)
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
}
/**
* Create a server based on a Template. This method uses Template.hardwareId() and Template.imageId() to
* also demonstrate iterating through Hardware and Images. Alternatively you do the same without iterating
* using the following Template.
*
* Template template = computeService.templateBuilder()
* .locationId(getLocationId())
* .osFamily(OsFamily.CENTOS)
* .osVersionMatches("6")
* .minRam(28*1024)
* .build();
*/
private void createServer() throws RunNodesException, TimeoutException {
System.out.format("Create Server%n");
// TODO: make fromHardware(...) and fromImage(...) work as well. Currently,
// fromHardware chooses a deprecated platform and the call fails, while using
// hardwareId() and fromImage() causes no image to be found.
Template template = computeService.templateBuilder()
.locationId(ZONE)
.hardwareId(getHardware().getId())
.imageId(getImage().getId())
.build();
// This method will continue to poll for the server status and won't
// return until this server is ACTIVE.
// TODO: does GCE also log what's happening during the polling, like for
// Rackspace? If so, add an example for that.
Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(NAME, 1, template);
NodeMetadata nodeMetadata = nodes.iterator().next();
String publicAddress = nodeMetadata.getPublicAddresses().iterator().next();
System.out.format(" %s%n", nodeMetadata);
System.out.format(" Instance %s started with IP %s%n", nodeMetadata.getName(), publicAddress);
}
/**
* This method uses the generic ComputeService.listHardwareProfiles() to find the hardware profile.
*
* @return The Hardware for a f1-micro instance.
*/
private Hardware getHardware() {
System.out.format(" Hardware Profiles%n");
Set<? extends Hardware> profiles = computeService.listHardwareProfiles();
Hardware result = null;
for (Hardware profile: profiles) {
System.out.format(" %s%n", profile);
if (profile.getId().equals(ZONE + "/f1-micro")) {
result = profile;
}
}
if (result == null) {
System.err.println("f1-micro flavor not found. Using first flavor found.%n");
result = profiles.iterator().next();
}
return result;
}
/**
* This method uses the generic ComputeService.listImages() to find the image.
*
* @return A Debian Wheezy Image
*/
private Image getImage() {
System.out.format(" Images%n");
Set<? extends Image> images = computeService.listImages();
Image result = null;
for (Image image: images) {
System.out.format(" %s%n", image);
if (image.getOperatingSystem().getVersion().equals("debian.7.wheezy")) {
result = image;
}
}
if (result == null) {
System.err.println("Image with Debian Wheezy operating system not found. Using first image found.%n");
result = images.iterator().next();
}
return result;
}
/**
* Always close your service when you're done with it.
*/
public void close() throws IOException {
Closeables.close(computeService.getContext(), true);
}
}
| Small improvements to the CreateServer GCE example.
| google/src/main/java/org/jclouds/examples/google/computeengine/CreateServer.java | Small improvements to the CreateServer GCE example. |
|
Java | apache-2.0 | 6e9c830c7dcaca00557fef0f5237ee7035e71a3f | 0 | sergiomt/judal,sergiomt/judal,sergiomt/judal | package org.judal.jdbc.jdc;
import com.knowgate.debug.DebugFile;
/**
* This file is licensed under the Apache License version 2.0.
* 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.
*/
/**
* <p>Connection pool daemon thread</p>
* This thread scans a ConnectionPool every given interval calling
* ConnectionPool.reapConnections() for closing unused connections.
*/
public class JDCConnectionReaper extends Thread {
/**
* Reference to reaped connection pool
*/
private JDCConnectionPool pool;
/**
* Used to stop the Connection reaper thread
*/
private boolean keepruning;
/**
* Connection Reaper call interval (default = 10 mins)
*/
private long delay=600000l;
/**
* <p>Constructor</p>
* @param forpool JDCConnectionPool
*/
JDCConnectionReaper(JDCConnectionPool forpool) {
pool = forpool;
keepruning = true;
try {
checkAccess();
setDaemon(true);
setPriority(MIN_PRIORITY);
setName("JDC-Connection-Reaper-" + getId());
} catch (SecurityException ignore) { }
}
/**
* Get connection reaper call interval
* @return long Number of milliseconds between reaper calls
*/
public long getDelay() {
return delay;
}
/**
* <p>Set connection reaper call interval</p>
* The default value is 10 minutes
* @param lDelay long Number of milliseconds between reaper calls
* @throws IllegalArgumentException if lDelay is less than 1000
*/
public void setDelay(long lDelay) throws IllegalArgumentException {
if (lDelay<1000l && lDelay>0l)
throw new IllegalArgumentException("ConnectionReaper delay cannot be smaller than 1000 miliseconds");
delay=lDelay;
}
public void halt() {
keepruning = false;
interrupt();
}
/**
* Reap connections every n-minutes
*/
public void run() {
if (DebugFile.trace)
DebugFile.writeln("Begin JDCConnectionReaper.run() delay=" + delay);
while (keepruning) {
try {
sleep(delay);
} catch( InterruptedException e) { }
if (keepruning) pool.reapConnections();
} // wend
if (DebugFile.trace)
DebugFile.writeln("End JDCConnectionReaper.run()");
} // run
} // ConnectionReaper
| jdbc/src/main/java/org/judal/jdbc/jdc/JDCConnectionReaper.java | package org.judal.jdbc.jdc;
import com.knowgate.debug.DebugFile;
/**
* This file is licensed under the Apache License version 2.0.
* 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.
*/
/**
* <p>Connection pool daemon thread</p>
* This thread scans a ConnectionPool every given interval calling
* ConnectionPool.reapConnections() for closing unused connections.
*/
public class JDCConnectionReaper extends Thread {
/**
* Reference to reaped connection pool
*/
private JDCConnectionPool pool;
/**
* Used to stop the Connection reaper thread
*/
private boolean keepruning;
/**
* Connection Reaper call interval (default = 10 mins)
*/
private long delay=600000l;
/**
* <p>Constructor</p>
* @param forpool JDCConnectionPool
*/
JDCConnectionReaper(JDCConnectionPool forpool) {
pool = forpool;
keepruning = true;
try {
checkAccess();
setDaemon(true);
setPriority(MIN_PRIORITY);
} catch (SecurityException ignore) { }
}
/**
* Get connection reaper call interval
* @return long Number of milliseconds between reaper calls
*/
public long getDelay() {
return delay;
}
/**
* <p>Set connection reaper call interval</p>
* The default value is 10 minutes
* @param lDelay long Number of milliseconds between reaper calls
* @throws IllegalArgumentException if lDelay is less than 1000
*/
public void setDelay(long lDelay) throws IllegalArgumentException {
if (lDelay<1000l && lDelay>0l)
throw new IllegalArgumentException("ConnectionReaper delay cannot be smaller than 1000 miliseconds");
delay=lDelay;
}
public void halt() {
keepruning=false;
}
/**
* Reap connections every n-minutes
*/
public void run() {
if (DebugFile.trace)
DebugFile.writeln("Begin JDCConnectionReaper.run() delay=" + delay);
while (keepruning) {
try {
sleep(delay);
} catch( InterruptedException e) { }
if (keepruning) pool.reapConnections();
} // wend
if (DebugFile.trace)
DebugFile.writeln("End JDCConnectionReaper.run()");
} // run
} // ConnectionReaper
| Interrupt connection reapear inmediatedly on halt request
| jdbc/src/main/java/org/judal/jdbc/jdc/JDCConnectionReaper.java | Interrupt connection reapear inmediatedly on halt request |
|
Java | apache-2.0 | 331dd27e85ed1f604e4d247e2923334296dca7c1 | 0 | asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin | package org.asciidoc.intellij.psi;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementResolveResult;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiPolyVariantReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.ResolveResult;
import icons.AsciiDocIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class AsciiDocReference extends PsiReferenceBase<PsiElement> implements PsiPolyVariantReference {
private String key;
public AsciiDocReference(@NotNull PsiElement element, TextRange textRange) {
super(element, textRange);
key = element.getText().substring(textRange.getStartOffset(), textRange.getEndOffset());
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
Project project = myElement.getProject();
final List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project, key);
final List<AsciiDocSection> sections = AsciiDocFileUtil.findSections(project, key);
List<ResolveResult> results = new ArrayList<>();
for (AsciiDocBlockId id : ids) {
results.add(new PsiElementResolveResult(id));
}
for (AsciiDocSection section : sections) {
results.add(new PsiElementResolveResult(section));
}
if (results.size() > 0) {
List<ResolveResult> sameFile = new ArrayList<>();
PsiFile myFile = myElement.getContainingFile();
for (ResolveResult result : results) {
if (result.getElement() != null && result.getElement().getContainingFile() == myFile) {
sameFile.add(result);
}
}
if (sameFile.size() > 0) {
results = sameFile;
}
}
return results.toArray(new ResolveResult[0]);
}
@Nullable
@Override
public PsiElement resolve() {
ResolveResult[] resolveResults = multiResolve(false);
return resolveResults.length == 1 ? resolveResults[0].getElement() : null;
}
@NotNull
@Override
public Object[] getVariants() {
Project project = myElement.getProject();
List<LookupElement> variants = new ArrayList<>();
List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project);
for (final AsciiDocBlockId id : ids) {
if (id.getId() != null && id.getId().length() > 0) {
variants.add(LookupElementBuilder.create(id)
.withIcon(AsciiDocIcons.ASCIIDOC_ICON)
.withTypeText(id.getContainingFile().getName())
);
}
}
// don't include list of autogenerated IDs for sections here as they will have suffixes if they appear multiple times
return variants.toArray();
}
}
| src/main/java/org/asciidoc/intellij/psi/AsciiDocReference.java | package org.asciidoc.intellij.psi;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementResolveResult;
import com.intellij.psi.PsiPolyVariantReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.ResolveResult;
import icons.AsciiDocIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class AsciiDocReference extends PsiReferenceBase<PsiElement> implements PsiPolyVariantReference {
private String key;
public AsciiDocReference(@NotNull PsiElement element, TextRange textRange) {
super(element, textRange);
key = element.getText().substring(textRange.getStartOffset(), textRange.getEndOffset());
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
Project project = myElement.getProject();
final List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project, key);
final List<AsciiDocSection> sections = AsciiDocFileUtil.findSections(project, key);
List<ResolveResult> results = new ArrayList<>();
for (AsciiDocBlockId id : ids) {
results.add(new PsiElementResolveResult(id));
}
for (AsciiDocSection section : sections) {
results.add(new PsiElementResolveResult(section));
}
return results.toArray(new ResolveResult[0]);
}
@Nullable
@Override
public PsiElement resolve() {
ResolveResult[] resolveResults = multiResolve(false);
return resolveResults.length == 1 ? resolveResults[0].getElement() : null;
}
@NotNull
@Override
public Object[] getVariants() {
Project project = myElement.getProject();
List<LookupElement> variants = new ArrayList<>();
List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project);
for (final AsciiDocBlockId id : ids) {
if (id.getId() != null && id.getId().length() > 0) {
variants.add(LookupElementBuilder.create(id)
.withIcon(AsciiDocIcons.ASCIIDOC_ICON)
.withTypeText(id.getContainingFile().getName())
);
}
}
// don't include list of autogenerated IDs for sections here as they will have suffixes if they appear multiple times
return variants.toArray();
}
}
| prefer reference targets defined in current file over references defined in other files
| src/main/java/org/asciidoc/intellij/psi/AsciiDocReference.java | prefer reference targets defined in current file over references defined in other files |
|
Java | apache-2.0 | b5b1e6b6479464efa92efab5ac0924651c619771 | 0 | sidorovis/stsc.performance | package stsc.performance;
import java.util.List;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import stsc.common.BadSignalException;
import stsc.common.TimeTracker;
import stsc.common.algorithms.BadAlgorithmException;
import stsc.common.storage.StockStorage;
import stsc.general.simulator.multistarter.StrategySearcher;
import stsc.general.simulator.multistarter.StrategySearcherException;
import stsc.general.simulator.multistarter.genetic.SimulatorSettingsGeneticListImpl;
import stsc.general.simulator.multistarter.genetic.StrategyGeneticSearcher;
import stsc.general.simulator.multistarter.grid.SimulatorSettingsGridFactory;
import stsc.general.simulator.multistarter.grid.SimulatorSettingsGridList;
import stsc.general.simulator.multistarter.grid.StrategyGridSearcher;
import stsc.general.statistic.cost.comparator.MetricsSameComparator;
import stsc.general.statistic.cost.function.CostWeightedSumFunction;
import stsc.general.strategy.TradingStrategy;
import stsc.general.strategy.selector.StatisticsByCostSelector;
import stsc.general.strategy.selector.StrategySelector;
import stsc.storage.mocks.StockStorageMock;
class PerformanceCalculator {
final StockStorage stockStorage;
final private PerformanceCalculatorSettings settings;
PerformanceCalculator(PerformanceCalculatorSettings settings) throws Exception {
this.settings = settings;
this.stockStorage = StockStorageMock.getStockStorage();
if (settings.printAdditionalInfo && settings.searcherType == SearcherType.GENETIC_SEARCHER) {
System.out.print(settings.maxSelectionIndex + " " + settings.populationSize + " ");
}
if (settings.printStarterInfo) {
System.out.println("Size of stocks: " + stockStorage.getStockNames().size());
calculateAmountOfSimulations(stockStorage, settings);
}
if (settings.shouldWarmUp) {
warmUp();
}
}
public void calculateTimeStatistics() throws Exception {
for (int i = 10; i <= 31; ++i) {
calculateForThreads(settings.startOfPeriod.plusDays(i));
}
for (int i = 1; i <= 12; ++i) {
calculateForThreads(settings.startOfPeriod.plusMonths(i));
}
for (int i = 1; i <= 12; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
for (int i = 42; i <= 42; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
}
public void calculateSmallStatistics() throws Exception {
for (int i = 3; i <= 3; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
}
private void calculateForThreads(LocalDate endDate) throws Exception {
if (settings.printAdditionalInfo)
System.out.print(Days.daysBetween(settings.startOfPeriod, endDate).getDays());
for (int thread = settings.threadsFrom; thread <= settings.threadsTo; ++thread) {
calculateAverageTime(endDate, true, thread);
}
if (settings.printAdditionalInfo)
System.out.println();
}
static public void calculateAmountOfSimulations(StockStorage stockStorage, PerformanceCalculatorSettings settings) throws StrategySearcherException {
final SimulatorSettingsGridFactory factory = SimulatorSettingsGenerator.getGridFactory(settings.performanceForGridTest, stockStorage, settings.elements,
settings.getStartOfPeriod(), getDateRepresentation(settings.startOfPeriod.plusMonths(1)));
System.out.println("Simulation amount: " + factory.size());
}
private void warmUp() throws Exception {
final LocalDate newDate = settings.startOfPeriod.plusDays(31);
final int[] threadToWarmUp = { 1, 2, 8 };
for (int i : threadToWarmUp) {
calculateAverageTime(newDate, false, i);
}
final LocalDate tenDate = settings.startOfPeriod.plusDays(10);
for (int i : threadToWarmUp) {
calculateAverageTime(tenDate, false, i);
}
}
private double calculateAverageTime(LocalDate endDate, boolean printData, int threadAmount) throws Exception {
final String endOfPeriod = getDateRepresentation(endDate);
double time = 0.0;
double avGain = 0.0;
for (int i = 0; i < settings.calculationsForAverage; ++i) {
final PerformanceResult result = timeForSearch(threadAmount, endOfPeriod);
time += TimeTracker.lengthInSeconds(result.timeTracker.length());
avGain += result.sumAvGainForBest;
}
final double avTime = time / settings.calculationsForAverage;
final double avRes = avGain / settings.calculationsForAverage;
if (printData && settings.printAvGainAndTime) {
System.out.print(" " + settings.format(avTime) + " " + settings.format(avRes) + " ");
}
return avTime;
}
public PerformanceResult timeForSearch(int threadSize, String endOfPeriod)
throws StrategySearcherException, BadAlgorithmException, BadSignalException, InterruptedException {
final TimeTracker timeTracker = new TimeTracker();
final StrategySearcher searcher = generateSearcher(threadSize, endOfPeriod);
final List<TradingStrategy> strategies = searcher.waitAndGetSelector().getStrategies();
return createResult(strategies, timeTracker);
}
private StrategySearcher generateSearcher(int threadSize, String endOfPeriod) throws InterruptedException {
final String startDate = getDateRepresentation(settings.startOfPeriod);
final StrategySelector selector = new StatisticsByCostSelector(settings.storedStrategyAmount, new CostWeightedSumFunction(),
new MetricsSameComparator());
if (settings.searcherType == SearcherType.GRID_SEARCHER) {
final SimulatorSettingsGridList list = SimulatorSettingsGenerator
.getGridFactory(settings.performanceForGridTest, stockStorage, settings.elements, startDate, endOfPeriod).getList();
return StrategyGridSearcher.getBuilder(). //
setSimulatorSettingsGridList(list). //
setSelector(selector). //
setThreadAmount(threadSize).build();
} else {
final SimulatorSettingsGeneticListImpl list = SimulatorSettingsGenerator
.getGeneticFactory(settings.performanceForGridTest, stockStorage, settings.elements, startDate, endOfPeriod).getList();
return StrategyGeneticSearcher.getBuilder().withGeneticList(list).withStrategySelector(selector).withThreadAmount(threadSize)
.withMaxPopulationsAmount(settings.maxSelectionIndex).withPopulationSize(settings.populationSize).build();
}
}
private static PerformanceResult createResult(List<TradingStrategy> strategies, TimeTracker timeTracker) {
double sumGetAvGain = 0.0;
timeTracker.finish();
sumGetAvGain = strategies.get(0).getAvGain();
// TODO strange comment should be deleted or returned back
// for (Statistics statistic : statistics) {
// sumGetAvGain += statistic.getAvGain();
// }
return new PerformanceResult(timeTracker, sumGetAvGain);
}
static private String getDateRepresentation(LocalDate date) {
int day = date.getDayOfMonth();
int month = date.getMonthOfYear();
int year = date.getYear();
return String.format("%02d-%02d-%04d", day, month, year);
}
}
| src/main/java/stsc/performance/PerformanceCalculator.java | package stsc.performance;
import java.util.List;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import stsc.common.BadSignalException;
import stsc.common.TimeTracker;
import stsc.common.algorithms.BadAlgorithmException;
import stsc.common.storage.StockStorage;
import stsc.general.simulator.multistarter.StrategySearcher;
import stsc.general.simulator.multistarter.StrategySearcherException;
import stsc.general.simulator.multistarter.genetic.SimulatorSettingsGeneticListImpl;
import stsc.general.simulator.multistarter.genetic.StrategyGeneticSearcher;
import stsc.general.simulator.multistarter.grid.SimulatorSettingsGridFactory;
import stsc.general.simulator.multistarter.grid.SimulatorSettingsGridList;
import stsc.general.simulator.multistarter.grid.StrategyGridSearcher;
import stsc.general.statistic.cost.comparator.MetricsSameComparator;
import stsc.general.statistic.cost.function.CostWeightedSumFunction;
import stsc.general.strategy.TradingStrategy;
import stsc.general.strategy.selector.StatisticsByCostSelector;
import stsc.general.strategy.selector.StrategySelector;
import stsc.storage.mocks.StockStorageMock;
class PerformanceCalculator {
final StockStorage stockStorage;
final private PerformanceCalculatorSettings settings;
PerformanceCalculator(PerformanceCalculatorSettings settings) throws Exception {
this.settings = settings;
this.stockStorage = StockStorageMock.getStockStorage();
if (settings.printAdditionalInfo && settings.searcherType == SearcherType.GENETIC_SEARCHER) {
System.out.print(settings.maxSelectionIndex + " " + settings.populationSize + " ");
}
if (settings.printStarterInfo) {
System.out.println("Size of stocks: " + stockStorage.getStockNames().size());
calculateAmountOfSimulations(stockStorage, settings);
}
if (settings.shouldWarmUp) {
warmUp();
}
}
public void calculateTimeStatistics() throws Exception {
for (int i = 10; i <= 31; ++i) {
calculateForThreads(settings.startOfPeriod.plusDays(i));
}
for (int i = 1; i <= 12; ++i) {
calculateForThreads(settings.startOfPeriod.plusMonths(i));
}
for (int i = 1; i <= 12; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
for (int i = 42; i <= 42; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
}
public void calculateSmallStatistics() throws Exception {
for (int i = 3; i <= 3; i += 1) {
calculateForThreads(settings.startOfPeriod.plusYears(i));
}
}
private void calculateForThreads(LocalDate endDate) throws Exception {
if (settings.printAdditionalInfo)
System.out.print(Days.daysBetween(settings.startOfPeriod, endDate).getDays());
for (int thread = settings.threadsFrom; thread <= settings.threadsTo; ++thread) {
calculateAverageTime(endDate, true, thread);
}
if (settings.printAdditionalInfo)
System.out.println();
}
static public void calculateAmountOfSimulations(StockStorage stockStorage, PerformanceCalculatorSettings settings) throws StrategySearcherException {
final SimulatorSettingsGridFactory factory = SimulatorSettingsGenerator.getGridFactory(settings.performanceForGridTest, stockStorage, settings.elements,
settings.getStartOfPeriod(), getDateRepresentation(settings.startOfPeriod.plusMonths(1)));
System.out.println("Simulation amount: " + factory.size());
}
private void warmUp() throws Exception {
final LocalDate newDate = settings.startOfPeriod.plusDays(31);
final int[] threadToWarmUp = { 1, 2, 8 };
for (int i : threadToWarmUp) {
calculateAverageTime(newDate, false, i);
}
final LocalDate tenDate = settings.startOfPeriod.plusDays(10);
for (int i : threadToWarmUp) {
calculateAverageTime(tenDate, false, i);
}
}
private double calculateAverageTime(LocalDate endDate, boolean printData, int threadAmount) throws Exception {
final String endOfPeriod = getDateRepresentation(endDate);
double time = 0.0;
double avGain = 0.0;
for (int i = 0; i < settings.calculationsForAverage; ++i) {
final PerformanceResult result = timeForSearch(threadAmount, endOfPeriod);
time += TimeTracker.lengthInSeconds(result.timeTracker.length());
avGain += result.sumAvGainForBest;
}
final double avTime = time / settings.calculationsForAverage;
final double avRes = avGain / settings.calculationsForAverage;
if (printData && settings.printAvGainAndTime) {
System.out.print(" " + settings.format(avTime) + " " + settings.format(avRes) + " ");
}
return avTime;
}
public PerformanceResult timeForSearch(int threadSize, String endOfPeriod) throws StrategySearcherException, BadAlgorithmException, BadSignalException, InterruptedException {
final TimeTracker timeTracker = new TimeTracker();
final StrategySearcher searcher = generateSearcher(threadSize, endOfPeriod);
final List<TradingStrategy> strategies = searcher.waitAndGetSelector().getStrategies();
return createResult(strategies, timeTracker);
}
private StrategySearcher generateSearcher(int threadSize, String endOfPeriod) throws InterruptedException {
final String startDate = getDateRepresentation(settings.startOfPeriod);
final StrategySelector selector = new StatisticsByCostSelector(settings.storedStrategyAmount, new CostWeightedSumFunction(), new MetricsSameComparator());
if (settings.searcherType == SearcherType.GRID_SEARCHER) {
final SimulatorSettingsGridList list = SimulatorSettingsGenerator
.getGridFactory(settings.performanceForGridTest, stockStorage, settings.elements, startDate, endOfPeriod).getList();
return new StrategyGridSearcher(list, selector, threadSize);
} else {
final SimulatorSettingsGeneticListImpl list = SimulatorSettingsGenerator
.getGeneticFactory(settings.performanceForGridTest, stockStorage, settings.elements, startDate, endOfPeriod).getList();
return StrategyGeneticSearcher.getBuilder().withGeneticList(list).withStrategySelector(selector).withThreadAmount(threadSize)
.withMaxPopulationsAmount(settings.maxSelectionIndex).withPopulationSize(settings.populationSize).build();
}
}
private static PerformanceResult createResult(List<TradingStrategy> strategies, TimeTracker timeTracker) {
double sumGetAvGain = 0.0;
timeTracker.finish();
sumGetAvGain = strategies.get(0).getAvGain();
// TODO strange comment should be deleted or returned back
// for (Statistics statistic : statistics) {
// sumGetAvGain += statistic.getAvGain();
// }
return new PerformanceResult(timeTracker, sumGetAvGain);
}
static private String getDateRepresentation(LocalDate date) {
int day = date.getDayOfMonth();
int month = date.getMonthOfYear();
int year = date.getYear();
return String.format("%02d-%02d-%04d", day, month, year);
}
}
| added usage of StrategyGridSearcherBuilder | src/main/java/stsc/performance/PerformanceCalculator.java | added usage of StrategyGridSearcherBuilder |
|
Java | apache-2.0 | f0de9a7b7773d236624b7a975c654058a6a32b98 | 0 | Alluxio/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,PasaLab/tachyon,maobaolong/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,aaudiber/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,madanadit/alluxio,riversand963/alluxio,bf8086/alluxio,madanadit/alluxio,wwjiang007/alluxio,riversand963/alluxio,Reidddddd/alluxio,uronce-cc/alluxio,calvinjia/tachyon,madanadit/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,maboelhassan/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,bf8086/alluxio,wwjiang007/alluxio,apc999/alluxio,ChangerYoung/alluxio,jswudi/alluxio,jswudi/alluxio,bf8086/alluxio,calvinjia/tachyon,bf8086/alluxio,apc999/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,maobaolong/alluxio,jsimsa/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,madanadit/alluxio,maobaolong/alluxio,jswudi/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,riversand963/alluxio,jswudi/alluxio,PasaLab/tachyon,wwjiang007/alluxio,ShailShah/alluxio,aaudiber/alluxio,calvinjia/tachyon,madanadit/alluxio,maboelhassan/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,calvinjia/tachyon,wwjiang007/alluxio,calvinjia/tachyon,uronce-cc/alluxio,maobaolong/alluxio,jswudi/alluxio,ShailShah/alluxio,jsimsa/alluxio,maobaolong/alluxio,apc999/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,madanadit/alluxio,riversand963/alluxio,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,maobaolong/alluxio,Alluxio/alluxio,apc999/alluxio,bf8086/alluxio,jsimsa/alluxio,jsimsa/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,bf8086/alluxio,Reidddddd/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,aaudiber/alluxio,wwjiang007/alluxio,bf8086/alluxio,jsimsa/alluxio,bf8086/alluxio,maobaolong/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,Alluxio/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,ShailShah/alluxio,PasaLab/tachyon,Alluxio/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,uronce-cc/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,apc999/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,riversand963/alluxio,Reidddddd/alluxio,madanadit/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,maboelhassan/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,riversand963/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,ShailShah/alluxio,jswudi/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,apc999/alluxio,Alluxio/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the “License”). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.keyvalue;
import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.client.ClientContext;
import alluxio.client.file.FileSystem;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.PreconditionMessage;
import alluxio.thrift.PartitionInfo;
import alluxio.util.io.BufferUtils;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Default implementation of {@link KeyValueStoreWriter} to create an Alluxio key-value store.
*/
@NotThreadSafe
class BaseKeyValueStoreWriter implements KeyValueStoreWriter {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final FileSystem mFileSystem = FileSystem.Factory.get();
private final KeyValueMasterClient mMasterClient;
private final AlluxioURI mStoreUri;
private long mPartitionIndex;
private KeyValuePartitionWriter mWriter = null;
/** Min key in the current partition. */
private ByteBuffer mKeyStart = null;
/** Max key in the current partition. */
private ByteBuffer mKeyLimit = null;
/** Whether this writer is closed. */
private boolean mClosed;
/** Whether this writer is canceled. */
private boolean mCanceled;
/** Byte array of the last input key. */
private byte[] mLastKey = null;
/**
* Constructs a {@link BaseKeyValueStoreWriter}. This constructor will create a new key-value
* store at the given {@link AlluxioURI}.
*
* @param uri URI of the store
* @throws IOException if a non-Alluxio exception occurs
* @throws AlluxioException if an unexpected Alluxio exception is thrown
*/
BaseKeyValueStoreWriter(AlluxioURI uri) throws IOException, AlluxioException {
LOG.info("Create KeyValueStoreWriter for {}", uri);
mMasterClient =
new KeyValueMasterClient(ClientContext.getMasterAddress(), ClientContext.getConf());
mStoreUri = Preconditions.checkNotNull(uri);
mMasterClient.createStore(mStoreUri);
mPartitionIndex = 0;
mClosed = false;
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
try {
if (mCanceled) {
mWriter.cancel();
// TODO(binfan): cancel all other written partitions
} else {
completePartition();
mMasterClient.completeStore(mStoreUri);
}
} catch (AlluxioException e) {
throw new IOException(e);
} finally {
mMasterClient.close();
}
mClosed = true;
}
@Override
public void cancel() throws IOException {
mCanceled = true;
close();
}
@Override
public void put(byte[] key, byte[] value) throws IOException, AlluxioException {
Preconditions.checkNotNull(key, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkNotNull(value, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkArgument(key.length > 0, PreconditionMessage.ERR_PUT_EMPTY_KEY);
Preconditions.checkArgument(value.length > 0, PreconditionMessage.ERR_PUT_EMPTY_VALUE);
// Since the input keys are guaranteed in non-decreasing order by the client, only the last
// input key needs to be checked in order to prevent inputting same key.
if (mLastKey != null && Arrays.equals(key, mLastKey)) {
throw new IOException(ExceptionMessage.KEY_ALREADY_EXISTS.getMessage());
}
// If this is the first put to the first partition in this store, create a new partition; or
// if this is a put to an existing but full partition, create a new partition and switch to
// this one.
if (mWriter == null || !mWriter.canPut(key, value)) {
// Need to save the existing partition before switching to the next partition.
if (mWriter != null) {
completePartition();
}
mWriter = KeyValuePartitionWriter.Factory.create(getPartitionName());
mKeyStart = null;
mKeyLimit = null;
}
// If we are still unable to put this key-value pair after switching partition, throw exception.
if (!mWriter.canPut(key, value)) {
throw new IOException(ExceptionMessage.KEY_VALUE_TOO_LARGE
.getMessage(key.length, value.length));
}
mWriter.put(key, value);
// Update the last input key.
mLastKey = key;
ByteBuffer keyBuf = ByteBuffer.wrap(key);
// Update the min key in the current partition.
if (mKeyStart == null || keyBuf.compareTo(mKeyStart) < 0) {
mKeyStart = ByteBuffer.allocate(key.length);
mKeyStart.put(key);
mKeyStart.flip();
}
// Update the max key in the current partition.
if (mKeyLimit == null || keyBuf.compareTo(mKeyLimit) > 0) {
mKeyLimit = ByteBuffer.allocate(key.length);
mKeyLimit.put(key);
mKeyLimit.flip();
}
}
@Override
public void put(ByteBuffer key, ByteBuffer value) throws IOException, AlluxioException {
Preconditions.checkNotNull(key, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkNotNull(value, PreconditionMessage.ERR_PUT_NULL_VALUE);
// TODO(binfan): make efficient implementation
byte[] keyArray = BufferUtils.newByteArrayFromByteBuffer(key);
byte[] valueArray = BufferUtils.newByteArrayFromByteBuffer(value);
put(keyArray, valueArray);
}
/**
* @return {@link AlluxioURI} to the current partition file
*/
private AlluxioURI getPartitionName() {
return new AlluxioURI(String.format("%s/part-%05d", mStoreUri, mPartitionIndex));
}
/**
* Completes the current partition.
*
* @throws IOException if non-Alluxio error occurs
* @throws AlluxioException if Alluxio error occurs
*/
private void completePartition() throws IOException, AlluxioException {
if (mWriter == null) {
return;
}
mWriter.close();
List<Long> blockIds = mFileSystem.getStatus(getPartitionName()).getBlockIds();
long blockId = blockIds.get(0);
PartitionInfo info = new PartitionInfo(mKeyStart, mKeyLimit, blockId, mWriter.keyCount());
mMasterClient.completePartition(mStoreUri, info);
mPartitionIndex++;
}
}
| keyvalue/client/src/main/java/alluxio/client/keyvalue/BaseKeyValueStoreWriter.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the “License”). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.keyvalue;
import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.client.ClientContext;
import alluxio.client.file.FileSystem;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.PreconditionMessage;
import alluxio.thrift.PartitionInfo;
import alluxio.util.io.BufferUtils;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Default implementation of {@link KeyValueStoreWriter} to create an Alluxio key-value store.
*/
@NotThreadSafe
class BaseKeyValueStoreWriter implements KeyValueStoreWriter {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final FileSystem mFileSystem = FileSystem.Factory.get();
private final KeyValueMasterClient mMasterClient;
private final AlluxioURI mStoreUri;
private long mPartitionIndex;
private KeyValuePartitionWriter mWriter = null;
/** Min key in the current partition. */
private ByteBuffer mKeyStart = null;
/** Max key in the current partition. */
private ByteBuffer mKeyLimit = null;
/** Whether this writer is closed. */
private boolean mClosed;
/** Whether this writer is canceled. */
private boolean mCanceled;
/** Byte array of the last input key. */
private byte[] mLastKey = null;
/**
* Constructs a {@link BaseKeyValueStoreWriter}. This constructor will create a new key-value
* store at the given {@link AlluxioURI}.
*
* @param uri URI of the store
* @throws IOException if a non-Alluxio exception occurs
* @throws AlluxioException if an unexpected Alluxio exception is thrown
*/
BaseKeyValueStoreWriter(AlluxioURI uri) throws IOException, AlluxioException {
LOG.info("Create KeyValueStoreWriter for {}", uri);
mMasterClient =
new KeyValueMasterClient(ClientContext.getMasterAddress(), ClientContext.getConf());
mStoreUri = Preconditions.checkNotNull(uri);
mMasterClient.createStore(mStoreUri);
mPartitionIndex = 0;
mClosed = false;
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
try {
if (mCanceled) {
mWriter.cancel();
// TODO(binfan): cancel all other written partitions
} else {
completePartition();
mMasterClient.completeStore(mStoreUri);
}
} catch (AlluxioException e) {
throw new IOException(e);
} finally {
mMasterClient.close();
}
mClosed = true;
}
@Override
public void cancel() throws IOException {
mCanceled = true;
close();
}
@Override
public void put(byte[] key, byte[] value) throws IOException, AlluxioException {
Preconditions.checkNotNull(key, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkNotNull(value, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkArgument(key.length > 0, PreconditionMessage.ERR_PUT_EMPTY_KEY);
Preconditions.checkArgument(value.length > 0, PreconditionMessage.ERR_PUT_EMPTY_VALUE);
// Since the input keys are guaranteed in non-decreasing order by the client, only the last
// input key needs to be checked in order to prevent inputting same key.
if (mLastKey != null && Arrays.equals(key, mLastKey)) {
throw new IOException(ExceptionMessage.KEY_ALREADY_EXISTS.getMessage());
}
// If this is the first put to the first partition in this store, create a new partition; or
// if this is a put to an existing but full partition, create a new partition and switch to
// this one.
if (mWriter == null || !mWriter.canPut(key, value)) {
// Need to save the existing partition before switching to the next partition.
if (mWriter != null) {
completePartition();
}
mWriter = KeyValuePartitionWriter.Factory.create(getPartitionName());
mKeyStart = null;
mKeyLimit = null;
}
// If we are still unable to put this key-value pair after switching partition, throw exception.
if (!mWriter.canPut(key, value)) {
throw new IOException(ExceptionMessage.KEY_VALUE_TOO_LARGE
.getMessage(key.length, value.length));
}
mWriter.put(key, value);
// Update the last input key.
mLastKey = key;
ByteBuffer keyBuf = ByteBuffer.wrap(key);
// Update the min key in the current partition.
if (mKeyStart == null || keyBuf.compareTo(mKeyStart) < 0) {
mKeyStart = ByteBuffer.allocate(key.length);
mKeyStart.put(key);
mKeyStart.flip();
}
// Update the max key in the current partition.
if (mKeyLimit == null || keyBuf.compareTo(mKeyLimit) > 0) {
mKeyLimit = ByteBuffer.allocate(key.length);
mKeyLimit.put(key);
mKeyLimit.flip();
}
}
@Override
public void put(ByteBuffer key, ByteBuffer value) throws IOException, AlluxioException {
Preconditions.checkNotNull(key, PreconditionMessage.ERR_PUT_NULL_KEY);
Preconditions.checkNotNull(value, PreconditionMessage.ERR_PUT_NULL_VALUE);
// TODO(binfan): make efficient implementation
byte[] keyArray = BufferUtils.newByteArrayFromByteBuffer(key);
byte[] valueArray = BufferUtils.newByteArrayFromByteBuffer(value);
put(keyArray, valueArray);
}
/**
* @return {@link AlluxioURI} to the current partition file
*/
private AlluxioURI getPartitionName() {
return new AlluxioURI(String.format("%s/part-%05d", mStoreUri, mPartitionIndex));
}
/**
* Completes the current partition.
*
* @throws IOException if non-Alluxio error occurs
* @throws AlluxioException if Alluxio error occurs
*/
private void completePartition() throws IOException, AlluxioException {
if (mWriter == null) {
return;
}
int keyCount = mWriter.keyCount();
mWriter.close();
List<Long> blockIds = mFileSystem.getStatus(getPartitionName()).getBlockIds();
long blockId = blockIds.get(0);
PartitionInfo info = new PartitionInfo(mKeyStart, mKeyLimit, blockId, keyCount);
mMasterClient.completePartition(mStoreUri, info);
mPartitionIndex++;
}
}
| Use mWriter.keyCount() instead
| keyvalue/client/src/main/java/alluxio/client/keyvalue/BaseKeyValueStoreWriter.java | Use mWriter.keyCount() instead |
|
Java | apache-2.0 | eddb84d5261ab6e84ec845c16122e1e197906be2 | 0 | mtransitapps/ca-winnipeg-transit-bus-parser,mtransitapps/ca-winnipeg-transit-bus-parser | package org.mtransit.parser.ca_winnipeg_transit_bus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.Utils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
// http://winnipegtransit.com/en/schedules-maps-tools/transittools/open-data/
// http://gtfs.winnipegtransit.com/google_transit.zip
public class WinnipegTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-winnipeg-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new WinnipegTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Winnipeg Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating Winnipeg Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
if (!Utils.isDigitsOnly(gRoute.getRouteId())) {
return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID
}
return super.getRouteId(gRoute);
}
@Override
public String getRouteLongName(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteLongName())) {
int routeId = Integer.parseInt(gRoute.getRouteId());
switch (routeId) {
case 72:
return UNIVERSITY_OF_MANITOBA + " - " + RICHMOND_WEST;
case 76:
return UNIVERSITY_OF_MANITOBA + " - " + ST_VITAL_CTR;
case 84:
return WHYTE_RDG;
case 86:
return WHYTE_RDG;
}
System.out.printf("\nUnexpected route long name %s!\n", gRoute);
System.exit(-1);
return null;
}
return cleanTripHeadsign(gRoute.getRouteLongName()); // used in real-time API
}
private static final String AGENCY_COLOR_BLUE = "3256A3"; // BLUE (from PDF map logo)
private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_231F20 = "231F20";
private static final String COLOR_FFFFFF = "FFFFFF";
private static final String COLOR_F0B40F = "F0B40F";
private static final String COLOR_FFFF00 = "FFFF00";
@Override
public String getRouteColor(GRoute gRoute) {
if (COLOR_FFFFFF.equalsIgnoreCase(gRoute.getRouteColor())) {
return COLOR_231F20;
}
if (COLOR_FFFF00.equalsIgnoreCase(gRoute.getRouteColor())) {
return COLOR_F0B40F;
}
return super.getRouteColor(gRoute);
}
private static final String AND = " & ";
private static final String SLASH = " / ";
private static final String ASSINIBOINE_PARK = "Assiniboine Pk";
private static final String COUNTER_CLOCKWISE = "Counter-Clockwise";
private static final String DOWNTOWN = "Downtown";
private static final String CITY_HALL = "City Hall";
private static final String WINDERMERE = "Windermere";
private static final String BROADWAY = "Broadway";
private static final String FERRY_RD = "Ferry Rd";
private static final String SELKIRK = "Selkirk";
private static final String OSBORNE = "Osborne";
private static final String MISERICORDIA = "Misericordia";
private static final String NORTH_MAIN = "North Main";
private static final String CORYDON = "Corydon";
private static final String RED_RIVER_COLLEGE = "Red River College";
private static final String WINDSOR_PARK = "Windsor Pk";
private static final String WATT = "Watt";
private static final String AIRPORT = "Airport";
private static final String POLO_PARK = "Polo Pk";
private static final String PORTAGE_WEST = "Portage West";
private static final String INKSTER = "Inkster";
private static final String INKSTER_PARK = INKSTER + " Pk";
private static final String INKSTER_IND_PARK = INKSTER + " Ind Pk";
private static final String OMANDS_CREEK = "Omands Crk";
private static final String MAPLES = "Maples";
private static final String TEMPLETON = "Templeton";
private static final String THE_FORKS = "The Forks";
private static final String UNIVERSITY_OF_SHORT = "U Of ";
private static final String UNIVERSITY_OF_MANITOBA = UNIVERSITY_OF_SHORT + "Manitoba";
private static final String UNIVERSITY_OF_WINNIPEG = UNIVERSITY_OF_SHORT + "Winnipeg";
private static final String UNICITY = "Unicity";
private static final String WAL_MART = "WalMart";
private static final String PORTAGE = "Portage";
private static final String MURRAY_PARK = "Murray Pk";
private static final String HENDERSON = "Henderson";
private static final String KILDONAN = "Kildonan";
private static final String KILDONAN_PL = KILDONAN + " Pl";
private static final String NORTH_TRANSCONA = "North Transcona";
private static final String CROSSROADS_STN = "Crossroads Sta";
private static final String SOUTH_ST_VITAL = "South St Vital";
private static final String RIVERVIEW = "Riverview";
private static final String PATERSON_LOOP = "Paterson Loop";
private static final String ST_VITAL_CTR = "St Vital Ctr";
private static final String TRANSCONA = "Transcona";
private static final String SOUTH_TRANSCONA = "South " + TRANSCONA;
private static final String RICHMOND_WEST = "Richmond West";
private static final String WESTDALE = "Westdale";
private static final String BALMORAL_STA = "Balmoral Sta";
private static final String OAK_POINT = "Oak Pt";
private static final String MEADOWS_WEST = "Mdws West";
private static final String SOUTH_POINTE = "South Pte";
private static final String ALDGATE = "Aldgate";
private static final String ISLAND_LAKES = "Isl Lks";
private static final String ST_NORBERT = "St Norbert";
private static final String ST_AMANT = "St Amant";
private static final String NORTH_KILDONAN = "North Kildonan";
private static final String GLENWAY = "Glenway";
private static final String RIVERBEND = "Riverbend";
private static final String LEILA = "Leila";
private static final String WHELLAMS = "Whellams";
private static final String WHELLAMS_LOOP = WHELLAMS + " Loop";
private static final String WHYTE_RDG = "Whyte Rdg";
private static final String WOODHAVEN = "Woodhaven";
private static final String ROUGE = "Rouge";
private static final String TO = " to ";
private static final String VIA = " via ";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>();
map2.put(15L, new RouteTripSpec(15L, //
0, MTrip.HEADSIGN_TYPE_STRING, AIRPORT, //
1, MTrip.HEADSIGN_TYPE_STRING, INKSTER_PARK) //
.addTripSort(0, //
Arrays.asList(new String[] { //
"30659", // != Eastbound Church at Keewatin <=
"30556", // != Eastbound Church at Bunting
"30654", // != Westbound Church at Keewatin <=
"30532", // != Southbound Fife at Huron
"30535", // == Southbound Fife at Church
"30536", // Southbound Fife at Admiral
"30521", // == Eastbound Mountain at Fife
"30756", // != <> Westbound Fife at Fife Loop <=
"30477", // == != Eastbound Mountain at McPhillips West
"30079", // Eastbound Mountain at Main
"10541", // Westbound Portage at Garry
"20083", // == Westbound Sargent at Century
"20018", // != Westbound Sargent at Bradford
"20121", // != Northbound Flight at Standard Aero
"20422", // != Northbound Century at Sargent
"20040", // != Westbound Wellington at Canada Post
"20523", // == Westbound Wellington at Flight
"20070", // Westbound Wellington at Airport Terminal (Rte 15)
})) //
.addTripSort(1, //
Arrays.asList(new String[] { //
"20070", // Westbound Wellington at Airport Terminal (Rte 15)
"20147", // == Eastbound Wellington at Flight
"20041", // != Eastbound Wellington at Canada Post
"20063", // != Southbound King Edward at Wellington South
"20122", // != Southbound Flight at Sargent
"20144", // != Eastbound Sargent at Berry
"20085", // == Eastbound Sargent at King Edward
"10583", // Eastbound Portage at Fort
"30078", // Westbound Mountain at Main
"30520", // == != Westbound Mountain at McPhillips West
"30756", // != <> Westbound Fife at Fife Loop =>
"30519", // != Westbound Mountain at Fife CONTINUE
"30518", // == Northbound Fife at Admiral
"30533", // != Westbound Church at Fife
"30654", // != Westbound Church at Keewatin =>
"30517", // != Northbound Fife at Church
"30659", // != Eastbound Church at Keewatin =>
})) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String gTripHeadsign = gTrip.getTripHeadsign();
int indexOfTO = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH).indexOf(TO);
if (indexOfTO >= 0) {
String gTripHeadsignAfterTO = gTripHeadsign.substring(indexOfTO + TO.length());
gTripHeadsign = gTripHeadsignAfterTO;
}
int indexOfVIA = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH).indexOf(VIA);
if (indexOfVIA >= 0) {
String gTripHeadsignBeforeVIA = gTripHeadsign.substring(0, indexOfVIA);
gTripHeadsign = gTripHeadsignBeforeVIA;
}
mTrip.setHeadsignString(cleanTripHeadsign(gTripHeadsign), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 1L) {
if (Arrays.asList( //
"The Forks", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("The Forks", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 2L) {
if (Arrays.asList( //
DOWNTOWN, //
DOWNTOWN + " Spirit-Counterclockwise", //
COUNTER_CLOCKWISE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(COUNTER_CLOCKWISE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 10L) {
if (Arrays.asList( //
DOWNTOWN, //
"St Boniface" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("St Boniface", mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
DOWNTOWN, //
"Wolseley-Provencher", //
"Wolseley" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Wolseley", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 11L) {
if (Arrays.asList( //
CITY_HALL, //
DOWNTOWN, //
GLENWAY, //
THE_FORKS, //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
NORTH_KILDONAN, //
KILDONAN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
ASSINIBOINE_PARK, //
"Crestview", //
HENDERSON, //
"St Charles", //
PORTAGE + AND + WOODHAVEN, //
UNIVERSITY_OF_WINNIPEG, //
"Westwood", //
POLO_PARK, //
PORTAGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 12L) {
if (Arrays.asList( //
"Health Sciences Ctr", //
"Valour" + AND + PORTAGE, //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 14L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"St Mary's" + AND + "Dakota", //
FERRY_RD //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(FERRY_RD, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
SOUTH_ST_VITAL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_ST_VITAL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 15L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Mtn" + AND + "Fife", // <>
AIRPORT //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(AIRPORT, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Mtn" + AND + "Fife", // <>
INKSTER_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INKSTER_PARK, mTrip.getHeadsignId()); // Mtn & Fife
return true;
}
} else if (mTrip.getRouteId() == 16L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Kingston Row", // <>
SELKIRK + AND + "McPhillips", // <>
"Main" + AND + "Pioneer", // <>
"Plz Dr", //
ISLAND_LAKES, //
OSBORNE + " Junction", //
ST_VITAL_CTR, //
"Southdale Ctr", //
ST_VITAL_CTR + SLASH + "Southdale Ctr" // merge
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("St Vital Ctr" + SLASH + "Southdale Ctr", mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Kingston Row", // <>
"Selkirk" + AND + "McPhillips", // <>
"Main" + AND + "Pioneer", // <>
"Tyndall Pk" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Tyndall Pk", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 17L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Seven Oaks Hosp", //
"Amber Trails", //
MAPLES //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MAPLES, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Memorial" + AND + "Broadway", //
"Gdn City Ctr", //
MISERICORDIA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISERICORDIA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 18L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Main" + AND + "Templeton", //
"Gdn City Ctr", // !=
RIVERBEND, // !=
NORTH_MAIN // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_MAIN, mTrip.getHeadsignId()); // RIVERBEND
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Main" + AND + "McAdam", //
CORYDON + AND + "Cambridge", //
"Tuxedo", //
ASSINIBOINE_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ASSINIBOINE_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 19L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Elizabeth" + AND + "Drake", //
RED_RIVER_COLLEGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RED_RIVER_COLLEGE, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
WINDSOR_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WINDSOR_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 20L) {
if (Arrays.asList( //
DOWNTOWN, //
PORTAGE + AND + "Tylehurst", //
"Redwood" + AND + "Main", //
AIRPORT //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(AIRPORT, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
"Fort" + AND + PORTAGE, //
WATT + AND + "Leighton" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WATT + AND + "Leighton", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 21L) {
if (Arrays.asList( //
"Crestview", //
"Grace Hosp", //
"St Charles", //
"Westwood", //
PORTAGE_WEST // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE_WEST, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 22L) {
if (Arrays.asList( //
"Crestview", //
"St Charles", //
"Westwood", //
PORTAGE_WEST // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE_WEST, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 24L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 26L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 28L) {
if (Arrays.asList( //
"I", //
OMANDS_CREEK, //
RED_RIVER_COLLEGE, //
INKSTER_IND_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INKSTER_IND_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 29L) {
if (Arrays.asList( //
CITY_HALL, // !=
WINDERMERE, // !=
CITY_HALL + SLASH + WINDERMERE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL + SLASH + WINDERMERE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 31L) {
if (Arrays.asList( //
MEADOWS_WEST, // !=
OAK_POINT, // !=
MEADOWS_WEST + SLASH + OAK_POINT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MEADOWS_WEST + SLASH + OAK_POINT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 32L) {
if (Arrays.asList( //
"Main" + AND + "Seven Oaks", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
LEILA, // !=
RIVERBEND, // !=
LEILA + SLASH + RIVERBEND // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(LEILA + SLASH + RIVERBEND, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 33L) {
if (Arrays.asList( //
"McPhillips" + AND + "Mapleglen", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Jefferson", //
"Mapleglen" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Mapleglen", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 36L) {
if (Arrays.asList( //
"Health Sciences Ctr", //
MAPLES //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MAPLES, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 38L) {
if (Arrays.asList( //
PORTAGE + AND + "Fort", //
"Templeton" + AND + "Salter", //
"William Stephenson" + AND + "Main", //
THE_FORKS //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(THE_FORKS, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 41L) {
if (Arrays.asList( //
NORTH_KILDONAN, // !=
GLENWAY, // !=
GLENWAY + SLASH + NORTH_KILDONAN // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(GLENWAY + SLASH + NORTH_KILDONAN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 44L) {
if (Arrays.asList( //
"London" + AND + "Munroe", //
DOWNTOWN, //
BROADWAY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BROADWAY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 45L) {
if (Arrays.asList( //
"Main" + AND + "Pioneer", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Munroe" + AND + "Prevette", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 46L) {
if (Arrays.asList( //
"Plessis" + AND + "Regent", //
BALMORAL_STA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BALMORAL_STA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 47L) {
if (Arrays.asList( //
"Main" + AND + PORTAGE, //
KILDONAN_PL, //
BALMORAL_STA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BALMORAL_STA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 49L) {
if (Arrays.asList( //
"Dugald" + AND + "Beghin", //
NORTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 50L) {
if (Arrays.asList( //
WINDSOR_PARK, //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 54L) {
if (Arrays.asList( //
ST_AMANT, // !=
SOUTH_ST_VITAL, // !=
SOUTH_ST_VITAL + SLASH + ST_AMANT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_ST_VITAL + SLASH + ST_AMANT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 55L) {
if (Arrays.asList( //
PORTAGE + AND + "Garry", //
"St Anne's" + AND + "Niakwa", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 56L) {
if (Arrays.asList( //
PORTAGE + AND + "Garry", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 59L) {
if (Arrays.asList( //
ALDGATE, // !=
ISLAND_LAKES, // !=
ALDGATE + SLASH + ISLAND_LAKES // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ALDGATE + SLASH + ISLAND_LAKES, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 65L) {
if (Arrays.asList( //
"Kenaston", //
"Roblin" + AND + "Dieppe", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 66L) {
if (Arrays.asList( //
"Grant" + AND + "Kenaston", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Dieppe Loop", //
POLO_PARK, // !=
UNICITY, // !=
UNICITY + SLASH + POLO_PARK // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY + SLASH + POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 68L) {
if (Arrays.asList( //
"Stradbrook" + AND + "Osborne", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 71L) {
if (Arrays.asList( //
TEMPLETON, // !=
WAL_MART, // !=
WAL_MART + SLASH + TEMPLETON // != ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WAL_MART + SLASH + TEMPLETON, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Arlington" + AND + "Mtn", //
PORTAGE//
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 72L) {
if (Arrays.asList( //
"Dalhousie", //
"Dalhousie" + AND + "Pembina", //
"Killarney" + AND + "Pembina", //
UNIVERSITY_OF_MANITOBA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 75L) {
if (Arrays.asList( //
"Speers" + AND + "Elizabeth", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 77L) {
if (Arrays.asList( //
"Gdn City Ctr", // <>
"Main" + AND + "Margaret", // <>
"Keewatin" + AND + "Inkster", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Gdn City Ctr", // <>
"Main" + AND + "Margaret", // <>
RED_RIVER_COLLEGE, //
"Whellams Ln", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 79L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 83L) {
if (Arrays.asList( //
"Crestview" + AND + "Ashern", //
UNICITY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Grace Hosp", //
"Thompson" + AND + "Ness", //
MURRAY_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MURRAY_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 85L) {
if (Arrays.asList( //
"Springfield Loop", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
HENDERSON + AND + WHELLAMS, //
WHELLAMS_LOOP //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WHELLAMS_LOOP, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 87L) {
if (Arrays.asList( //
"Beghin" + AND + "Dugald", //
SOUTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 89L) {
if (Arrays.asList( //
"Day" + AND + "Regent", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 90L) {
if (Arrays.asList( //
KILDONAN_PL, //
NORTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 92L) {
if (Arrays.asList( //
KILDONAN_PL, //
CROSSROADS_STN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CROSSROADS_STN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 94L) {
if (Arrays.asList( //
"Chevrier" + AND + "Pembina", //
"Windermere" + AND + "Pembina", //
"Walmart" + AND + "Kenaston", //
"Wildwood", //
"Wildwood Pk" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Wildwood Pk", mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Henlow" + AND + "Scurfield", //
WHYTE_RDG).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WHYTE_RDG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 95L) {
if (Arrays.asList( //
"Fort Rouge Sta", // <>
"Pan Am Pool", //
"Shaftesbury Pk", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Fort Rouge Sta", // <>
"Osborne", //
RIVERVIEW//
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RIVERVIEW, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 96L) {
if (Arrays.asList( //
"Southdale Ctr", //
PATERSON_LOOP //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PATERSON_LOOP, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Southdale Ctr", //
ST_VITAL_CTR //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ST_VITAL_CTR, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 98L) {
if (Arrays.asList( //
WESTDALE, //
UNICITY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 99L) {
if (Arrays.asList( //
"Stradbrook" + AND + "Donald", //
DOWNTOWN // <>
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
DOWNTOWN, // <>
MISERICORDIA, // !=
WINDERMERE, // !=
WINDERMERE + AND + "Pembina", //
MISERICORDIA + SLASH + WINDERMERE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISERICORDIA + SLASH + WINDERMERE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 137L) {
if (Arrays.asList( //
UNIVERSITY_OF_MANITOBA, // !=
ST_NORBERT, // !=
ST_NORBERT + SLASH + UNIVERSITY_OF_MANITOBA // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ST_NORBERT + SLASH + UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 162L) {
if (Arrays.asList( //
"Killarney" + AND + "Pembina", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Turnbull Dr", //
ST_NORBERT, // !=
UNIVERSITY_OF_MANITOBA, // !=
UNIVERSITY_OF_MANITOBA + SLASH + ST_NORBERT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA + SLASH + ST_NORBERT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 163L) {
if (Arrays.asList( //
"Pembina" + AND + "Univ Cresc.", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 170L) {
if (Arrays.asList( //
"Killarney" + AND + "Pembina", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
ST_NORBERT, //
UNIVERSITY_OF_MANITOBA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 181L) {
if (Arrays.asList( //
"Pembina" + AND + "Pt", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 183L) {
if (Arrays.asList( //
RICHMOND_WEST, // !=
SOUTH_POINTE, // !=
RICHMOND_WEST + SLASH + SOUTH_POINTE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RICHMOND_WEST + SLASH + SOUTH_POINTE, mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trip to merge %s & %s.\n", mTrip, mTripToMerge);
System.exit(-1);
return false;
}
private static final Pattern POINT = Pattern.compile("((^|\\S){1}(\\.)(\\S|$){1})", Pattern.CASE_INSENSITIVE);
private static final String POINT_REPLACEMENT = "$2$3 $4";
private static final Pattern UNIVERSITY_OF = Pattern.compile("(university of )", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_OF_REPLACEMENT = UNIVERSITY_OF_SHORT;
private static final Pattern MISERICORDIA_HEALTH_CTR = Pattern.compile("(misericordia health centre)", Pattern.CASE_INSENSITIVE);
private static final String MISERICORDIA_HEALTH_CTR_REPLACEMENT = MISERICORDIA;
private static final Pattern AIRPORT_TERMINAL = Pattern.compile("(airport terminal)", Pattern.CASE_INSENSITIVE);
private static final String AIRPORT_TERMINAL_REPLACEMENT = AIRPORT;
private static final Pattern INKSTER_IND_PK = Pattern.compile("(inkster industrial park)", Pattern.CASE_INSENSITIVE);
private static final String INKSTER_IND_PK_REPLACEMENT = INKSTER_IND_PARK;
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = POINT.matcher(tripHeadsign).replaceAll(POINT_REPLACEMENT);
tripHeadsign = UNIVERSITY_OF.matcher(tripHeadsign).replaceAll(UNIVERSITY_OF_REPLACEMENT);
tripHeadsign = MISERICORDIA_HEALTH_CTR.matcher(tripHeadsign).replaceAll(MISERICORDIA_HEALTH_CTR_REPLACEMENT);
tripHeadsign = AIRPORT_TERMINAL.matcher(tripHeadsign).replaceAll(AIRPORT_TERMINAL_REPLACEMENT);
tripHeadsign = INKSTER_IND_PK.matcher(tripHeadsign).replaceAll(INKSTER_IND_PK_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern START_WITH_BOUND = Pattern.compile("(^){1}(eastbound|westbound|southbound|northbound)(\\s){1}", Pattern.CASE_INSENSITIVE);
@Override
public String cleanStopName(String gStopName) {
gStopName = START_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = POINT.matcher(gStopName).replaceAll(POINT_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
if (!Utils.isDigitsOnly(gStop.getStopId())) {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
}
return super.getStopId(gStop);
}
}
| src/org/mtransit/parser/ca_winnipeg_transit_bus/WinnipegTransitBusAgencyTools.java | package org.mtransit.parser.ca_winnipeg_transit_bus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.Utils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
// http://winnipegtransit.com/en/schedules-maps-tools/transittools/open-data/
// http://gtfs.winnipegtransit.com/google_transit.zip
public class WinnipegTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-winnipeg-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new WinnipegTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Winnipeg Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating Winnipeg Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
if (!Utils.isDigitsOnly(gRoute.getRouteId())) {
return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID
}
return super.getRouteId(gRoute);
}
@Override
public String getRouteLongName(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteLongName())) {
int routeId = Integer.parseInt(gRoute.getRouteId());
switch (routeId) {
case 72:
return UNIVERSITY_OF_MANITOBA + " - " + RICHMOND_WEST;
case 76:
return UNIVERSITY_OF_MANITOBA + " - " + ST_VITAL_CTR;
case 84:
return WHYTE_RDG;
case 86:
return WHYTE_RDG;
}
System.out.printf("\nUnexpected route long name %s!\n", gRoute);
System.exit(-1);
return null;
}
return cleanTripHeadsign(gRoute.getRouteLongName()); // used in real-time API
}
private static final String AGENCY_COLOR_BLUE = "3256A3"; // BLUE (from PDF map logo)
private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_231F20 = "231F20";
private static final String COLOR_FFFFFF = "FFFFFF";
private static final String COLOR_F0B40F = "F0B40F";
private static final String COLOR_FFFF00 = "FFFF00";
@Override
public String getRouteColor(GRoute gRoute) {
if (COLOR_FFFFFF.equalsIgnoreCase(gRoute.getRouteColor())) {
return COLOR_231F20;
}
if (COLOR_FFFF00.equalsIgnoreCase(gRoute.getRouteColor())) {
return COLOR_F0B40F;
}
return super.getRouteColor(gRoute);
}
private static final String AND = " & ";
private static final String SLASH = " / ";
private static final String ASSINIBOINE_PARK = "Assiniboine Pk";
private static final String COUNTER_CLOCKWISE = "Counter-Clockwise";
private static final String DOWNTOWN = "Downtown";
private static final String CITY_HALL = "City Hall";
private static final String WINDERMERE = "Windermere";
private static final String BROADWAY = "Broadway";
private static final String FERRY_RD = "Ferry Rd";
private static final String SELKIRK = "Selkirk";
private static final String OSBORNE = "Osborne";
private static final String MISERICORDIA = "Misericordia";
private static final String NORTH_MAIN = "North Main";
private static final String CORYDON = "Corydon";
private static final String RED_RIVER_COLLEGE = "Red River College";
private static final String WINDSOR_PARK = "Windsor Pk";
private static final String WATT = "Watt";
private static final String AIRPORT = "Airport";
private static final String POLO_PARK = "Polo Pk";
private static final String PORTAGE_WEST = "Portage West";
private static final String INKSTER = "Inkster";
private static final String INKSTER_PARK = INKSTER + " Pk";
private static final String INKSTER_IND_PARK = INKSTER + " Ind Pk";
private static final String OMANDS_CREEK = "Omands Crk";
private static final String MAPLES = "Maples";
private static final String TEMPLETON = "Templeton";
private static final String THE_FORKS = "The Forks";
private static final String UNIVERSITY_OF_SHORT = "U Of ";
private static final String UNIVERSITY_OF_MANITOBA = UNIVERSITY_OF_SHORT + "Manitoba";
private static final String UNIVERSITY_OF_WINNIPEG = UNIVERSITY_OF_SHORT + "Winnipeg";
private static final String UNICITY = "Unicity";
private static final String WAL_MART = "WalMart";
private static final String PORTAGE = "Portage";
private static final String MURRAY_PARK = "Murray Pk";
private static final String HENDERSON = "Henderson";
private static final String KILDONAN = "Kildonan";
private static final String KILDONAN_PL = KILDONAN + " Pl";
private static final String NORTH_TRANSCONA = "North Transcona";
private static final String CROSSROADS_STN = "Crossroads Sta";
private static final String SOUTH_ST_VITAL = "South St Vital";
private static final String RIVERVIEW = "Riverview";
private static final String PATERSON_LOOP = "Paterson Loop";
private static final String ST_VITAL_CTR = "St Vital Ctr";
private static final String TRANSCONA = "Transcona";
private static final String SOUTH_TRANSCONA = "South " + TRANSCONA;
private static final String RICHMOND_WEST = "Richmond West";
private static final String WESTDALE = "Westdale";
private static final String BALMORAL_STA = "Balmoral Sta";
private static final String OAK_POINT = "Oak Pt";
private static final String MEADOWS_WEST = "Mdws West";
private static final String SOUTH_POINTE = "South Pte";
private static final String ALDGATE = "Aldgate";
private static final String ISLAND_LAKES = "Isl Lks";
private static final String ST_NORBERT = "St Norbert";
private static final String ST_AMANT = "St Amant";
private static final String NORTH_KILDONAN = "North Kildonan";
private static final String GLENWAY = "Glenway";
private static final String RIVERBEND = "Riverbend";
private static final String LEILA = "Leila";
private static final String WHELLAMS = "Whellams";
private static final String WHELLAMS_LOOP = WHELLAMS + " Loop";
private static final String WHYTE_RDG = "Whyte Rdg";
private static final String WOODHAVEN = "Woodhaven";
private static final String ROUGE = "Rouge";
private static final String TO = " to ";
private static final String VIA = " via ";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>();
map2.put(15L, new RouteTripSpec(15L, //
0, MTrip.HEADSIGN_TYPE_STRING, AIRPORT, //
1, MTrip.HEADSIGN_TYPE_STRING, INKSTER_PARK) //
.addTripSort(0, //
Arrays.asList(new String[] { //
"30659", // != Eastbound Church at Keewatin <=
"30556", // != Eastbound Church at Bunting
"30654", // != Westbound Church at Keewatin <=
"30532", // != Southbound Fife at Huron
"30535", // == Southbound Fife at Church
"30536", // Southbound Fife at Admiral
"30521", // == Eastbound Mountain at Fife
"30756", // != <> Westbound Fife at Fife Loop <=
"30477", // == != Eastbound Mountain at McPhillips West
"30079", // Eastbound Mountain at Main
"10541", // Westbound Portage at Garry
"20083", // == Westbound Sargent at Century
"20018", // != Westbound Sargent at Bradford
"20121", // != Northbound Flight at Standard Aero
"20422", // != Northbound Century at Sargent
"20040", // != Westbound Wellington at Canada Post
"20523", // == Westbound Wellington at Flight
"20070", // Westbound Wellington at Airport Terminal (Rte 15)
})) //
.addTripSort(1, //
Arrays.asList(new String[] { //
"20070", // Westbound Wellington at Airport Terminal (Rte 15)
"20147", // == Eastbound Wellington at Flight
"20041", // != Eastbound Wellington at Canada Post
"20063", // != Southbound King Edward at Wellington South
"20122", // != Southbound Flight at Sargent
"20144", // != Eastbound Sargent at Berry
"20085", // == Eastbound Sargent at King Edward
"10583", // Eastbound Portage at Fort
"30078", // Westbound Mountain at Main
"30520", // == != Westbound Mountain at McPhillips West
"30756", // != <> Westbound Fife at Fife Loop =>
"30519", // != Westbound Mountain at Fife CONTINUE
"30518", // == Northbound Fife at Admiral
"30533", // != Westbound Church at Fife
"30654", // != Westbound Church at Keewatin =>
"30517", // != Northbound Fife at Church
"30659", // != Eastbound Church at Keewatin =>
})) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String gTripHeadsign = gTrip.getTripHeadsign();
int indexOfTO = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH).indexOf(TO);
if (indexOfTO >= 0) {
String gTripHeadsignAfterTO = gTripHeadsign.substring(indexOfTO + TO.length());
gTripHeadsign = gTripHeadsignAfterTO;
}
int indexOfVIA = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH).indexOf(VIA);
if (indexOfVIA >= 0) {
String gTripHeadsignBeforeVIA = gTripHeadsign.substring(0, indexOfVIA);
gTripHeadsign = gTripHeadsignBeforeVIA;
}
mTrip.setHeadsignString(cleanTripHeadsign(gTripHeadsign), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 1L) {
if (Arrays.asList( //
"The Forks", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("The Forks", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 2L) {
if (Arrays.asList( //
DOWNTOWN, //
DOWNTOWN + " Spirit-Counterclockwise", //
COUNTER_CLOCKWISE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(COUNTER_CLOCKWISE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 10L) {
if (Arrays.asList( //
DOWNTOWN, //
"St Boniface" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("St Boniface", mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
DOWNTOWN, //
"Wolseley-Provencher", //
"Wolseley" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Wolseley", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 11L) {
if (Arrays.asList( //
CITY_HALL, //
DOWNTOWN, //
GLENWAY, //
THE_FORKS, //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
NORTH_KILDONAN, //
KILDONAN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
ASSINIBOINE_PARK, //
"Crestview", //
HENDERSON, //
"St Charles", //
PORTAGE + AND + WOODHAVEN, //
UNIVERSITY_OF_WINNIPEG, //
"Westwood", //
POLO_PARK, //
PORTAGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 12L) {
if (Arrays.asList( //
"Health Sciences Ctr", //
"Valour" + AND + PORTAGE, //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 14L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"St Mary's" + AND + "Dakota", //
FERRY_RD //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(FERRY_RD, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
SOUTH_ST_VITAL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_ST_VITAL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 15L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Mtn" + AND + "Fife", // <>
AIRPORT //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(AIRPORT, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Mtn" + AND + "Fife", // <>
INKSTER_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INKSTER_PARK, mTrip.getHeadsignId()); // Mtn & Fife
return true;
}
} else if (mTrip.getRouteId() == 16L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Kingston Row", // <>
SELKIRK + AND + "McPhillips", // <>
"Plz Dr", //
ISLAND_LAKES, //
OSBORNE + " Junction", //
ST_VITAL_CTR, //
"Southdale Ctr", //
ST_VITAL_CTR + SLASH + "Southdale Ctr" // merge
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("St Vital Ctr" + SLASH + "Southdale Ctr", mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Kingston Row", // <>
"Selkirk" + AND + "McPhillips", // <>
"Tyndall Pk" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Tyndall Pk", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 17L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Seven Oaks Hosp", //
"Amber Trails", //
MAPLES //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MAPLES, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Memorial" + AND + "Broadway", //
"Gdn City Ctr", //
MISERICORDIA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISERICORDIA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 18L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Main" + AND + "Templeton", //
"Gdn City Ctr", // !=
RIVERBEND, // !=
NORTH_MAIN // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_MAIN, mTrip.getHeadsignId()); // RIVERBEND
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
"Main" + AND + "McAdam", //
CORYDON + AND + "Cambridge", //
"Tuxedo", //
ASSINIBOINE_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ASSINIBOINE_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 19L) {
if (Arrays.asList( //
DOWNTOWN, // <>
"Elizabeth" + AND + "Drake", //
RED_RIVER_COLLEGE //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RED_RIVER_COLLEGE, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
DOWNTOWN, // <>
WINDSOR_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WINDSOR_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 20L) {
if (Arrays.asList( //
DOWNTOWN, //
PORTAGE + AND + "Tylehurst", //
"Redwood" + AND + "Main", //
AIRPORT //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(AIRPORT, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
"Fort" + AND + PORTAGE, //
WATT + AND + "Leighton" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WATT + AND + "Leighton", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 21L) {
if (Arrays.asList( //
"Crestview", //
"Grace Hosp", //
"St Charles", //
"Westwood", //
PORTAGE_WEST // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE_WEST, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 22L) {
if (Arrays.asList( //
"Crestview", //
"St Charles", //
"Westwood", //
PORTAGE_WEST // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE_WEST, mTrip.getHeadsignId());
return true;
}
if (Arrays.asList( //
PORTAGE + AND + ROUGE, //
PORTAGE + AND + WOODHAVEN, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 24L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK, //
CITY_HALL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 26L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 28L) {
if (Arrays.asList( //
"I", //
OMANDS_CREEK, //
RED_RIVER_COLLEGE, //
INKSTER_IND_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INKSTER_IND_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 29L) {
if (Arrays.asList( //
CITY_HALL, // !=
WINDERMERE, // !=
CITY_HALL + SLASH + WINDERMERE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CITY_HALL + SLASH + WINDERMERE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 31L) {
if (Arrays.asList( //
MEADOWS_WEST, // !=
OAK_POINT, // !=
MEADOWS_WEST + SLASH + OAK_POINT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MEADOWS_WEST + SLASH + OAK_POINT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 32L) {
if (Arrays.asList( //
"Main" + AND + "Seven Oaks", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
LEILA, // !=
RIVERBEND, // !=
LEILA + SLASH + RIVERBEND // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(LEILA + SLASH + RIVERBEND, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 33L) {
if (Arrays.asList( //
"McPhillips" + AND + "Mapleglen", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Jefferson", //
"Mapleglen" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Mapleglen", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 36L) {
if (Arrays.asList( //
"Health Sciences Ctr", //
MAPLES //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MAPLES, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 38L) {
if (Arrays.asList( //
PORTAGE + AND + "Fort", //
"Templeton" + AND + "Salter", //
"William Stephenson" + AND + "Main", //
THE_FORKS //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(THE_FORKS, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 41L) {
if (Arrays.asList( //
NORTH_KILDONAN, // !=
GLENWAY, // !=
GLENWAY + SLASH + NORTH_KILDONAN // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(GLENWAY + SLASH + NORTH_KILDONAN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 44L) {
if (Arrays.asList( //
"London" + AND + "Munroe", //
DOWNTOWN, //
BROADWAY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BROADWAY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 45L) {
if (Arrays.asList( //
"Main" + AND + "Pioneer", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Munroe" + AND + "Prevette", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 46L) {
if (Arrays.asList( //
"Plessis" + AND + "Regent", //
BALMORAL_STA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BALMORAL_STA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 47L) {
if (Arrays.asList( //
"Main" + AND + PORTAGE, //
KILDONAN_PL, //
BALMORAL_STA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BALMORAL_STA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 49L) {
if (Arrays.asList( //
"Dugald" + AND + "Beghin", //
NORTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 50L) {
if (Arrays.asList( //
WINDSOR_PARK, //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 54L) {
if (Arrays.asList( //
ST_AMANT, // !=
SOUTH_ST_VITAL, // !=
SOUTH_ST_VITAL + SLASH + ST_AMANT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_ST_VITAL + SLASH + ST_AMANT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 55L) {
if (Arrays.asList( //
PORTAGE + AND + "Garry", //
"St Anne's" + AND + "Niakwa", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 56L) {
if (Arrays.asList( //
PORTAGE + AND + "Garry", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 59L) {
if (Arrays.asList( //
ALDGATE, // !=
ISLAND_LAKES, // !=
ALDGATE + SLASH + ISLAND_LAKES // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ALDGATE + SLASH + ISLAND_LAKES, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 65L) {
if (Arrays.asList( //
"Kenaston", //
"Roblin" + AND + "Dieppe", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 66L) {
if (Arrays.asList( //
"Grant" + AND + "Kenaston", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Dieppe Loop", //
POLO_PARK, // !=
UNICITY, // !=
UNICITY + SLASH + POLO_PARK // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY + SLASH + POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 68L) {
if (Arrays.asList( //
"Stradbrook" + AND + "Osborne", //
UNIVERSITY_OF_WINNIPEG //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_WINNIPEG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 71L) {
if (Arrays.asList( //
TEMPLETON, // !=
WAL_MART, // !=
WAL_MART + SLASH + TEMPLETON // != ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WAL_MART + SLASH + TEMPLETON, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Arlington" + AND + "Mtn", //
PORTAGE//
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PORTAGE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 72L) {
if (Arrays.asList( //
"Dalhousie", //
"Dalhousie" + AND + "Pembina", //
"Killarney" + AND + "Pembina", //
UNIVERSITY_OF_MANITOBA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 77L) {
if (Arrays.asList( //
"Gdn City Ctr", // <>
"Main" + AND + "Margaret", // <>
"Keewatin" + AND + "Inkster", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Gdn City Ctr", // <>
"Main" + AND + "Margaret", // <>
RED_RIVER_COLLEGE, //
"Whellams Ln", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 79L) {
if (Arrays.asList( //
PORTAGE + AND + "Tylehurst", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 83L) {
if (Arrays.asList( //
"Crestview" + AND + "Ashern", //
UNICITY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Grace Hosp", //
"Thompson" + AND + "Ness", //
MURRAY_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MURRAY_PARK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 85L) {
if (Arrays.asList( //
"Springfield Loop", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
HENDERSON + AND + WHELLAMS, //
WHELLAMS_LOOP //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WHELLAMS_LOOP, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 87L) {
if (Arrays.asList( //
"Beghin" + AND + "Dugald", //
SOUTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 89L) {
if (Arrays.asList( //
"Day" + AND + "Regent", //
KILDONAN_PL //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(KILDONAN_PL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 90L) {
if (Arrays.asList( //
KILDONAN_PL, //
NORTH_TRANSCONA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(NORTH_TRANSCONA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 92L) {
if (Arrays.asList( //
KILDONAN_PL, //
CROSSROADS_STN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(CROSSROADS_STN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 94L) {
if (Arrays.asList( //
"Chevrier" + AND + "Pembina", //
"Windermere" + AND + "Pembina", //
"Walmart" + AND + "Kenaston", //
"Wildwood", //
"Wildwood Pk" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Wildwood Pk", mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Henlow" + AND + "Scurfield", //
WHYTE_RDG).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WHYTE_RDG, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 95L) {
if (Arrays.asList( //
"Fort Rouge Sta", // <>
"Pan Am Pool", //
"Shaftesbury Pk", //
POLO_PARK //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(POLO_PARK, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Fort Rouge Sta", // <>
"Osborne", //
RIVERVIEW//
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RIVERVIEW, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 96L) {
if (Arrays.asList( //
"Southdale Ctr", //
PATERSON_LOOP //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(PATERSON_LOOP, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Southdale Ctr", //
ST_VITAL_CTR //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ST_VITAL_CTR, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 98L) {
if (Arrays.asList( //
WESTDALE, //
UNICITY //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNICITY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 99L) {
if (Arrays.asList( //
"Stradbrook" + AND + "Donald", //
DOWNTOWN // <>
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
DOWNTOWN, // <>
MISERICORDIA, // !=
WINDERMERE, // !=
WINDERMERE + AND + "Pembina", //
MISERICORDIA + SLASH + WINDERMERE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(MISERICORDIA + SLASH + WINDERMERE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 137L) {
if (Arrays.asList( //
UNIVERSITY_OF_MANITOBA, // !=
ST_NORBERT, // !=
ST_NORBERT + SLASH + UNIVERSITY_OF_MANITOBA // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ST_NORBERT + SLASH + UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 162L) {
if (Arrays.asList( //
"Killarney" + AND + "Pembina", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
"Turnbull Dr", //
ST_NORBERT, // !=
UNIVERSITY_OF_MANITOBA, // !=
UNIVERSITY_OF_MANITOBA + SLASH + ST_NORBERT // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA + SLASH + ST_NORBERT, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 163L) {
if (Arrays.asList( //
"Pembina" + AND + "Univ Cresc.", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 170L) {
if (Arrays.asList( //
"Killarney" + AND + "Pembina", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList( //
ST_NORBERT, //
UNIVERSITY_OF_MANITOBA //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(UNIVERSITY_OF_MANITOBA, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 181L) {
if (Arrays.asList( //
"Pembina" + AND + "Pt", //
DOWNTOWN //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 183L) {
if (Arrays.asList( //
RICHMOND_WEST, // !=
SOUTH_POINTE, // !=
RICHMOND_WEST + SLASH + SOUTH_POINTE // ++
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(RICHMOND_WEST + SLASH + SOUTH_POINTE, mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trip to merge %s & %s.\n", mTrip, mTripToMerge);
System.exit(-1);
return false;
}
private static final Pattern POINT = Pattern.compile("((^|\\S){1}(\\.)(\\S|$){1})", Pattern.CASE_INSENSITIVE);
private static final String POINT_REPLACEMENT = "$2$3 $4";
private static final Pattern UNIVERSITY_OF = Pattern.compile("(university of )", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_OF_REPLACEMENT = UNIVERSITY_OF_SHORT;
private static final Pattern MISERICORDIA_HEALTH_CTR = Pattern.compile("(misericordia health centre)", Pattern.CASE_INSENSITIVE);
private static final String MISERICORDIA_HEALTH_CTR_REPLACEMENT = MISERICORDIA;
private static final Pattern AIRPORT_TERMINAL = Pattern.compile("(airport terminal)", Pattern.CASE_INSENSITIVE);
private static final String AIRPORT_TERMINAL_REPLACEMENT = AIRPORT;
private static final Pattern INKSTER_IND_PK = Pattern.compile("(inkster industrial park)", Pattern.CASE_INSENSITIVE);
private static final String INKSTER_IND_PK_REPLACEMENT = INKSTER_IND_PARK;
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = POINT.matcher(tripHeadsign).replaceAll(POINT_REPLACEMENT);
tripHeadsign = UNIVERSITY_OF.matcher(tripHeadsign).replaceAll(UNIVERSITY_OF_REPLACEMENT);
tripHeadsign = MISERICORDIA_HEALTH_CTR.matcher(tripHeadsign).replaceAll(MISERICORDIA_HEALTH_CTR_REPLACEMENT);
tripHeadsign = AIRPORT_TERMINAL.matcher(tripHeadsign).replaceAll(AIRPORT_TERMINAL_REPLACEMENT);
tripHeadsign = INKSTER_IND_PK.matcher(tripHeadsign).replaceAll(INKSTER_IND_PK_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern START_WITH_BOUND = Pattern.compile("(^){1}(eastbound|westbound|southbound|northbound)(\\s){1}", Pattern.CASE_INSENSITIVE);
@Override
public String cleanStopName(String gStopName) {
gStopName = START_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = POINT.matcher(gStopName).replaceAll(POINT_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
if (!Utils.isDigitsOnly(gStop.getStopId())) {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
}
return super.getStopId(gStop);
}
}
| Compatibility with latest update
| src/org/mtransit/parser/ca_winnipeg_transit_bus/WinnipegTransitBusAgencyTools.java | Compatibility with latest update |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.