diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIEventForm.java b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIEventForm.java
index 7fc2e860..90ba90b1 100644
--- a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIEventForm.java
+++ b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIEventForm.java
@@ -1,2242 +1,2252 @@
/**
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
**/
package org.exoplatform.calendar.webui.popup;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.exoplatform.calendar.CalendarUtils;
import org.exoplatform.calendar.service.Attachment;
import org.exoplatform.calendar.service.Calendar;
import org.exoplatform.calendar.service.CalendarEvent;
import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.service.CalendarSetting;
import org.exoplatform.calendar.service.Reminder;
import org.exoplatform.calendar.service.Utils;
import org.exoplatform.calendar.webui.CalendarView;
import org.exoplatform.calendar.webui.UICalendarPortlet;
import org.exoplatform.calendar.webui.UICalendarViewContainer;
import org.exoplatform.calendar.webui.UIFormDateTimePicker;
import org.exoplatform.calendar.webui.UIListContainer;
import org.exoplatform.calendar.webui.UIMiniCalendar;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.download.DownloadResource;
import org.exoplatform.download.DownloadService;
import org.exoplatform.download.InputStreamDownloadResource;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.mail.MailService;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.upload.UploadService;
import org.exoplatform.web.application.AbstractApplicationMessage;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.web.application.RequestContext;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.ComponentConfigs;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIPopupWindow;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.core.model.SelectItem;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.core.model.SelectOption;
import org.exoplatform.webui.core.model.SelectOptionGroup;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormInputInfo;
import org.exoplatform.webui.form.UIFormInputWithActions;
import org.exoplatform.webui.form.UIFormInputWithActions.ActionData;
import org.exoplatform.webui.form.UIFormRadioBoxInput;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormSelectBoxWithGroups;
import org.exoplatform.webui.form.UIFormTabPane;
import org.exoplatform.webui.form.UIFormTextAreaInput;
import org.exoplatform.webui.form.ext.UIFormComboBox;
import org.exoplatform.webui.form.input.UICheckBoxInput;
import org.exoplatform.webui.organization.account.UIUserSelector;
/**
* Created by The eXo Platform SARL
* Author : Hung Nguyen
* [email protected]
* Editor : Tuan Pham
* [email protected]
* Aus 01, 2007 2:48:18 PM
*/
@ComponentConfigs ( {
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "system:/groovy/webui/form/UIFormTabPane.gtmpl",
events = {
@EventConfig(listeners = UIEventForm.SaveActionListener.class),
@EventConfig(listeners = UIEventForm.AddCategoryActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.RemoveEmailActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.MoveNextActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.MovePreviousActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.DeleteUserActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.AddAttachmentActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.RemoveAttachmentActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.DownloadAttachmentActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.AddParticipantActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.AddUserActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.OnChangeActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.CancelActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIFormTabPane.SelectTabActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.ConfirmOKActionListener.class, name = "ConfirmOK", phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.ConfirmCancelActionListener.class, name = "ConfirmCancel", phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.ConfirmUpdateOnlyInstance.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.ConfirmUpdateAllSeries.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.ConfirmUpdateCancel.class, phase = Phase.DECODE),
@EventConfig(listeners = UIEventForm.EditRepeatActionListener.class, phase = Phase.DECODE)
}
)
,
@ComponentConfig(
id = "UIPopupWindowAddUserEventForm",
type = UIPopupWindow.class,
template = "system:/groovy/webui/core/UIPopupWindow.gtmpl",
events = {
@EventConfig(listeners = UIPopupWindow.CloseActionListener.class, name = "ClosePopup") ,
@EventConfig(listeners = UIEventForm.AddActionListener.class, name = "Add", phase = Phase.DECODE),
@EventConfig(listeners = UITaskForm.CloseActionListener.class, name = "Close", phase = Phase.DECODE)
}
)
}
)
public class UIEventForm extends UIFormTabPane implements UIPopupComponent, UISelector{
private static final Log LOG = ExoLogger.getExoLogger(UIEventForm.class);
final public static String TAB_EVENTDETAIL = "eventDetail".intern() ;
final public static String TAB_EVENTREMINDER = "eventReminder".intern() ;
final public static String TAB_EVENTSHARE = "eventShare".intern() ;
final public static String TAB_EVENTATTENDER = "eventAttender".intern() ;
final public static String FIELD_MEETING = "participant".intern() ;
final public static String FIELD_ISSENDMAIL = "isSendMail".intern() ;
final public static String ITEM_PUBLIC = "public".intern() ;
final public static String ITEM_PRIVATE = "private".intern() ;
final public static String ITEM_AVAILABLE = "available".intern() ;
final public static String ITEM_BUSY = "busy".intern() ;
final public static String ITEM_OUTSIDE = "outside".intern() ;
final public static String ITEM_REPEAT = "true".intern() ;
final public static String ITEM_UNREPEAT = "false".intern() ;
final public static String ITEM_ALWAYS = "always".intern();
final public static String ITEM_NERVER = "never".intern();
final public static String ITEM_ASK = "ask".intern();
final public static String ACT_REMOVE = "RemoveAttachment".intern() ;
final public static String ACT_DOWNLOAD = "DownloadAttachment".intern() ;
final public static String ACT_ADDEMAIL = "AddEmailAddress".intern() ;
final public static String ACT_ADDCATEGORY = "AddCategory".intern() ;
final public static String ACT_EDITREPEAT = "EditRepeat".intern();
final public static String STATUS_EMPTY = "".intern();
final public static String STATUS_PENDING = "pending".intern();
final public static String STATUS_YES = "yes".intern();
final public static String STATUS_NO = "no".intern();
public final static String RP_END_BYDATE = "endByDate";
public final static String RP_END_AFTER = "endAfter";
public final static String RP_END_NEVER = "neverEnd";
public boolean isAddNew_ = true ;
private boolean isChangedSignificantly = false;
private CalendarEvent calendarEvent_ = null ;
protected String calType_ = "0" ;
protected String invitationMsg_ = "" ;
protected String participantList_ = "" ;
private String errorMsg_ = null ;
private String errorValues = null ;
protected Map<String, String> participants_ = new LinkedHashMap<String, String>() ;
protected Map<String, String> participantStatus_ = new LinkedHashMap<String, String>() ;
protected LinkedList<ParticipantStatus> participantStatusList_ = new LinkedList<ParticipantStatus>();
private String oldCalendarId_ = null ;
private String newCalendarId_ = null ;
private String saveEventInvitation = "";
private String saveEventNoInvitation = "";
private CalendarEvent repeatEvent;
private String repeatSummary;
public static final int LIMIT_FILE_UPLOAD = 10;
public UIEventForm() throws Exception {
super("UIEventForm");
this.setId("UIEventForm");
saveEventInvitation = "SaveEvent-Invitation" ;
saveEventNoInvitation = "SaveEvent-NoSendInvitation" ;
try{
saveEventInvitation = getLabel("SaveEvent-Invitation") ;
saveEventNoInvitation = getLabel("SaveEvent-NoSendInvitation") ;
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to get label: " + saveEventInvitation, e);
LOG.debug("Fail to get label: " + saveEventNoInvitation, e);
}
}
UIEventDetailTab eventDetailTab = new UIEventDetailTab(TAB_EVENTDETAIL) ;
addChild(eventDetailTab) ;
UIEventReminderTab eventReminderTab = new UIEventReminderTab(TAB_EVENTREMINDER) ;
addChild(eventReminderTab) ;
UIEventShareTab eventShareTab = new UIEventShareTab(TAB_EVENTSHARE) ;
eventShareTab.addUIFormInput(new UIFormRadioBoxInput(UIEventShareTab.FIELD_SHARE, UIEventShareTab.FIELD_SHARE, getShareValue()) ) ;
eventShareTab.addUIFormInput(new UIFormRadioBoxInput(UIEventShareTab.FIELD_STATUS, UIEventShareTab.FIELD_STATUS, getStatusValue()) ) ;
eventShareTab.addUIFormInput(new UIFormRadioBoxInput(UIEventShareTab.FIELD_SEND, UIEventShareTab.FIELD_SEND, CalendarUtils.getSendValue(null)) ) ;
eventShareTab.addUIFormInput(new UIFormInputInfo(UIEventShareTab.FIELD_INFO, UIEventShareTab.FIELD_INFO, null) ) ;
eventShareTab.addUIFormInput(new UIFormTextAreaInput(FIELD_MEETING, FIELD_MEETING, null)) ;
List<ActionData> actions = new ArrayList<ActionData>() ;
ActionData addUser = new ActionData() ;
addUser.setActionListener("AddParticipant") ;
addUser.setActionName("AddUser") ;
addUser.setActionParameter(TAB_EVENTSHARE);
addUser.setActionType(ActionData.TYPE_ICON) ;
addUser.setCssIconClass("uiIconPlus uiIconLightGray") ;
actions.add(addUser) ;
eventShareTab.setActionField(UIEventShareTab.FIELD_INFO, actions) ;
addChild(eventShareTab) ;
UIEventAttenderTab eventAttenderTab = new UIEventAttenderTab(TAB_EVENTATTENDER) ;
addChild(eventAttenderTab) ;
setSelectedTab(eventDetailTab.getId()) ;
}
@Override
public String getLabel(String id) {
try {
return super.getLabel(id) ;
} catch (Exception e) {
LOG.warn("Can not find " + getId() + ".label." + id);
return id ;
}
}
public void initForm(CalendarSetting calSetting, CalendarEvent eventCalendar, String formTime) throws Exception {
reset() ;
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
((UIFormDateTimePicker)eventDetailTab.getChildById(UIEventDetailTab.FIELD_FROM)).setDateFormatStyle(calSetting.getDateFormat()) ;
((UIFormDateTimePicker)eventDetailTab.getChildById(UIEventDetailTab.FIELD_TO)).setDateFormatStyle(calSetting.getDateFormat()) ;
UIEventAttenderTab attenderTab = getChildById(TAB_EVENTATTENDER) ;
List<SelectItemOption<String>> fromTimes
= CalendarUtils.getTimesSelectBoxOptions(calSetting.getTimeFormat(),calSetting.getTimeFormat(), calSetting.getTimeInterval()) ;
List<SelectItemOption<String>> toTimes
= CalendarUtils.getTimesSelectBoxOptions(calSetting.getTimeFormat(),calSetting.getTimeFormat(), calSetting.getTimeInterval()) ;
eventDetailTab.getUIFormComboBox(UIEventDetailTab.FIELD_FROM_TIME).setOptions(fromTimes) ;
eventDetailTab.getUIFormComboBox(UIEventDetailTab.FIELD_TO_TIME).setOptions(toTimes) ;
List<SelectItemOption<String>> fromOptions = CalendarUtils.getTimesSelectBoxOptions(calSetting.getTimeFormat(),calSetting.getTimeFormat()) ;
List<SelectItemOption<String>> toOptions = CalendarUtils.getTimesSelectBoxOptions(calSetting.getTimeFormat(),calSetting.getTimeFormat()) ;
attenderTab.getUIFormComboBox(UIEventAttenderTab.FIELD_FROM_TIME).setOptions(fromOptions) ;
attenderTab.getUIFormComboBox(UIEventAttenderTab.FIELD_TO_TIME).setOptions(toOptions) ;
if(eventCalendar != null) {
isAddNew_ = false ;
calendarEvent_ = eventCalendar ;
repeatEvent = new CalendarEvent(calendarEvent_);
setEventSumary(eventCalendar.getSummary()) ;
setEventDescription(eventCalendar.getDescription()) ;
setEventAllDate(CalendarUtils.isAllDayEvent(eventCalendar)) ;
setEventFromDate(eventCalendar.getFromDateTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
setEventCheckTime(eventCalendar.getFromDateTime()) ;
setEventToDate(eventCalendar.getToDateTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
setSelectedCalendarId(eventCalendar.getCalendarId()) ;
String eventCategoryId = eventCalendar.getEventCategoryId() ;
if(!CalendarUtils.isEmpty(eventCategoryId)) {
UIFormSelectBox selectBox = eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY) ;
boolean hasEventCategory = false ;
for (SelectItemOption<String> o : selectBox.getOptions()) {
if (o.getValue().equals(eventCategoryId)) {
hasEventCategory = true ;
break ;
}
}
if (!hasEventCategory){
selectBox.getOptions().add(new SelectItemOption<String>(eventCalendar.getEventCategoryName(), eventCategoryId)) ;
}
setSelectedCategory(eventCategoryId) ;
}
setEventPlace(eventCalendar.getLocation()) ;
setEventIsRepeat(eventCalendar.getRepeatType() != null && !CalendarEvent.RP_NOREPEAT.equals(eventCalendar.getRepeatType()));
setRepeatSummary(buildRepeatSummary(calendarEvent_));
// if it's exception occurrence, disabled repeat checkbox, it means you can't convert a exception occurrence to a repeating event
if ((CalendarEvent.RP_NOREPEAT.equals(calendarEvent_.getRepeatType()) || calendarEvent_.getRepeatType() == null) && !CalendarUtils.isEmpty(calendarEvent_.getRecurrenceId())
&& calendarEvent_.getIsExceptionOccurrence()) {
getChild(UIEventDetailTab.class).getUICheckBoxInput(UIEventDetailTab.FIELD_ISREPEAT).setDisabled(true);
}
setSelectedEventPriority(eventCalendar.getPriority()) ;
if(eventCalendar.getReminders() != null)
setEventReminders(eventCalendar.getReminders()) ;
setAttachments(eventCalendar.getAttachment()) ;
if(eventCalendar.isPrivate()) {
setSelectedShareType(UIEventForm.ITEM_PRIVATE) ;
} else {
setSelectedShareType(UIEventForm.ITEM_PUBLIC) ;
}
setSendOption(eventCalendar.getSendOption());
setMessage(eventCalendar.getMessage());
setParticipantStatusValues(eventCalendar.getParticipantStatus());
getChild(UIEventShareTab.class).setParticipantStatusList(participantStatusList_);
setSelectedEventState(eventCalendar.getEventState()) ;
setMeetingInvitation(eventCalendar.getInvitation()) ;
StringBuffer pars = new StringBuffer() ;
if(eventCalendar.getParticipant() != null) {
for(String par : eventCalendar.getParticipant()) {
if(!CalendarUtils.isEmpty(pars.toString())) pars.append(CalendarUtils.BREAK_LINE) ;
pars.append(par) ;
}
}
setParticipant(pars.toString()) ;
if(eventCategoryId != null) {
UIFormSelectBox uiSelectBox = eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY) ;
if(!isAddNew_ && ! String.valueOf(Calendar.TYPE_PRIVATE).equalsIgnoreCase(calType_) ){
SelectItemOption<String> item = new SelectItemOption<String>(eventCalendar.getEventCategoryName(), eventCalendar.getEventCategoryId()) ;
uiSelectBox.getOptions().add(item) ;
uiSelectBox.setValue(eventCalendar.getEventCategoryId());
uiSelectBox.setDisabled(true) ;
eventDetailTab.getUIFormSelectBoxGroup(UIEventDetailTab.FIELD_CALENDAR).setDisabled(true) ;
eventDetailTab.setActionField(UIEventDetailTab.FIELD_CATEGORY, null) ;
}
}
attenderTab.calendar_.setTime(eventCalendar.getFromDateTime()) ;
} else {
java.util.Calendar cal = getCalendar(this, formTime, calSetting);
setEventFromDate(cal.getTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
cal.add(java.util.Calendar.MINUTE, (int)calSetting.getTimeInterval()*2) ;
setEventCheckTime(cal.getTime()) ;
setEventToDate(cal.getTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
StringBuffer pars = new StringBuffer(CalendarUtils.getCurrentUser()) ;
setMeetingInvitation(new String[] { CalendarUtils.getOrganizationService().getUserHandler().findUserByName(pars.toString()).getEmail() }) ;
setParticipant(pars.toString()) ;
setSendOption(calSetting.getSendOption());
getChild(UIEventShareTab.class).setParticipantStatusList(participantStatusList_);
attenderTab.updateParticipants(pars.toString());
setRepeatSummary(buildRepeatSummary(null));
}
}
public boolean isReminderByEmail(List<Reminder> reminders){
for(Reminder rm : reminders) {
return (Reminder.TYPE_EMAIL.equals(rm.getReminderType()));
}
return false;
}
public static java.util.Calendar getCalendar(UIForm uiForm,String formTime,CalendarSetting calSetting) {
java.util.Calendar cal = CalendarUtils.getInstanceOfCurrentCalendar() ;
try {
cal.setTimeInMillis(Long.parseLong(formTime)) ;
} catch (Exception e) {
UIMiniCalendar miniCalendar = uiForm.getAncestorOfType(UICalendarPortlet.class).findFirstComponentOfType(UIMiniCalendar.class) ;
cal.setTime(miniCalendar.getCurrentCalendar().getTime()) ;
}
Long beginMinute = (cal.get(java.util.Calendar.MINUTE)/calSetting.getTimeInterval())*calSetting.getTimeInterval() ;
cal.set(java.util.Calendar.MINUTE, beginMinute.intValue()) ;
return cal;
}
private void setEventCheckTime(Date time) {
UIEventAttenderTab uiAttenderTab = getChildById(TAB_EVENTATTENDER) ;
uiAttenderTab.calendar_.setTime(time) ;
}
private boolean setCalendarOptionOfSpaceAsSelected(String spaceId, List<? extends SelectItem> items, UIFormSelectBoxWithGroups selectBoxWithGroups) {
if (spaceId == null || items == null) {
return false;
}
for (SelectItem si : items) {
if (si instanceof SelectOption) {
SelectOption so = (SelectOption) si;
// find Calendar option of space of which value end with space id.
if (so.getValue().endsWith(spaceId)) {
selectBoxWithGroups.setValue(so.getValue());
return true;
}
} else if (si instanceof SelectOptionGroup) {
if (setCalendarOptionOfSpaceAsSelected(spaceId, ((SelectOptionGroup) si).getOptions(), selectBoxWithGroups)) {
return true;
}
}
}
return false;
}
public void update(String calType, List<SelectItem> options) throws Exception{
UIEventDetailTab uiEventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormSelectBoxWithGroups selectBoxWithGroups = uiEventDetailTab.getUIFormSelectBoxGroup(UIEventDetailTab.FIELD_CALENDAR);
if(options != null) {
selectBoxWithGroups.setOptions(options) ;
}else {
selectBoxWithGroups.setOptions(getCalendars()) ;
}
String spaceId = UICalendarPortlet.getSpaceId();
if (spaceId != null) {
setCalendarOptionOfSpaceAsSelected(spaceId, selectBoxWithGroups.getOptions(), selectBoxWithGroups);
}
calType_ = calType ;
}
private List<SelectItem> getCalendars() throws Exception {
return CalendarUtils.getCalendarOption() ;
}
protected void refreshCategory()throws Exception {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY).setOptions(CalendarUtils.getCategory()) ;
}
private List<SelectItemOption<String>> getShareValue() {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
options.add(new SelectItemOption<String>(ITEM_PRIVATE, ITEM_PRIVATE)) ;
options.add(new SelectItemOption<String>(ITEM_PUBLIC, ITEM_PUBLIC)) ;
return options ;
}
private List<SelectItemOption<String>> getStatusValue() {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
options.add(new SelectItemOption<String>(ITEM_BUSY, ITEM_BUSY)) ;
options.add(new SelectItemOption<String>(ITEM_AVAILABLE, ITEM_AVAILABLE)) ;
options.add(new SelectItemOption<String>(ITEM_OUTSIDE, ITEM_OUTSIDE)) ;
return options ;
}
@Override
public String[] getActions() {
return new String[]{"Save", "Cancel"} ;
}
@Override
public void activate() throws Exception {}
@Override
public void deActivate() throws Exception {}
@Override
public void updateSelect(String selectField, String value) throws Exception { }
private boolean isReminderValid() throws Exception {
if(getEmailReminder()) {
if(CalendarUtils.isEmpty(getEmailAddress())) {
errorMsg_ = "UIEventForm.msg.event-email-required" ;
errorValues = "";
return false ;
}
else if(!CalendarUtils.isValidEmailAddresses(getEmailAddress())) {
errorMsg_ = "UIEventForm.msg.event-email-invalid" ;
errorValues = CalendarUtils.invalidEmailAddresses(getEmailAddress()) ;
return false ;
}
}
errorMsg_ = null ;
return true ;
}
protected boolean isEventDetailValid(CalendarSetting calendarSetting) throws Exception{
String dateFormat = calendarSetting.getDateFormat() ;
String timeFormat = calendarSetting.getTimeFormat() ;
Date from = null ;
Date to = null ;
if(CalendarUtils.isEmpty(getCalendarId())) {
errorMsg_ = getId() + ".msg.event-calendar-required" ;
return false ;
}
if(CalendarUtils.isEmpty(getEventCategory())) {
errorMsg_ = getId() + ".msg.event-category-required" ;
return false ;
}
if(CalendarUtils.isEmpty(getEventFormDateValue())) {
errorMsg_ = getId() + ".msg.event-fromdate-required" ;
return false ;
}
if(CalendarUtils.isEmpty(getEventToDateValue())){
errorMsg_ = getId() + ".msg.event-todate-required" ;
return false ;
}
try {
from = getEventFromDate(dateFormat, timeFormat) ;
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Faile to get event from date", e);
}
errorMsg_ = getId() + ".msg.event-fromdate-notvalid" ;
return false ;
}
if(from == null){
errorMsg_ = getId() + ".msg.event-fromdate-notvalid" ;
return false ;
}
try {
to = getEventToDate(dateFormat, timeFormat) ;
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to get event to date", e);
}
errorMsg_ = getId() + ".msg.event-fromdate-notvalid" ;
return false ;
}
if(to == null){
errorMsg_ = getId() + ".msg.event-fromdate-notvalid" ;
return false ;
}
if(from.after(to) || from.equals(to)){
errorMsg_ = "UIEventForm.msg.event-date-time-LOGic" ;
return false ;
}
errorMsg_ = null ;
return true ;
}
private boolean isParticipantValid() throws Exception {
if(isSendMail() && getMeetingInvitation() == null) {
errorMsg_ = "UIEventForm.msg.error-particimant-email-required" ;
return false ;
}
errorMsg_ = null ;
return true ;
}
protected String getEventSumary() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIStringInput(UIEventDetailTab.FIELD_EVENT).getValue() ;
}
protected void setEventSumary(String value) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIStringInput(UIEventDetailTab.FIELD_EVENT).setValue(value) ;
}
protected String getEventDescription() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIFormTextAreaInput(UIEventDetailTab.FIELD_DESCRIPTION).getValue() ;
}
protected void setEventDescription(String value) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIFormTextAreaInput(UIEventDetailTab.FIELD_DESCRIPTION).setValue(value) ;
}
protected String getCalendarId() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
String value = eventDetailTab.getUIFormSelectBoxGroup(UIEventDetailTab.FIELD_CALENDAR).getValue() ;
newCalendarId_ = value ;
if (!CalendarUtils.isEmpty(value) && value.split(CalendarUtils.COLON).length>0) {
calType_ = value.split(CalendarUtils.COLON)[0] ;
return value.split(CalendarUtils.COLON)[1] ;
}
return value ;
}
public void setSelectedCalendarId(String value) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
String selectedCal = new StringBuffer(calType_).append(CalendarUtils.COLON).append(value).toString();
eventDetailTab.getUIFormSelectBoxGroup(UIEventDetailTab.FIELD_CALENDAR).setValue(selectedCal);
oldCalendarId_ = selectedCal ;
}
protected String getEventCategory() {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY).getValue() ;
}
public void setSelectedCategory(String value) {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY).setValue(value);
}
protected Date getEventFromDate(String dateFormat,String timeFormat) throws Exception {
try {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormDateTimePicker fromField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_FROM) ;
UIFormComboBox timeField = eventDetailTab.getUIFormComboBox(UIEventDetailTab.FIELD_FROM_TIME) ;
return UITaskForm.getBeginDate(getEventAllDate(), dateFormat, fromField.getValue(), timeFormat, timeField.getValue());
} catch (Exception e) {
return null;
}
}
protected String getEventFormDateValue () {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormDateTimePicker fromField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_FROM) ;
return fromField.getValue() ;
}
protected void setEventFromDate(Date date,String dateFormat, String timeFormat) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIEventAttenderTab eventAttenderTab = getChildById(TAB_EVENTATTENDER) ;
UIFormDateTimePicker fromField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_FROM) ;
UIFormComboBox timeField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_FROM_TIME) ;
WebuiRequestContext context = RequestContext.getCurrentInstance() ;
Locale locale = context.getParentAppRequestContext().getLocale() ;
DateFormat df = new SimpleDateFormat(dateFormat, locale) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
fromField.setValue(df.format(date)) ;
df = new SimpleDateFormat(timeFormat, locale) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
timeField.setValue(df.format(date)) ;
eventAttenderTab.setEventFromDate(date, timeFormat) ;
}
protected Date getEventToDate(String dateFormat, String timeFormat) throws Exception {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormDateTimePicker toField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_TO) ;
UIFormComboBox timeField = eventDetailTab.getUIFormComboBox(UIEventDetailTab.FIELD_TO_TIME) ;
return UITaskForm.getToDate(getEventAllDate(), dateFormat, toField.getValue(), timeFormat, timeField.getValue());
}
protected void setEventToDate(Date date,String dateFormat, String timeFormat) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIEventAttenderTab eventAttenderTab = getChildById(TAB_EVENTATTENDER) ;
UIFormDateTimePicker toField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_TO) ;
UIFormComboBox timeField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_TO_TIME) ;
WebuiRequestContext context = RequestContext.getCurrentInstance() ;
Locale locale = context.getParentAppRequestContext().getLocale() ;
DateFormat df = new SimpleDateFormat(dateFormat, locale) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
toField.setValue(df.format(date)) ;
df = new SimpleDateFormat(timeFormat, locale) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
timeField.setValue(df.format(date)) ;
eventAttenderTab.setEventToDate(date, timeFormat) ;
}
protected String getEventToDateValue () {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormDateTimePicker toField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_TO) ;
return toField.getValue() ;
}
protected boolean getEventAllDate() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUICheckBoxInput(UIEventDetailTab.FIELD_CHECKALL).isChecked() ;
}
protected void setEventAllDate(boolean isCheckAll) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUICheckBoxInput(UIEventDetailTab.FIELD_CHECKALL).setChecked(isCheckAll) ;
}
protected String getEventRepeat() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_REPEAT).getValue() ;
}
protected void setEventRepeat(String type) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_REPEAT).setValue(type) ;
}
protected boolean getEventIsRepeat() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUICheckBoxInput(UIEventDetailTab.FIELD_ISREPEAT).isChecked();
}
protected void setEventIsRepeat(boolean isRepeat) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUICheckBoxInput(UIEventDetailTab.FIELD_ISREPEAT).setChecked(isRepeat);
}
protected String getEventRepeatUntilValue() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
UIFormDateTimePicker untilField = eventDetailTab.getChildById(UIEventDetailTab.FIELD_REPEAT_UNTIL);
return untilField.getValue();
}
protected String getEventPlace() {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIStringInput(UIEventDetailTab.FIELD_PLACE).getValue();
}
protected void setEventPlace(String value) {
UIEventDetailTab eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIStringInput(UIEventDetailTab.FIELD_PLACE).setValue(value) ;
}
protected boolean getEmailReminder() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUICheckBoxInput(UIEventReminderTab.REMIND_BY_EMAIL).isChecked() ;
}
public void setEmailReminder(boolean isChecked) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUICheckBoxInput(UIEventReminderTab.REMIND_BY_EMAIL).setChecked(isChecked) ;
}
protected String getEmailRemindBefore() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUIFormSelectBox(UIEventReminderTab.EMAIL_REMIND_BEFORE).getValue() ;
}
protected boolean isEmailRepeat() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return Boolean.parseBoolean(eventReminderTab.getUICheckBoxInput(UIEventReminderTab.EMAIL_IS_REPEAT).getValue().toString()) ;
}
public void setEmailRepeat(Boolean value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUICheckBoxInput(UIEventReminderTab.EMAIL_IS_REPEAT).setChecked(value) ;
}
protected String getEmailRepeatInterVal() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUIFormSelectBox(UIEventReminderTab.EMAIL_REPEAT_INTERVAL).getValue() ;
}
protected void setEmailRepeatInterVal(long value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUIFormSelectBox(UIEventReminderTab.EMAIL_REPEAT_INTERVAL).setValue(String.valueOf(value)) ;
}
protected Boolean isPopupRepeat() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return Boolean.parseBoolean(eventReminderTab.getUICheckBoxInput(UIEventReminderTab.POPUP_IS_REPEAT).getValue().toString()) ;
}
protected void setPopupRepeat(Boolean value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUICheckBoxInput(UIEventReminderTab.POPUP_IS_REPEAT).setChecked(value) ;
}
protected String getPopupRepeatInterVal() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUIFormSelectBox(UIEventReminderTab.POPUP_REPEAT_INTERVAL).getValue() ;
}
public void setEmailRemindBefore(String value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUIFormSelectBox(UIEventReminderTab.EMAIL_REMIND_BEFORE).setValue(value) ;
}
protected String getEmailAddress() throws Exception {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUIStringInput(UIEventReminderTab.FIELD_EMAIL_ADDRESS).getValue() ;
}
public void setEmailAddress(String value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUIStringInput(UIEventReminderTab.FIELD_EMAIL_ADDRESS).setValue(value) ;
}
protected boolean getPopupReminder() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUICheckBoxInput(UIEventReminderTab.REMIND_BY_POPUP).isChecked() ;
}
protected void setPopupReminder(boolean isChecked) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUICheckBoxInput(UIEventReminderTab.REMIND_BY_POPUP).setChecked(isChecked) ;
}
protected String getPopupReminderTime() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
return eventReminderTab.getUIFormSelectBox(UIEventReminderTab.POPUP_REMIND_BEFORE).getValue() ;
}
protected void setPopupRemindBefore(String value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUIFormSelectBox(UIEventReminderTab.POPUP_REMIND_BEFORE).setValue(value) ;
}
protected long getPopupReminderSnooze() {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
try {
String time = eventReminderTab.getUIFormSelectBox(UIEventReminderTab.POPUP_REPEAT_INTERVAL).getValue() ;
return Long.parseLong(time) ;
} catch (Exception e){
if (LOG.isDebugEnabled()) {
LOG.debug("Can't get time from POPUP_REPEAT_INTERVAL", e);
}
}
return 0 ;
}
protected List<Attachment> getAttachments(String eventId, boolean isAddNew) {
UIEventDetailTab uiEventDetailTab = getChild(UIEventDetailTab.class) ;
return uiEventDetailTab.getAttachments() ;
}
protected long getTotalAttachment() {
UIEventDetailTab uiEventDetailTab = getChild(UIEventDetailTab.class) ;
long attSize = 0 ;
for(Attachment att : uiEventDetailTab.getAttachments()) {
attSize = attSize + att.getSize() ;
}
return attSize ;
}
protected void setAttachments(List<Attachment> attachment) throws Exception {
UIEventDetailTab uiEventDetailTab = getChild(UIEventDetailTab.class) ;
uiEventDetailTab.setAttachments(attachment) ;
uiEventDetailTab.refreshUploadFileList() ;
}
protected void setPopupRepeatInterval(long value) {
UIEventReminderTab eventReminderTab = getChildById(TAB_EVENTREMINDER) ;
eventReminderTab.getUIFormSelectBox(UIEventReminderTab.POPUP_REPEAT_INTERVAL).setValue(String.valueOf(value)) ;
}
protected void setEventReminders(List<Reminder> reminders){
for(Reminder rm : reminders) {
if(Reminder.TYPE_EMAIL.equals(rm.getReminderType())) {
setEmailReminder(true) ;
setEmailAddress(rm.getEmailAddress()) ;
setEmailRepeat(rm.isRepeat()) ;
setEmailRemindBefore(String.valueOf(rm.getAlarmBefore())) ;
setEmailRepeatInterVal(rm.getRepeatInterval()) ;
} else if(Reminder.TYPE_POPUP.equals(rm.getReminderType())) {
setPopupReminder(true) ;
setPopupRepeat(rm.isRepeat()) ;
setPopupRemindBefore(String.valueOf(rm.getAlarmBefore()));
setPopupRepeatInterval(rm.getRepeatInterval()) ;
}
}
}
protected List<Reminder> getEventReminders(Date fromDateTime, List<Reminder> currentReminders) throws Exception {
List<Reminder> reminders = new ArrayList<Reminder>() ;
if(getEmailReminder()) {
Reminder email = new Reminder() ;
if(currentReminders != null) {
for(Reminder rm : currentReminders) {
if(rm.getReminderType().equals(Reminder.TYPE_EMAIL)) {
email = rm ;
break ;
}
}
}
email.setReminderType(Reminder.TYPE_EMAIL) ;
email.setReminderOwner(CalendarUtils.getCurrentUser());
email.setAlarmBefore(Long.parseLong(getEmailRemindBefore())) ;
StringBuffer sbAddress = new StringBuffer() ;
for(String s : getEmailAddress().replaceAll(CalendarUtils.SEMICOLON, CalendarUtils.COMMA).split(CalendarUtils.COMMA)) {
s = s.trim() ;
if(sbAddress.indexOf(s) < 0) {
if(sbAddress.length() > 0) sbAddress.append(CalendarUtils.COMMA) ;
sbAddress.append(s) ;
}
}
email.setEmailAddress(sbAddress.toString()) ;
email.setRepeate(isEmailRepeat()) ;
email.setRepeatInterval(Long.parseLong(getEmailRepeatInterVal())) ;
email.setFromDateTime(fromDateTime) ;
if (!CalendarUtils.isEmpty(email.getEmailAddress())) reminders.add(email) ;
}
if(getPopupReminder()) {
Reminder popup = new Reminder() ;
if(currentReminders != null) {
for(Reminder rm : currentReminders) {
if(rm.getReminderType().equals(Reminder.TYPE_POPUP)) {
popup = rm ;
break ;
}
}
}
StringBuffer sb = new StringBuffer() ;
boolean isExist = false ;
if(!isExist) {
if(sb.length() >0) sb.append(CalendarUtils.COMMA);
sb.append(CalendarUtils.getCurrentUser());
}
popup.setReminderOwner(sb.toString()) ;
popup.setReminderType(Reminder.TYPE_POPUP) ;
popup.setAlarmBefore(Long.parseLong(getPopupReminderTime()));
popup.setRepeate(isPopupRepeat()) ;
popup.setRepeatInterval(Long.parseLong(getPopupRepeatInterVal())) ;
popup.setFromDateTime(fromDateTime) ;
reminders.add(popup) ;
}
return reminders ;
}
protected String getEventPriority() {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
return eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_PRIORITY).getValue() ;
}
protected void setSelectedEventPriority(String value) {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTDETAIL) ;
eventDetailTab.getUIFormSelectBox(UIEventDetailTab.FIELD_PRIORITY).setValue(value) ;
}
protected String getEventState() {
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
return eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_STATUS).getValue() ;
}
public void setSelectedEventState(String value) {
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_STATUS).setValue(value) ;
}
protected String getShareType() {
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
return eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_SHARE).getValue() ;
}
protected String getSendOption(){
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
return eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_SEND).getValue() ;
}
protected void setSendOption(String value){
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_SEND).setValue(value) ;
}
public String getMessage() {
return invitationMsg_;
}
public void setMessage(String invitationMsg) {
this.invitationMsg_ = invitationMsg;
}
protected void setSelectedShareType(String value) {
UIEventShareTab eventDetailTab = getChildById(TAB_EVENTSHARE) ;
eventDetailTab.getUIFormRadioBoxInput(UIEventShareTab.FIELD_SHARE).setValue(value) ;
}
protected String[] getMeetingInvitation() {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTSHARE) ;
String invitation = eventDetailTab.getUIFormTextAreaInput(FIELD_MEETING).getValue() ;
if(CalendarUtils.isEmpty(invitation)) return null ;
else return invitation.replace(CalendarUtils.SEMICOLON, CalendarUtils.COMMA).split(CalendarUtils.COMMA) ;
}
protected String getInvitationEmail() {
StringBuilder buider = new StringBuilder("") ;
for (Entry<String, String> par : participantStatus_.entrySet()) {
if (buider.length() > 0 && par.getKey().contains("@")) buider.append(CalendarUtils.COMMA) ;
if(par.getKey().contains("@")) buider.append(par.getKey().substring(par.getKey()
.lastIndexOf(CalendarUtils.OPEN_PARENTHESIS) + 1).replace(CalendarUtils.CLOSE_PARENTHESIS, "")) ;
}
return buider.toString() ;
}
protected void setMeetingInvitation(String[] values) {
UIFormInputWithActions eventDetailTab = getChildById(TAB_EVENTSHARE) ;
StringBuffer sb = new StringBuffer() ;
if(values != null) {
for(String s : values) {
if(sb.length() > 0) sb.append(CalendarUtils.COMMA) ;
sb.append(s) ;
}
}
eventDetailTab.getUIFormTextAreaInput(FIELD_MEETING).setValue(sb.toString()) ;
}
protected String getParticipantValues() {
StringBuilder buider = new StringBuilder("") ;
for (String par : participants_.keySet()) {
if (buider.length() > 0) buider.append(CalendarUtils.BREAK_LINE) ;
buider.append(par) ;
}
return buider.toString() ;
}
protected String getParticipantStatusValues() {
StringBuilder buider = new StringBuilder("") ;
for (Entry<String, String> par : participantStatus_.entrySet()) {
if (buider.length() > 0) buider.append(CalendarUtils.BREAK_LINE) ;
buider.append(par.getKey()+":"+par.getValue()) ;
}
return buider.toString() ;
}
protected void setParticipantStatusValues(String[] values) throws Exception {
participantStatus_.clear();
participantStatusList_.clear();
for (String par : values) {
String[] entry = par.split(":");
if(entry.length> 0 && StringUtils.isNotBlank(entry[0])){
if(entry.length>1){
participantStatus_.put(entry[0], entry[1]);
participantStatusList_.add(new ParticipantStatus(entry[0],entry[1]));
} else if(entry.length == 1){
participantStatus_.put(entry[0], STATUS_EMPTY);
participantStatusList_.add(new ParticipantStatus(entry[0],STATUS_EMPTY));
}
}
}
}
public void setParticipant(String values) throws Exception{
OrganizationService orgService = CalendarUtils.getOrganizationService() ;
StringBuffer sb = new StringBuffer() ;
for(String s : values.split("[\\r\\n]+")) {
User user = orgService.getUserHandler().findUserByName(s) ;
if(user != null) {
participants_.put(s.trim(), user.getEmail()) ;
if(!CalendarUtils.isEmpty(sb.toString())) sb.append(CalendarUtils.BREAK_LINE) ;
sb.append(s.trim()) ;
}
}
((UIEventAttenderTab)getChildById(TAB_EVENTATTENDER)).updateParticipants(getParticipantValues()) ;
}
public String getParticipantStatus() {
StringBuilder buider = new StringBuilder("") ;
for (String par : participantStatus_.keySet()) {
if (buider.length() > 0) buider.append(CalendarUtils.BREAK_LINE) ;
buider.append(par) ;
}
return buider.toString() ;
}
public void setParticipantStatus(String values) throws Exception{
String[] array = values.split(CalendarUtils.BREAK_LINE);
for(String s : array) {
if(s.trim().length()>0)
if(participantStatus_.put(s.trim(), STATUS_EMPTY) == null)
participantStatusList_.add(new ParticipantStatus(s.trim(),STATUS_EMPTY));
}
}
protected boolean isSendMail() {
return false ;
}
/**
* Fill data from invitation event to current event form
* @param calSetting
* @param event
* @param calendarId
* @param formtime
* @throws Exception
*/
public void importInvitationEvent(CalendarSetting calSetting, CalendarEvent event, String calendarId, String formtime) throws Exception {
if(event != null) {
setEventSumary(event.getSummary()) ;
setEventDescription(event.getDescription()) ;
setEventAllDate(CalendarUtils.isAllDayEvent(event)) ;
setEventFromDate(event.getFromDateTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
setEventCheckTime(event.getFromDateTime()) ;
setEventToDate(event.getToDateTime(),calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
setSelectedCalendarId(calendarId) ;
setEventPlace(event.getLocation()) ;
setEventRepeat(event.getRepeatType()) ;
setEventReminders(event.getReminders()) ;
setAttachments(event.getAttachment()) ;
setMessage(event.getMessage());
setParticipantStatusValues(event.getParticipantStatus());
}
}
protected void sendMail(MailService svr, OrganizationService orSvr,CalendarSetting setting, String fromId, String toId, CalendarEvent event) throws Exception {
List<Attachment> atts = getAttachments(null, false);
DateFormat df = new SimpleDateFormat(setting.getDateFormat() + " " + setting.getTimeFormat()) ;
User invitor = orSvr.getUserHandler().findUserByName(CalendarUtils.getCurrentUser()) ;
StringBuffer sbSubject = new StringBuffer("["+getLabel("invitation")+"] ") ;
sbSubject.append(event.getSummary()) ;
sbSubject.append(" ") ;
sbSubject.append(df.format(event.getFromDateTime())) ;
StringBuffer sbBody = new StringBuffer() ;
sbBody.append("<div style=\"margin: 20px auto; padding: 8px; background: rgb(224, 236, 255) none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 500px;\">") ;
sbBody.append("<table style=\"margin: 0px; padding: 0px; border-collapse: collapse; border-spacing: 0px; width: 100%; line-height: 16px;\">") ;
sbBody.append("<tbody>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap; \">"+getLabel("fromWho")+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\"> " + invitor.getUserName() +"("+invitor.getEmail()+")" + " </td>") ;
sbBody.append("</tr>") ;
//
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(UIEventDetailTab.FIELD_MESSAGE)+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\">" + event.getMessage()+ "</td>") ;
sbBody.append("</tr>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(UIEventDetailTab.FIELD_EVENT)+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\">" + event.getSummary()+ "</td>") ;
sbBody.append("</tr>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(UIEventDetailTab.FIELD_DESCRIPTION)+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\">" + (event.getDescription() != null && event.getDescription().trim().length() > 0 ? event.getDescription() : " ") + "</td>") ;
sbBody.append("</tr>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel("when")+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\"> <div>"+getLabel(UIEventDetailTab.FIELD_FROM)+": " +df.format(event.getFromDateTime())+"</div>");
sbBody.append("<div>"+getLabel(UIEventDetailTab.FIELD_TO)+": "+df.format(event.getToDateTime())+"</div></td>") ;
sbBody.append("</tr>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(UIEventDetailTab.FIELD_PLACE)+":</td>") ;
sbBody.append("<td style=\"padding: 4px;\">" + (event.getLocation() != null && event.getLocation().trim().length() > 0 ? event.getLocation(): " ") + "</td>") ;
sbBody.append("</tr>") ;
sbBody.append("<tr>") ;
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(FIELD_MEETING)+"</td>") ;
toId = toId.replace(CalendarUtils.BREAK_LINE, CalendarUtils.COMMA);
if (CalendarUtils.isEmpty(getInvitationEmail())) {
sbBody.append("<td style=\"padding: 4px;\">" +toId + "</td>") ;
} else {
String newInvi = getInvitationEmail().replace(",", ", ") ;
sbBody.append("<td style=\"padding: 4px;\">" +toId + ", " + newInvi + "</td>") ;
}
sbBody.append("</tr>");
if(!atts.isEmpty()){
sbBody.append("<tr>");
sbBody.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">"+getLabel(UIEventDetailTab.FIELD_ATTACHMENTS)+":</td>");
StringBuffer sbf = new StringBuffer();
for(Attachment att : atts) {
if(sbf.length() > 0) sbf.append(",") ;
sbf.append(att.getName());
}
sbBody.append("<td style=\"padding: 4px;\"> ("+atts.size()+") " +sbf.toString()+" </td>");
sbBody.append("</tr>");
}
Map<String, String> eXoIdMap = new HashMap<String, String>();
StringBuffer sbAddress = new StringBuffer() ;
if(event.getInvitation()!= null) {
for(String s : event.getInvitation()) {
s = s.trim() ;
if(sbAddress.length() > 0) sbAddress.append(",") ;
sbAddress.append(s) ;
eXoIdMap.put(s, null);
}
}
OrganizationService orgService = CalendarUtils.getOrganizationService() ;
StringBuffer sb = new StringBuffer() ;
for(String s : toId.split(CalendarUtils.COMMA)) {
User user = orgService.getUserHandler().findUserByName(s) ;
if(user != null) {
if(!CalendarUtils.isEmpty(sb.toString())) sb.append(CalendarUtils.COMMA) ;
sb.append(user.getEmail()) ;
eXoIdMap.put(user.getEmail(), s);
}
}
if(sbAddress.length() > 0 && sb.toString().trim().length() > 0 ) sbAddress.append(",") ;
sbAddress.append(sb.toString().trim()) ;
StringBuffer values = new StringBuffer(fromId) ;
User user = orSvr.getUserHandler().findUserByName(fromId) ;
values.append(CalendarUtils.SEMICOLON + " ") ;
values.append(toId) ;
values.append(CalendarUtils.SEMICOLON + " ") ;
values.append(event.getCalType()) ;
values.append(CalendarUtils.SEMICOLON + " ") ;
values.append(event.getCalendarId()) ;
values.append(CalendarUtils.SEMICOLON + " ") ;
values.append(event.getId()) ;
CalendarService calService = CalendarUtils.getCalendarService() ;
org.exoplatform.services.mail.MailService mService = getApplicationComponent(org.exoplatform.services.mail.impl.MailServiceImpl.class) ;
org.exoplatform.services.mail.Attachment attachmentCal = new org.exoplatform.services.mail.Attachment() ;
try {
OutputStream out = calService.getCalendarImportExports(CalendarService.ICALENDAR).exportEventCalendar(fromId, event.getCalendarId(), event.getCalType(), event.getId()) ;
ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes()) ;
attachmentCal.setInputStream(is) ;
attachmentCal.setName("icalendar.ics");
attachmentCal.setMimeType("text/calendar") ;
} catch (Exception e) {
attachmentCal = null;
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to create attachment", e);
}
for (String s : sbAddress.toString().split(CalendarUtils.COMMA)) {
if (CalendarUtils.isEmpty(s)) continue;
org.exoplatform.services.mail.Message message = new org.exoplatform.services.mail.Message();
message.setSubject(sbSubject.toString()) ;
message.setBody(getBodyMail(sbBody.toString(), eXoIdMap, s, invitor, event)) ;
message.setTo(s) ;
message.setMimeType(Utils.MIMETYPE_TEXTHTML) ;
message.setFrom(user.getEmail()) ;
if (attachmentCal != null) {
message.addAttachment(attachmentCal) ;
}
if(!atts.isEmpty()){
for(Attachment att : atts) {
org.exoplatform.services.mail.Attachment attachment = new org.exoplatform.services.mail.Attachment() ;
attachment.setInputStream(att.getInputStream()) ;
attachment.setMimeType(att.getMimeType()) ;
message.addAttachment(attachment) ;
}
}
mService.sendMessage(message) ;
}
}
}
private String getBodyMail(String sbBody,Map<String, String> eXoIdMap,String s,User invitor,CalendarEvent event) throws Exception {
StringBuilder body = new StringBuilder(sbBody.toString());
String eXoId = CalendarUtils.isEmpty(eXoIdMap.get(s)) ? "null":eXoIdMap.get(s);
body.append("<tr>");
body.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">");
body.append(getLabel("likeToAttend")+" </td><td> <a href=\"" + getReplyInvitationLink(org.exoplatform.calendar.service.Utils.ACCEPT, invitor, s, eXoId, event) + "\" >"+getLabel("yes")+"</a>" + " - " + "<a href=\"" + getReplyInvitationLink(org.exoplatform.calendar.service.Utils.NOTSURE, invitor, s, eXoId, event) + "\" >"+getLabel("notSure")+"</a>" + " - " + "<a href=\"" + getReplyInvitationLink(org.exoplatform.calendar.service.Utils.DENY, invitor, s, eXoId, event) + "\" >"+getLabel("no")+"</a>");
body.append("</td></tr>");
body.append("<tr>");
body.append("<td style=\"padding: 4px; text-align: right; vertical-align: top; white-space:nowrap;\">");
body.append(getLabel("seeMoreDetails")+" </td><td><a href=\"" + getReplyInvitationLink(org.exoplatform.calendar.service.Utils.ACCEPT_IMPORT, invitor, s, eXoId, event) + "\" >"+getLabel("importToExoCalendar")+"</a> "+getLabel("or")+" <a href=\"" + getReplyInvitationLink(org.exoplatform.calendar.service.Utils.JUMP_TO_CALENDAR, invitor, s, eXoId, event) + "\" >"+getLabel("jumpToExoCalendar")+"</a>");
body.append("</td></tr>");
body.append("</tbody>");
body.append("</table>");
body.append("</div>") ;
return body.toString();
}
protected String getReplyInvitationLink(int answer, User invitor, String invitee, String eXoId, CalendarEvent event) throws Exception{
String portalURL = CalendarUtils.getServerBaseUrl() + PortalContainer.getCurrentPortalContainerName();
String restURL = portalURL + "/" + PortalContainer.getCurrentRestContextName();
String calendarURL = CalendarUtils.getCalendarURL();
if (answer == org.exoplatform.calendar.service.Utils.ACCEPT || answer == org.exoplatform.calendar.service.Utils.DENY ||
answer == org.exoplatform.calendar.service.Utils.NOTSURE) {
return (restURL + "/cs/calendar" + CalendarUtils.INVITATION_URL + event.getCalendarId() + "/" + event.getCalType() + "/" + event.getId() + "/" + invitor.getUserName() + "/" + invitee + "/" + eXoId + "/" + answer);
}
if (answer == org.exoplatform.calendar.service.Utils.ACCEPT_IMPORT) {
return (calendarURL + CalendarUtils.INVITATION_IMPORT_URL + invitor.getUserName() + "/" + event.getId() + "/" + event.getCalType());
}
if (answer == org.exoplatform.calendar.service.Utils.JUMP_TO_CALENDAR) {
return (calendarURL + CalendarUtils.INVITATION_DETAIL_URL + invitor.getUserName() + "/" + event.getId() + "/" + event.getCalType());
}
return "";
}
public Attachment getAttachment(String attId) {
UIEventDetailTab uiDetailTab = getChildById(TAB_EVENTDETAIL) ;
for (Attachment att : uiDetailTab.getAttachments()) {
if(att.getId().equals(attId)) {
return att ;
}
}
return null;
}
public List<ParticipantStatus> getParticipantStatusList() {
return participantStatusList_;
}
public static void downloadAtt(Event<?> event, UIForm uiForm, boolean isEvent) throws Exception {
String attId = event.getRequestContext().getRequestParameter(OBJECTID) ;
Attachment attach = null;
if (isEvent) {
UIEventForm uiEventForm = (UIEventForm)uiForm;
attach = uiEventForm.getAttachment(attId) ;
} else {
UITaskForm uiTaskForm = (UITaskForm)uiForm;
attach = uiTaskForm.getAttachment(attId);
}
if(attach != null) {
String mimeType = attach.getMimeType().substring(attach.getMimeType().indexOf("/")+1) ;
DownloadResource dresource = new InputStreamDownloadResource(attach.getInputStream(), mimeType);
DownloadService dservice = (DownloadService)PortalContainer.getInstance().getComponentInstanceOfType(DownloadService.class);
dresource.setDownloadName(attach.getName());
String downloadLink = dservice.getDownloadLink(dservice.addDownloadResource(dresource));
event.getRequestContext().getJavascriptManager().addJavascript("ajaxRedirect('" + downloadLink + "');");
if (isEvent) {
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getChildById(TAB_EVENTDETAIL)) ;
} else {
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getChildById(UITaskForm.TAB_TASKDETAIL)) ;
}
}
}
private boolean isSignificantChanged(CalendarEvent newCalendarEvent, CalendarEvent oldCalendarEvent) {
return newCalendarEvent != null && oldCalendarEvent != null && (
(oldCalendarEvent.getSummary() != null && !oldCalendarEvent.getSummary().equalsIgnoreCase(newCalendarEvent.getSummary()) || newCalendarEvent.getSummary() != null && !newCalendarEvent.getSummary().equalsIgnoreCase(oldCalendarEvent.getSummary()))
|| (oldCalendarEvent.getDescription() != null && !oldCalendarEvent.getDescription().equalsIgnoreCase(newCalendarEvent.getDescription()) || newCalendarEvent.getDescription() != null && !newCalendarEvent.getDescription().equalsIgnoreCase(oldCalendarEvent.getDescription()))
|| (oldCalendarEvent.getLocation() != null && !oldCalendarEvent.getLocation().equalsIgnoreCase(newCalendarEvent.getLocation()) || newCalendarEvent.getLocation() != null && !newCalendarEvent.getLocation().equalsIgnoreCase(oldCalendarEvent.getLocation()))
|| (!oldCalendarEvent.getFromDateTime().equals(newCalendarEvent.getFromDateTime()))
|| (!oldCalendarEvent.getToDateTime().equals(newCalendarEvent.getToDateTime()))
);
}
private CalendarEvent sendInvitation(Event<UIEventForm> event, CalendarSetting calSetting, CalendarEvent calendarEvent) throws Exception {
String username = RequestContext.getCurrentInstance().getRemoteUser();
String toId = null;
if (this.isAddNew_ || this.isChangedSignificantly) {
toId = getParticipantValues();
} else {
// select new Invitation email
Map<String, String> invitations = new LinkedHashMap<String, String>();
for (String s : calendarEvent.getInvitation())
invitations.put(s, s);
for (String parSt : calendarEvent.getParticipantStatus()) {
String[] entry = parSt.split(":");
// is old
if (entry.length > 1 && entry[0].contains("@"))
invitations.remove(entry[0]);
}
calendarEvent.setInvitation(invitations.keySet().toArray(new String[invitations.size()]));
// select new User
StringBuilder builder = new StringBuilder("");
for (String parSt : calendarEvent.getParticipantStatus()) {
String[] entry = parSt.split(":");
// is new
if ((entry.length == 1) && (!entry[0].contains("@"))) {
if (builder.length() > 0)
builder.append(CalendarUtils.BREAK_LINE);
builder.append(entry[0]);
}
}
if (builder.toString().trim().length() > 0 || invitations.size() > 0) {
toId = builder.toString();
}
}
try {
if (toId != null) {
sendMail(CalendarUtils.getMailService(), CalendarUtils.getOrganizationService(), calSetting, username, toId, calendarEvent);
List<String> parsUpdated = new LinkedList<String>();
for (String parSt : calendarEvent.getParticipantStatus()) {
String[] entry = parSt.split(":");
if (entry.length > 1)
parsUpdated.add(entry[0] + ":" + entry[1]);
else
parsUpdated.add(entry[0] + ":" + STATUS_PENDING);
}
calendarEvent.setParticipantStatus(parsUpdated.toArray(new String[parsUpdated.size()]));
}
return calendarEvent;
} catch (Exception e) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.error-send-email", null));
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to send mail ivitation to the participant", e);
}
}
return null;
}
public void saveAndNoAsk(Event<UIEventForm> event, boolean isSend, boolean updateSeries)throws Exception {
UIEventForm uiForm = event.getSource() ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupAction uiPopupAction = uiForm.getAncestorOfType(UIPopupAction.class) ;
UICalendarViewContainer uiViewContainer = calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
CalendarSetting calSetting = calendarPortlet.getCalendarSetting() ;
CalendarService calService = CalendarUtils.getCalendarService() ;
String summary = uiForm.getEventSumary().trim() ;
summary = CalendarUtils.enCodeTitle(summary);
String location = uiForm.getEventPlace() ;
- if(!CalendarUtils.isEmpty(location)) location = location.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
+ if(!CalendarUtils.isEmpty(location)) {
+ location = location.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
+ }
+ else {
+ location = null;
+ }
String description = uiForm.getEventDescription() ;
- if(!CalendarUtils.isEmpty(description)) description = description.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
+ if(!CalendarUtils.isEmpty(description)) {
+ description = description.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
+ }
+ else {
+ description = null;
+ }
if(!uiForm.isEventDetailValid(calSetting)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, null));
uiForm.setSelectedTab(TAB_EVENTDETAIL) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isReminderValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] {uiForm.errorValues} ));
uiForm.setSelectedTab(TAB_EVENTREMINDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isParticipantValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] { uiForm.errorValues }));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
Date from = uiForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
Date to = uiForm.getEventToDate(calSetting.getDateFormat(),calSetting.getTimeFormat()) ;
if(from.after(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.event-date-time-logic", null, AbstractApplicationMessage.WARNING)) ;
return ;
}
String username = CalendarUtils.getCurrentUser() ;
String calendarId = uiForm.getCalendarId() ;
if(from.equals(to)) {
to = CalendarUtils.getEndDay(from).getTime() ;
}
if(uiForm.getEventAllDate()) {
java.util.Calendar tempCal = CalendarUtils.getInstanceOfCurrentCalendar() ;
tempCal.setTime(to) ;
tempCal.add(java.util.Calendar.MILLISECOND, -1) ;
to = tempCal.getTime() ;
}
Calendar currentCalendar = CalendarUtils.getCalendar(uiForm.calType_, calendarId);
if(currentCalendar == null) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
return ;
}
boolean canEdit = false ;
if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)) {
canEdit = CalendarUtils.canEdit(null, org.exoplatform.calendar.service.Utils.getEditPerUsers(currentCalendar), username) ;
} else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)) {
canEdit = CalendarUtils.canEdit(
CalendarUtils.getOrganizationService(), currentCalendar.getEditPermission(), username) ;
}
if(!canEdit && !uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE) ) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-permission-to-edit", null,1));
return ;
}
CalendarEvent calendarEvent = null ;
CalendarEvent oldCalendarEvent = null;
String[] pars = uiForm.getParticipantValues().split(CalendarUtils.BREAK_LINE) ;
String eventId = null ;
if(uiForm.isAddNew_){
calendarEvent = new CalendarEvent() ;
} else {
calendarEvent = uiForm.calendarEvent_ ;
oldCalendarEvent = new CalendarEvent();
oldCalendarEvent.setSummary(calendarEvent.getSummary());
oldCalendarEvent.setDescription(calendarEvent.getDescription());
oldCalendarEvent.setLocation(calendarEvent.getLocation());
oldCalendarEvent.setFromDateTime(calendarEvent.getFromDateTime());
oldCalendarEvent.setToDateTime(calendarEvent.getToDateTime());
}
calendarEvent.setFromDateTime(from) ;
calendarEvent.setToDateTime(to);
calendarEvent.setSendOption(uiForm.getSendOption());
calendarEvent.setMessage(uiForm.getMessage());
String[] parStatus = uiForm.getParticipantStatusValues().split(CalendarUtils.BREAK_LINE) ;
calendarEvent.setParticipantStatus(parStatus);
calendarEvent.setParticipant(pars) ;
if(CalendarUtils.isEmpty(uiForm.getInvitationEmail())) calendarEvent.setInvitation(ArrayUtils.EMPTY_STRING_ARRAY);
else
if(CalendarUtils.isValidEmailAddresses(uiForm.getInvitationEmail())) {
String addressList = uiForm.getInvitationEmail().replaceAll(CalendarUtils.SEMICOLON,CalendarUtils.COMMA) ;
Map<String, String> emails = new LinkedHashMap<String, String>() ;
for(String email : addressList.split(CalendarUtils.COMMA)) {
String address = email.trim() ;
if (!emails.containsKey(address)) emails.put(address, address) ;
}
if(!emails.isEmpty()) calendarEvent.setInvitation(emails.keySet().toArray(new String[emails.size()])) ;
} else {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.event-email-invalid"
, new String[] { CalendarUtils.invalidEmailAddresses(uiForm.getInvitationEmail())}));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
calendarEvent.setCalendarId(uiForm.getCalendarId()) ;
calendarEvent.setEventType(CalendarEvent.TYPE_EVENT) ;
calendarEvent.setSummary(summary) ;
calendarEvent.setDescription(description) ;
calendarEvent.setCalType(uiForm.calType_) ;
calendarEvent.setCalendarId(calendarId) ;
calendarEvent.setEventCategoryId(uiForm.getEventCategory()) ;
UIFormSelectBox selectBox = ((UIFormInputWithActions)uiForm.getChildById(TAB_EVENTDETAIL))
.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY) ;
for (SelectItemOption<String> o : selectBox.getOptions()) {
if (o.getValue().equals(selectBox.getValue())) {
calendarEvent.setEventCategoryName(o.getLabel()) ;
break ;
}
}
calendarEvent.setLocation(location) ;
if (uiForm.getEventIsRepeat()) {
if (repeatEvent != null) {
// copy repeat properties from repeatEvent to calendarEvent
calendarEvent.setRepeatType(repeatEvent.getRepeatType());
calendarEvent.setRepeatInterval(repeatEvent.getRepeatInterval());
calendarEvent.setRepeatCount(repeatEvent.getRepeatCount());
calendarEvent.setRepeatUntilDate(repeatEvent.getRepeatUntilDate());
calendarEvent.setRepeatByDay(repeatEvent.getRepeatByDay());
calendarEvent.setRepeatByMonthDay(repeatEvent.getRepeatByMonthDay());
}
} else {
calendarEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
calendarEvent.setRepeatInterval(0);
calendarEvent.setRepeatCount(0);
calendarEvent.setRepeatUntilDate(null);
calendarEvent.setRepeatByDay(null);
calendarEvent.setRepeatByMonthDay(null);
}
calendarEvent.setPriority(uiForm.getEventPriority()) ;
calendarEvent.setPrivate(UIEventForm.ITEM_PRIVATE.equals(uiForm.getShareType())) ;
calendarEvent.setEventState(uiForm.getEventState()) ;
calendarEvent.setAttachment(uiForm.getAttachments(calendarEvent.getId(), uiForm.isAddNew_)) ;
calendarEvent.setReminders(uiForm.getEventReminders(from, calendarEvent.getReminders())) ;
eventId = calendarEvent.getId() ;
CalendarView calendarView = (CalendarView)uiViewContainer.getRenderedChild() ;
this.isChangedSignificantly = this.isSignificantChanged(calendarEvent, oldCalendarEvent);
try {
if (calendarEvent != null && isSend) {
try {
CalendarEvent tempCal = sendInvitation(event, calSetting, calendarEvent);
calendarEvent = tempCal != null ? tempCal : calendarEvent;
} catch (Exception e) {
if (LOG.isWarnEnabled()) LOG.warn("Sending invitation failed!" , e);
}
}
if(uiForm.isAddNew_){
if(uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE)) {
calService.saveUserEvent(username, calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)){
calService.saveEventToSharedCalendar(username , calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)){
calService.savePublicEvent(calendarId, calendarEvent, uiForm.isAddNew_) ;
}
} else {
String fromCal = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String toCal = uiForm.newCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String fromType = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
String toType = uiForm.newCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
listEvent.add(calendarEvent) ;
// if the event (before change) is a virtual occurrence
if (!uiForm.calendarEvent_.getRepeatType().equals(CalendarEvent.RP_NOREPEAT) && !CalendarUtils.isEmpty(uiForm.calendarEvent_.getRecurrenceId())) {
if (!updateSeries) {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
} else {
// update series:
if (CalendarUtils.isSameDate(oldCalendarEvent.getFromDateTime(), calendarEvent.getFromDateTime())) {
calService.updateRecurrenceSeries(fromCal, toCal, fromType, toType, calendarEvent, username);
}
else {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
}
}
}
else {
if (org.exoplatform.calendar.service.Utils.isExceptionOccurrence(calendarEvent_)) calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
else calService.moveEvent(fromCal, toCal, fromType, toType, listEvent, username) ;
}
UITaskForm.updateListView(calendarView, calendarEvent, calService, username);
}
if(calendarView instanceof UIListContainer) {
UIListContainer uiListContainer = (UIListContainer)calendarView ;
if (!uiListContainer.isDisplaySearchResult()) {
uiViewContainer.refresh() ;
}
} else {
uiViewContainer.refresh() ;
}
calendarView.setLastUpdatedEventId(eventId) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ;
UIMiniCalendar uiMiniCalendar = calendarPortlet.findFirstComponentOfType(UIMiniCalendar.class) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar) ;
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
}catch (Exception e) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.add-event-error", null));
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to add the event", e);
}
}
UIEventDetailTab uiDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
for (Attachment att : uiDetailTab.getAttachments()) {
UIAttachFileForm.removeUploadTemp(uiForm.getApplicationComponent(UploadService.class), att.getResourceId()) ;
}
}
public void setRepeatEvent(CalendarEvent repeatEvent) throws Exception {
this.repeatEvent = repeatEvent;
setEventIsRepeat(true);
setRepeatSummary(buildRepeatSummary(repeatEvent));
}
public void setRepeatSummary(String summary) {
repeatSummary = summary;
}
public String getRepeatSummary() {
return repeatSummary;
}
public CalendarEvent getRepeatEvent() {
return repeatEvent;
}
/**
* Build the repeating summary, i.e: daily every 2 days, until 02/03/2011. <br/>
* The summary structure is defined in resource bundle, it contains some parameters and </br>
* will be replaced by values from repeatEvent. <br/>
* <p>There are 6 parameters: {count}, {until}, {interval}, {byDays}, {theDay}, {theNumber}.<br/>
* Some labels in resource bundle to define numbers (the first, the second, ...) which were used in summary
* @param repeatEvent the repeating event
* @return summary string about repeating event
* @throws Exception
*/
public String buildRepeatSummary(CalendarEvent repeatEvent) throws Exception {
CalendarSetting calSetting = CalendarUtils.getCurrentUserCalendarSetting();
WebuiRequestContext context = RequestContext.getCurrentInstance() ;
Locale locale = context.getParentAppRequestContext().getLocale() ;
DateFormat format = new SimpleDateFormat(calSetting.getDateFormat(), locale);
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] dayOfWeeks = symbols.getWeekdays();
String summary = "";
if (repeatEvent == null) return "";
String repeatType = repeatEvent.getRepeatType();
if (CalendarEvent.RP_NOREPEAT.equals(repeatType) || repeatType == null) return "";
int interval = (int)repeatEvent.getRepeatInterval();
int count = (int)repeatEvent.getRepeatCount();
Date until = repeatEvent.getRepeatUntilDate();
String endType = RP_END_NEVER;
if (count > 0) endType = RP_END_AFTER;
if (until != null) endType = RP_END_BYDATE;
String pattern = "";
if (repeatType.equals(CalendarEvent.RP_DAILY)) {
if (interval == 1) {
//pattern = "Daily";
pattern = getLabel("daily");
} else {
//pattern = "Every {interval} days";
pattern = getLabel("every-day");
}
if (endType.equals(RP_END_AFTER)) {
//pattern = "Daily, {count} times";
//pattern = "Every {interval} days, {count} times";
pattern += ", ";
pattern += getLabel("count-times");
}
if (endType.equals(RP_END_BYDATE)) {
//pattern = "Daily, until {until}";
//pattern = "Every {interval} days, until {until}";
pattern += ", ";
pattern += getLabel("until");
}
summary = pattern.replace("{interval}", String.valueOf(interval)).replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
.replace("{until}", repeatEvent.getRepeatUntilDate()==null?"":format.format(repeatEvent.getRepeatUntilDate()));
return summary;
}
if (repeatType.equals(CalendarEvent.RP_WEEKLY)) {
if (interval == 1) {
//pattern = "Weekly on {byDays}";
pattern = getLabel("weekly");
} else {
//pattern = "Every {interval} weeks on {byDays}";
pattern = getLabel("every-week");
}
if (endType.equals(RP_END_AFTER)) {
//pattern = "Weekly on {byDays}, {count} times";
//pattern = "Every {interval} weeks on {byDays}, {count} times";
pattern += ", ";
pattern += getLabel("count-times");
}
if (endType.equals(RP_END_BYDATE)) {
//pattern = "Weekly on {byDays}, until {until}";
//pattern = "Every {interval} weeks on {byDays}, until {until}";
pattern += ", ";
pattern += getLabel("until");
}
String[] weeklyByDays = repeatEvent.getRepeatByDay();
StringBuffer byDays = new StringBuffer();
for (int i = 0; i < weeklyByDays.length; i++) {
if (i == 0) {
byDays.append(dayOfWeeks[UIRepeatEventForm.convertToDayOfWeek(weeklyByDays[0])]);
} else {
byDays.append(", ");
byDays.append(dayOfWeeks[UIRepeatEventForm.convertToDayOfWeek(weeklyByDays[i])]);
}
}
summary = pattern.replace("{interval}", String.valueOf(interval)).replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
.replace("{until}", repeatEvent.getRepeatUntilDate()==null?"":format.format(repeatEvent.getRepeatUntilDate())).replace("{byDays}", byDays.toString());
return summary;
}
if (repeatType.equals(CalendarEvent.RP_MONTHLY)) {
String monthlyType = UIRepeatEventForm.RP_MONTHLY_BYMONTHDAY;
if (repeatEvent.getRepeatByDay() != null && repeatEvent.getRepeatByDay().length > 0) monthlyType = UIRepeatEventForm.RP_MONTHLY_BYDAY;
if (interval == 1) {
// pattern = "Monthly on"
pattern = getLabel("monthly");
} else {
// pattern = "Every {interval} months on
pattern = getLabel("every-month");
}
if (monthlyType.equals(UIRepeatEventForm.RP_MONTHLY_BYDAY)) {
// pattern = "Monthly on {theNumber} {theDay}
// pattern = "Every {interval} months on {theNumber} {theDay}
pattern += " ";
pattern += getLabel("monthly-by-day");
} else {
// pattern = "Monthly on day {theDay}
// pattern = "Every {interval} months on day {theDay}
pattern += " ";
pattern += getLabel("monthly-by-month-day");
}
if (endType.equals(RP_END_AFTER)) {
pattern += ", ";
pattern += getLabel("count-times");
}
if (endType.equals(RP_END_BYDATE)) {
pattern += ", ";
pattern += getLabel("until");
}
String theNumber = ""; // the first, the second, the third, ...
String theDay = ""; // in monthly by day, it's Monday, Tuesday, ... (day of week), in monthly by monthday, it's 1-31 (day of month)
if (monthlyType.equals(UIRepeatEventForm.RP_MONTHLY_BYDAY)) {
java.util.Calendar temp = CalendarUtils.getInstanceOfCurrentCalendar();
temp.setTime(repeatEvent.getFromDateTime());
int weekOfMonth = temp.get(java.util.Calendar.WEEK_OF_MONTH);
java.util.Calendar temp2 = CalendarUtils.getInstanceOfCurrentCalendar();
temp2.setTime(temp.getTime());
temp2.add(java.util.Calendar.DATE, 7);
if (temp2.get(java.util.Calendar.MONTH) != temp.get(java.util.Calendar.MONTH)) weekOfMonth = 5;
int dayOfWeek = temp.get(java.util.Calendar.DAY_OF_WEEK);
String[] weekOfMonths = new String[] {getLabel("summary-the-first"), getLabel("summary-the-second"), getLabel("summary-the-third"),
getLabel("summary-the-fourth"), getLabel("summary-the-last")};
theNumber = weekOfMonths[weekOfMonth-1];
theDay = dayOfWeeks[dayOfWeek];
} else {
java.util.Calendar temp = CalendarUtils.getInstanceOfCurrentCalendar();
temp.setTime(repeatEvent.getFromDateTime());
int dayOfMonth = temp.get(java.util.Calendar.DAY_OF_MONTH);
theDay = String.valueOf(dayOfMonth);
}
summary = pattern.replace("{interval}", String.valueOf(interval)).replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
.replace("{until}", repeatEvent.getRepeatUntilDate()==null?"":format.format(repeatEvent.getRepeatUntilDate())).replace("{theDay}", theDay).replace("{theNumber}", theNumber);
return summary;
}
if (repeatType.equals(CalendarEvent.RP_YEARLY)) {
if (interval == 1) {
// pattern = "Yearly on {theDay}"
pattern = getLabel("yearly");
} else {
// pattern = "Every {interval} years on {theDay}"
pattern = getLabel("every-year");
}
if (endType.equals(RP_END_AFTER)) {
// pattern = "Yearly on {theDay}, {count} times"
// pattern = "Every {interval} years on {theDay}, {count} times"
pattern += ", ";
pattern += getLabel("count-times");
}
if (endType.equals(RP_END_BYDATE)) {
// pattern = "Yearly on {theDay}, until {until}"
// pattern = "Every {interval} years on {theDay}, until {until}"
pattern += ", ";
pattern += getLabel("until");
}
String theDay = format.format(repeatEvent.getFromDateTime()); //
summary = pattern.replace("{interval}", String.valueOf(interval)).replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
.replace("{until}", repeatEvent.getRepeatUntilDate()==null?"":format.format(repeatEvent.getRepeatUntilDate())).replace("{theDay}", theDay);
return summary;
}
return summary;
}
static public class AddCategoryActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIPopupContainer uiContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
UIPopupAction uiChildPopup = uiContainer.getChild(UIPopupAction.class) ;
UIEventCategoryManager categoryMan = uiChildPopup.activate(UIEventCategoryManager.class, 470) ;
categoryMan.categoryId_ = uiForm.getEventCategory() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiChildPopup) ;
}
}
static public class RemoveEmailActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
uiForm.setEmailAddress(uiForm.getEmailAddress());
Util.getPortalRequestContext().setResponseComplete(true);
}
}
static public class AddAttachmentActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventDetailTab detailTab = uiForm.getChild(UIEventDetailTab.class);
UIPopupContainer uiContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
UIPopupAction uiChildPopup = uiContainer.getChild(UIPopupAction.class) ;
UIAttachFileForm uiAttachFileForm = uiChildPopup.activate(UIAttachFileForm.class, 500) ;
uiAttachFileForm.setAttSize(uiForm.getTotalAttachment()) ;
uiAttachFileForm.setLimitNumberOfFiles(UIEventForm.LIMIT_FILE_UPLOAD - detailTab.getAttachments().size());
uiAttachFileForm.init();
event.getRequestContext().addUIComponentToUpdateByAjax(uiChildPopup) ;
}
}
static public class RemoveAttachmentActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIPopupContainer uiContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
if(uiContainer != null) uiContainer.deActivate() ;
UIEventDetailTab uiEventDetailTab = uiForm.getChild(UIEventDetailTab.class) ;
String attFileId = event.getRequestContext().getRequestParameter(OBJECTID);
Attachment attachfile = new Attachment();
for (Attachment att : uiEventDetailTab.attachments_) {
if (att.getId().equals(attFileId)) {
attachfile = att;
}
}
uiEventDetailTab.removeFromUploadFileList(attachfile);
uiEventDetailTab.refreshUploadFileList() ;
uiForm.setSelectedTab(TAB_EVENTDETAIL) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ;
}
}
static public class DownloadAttachmentActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
downloadAtt(event, uiForm, true);
}
}
static public class AddParticipantActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventAttenderTab tabAttender = uiForm.getChildById(TAB_EVENTATTENDER) ;
String values = uiForm.getParticipantValues() ;
tabAttender.updateParticipants(values) ;
event.getRequestContext().addUIComponentToUpdateByAjax(tabAttender) ;
UIPopupContainer uiContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
UIPopupAction uiPopupAction = uiContainer.getChild(UIPopupAction.class);
UIPopupContainer uiInvitationContainer= uiPopupAction.createUIComponent(UIPopupContainer.class, null, "UIInvitationContainer");
uiInvitationContainer.getChild(UIPopupAction.class).setId("UIPopupAction3") ;
uiInvitationContainer.getChild(UIPopupAction.class).getChild(UIPopupWindow.class).setId("UIPopupWindow");
UIInvitationForm uiInvitationForm = uiInvitationContainer.addChild(UIInvitationForm.class, null, null);
uiInvitationForm.setInvitationMsg(uiForm.invitationMsg_) ;
uiForm.participantList_ = new String("");
uiInvitationForm.setParticipantValue(uiForm.participantList_) ;
uiPopupAction.activate(uiInvitationContainer, 500, 0, true);
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
}
}
static public class AddActionListener extends EventListener<UIUserSelector> {
@Override
public void execute(Event<UIUserSelector> event) throws Exception {
UIUserSelector uiUserSelector = event.getSource();
UIPopupContainer uiContainer = uiUserSelector.getAncestorOfType(UIPopupContainer.class) ;
UIPopupWindow uiPoupPopupWindow = uiUserSelector.getParent() ;
UIEventForm uiEventForm = uiContainer.getChild(UIEventForm.class);
UIEventShareTab uiEventShareTab = uiEventForm.getChild(UIEventShareTab.class);
Long currentPage = uiEventShareTab.getCurrentPage();
String values = uiUserSelector.getSelectedUsers();
List<String> currentEmails = new ArrayList<String>() ;
String [] invitors = uiEventForm.getMeetingInvitation() ;
if (invitors != null) currentEmails.addAll(Arrays.asList(invitors)) ;
for (String value : values.split(CalendarUtils.COMMA)) {
String email = CalendarUtils.getOrganizationService().getUserHandler().findUserByName(value).getEmail() ;
if (!currentEmails.contains(email)) currentEmails.add(email) ;
if (!uiEventForm.participants_.keySet().contains(value)) {
uiEventForm.participants_.put(value, email) ;
}
}
for(Entry<String,String> entry : uiEventForm.participants_.entrySet()){
if(!uiEventForm.participantStatus_.keySet().contains(entry.getKey())){
if(uiEventForm.participantStatus_.put(entry.getKey(),STATUS_EMPTY)==null)
uiEventForm.participantStatusList_.add(uiEventForm.new ParticipantStatus(entry.getKey(),STATUS_EMPTY));
}
}
uiEventShareTab.setParticipantStatusList(uiEventForm.getParticipantStatusList());
uiEventShareTab.updateCurrentPage(currentPage.intValue());
((UIEventAttenderTab)uiEventForm.getChildById(TAB_EVENTATTENDER)).updateParticipants(uiEventForm.getParticipantValues()) ;
uiEventForm.setMeetingInvitation(currentEmails.toArray(new String[currentEmails.size()])) ;
//close select user popup
uiPoupPopupWindow.setShow(false) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer) ;
}
}
static public class AddUserActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIPopupContainer uiPopupContainer = uiForm.getParent();
uiPopupContainer.deActivate();
UIPopupWindow uiPopupWindow = uiPopupContainer.getChildById("UIPopupWindowAddUserEventForm") ;
if(uiPopupWindow == null)uiPopupWindow = uiPopupContainer.addChild(UIPopupWindow.class, "UIPopupWindowAddUserEventForm", "UIPopupWindowAddUserEventForm") ;
UIUserSelector uiUserSelector = uiPopupContainer.createUIComponent(UIUserSelector.class, null, null) ;
uiUserSelector.setShowSearch(true);
uiUserSelector.setShowSearchUser(true) ;
uiUserSelector.setShowSearchGroup(true);
uiPopupWindow.setUIComponent(uiUserSelector);
uiPopupWindow.setShow(true);
uiPopupWindow.setWindowSize(740, 400) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupContainer) ;
}
}
static public class MoveNextActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventDetailTab uiEventDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
UIEventAttenderTab uiEventAttenderTab = uiForm.getChildById(TAB_EVENTATTENDER) ;
uiEventAttenderTab.moveNextDay() ;
if(uiEventAttenderTab.isCheckFreeTime()) {
uiEventDetailTab.getUIFormDateTimePicker(UIEventDetailTab.FIELD_FROM).setCalendar(uiEventAttenderTab.calendar_) ;
uiEventDetailTab.getUIFormDateTimePicker(UIEventDetailTab.FIELD_TO).setCalendar(uiEventAttenderTab.calendar_) ;
}
uiForm.setSelectedTab(TAB_EVENTATTENDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ;
}
}
static public class MovePreviousActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventDetailTab uiEventDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
UIEventAttenderTab uiEventAttenderTab = uiForm.getChildById(TAB_EVENTATTENDER) ;
uiEventAttenderTab.movePreviousDay() ;
if(uiEventAttenderTab.isCheckFreeTime()) {
uiEventDetailTab.getUIFormDateTimePicker(UIEventDetailTab.FIELD_FROM).setCalendar(uiEventAttenderTab.calendar_) ;
uiEventDetailTab.getUIFormDateTimePicker(UIEventDetailTab.FIELD_TO).setCalendar(uiEventAttenderTab.calendar_) ;
}
uiForm.setSelectedTab(TAB_EVENTATTENDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ;
}
}
static public class DeleteUserActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventAttenderTab tabAttender = uiForm.getChildById(TAB_EVENTATTENDER) ;
String values = uiForm.getParticipantValues() ;
tabAttender.updateParticipants(values) ;
event.getRequestContext().addUIComponentToUpdateByAjax(tabAttender) ;
StringBuffer newPars = new StringBuffer() ;
for(String id : tabAttender.getParticipants()){
UICheckBoxInput input = tabAttender.getUICheckBoxInput(id) ;
if(input != null) {
if( input.isChecked()) {
tabAttender.parMap_.remove(id) ;
uiForm.participantStatus_.remove(id);
for(Iterator<ParticipantStatus> i = uiForm.participantStatusList_.iterator(); i.hasNext();){
ParticipantStatus participantStatus = i.next();
if(id.equalsIgnoreCase(participantStatus.getParticipant()))
i.remove();
}
uiForm.participants_.remove(id);
uiForm.removeChildById(id) ;
List<String> currentEmails = new ArrayList<String>() ;
String [] invitors = uiForm.getMeetingInvitation() ;
if (invitors != null) {
currentEmails.addAll(Arrays.asList(invitors)) ;
currentEmails.remove(CalendarUtils.getOrganizationService().getUserHandler().findUserByName(id.trim()).getEmail()) ;
uiForm.setMeetingInvitation(currentEmails.toArray(new String[currentEmails.size()])) ;
}
}else {
if(!CalendarUtils.isEmpty(newPars.toString())) newPars.append(CalendarUtils.BREAK_LINE) ;
newPars.append(id) ;
}
}
}
uiForm.getChild(UIEventShareTab.class).setParticipantStatusList(uiForm.getParticipantStatusList());
uiForm.setSelectedTab(TAB_EVENTATTENDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getChildById(TAB_EVENTATTENDER)) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getChildById(TAB_EVENTSHARE)) ;
}
}
static public class SaveActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UICalendarPortlet uiPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupContainer uiPopupContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
UIPopupAction uiPopupAction = uiPopupContainer.getChild(UIPopupAction.class);
if(!uiForm.isReminderValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] {uiForm.errorValues}, AbstractApplicationMessage.WARNING));
uiForm.setSelectedTab(TAB_EVENTREMINDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
else {
CalendarService calService = CalendarUtils.getCalendarService();
if(calService.isRemoteCalendar(CalendarUtils.getCurrentUser(), uiForm.getCalendarId())) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.cant-add-event-on-remote-calendar", null, AbstractApplicationMessage.WARNING));
return;
}
String sendOption = uiForm.getSendOption();
List<ParticipantStatus> lstPart = ((UIEventShareTab)uiForm.getChildById(TAB_EVENTSHARE)).getData();
if(CalendarSetting.ACTION_ASK.equalsIgnoreCase(sendOption)){
// Show Confirm
UIPopupAction pAction = uiPopupContainer.getChild(UIPopupAction.class) ;
UIConfirmForm confirmForm = pAction.activate(UIConfirmForm.class, 425);
if(lstPart.isEmpty()){
confirmForm.setConfirmMessage(uiForm.saveEventNoInvitation);
}else{
confirmForm.setConfirmMessage(uiForm.saveEventInvitation);
}
confirmForm.setConfig_id(uiForm.getId()) ;
String[] actions;
if (CalendarUtils.isEmpty(uiForm.getParticipantValues()) && CalendarUtils.isEmpty(uiForm.getInvitationEmail())) {
actions = new String[] {"ConfirmCancel"};
} else {
actions = new String[] {"ConfirmOK","ConfirmCancel"};
}
confirmForm.setActions(actions);
event.getRequestContext().addUIComponentToUpdateByAjax(pAction) ;
}
else {
CalendarSetting calSetting = uiPortlet.getCalendarSetting();
Date fromDate = uiForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
// if it's a virtual recurrence
CalendarEvent occurrence = uiForm.calendarEvent_;
if (occurrence != null && !occurrence.getRepeatType().equals(CalendarEvent.RP_NOREPEAT)
&& !CalendarUtils.isEmpty(occurrence.getRecurrenceId()) && CalendarUtils.isSameDate(fromDate, occurrence.getFromDateTime()) ) {
// popup confirm form
UIConfirmForm confirmForm = uiPopupAction.activate(UIConfirmForm.class, 600);
confirmForm.setConfirmMessage(uiForm.getLabel("update-recurrence-event-confirm-msg"));
confirmForm.setConfig_id(uiForm.getId()) ;
String[] actions = new String[] {"ConfirmUpdateOnlyInstance", "ConfirmUpdateAllSeries", "ConfirmUpdateCancel"};
confirmForm.setActions(actions);
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
} else {
if(CalendarSetting.ACTION_ALWAYS.equalsIgnoreCase(sendOption))
uiForm.saveAndNoAsk(event, true, false);
else
uiForm.saveAndNoAsk(event, false, false);
}
}
}
}
}
static public class OnChangeActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIEventAttenderTab attendTab = uiForm.getChildById(TAB_EVENTATTENDER) ;
UIFormInputWithActions eventShareTab = uiForm.getChildById(TAB_EVENTSHARE) ;
String values = uiForm.getParticipantValues() ;
boolean isCheckFreeTime = attendTab.getUICheckBoxInput(UIEventAttenderTab.FIELD_CHECK_TIME).isChecked() ;
if(CalendarUtils.isEmpty(values)) {
if(isCheckFreeTime) attendTab.getUICheckBoxInput(UIEventAttenderTab.FIELD_CHECK_TIME).setChecked(false) ;
uiForm.setSelectedTab(TAB_EVENTATTENDER) ;
attendTab.updateParticipants(values) ;
uiForm.setParticipant(values) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.participant-required", null));
event.getRequestContext().addUIComponentToUpdateByAjax(eventShareTab) ;
event.getRequestContext().addUIComponentToUpdateByAjax(attendTab) ;
} else {
StringBuilder sb1 = new StringBuilder() ;
StringBuilder sb2 = new StringBuilder() ;
for(String uName : values.split(CalendarUtils.BREAK_LINE)) {
User user = CalendarUtils.getOrganizationService().getUserHandler().findUserByName(uName.trim()) ;
if(user != null) {
if(sb1 != null && sb1.length() > 0) sb1.append(CalendarUtils.BREAK_LINE) ;
sb1.append(uName.trim()) ;
} else {
if(sb2 != null && sb2.length() > 0) sb2.append(CalendarUtils.BREAK_LINE) ;
sb2.append(uName.trim()) ;
}
}
attendTab.updateParticipants(sb1.toString());
uiForm.setParticipant(values) ;
if(sb2.length() > 0) {
if(isCheckFreeTime) attendTab.getUICheckBoxInput(UIEventAttenderTab.FIELD_CHECK_TIME).setChecked(false) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.name-not-correct", new Object[]{sb2.toString()}));
}
event.getRequestContext().addUIComponentToUpdateByAjax(eventShareTab) ;
event.getRequestContext().addUIComponentToUpdateByAjax(attendTab) ;
}
}
}
static public class CancelActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIPopupAction uiPopupAction = uiForm.getAncestorOfType(UIPopupAction.class);
UIEventDetailTab uiDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
for (Attachment att : uiDetailTab.getAttachments()) {
UIAttachFileForm.removeUploadTemp(uiForm.getApplicationComponent(UploadService.class), att.getResourceId()) ;
}
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
}
}
static public class ConfirmOKActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiEventForm = event.getSource();
uiEventForm.confirmSaveEvent(event, true);
}
}
static public class ConfirmCancelActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiEventForm = event.getSource();
uiEventForm.confirmSaveEvent(event, false);
}
}
public static class EditRepeatActionListener extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource() ;
UIPopupContainer uiContainer = uiForm.getAncestorOfType(UIPopupContainer.class) ;
UIPopupAction uiChildPopup = uiContainer.getChild(UIPopupAction.class) ;
UIRepeatEventForm repeatEventForm = uiChildPopup.activate(UIRepeatEventForm.class, 480) ;
repeatEventForm.init(uiForm.repeatEvent);
event.getRequestContext().addUIComponentToUpdateByAjax(uiChildPopup) ;
}
}
public static class ConfirmUpdateOnlyInstance extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource();
String sendOption = uiForm.getSendOption();
if (CalendarSetting.ACTION_ALWAYS.equals(sendOption)) {
uiForm.saveAndNoAsk(event, true, false);
}
else {
// update only this occurrence instance
uiForm.saveAndNoAsk(event, false, false);
}
}
}
public static class ConfirmUpdateAllSeries extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiForm = event.getSource();
String sendOption = uiForm.getSendOption();
if (CalendarSetting.ACTION_ALWAYS.equals(sendOption)) {
// update all occurrence in this series
uiForm.saveAndNoAsk(event, true, true);
}
else {
uiForm.saveAndNoAsk(event, false, true);
}
}
}
public static class ConfirmUpdateCancel extends EventListener<UIEventForm> {
@Override
public void execute(Event<UIEventForm> event) throws Exception {
UIEventForm uiEventForm = event.getSource();
UICalendarPortlet uiPortlet = uiEventForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupContainer uiPopupContainer = uiEventForm.getAncestorOfType(UIPopupContainer.class);
UIPopupAction uiPopupAction = uiPopupContainer.getChild(UIPopupAction.class);
uiPortlet.cancelAction();
uiPopupAction.deActivate();
}
}
/**
* This method was called when user saves event from event form
* @param event save event
* @param isSend send mail or not
* @throws Exception
*/
private void confirmSaveEvent(Event<UIEventForm> event, boolean isSend) throws Exception {
UIEventForm uiEventForm = event.getSource();
UICalendarPortlet uiPortlet = uiEventForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupContainer uiPopupContainer = uiEventForm.getAncestorOfType(UIPopupContainer.class);
UIPopupAction uiPopupAction = uiPopupContainer.getChild(UIPopupAction.class);
uiPopupAction.deActivate();
CalendarSetting calSetting = uiPortlet.getCalendarSetting();
Date fromDate = uiEventForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
// if it's a virtual recurrence
CalendarEvent occurrence = uiEventForm.calendarEvent_;
if (occurrence != null && !CalendarEvent.RP_NOREPEAT.equals(occurrence.getRepeatType())
&& !CalendarUtils.isEmpty(occurrence.getRecurrenceId()) && CalendarUtils.isSameDate(fromDate, occurrence.getFromDateTime()) ) {
// popup confirm form
UIConfirmForm confirmForm = uiPopupAction.activate(UIConfirmForm.class, 600);
confirmForm.setConfirmMessage(uiEventForm.getLabel("update-recurrence-event-confirm-msg"));
confirmForm.setConfig_id(uiEventForm.getId()) ;
String[] actions = new String[] {"ConfirmUpdateOnlyInstance", "ConfirmUpdateAllSeries", "ConfirmUpdateCancel"};
confirmForm.setActions(actions);
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
} else {
uiEventForm.saveAndNoAsk(event, isSend, false);
}
}
public class ParticipantStatus {
private String participant ;
private String name ;
private String email ;
private String status ;
public ParticipantStatus(String participant, String status) throws Exception {
this.participant = participant;
User user = CalendarUtils.getOrganizationService().getUserHandler().findUserByName(participant);
if (user != null) {
this.name = UIEventAttenderTab.getFullname(participant);
this.email = user.getEmail();
} else if (participant.matches(CalendarUtils.contactRegex)) {
this.name = participant.substring(0, participant.lastIndexOf(CalendarUtils.OPEN_PARENTHESIS));
this.email = participant.substring(participant.lastIndexOf(CalendarUtils.OPEN_PARENTHESIS) + 1)
.replace(CalendarUtils.CLOSE_PARENTHESIS, "");
} else {
this.name = participant;
this.email = participant;
}
this.status = status;
}
public String getParticipant() throws Exception {
return participant;
}
public void setParticipant(String participant) {
this.participant = participant;
}
public String getName() throws Exception {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() throws Exception {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
}
| false | true | public void saveAndNoAsk(Event<UIEventForm> event, boolean isSend, boolean updateSeries)throws Exception {
UIEventForm uiForm = event.getSource() ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupAction uiPopupAction = uiForm.getAncestorOfType(UIPopupAction.class) ;
UICalendarViewContainer uiViewContainer = calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
CalendarSetting calSetting = calendarPortlet.getCalendarSetting() ;
CalendarService calService = CalendarUtils.getCalendarService() ;
String summary = uiForm.getEventSumary().trim() ;
summary = CalendarUtils.enCodeTitle(summary);
String location = uiForm.getEventPlace() ;
if(!CalendarUtils.isEmpty(location)) location = location.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
String description = uiForm.getEventDescription() ;
if(!CalendarUtils.isEmpty(description)) description = description.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
if(!uiForm.isEventDetailValid(calSetting)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, null));
uiForm.setSelectedTab(TAB_EVENTDETAIL) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isReminderValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] {uiForm.errorValues} ));
uiForm.setSelectedTab(TAB_EVENTREMINDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isParticipantValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] { uiForm.errorValues }));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
Date from = uiForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
Date to = uiForm.getEventToDate(calSetting.getDateFormat(),calSetting.getTimeFormat()) ;
if(from.after(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.event-date-time-logic", null, AbstractApplicationMessage.WARNING)) ;
return ;
}
String username = CalendarUtils.getCurrentUser() ;
String calendarId = uiForm.getCalendarId() ;
if(from.equals(to)) {
to = CalendarUtils.getEndDay(from).getTime() ;
}
if(uiForm.getEventAllDate()) {
java.util.Calendar tempCal = CalendarUtils.getInstanceOfCurrentCalendar() ;
tempCal.setTime(to) ;
tempCal.add(java.util.Calendar.MILLISECOND, -1) ;
to = tempCal.getTime() ;
}
Calendar currentCalendar = CalendarUtils.getCalendar(uiForm.calType_, calendarId);
if(currentCalendar == null) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
return ;
}
boolean canEdit = false ;
if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)) {
canEdit = CalendarUtils.canEdit(null, org.exoplatform.calendar.service.Utils.getEditPerUsers(currentCalendar), username) ;
} else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)) {
canEdit = CalendarUtils.canEdit(
CalendarUtils.getOrganizationService(), currentCalendar.getEditPermission(), username) ;
}
if(!canEdit && !uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE) ) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-permission-to-edit", null,1));
return ;
}
CalendarEvent calendarEvent = null ;
CalendarEvent oldCalendarEvent = null;
String[] pars = uiForm.getParticipantValues().split(CalendarUtils.BREAK_LINE) ;
String eventId = null ;
if(uiForm.isAddNew_){
calendarEvent = new CalendarEvent() ;
} else {
calendarEvent = uiForm.calendarEvent_ ;
oldCalendarEvent = new CalendarEvent();
oldCalendarEvent.setSummary(calendarEvent.getSummary());
oldCalendarEvent.setDescription(calendarEvent.getDescription());
oldCalendarEvent.setLocation(calendarEvent.getLocation());
oldCalendarEvent.setFromDateTime(calendarEvent.getFromDateTime());
oldCalendarEvent.setToDateTime(calendarEvent.getToDateTime());
}
calendarEvent.setFromDateTime(from) ;
calendarEvent.setToDateTime(to);
calendarEvent.setSendOption(uiForm.getSendOption());
calendarEvent.setMessage(uiForm.getMessage());
String[] parStatus = uiForm.getParticipantStatusValues().split(CalendarUtils.BREAK_LINE) ;
calendarEvent.setParticipantStatus(parStatus);
calendarEvent.setParticipant(pars) ;
if(CalendarUtils.isEmpty(uiForm.getInvitationEmail())) calendarEvent.setInvitation(ArrayUtils.EMPTY_STRING_ARRAY);
else
if(CalendarUtils.isValidEmailAddresses(uiForm.getInvitationEmail())) {
String addressList = uiForm.getInvitationEmail().replaceAll(CalendarUtils.SEMICOLON,CalendarUtils.COMMA) ;
Map<String, String> emails = new LinkedHashMap<String, String>() ;
for(String email : addressList.split(CalendarUtils.COMMA)) {
String address = email.trim() ;
if (!emails.containsKey(address)) emails.put(address, address) ;
}
if(!emails.isEmpty()) calendarEvent.setInvitation(emails.keySet().toArray(new String[emails.size()])) ;
} else {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.event-email-invalid"
, new String[] { CalendarUtils.invalidEmailAddresses(uiForm.getInvitationEmail())}));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
calendarEvent.setCalendarId(uiForm.getCalendarId()) ;
calendarEvent.setEventType(CalendarEvent.TYPE_EVENT) ;
calendarEvent.setSummary(summary) ;
calendarEvent.setDescription(description) ;
calendarEvent.setCalType(uiForm.calType_) ;
calendarEvent.setCalendarId(calendarId) ;
calendarEvent.setEventCategoryId(uiForm.getEventCategory()) ;
UIFormSelectBox selectBox = ((UIFormInputWithActions)uiForm.getChildById(TAB_EVENTDETAIL))
.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY) ;
for (SelectItemOption<String> o : selectBox.getOptions()) {
if (o.getValue().equals(selectBox.getValue())) {
calendarEvent.setEventCategoryName(o.getLabel()) ;
break ;
}
}
calendarEvent.setLocation(location) ;
if (uiForm.getEventIsRepeat()) {
if (repeatEvent != null) {
// copy repeat properties from repeatEvent to calendarEvent
calendarEvent.setRepeatType(repeatEvent.getRepeatType());
calendarEvent.setRepeatInterval(repeatEvent.getRepeatInterval());
calendarEvent.setRepeatCount(repeatEvent.getRepeatCount());
calendarEvent.setRepeatUntilDate(repeatEvent.getRepeatUntilDate());
calendarEvent.setRepeatByDay(repeatEvent.getRepeatByDay());
calendarEvent.setRepeatByMonthDay(repeatEvent.getRepeatByMonthDay());
}
} else {
calendarEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
calendarEvent.setRepeatInterval(0);
calendarEvent.setRepeatCount(0);
calendarEvent.setRepeatUntilDate(null);
calendarEvent.setRepeatByDay(null);
calendarEvent.setRepeatByMonthDay(null);
}
calendarEvent.setPriority(uiForm.getEventPriority()) ;
calendarEvent.setPrivate(UIEventForm.ITEM_PRIVATE.equals(uiForm.getShareType())) ;
calendarEvent.setEventState(uiForm.getEventState()) ;
calendarEvent.setAttachment(uiForm.getAttachments(calendarEvent.getId(), uiForm.isAddNew_)) ;
calendarEvent.setReminders(uiForm.getEventReminders(from, calendarEvent.getReminders())) ;
eventId = calendarEvent.getId() ;
CalendarView calendarView = (CalendarView)uiViewContainer.getRenderedChild() ;
this.isChangedSignificantly = this.isSignificantChanged(calendarEvent, oldCalendarEvent);
try {
if (calendarEvent != null && isSend) {
try {
CalendarEvent tempCal = sendInvitation(event, calSetting, calendarEvent);
calendarEvent = tempCal != null ? tempCal : calendarEvent;
} catch (Exception e) {
if (LOG.isWarnEnabled()) LOG.warn("Sending invitation failed!" , e);
}
}
if(uiForm.isAddNew_){
if(uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE)) {
calService.saveUserEvent(username, calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)){
calService.saveEventToSharedCalendar(username , calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)){
calService.savePublicEvent(calendarId, calendarEvent, uiForm.isAddNew_) ;
}
} else {
String fromCal = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String toCal = uiForm.newCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String fromType = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
String toType = uiForm.newCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
listEvent.add(calendarEvent) ;
// if the event (before change) is a virtual occurrence
if (!uiForm.calendarEvent_.getRepeatType().equals(CalendarEvent.RP_NOREPEAT) && !CalendarUtils.isEmpty(uiForm.calendarEvent_.getRecurrenceId())) {
if (!updateSeries) {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
} else {
// update series:
if (CalendarUtils.isSameDate(oldCalendarEvent.getFromDateTime(), calendarEvent.getFromDateTime())) {
calService.updateRecurrenceSeries(fromCal, toCal, fromType, toType, calendarEvent, username);
}
else {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
}
}
}
else {
if (org.exoplatform.calendar.service.Utils.isExceptionOccurrence(calendarEvent_)) calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
else calService.moveEvent(fromCal, toCal, fromType, toType, listEvent, username) ;
}
UITaskForm.updateListView(calendarView, calendarEvent, calService, username);
}
if(calendarView instanceof UIListContainer) {
UIListContainer uiListContainer = (UIListContainer)calendarView ;
if (!uiListContainer.isDisplaySearchResult()) {
uiViewContainer.refresh() ;
}
} else {
uiViewContainer.refresh() ;
}
calendarView.setLastUpdatedEventId(eventId) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ;
UIMiniCalendar uiMiniCalendar = calendarPortlet.findFirstComponentOfType(UIMiniCalendar.class) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar) ;
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
}catch (Exception e) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.add-event-error", null));
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to add the event", e);
}
}
UIEventDetailTab uiDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
for (Attachment att : uiDetailTab.getAttachments()) {
UIAttachFileForm.removeUploadTemp(uiForm.getApplicationComponent(UploadService.class), att.getResourceId()) ;
}
}
| public void saveAndNoAsk(Event<UIEventForm> event, boolean isSend, boolean updateSeries)throws Exception {
UIEventForm uiForm = event.getSource() ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UIPopupAction uiPopupAction = uiForm.getAncestorOfType(UIPopupAction.class) ;
UICalendarViewContainer uiViewContainer = calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
CalendarSetting calSetting = calendarPortlet.getCalendarSetting() ;
CalendarService calService = CalendarUtils.getCalendarService() ;
String summary = uiForm.getEventSumary().trim() ;
summary = CalendarUtils.enCodeTitle(summary);
String location = uiForm.getEventPlace() ;
if(!CalendarUtils.isEmpty(location)) {
location = location.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
}
else {
location = null;
}
String description = uiForm.getEventDescription() ;
if(!CalendarUtils.isEmpty(description)) {
description = description.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,"") ;
}
else {
description = null;
}
if(!uiForm.isEventDetailValid(calSetting)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, null));
uiForm.setSelectedTab(TAB_EVENTDETAIL) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isReminderValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] {uiForm.errorValues} ));
uiForm.setSelectedTab(TAB_EVENTREMINDER) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
if(!uiForm.isParticipantValid()) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] { uiForm.errorValues }));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
Date from = uiForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat()) ;
Date to = uiForm.getEventToDate(calSetting.getDateFormat(),calSetting.getTimeFormat()) ;
if(from.after(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.event-date-time-logic", null, AbstractApplicationMessage.WARNING)) ;
return ;
}
String username = CalendarUtils.getCurrentUser() ;
String calendarId = uiForm.getCalendarId() ;
if(from.equals(to)) {
to = CalendarUtils.getEndDay(from).getTime() ;
}
if(uiForm.getEventAllDate()) {
java.util.Calendar tempCal = CalendarUtils.getInstanceOfCurrentCalendar() ;
tempCal.setTime(to) ;
tempCal.add(java.util.Calendar.MILLISECOND, -1) ;
to = tempCal.getTime() ;
}
Calendar currentCalendar = CalendarUtils.getCalendar(uiForm.calType_, calendarId);
if(currentCalendar == null) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
return ;
}
boolean canEdit = false ;
if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)) {
canEdit = CalendarUtils.canEdit(null, org.exoplatform.calendar.service.Utils.getEditPerUsers(currentCalendar), username) ;
} else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)) {
canEdit = CalendarUtils.canEdit(
CalendarUtils.getOrganizationService(), currentCalendar.getEditPermission(), username) ;
}
if(!canEdit && !uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE) ) {
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UICalendars.msg.have-no-permission-to-edit", null,1));
return ;
}
CalendarEvent calendarEvent = null ;
CalendarEvent oldCalendarEvent = null;
String[] pars = uiForm.getParticipantValues().split(CalendarUtils.BREAK_LINE) ;
String eventId = null ;
if(uiForm.isAddNew_){
calendarEvent = new CalendarEvent() ;
} else {
calendarEvent = uiForm.calendarEvent_ ;
oldCalendarEvent = new CalendarEvent();
oldCalendarEvent.setSummary(calendarEvent.getSummary());
oldCalendarEvent.setDescription(calendarEvent.getDescription());
oldCalendarEvent.setLocation(calendarEvent.getLocation());
oldCalendarEvent.setFromDateTime(calendarEvent.getFromDateTime());
oldCalendarEvent.setToDateTime(calendarEvent.getToDateTime());
}
calendarEvent.setFromDateTime(from) ;
calendarEvent.setToDateTime(to);
calendarEvent.setSendOption(uiForm.getSendOption());
calendarEvent.setMessage(uiForm.getMessage());
String[] parStatus = uiForm.getParticipantStatusValues().split(CalendarUtils.BREAK_LINE) ;
calendarEvent.setParticipantStatus(parStatus);
calendarEvent.setParticipant(pars) ;
if(CalendarUtils.isEmpty(uiForm.getInvitationEmail())) calendarEvent.setInvitation(ArrayUtils.EMPTY_STRING_ARRAY);
else
if(CalendarUtils.isValidEmailAddresses(uiForm.getInvitationEmail())) {
String addressList = uiForm.getInvitationEmail().replaceAll(CalendarUtils.SEMICOLON,CalendarUtils.COMMA) ;
Map<String, String> emails = new LinkedHashMap<String, String>() ;
for(String email : addressList.split(CalendarUtils.COMMA)) {
String address = email.trim() ;
if (!emails.containsKey(address)) emails.put(address, address) ;
}
if(!emails.isEmpty()) calendarEvent.setInvitation(emails.keySet().toArray(new String[emails.size()])) ;
} else {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.event-email-invalid"
, new String[] { CalendarUtils.invalidEmailAddresses(uiForm.getInvitationEmail())}));
uiForm.setSelectedTab(TAB_EVENTSHARE) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class)) ;
return ;
}
calendarEvent.setCalendarId(uiForm.getCalendarId()) ;
calendarEvent.setEventType(CalendarEvent.TYPE_EVENT) ;
calendarEvent.setSummary(summary) ;
calendarEvent.setDescription(description) ;
calendarEvent.setCalType(uiForm.calType_) ;
calendarEvent.setCalendarId(calendarId) ;
calendarEvent.setEventCategoryId(uiForm.getEventCategory()) ;
UIFormSelectBox selectBox = ((UIFormInputWithActions)uiForm.getChildById(TAB_EVENTDETAIL))
.getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY) ;
for (SelectItemOption<String> o : selectBox.getOptions()) {
if (o.getValue().equals(selectBox.getValue())) {
calendarEvent.setEventCategoryName(o.getLabel()) ;
break ;
}
}
calendarEvent.setLocation(location) ;
if (uiForm.getEventIsRepeat()) {
if (repeatEvent != null) {
// copy repeat properties from repeatEvent to calendarEvent
calendarEvent.setRepeatType(repeatEvent.getRepeatType());
calendarEvent.setRepeatInterval(repeatEvent.getRepeatInterval());
calendarEvent.setRepeatCount(repeatEvent.getRepeatCount());
calendarEvent.setRepeatUntilDate(repeatEvent.getRepeatUntilDate());
calendarEvent.setRepeatByDay(repeatEvent.getRepeatByDay());
calendarEvent.setRepeatByMonthDay(repeatEvent.getRepeatByMonthDay());
}
} else {
calendarEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
calendarEvent.setRepeatInterval(0);
calendarEvent.setRepeatCount(0);
calendarEvent.setRepeatUntilDate(null);
calendarEvent.setRepeatByDay(null);
calendarEvent.setRepeatByMonthDay(null);
}
calendarEvent.setPriority(uiForm.getEventPriority()) ;
calendarEvent.setPrivate(UIEventForm.ITEM_PRIVATE.equals(uiForm.getShareType())) ;
calendarEvent.setEventState(uiForm.getEventState()) ;
calendarEvent.setAttachment(uiForm.getAttachments(calendarEvent.getId(), uiForm.isAddNew_)) ;
calendarEvent.setReminders(uiForm.getEventReminders(from, calendarEvent.getReminders())) ;
eventId = calendarEvent.getId() ;
CalendarView calendarView = (CalendarView)uiViewContainer.getRenderedChild() ;
this.isChangedSignificantly = this.isSignificantChanged(calendarEvent, oldCalendarEvent);
try {
if (calendarEvent != null && isSend) {
try {
CalendarEvent tempCal = sendInvitation(event, calSetting, calendarEvent);
calendarEvent = tempCal != null ? tempCal : calendarEvent;
} catch (Exception e) {
if (LOG.isWarnEnabled()) LOG.warn("Sending invitation failed!" , e);
}
}
if(uiForm.isAddNew_){
if(uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE)) {
calService.saveUserEvent(username, calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)){
calService.saveEventToSharedCalendar(username , calendarId, calendarEvent, uiForm.isAddNew_) ;
}else if(uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)){
calService.savePublicEvent(calendarId, calendarEvent, uiForm.isAddNew_) ;
}
} else {
String fromCal = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String toCal = uiForm.newCalendarId_.split(CalendarUtils.COLON)[1].trim() ;
String fromType = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
String toType = uiForm.newCalendarId_.split(CalendarUtils.COLON)[0].trim() ;
List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
listEvent.add(calendarEvent) ;
// if the event (before change) is a virtual occurrence
if (!uiForm.calendarEvent_.getRepeatType().equals(CalendarEvent.RP_NOREPEAT) && !CalendarUtils.isEmpty(uiForm.calendarEvent_.getRecurrenceId())) {
if (!updateSeries) {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
} else {
// update series:
if (CalendarUtils.isSameDate(oldCalendarEvent.getFromDateTime(), calendarEvent.getFromDateTime())) {
calService.updateRecurrenceSeries(fromCal, toCal, fromType, toType, calendarEvent, username);
}
else {
calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
}
}
}
else {
if (org.exoplatform.calendar.service.Utils.isExceptionOccurrence(calendarEvent_)) calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
else calService.moveEvent(fromCal, toCal, fromType, toType, listEvent, username) ;
}
UITaskForm.updateListView(calendarView, calendarEvent, calService, username);
}
if(calendarView instanceof UIListContainer) {
UIListContainer uiListContainer = (UIListContainer)calendarView ;
if (!uiListContainer.isDisplaySearchResult()) {
uiViewContainer.refresh() ;
}
} else {
uiViewContainer.refresh() ;
}
calendarView.setLastUpdatedEventId(eventId) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ;
UIMiniCalendar uiMiniCalendar = calendarPortlet.findFirstComponentOfType(UIMiniCalendar.class) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar) ;
uiPopupAction.deActivate() ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction) ;
}catch (Exception e) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIEventForm.msg.add-event-error", null));
if (LOG.isDebugEnabled()) {
LOG.debug("Fail to add the event", e);
}
}
UIEventDetailTab uiDetailTab = uiForm.getChildById(TAB_EVENTDETAIL) ;
for (Attachment att : uiDetailTab.getAttachments()) {
UIAttachFileForm.removeUploadTemp(uiForm.getApplicationComponent(UploadService.class), att.getResourceId()) ;
}
}
|
diff --git a/src/net/idlesoft/android/apps/github/activities/Profile.java b/src/net/idlesoft/android/apps/github/activities/Profile.java
index 1e93826..9a963e9 100644
--- a/src/net/idlesoft/android/apps/github/activities/Profile.java
+++ b/src/net/idlesoft/android/apps/github/activities/Profile.java
@@ -1,218 +1,221 @@
/**
* Hubroid - A GitHub app for Android
*
* Copyright (c) 2011 Eddie Ringle.
*
* Licensed under the New BSD License.
*/
package net.idlesoft.android.apps.github.activities;
import java.io.IOException;
import net.idlesoft.android.apps.github.R;
import net.idlesoft.android.apps.github.adapters.InfoListAdapter;
import net.idlesoft.android.apps.github.utils.GravatarCache;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.service.UserService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Profile extends BaseActivity {
public JSONObject mJson;
public JSONArray mJsonFollowing;
private String mTarget;
private Bitmap mGravatar;
private User mUser = null;
protected boolean IsNotNullNorEmpty(final String subject)
{
if (subject != null && !subject.equals("")) {
return true;
} else {
return false;
}
}
protected JSONObject buildListItem(final String title, final String content)
throws JSONException {
return new JSONObject().put("title", title).put("content", content);
}
protected void buildUI()
{
if (mUser != null) {
((ImageView) findViewById(R.id.iv_profile_gravatar)).setImageBitmap(mGravatar);
((TextView) findViewById(R.id.tv_profile_username)).setText(mTarget);
final JSONArray listItems = new JSONArray();
try {
if (IsNotNullNorEmpty(mUser.getName())) {
listItems.put(buildListItem("Name", mUser.getName()));
}
if (IsNotNullNorEmpty(mUser.getCompany())) {
listItems.put(buildListItem("Company", mUser.getCompany()));
}
if (IsNotNullNorEmpty(mUser.getEmail())) {
listItems.put(buildListItem("Email", mUser.getEmail()));
}
if (IsNotNullNorEmpty(mUser.getBlog())) {
listItems.put(buildListItem("Blog", mUser.getBlog()));
}
if (IsNotNullNorEmpty(mUser.getLocation())) {
listItems.put(buildListItem("Location", mUser.getLocation()));
}
listItems.put(buildListItem("Public Activity", "View " + mTarget + "'s public activity"));
listItems.put(buildListItem("Repositories",
Integer.toString(mUser.getPublicRepos()
+ mUser.getTotalPrivateRepos())));
listItems.put(buildListItem("Followers / Following",
Integer.toString(mUser.getFollowers()) + " / "
+ Integer.toString(mUser.getFollowing())));
listItems.put(buildListItem("Gists",
Integer.toString(mUser.getPublicGists()
+ mUser.getPrivateGists())));
if (IsNotNullNorEmpty(mUser.getCreatedAt().toString())) {
listItems.put(buildListItem("Join Date",
mUser.getCreatedAt().toString()));
}
} catch (JSONException e) {
e.printStackTrace();
}
final ListView infoList = (ListView) findViewById(R.id.lv_profile_info);
final InfoListAdapter adapter = new InfoListAdapter(this, infoList);
adapter.loadData(listItems);
adapter.pushData();
infoList.setAdapter(adapter);
infoList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v,
final int position, final long id) {
try {
final String title = ((JSONObject) listItems.get(position))
.getString("title");
- final String content = ((JSONObject) listItems.get(position))
+ String content = ((JSONObject) listItems.get(position))
.getString("content");
final Intent intent;
if (title.equals("Email")) {
intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, content);
} else if (title.equals("Blog")) {
+ if (content.indexOf("://") == -1) {
+ content = "http://" + content;
+ }
intent = new Intent("android.intent.action.VIEW", Uri.parse(content));
} else if (title.equals("Public Activity")) {
intent = new Intent(Profile.this, NewsFeed.class);
intent.putExtra("username", mTarget);
} else if (title.equals("Repositories")) {
intent = new Intent(Profile.this, Repositories.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Followers / Following")) {
intent = new Intent(Profile.this, Users.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Gists")) {
intent = new Intent(Profile.this, Gists.class);
intent.putExtra("target", mTarget);
} else {
return;
}
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
private static class LoadProfileTask extends AsyncTask<Void, Void, Boolean> {
public Profile activity;
protected void onPreExecute() {
super.onPreExecute();
activity.getActionBar().setProgressBarVisibility(View.VISIBLE);
}
protected Boolean doInBackground(Void... params) {
UserService service = new UserService(activity.getGitHubClient());
try {
if (activity.mTarget.equalsIgnoreCase(activity.mUsername)) {
activity.mUser = service.getUser();
} else {
activity.mUser = service.getUser(activity.mTarget);
}
activity.mGravatar = GravatarCache.getDipGravatar(
GravatarCache.getGravatarID(activity.mTarget), 50.0f,
activity.getResources().getDisplayMetrics().density);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
protected void onPostExecute(Boolean result) {
if (result) {
activity.buildUI();
activity.getActionBar().setProgressBarVisibility(View.GONE);
} else {
Toast.makeText(activity, "Failed to load user profile.", Toast.LENGTH_SHORT).show();
activity.finish();
}
super.onPostExecute(result);
}
}
private LoadProfileTask mTask;
@Override
public void onCreate(final Bundle icicle) {
super.onCreate(icicle, R.layout.profile);
setupActionBar();
final Bundle extras = getIntent().getExtras();
if (extras != null) {
mTarget = extras.getString("username");
}
if (mTarget == null) {
mTarget = mUsername;
}
((TextView) findViewById(R.id.tv_profile_username)).setText(mTarget);
mTask = (LoadProfileTask) getLastNonConfigurationInstance();
if (mTask == null) {
mTask = new LoadProfileTask();
}
mTask.activity = Profile.this;
if (mTask.getStatus() == AsyncTask.Status.PENDING) {
mTask.execute();
}
}
public Object onRetainNonConfigurationInstance() {
return mTask;
}
}
| false | true | protected void buildUI()
{
if (mUser != null) {
((ImageView) findViewById(R.id.iv_profile_gravatar)).setImageBitmap(mGravatar);
((TextView) findViewById(R.id.tv_profile_username)).setText(mTarget);
final JSONArray listItems = new JSONArray();
try {
if (IsNotNullNorEmpty(mUser.getName())) {
listItems.put(buildListItem("Name", mUser.getName()));
}
if (IsNotNullNorEmpty(mUser.getCompany())) {
listItems.put(buildListItem("Company", mUser.getCompany()));
}
if (IsNotNullNorEmpty(mUser.getEmail())) {
listItems.put(buildListItem("Email", mUser.getEmail()));
}
if (IsNotNullNorEmpty(mUser.getBlog())) {
listItems.put(buildListItem("Blog", mUser.getBlog()));
}
if (IsNotNullNorEmpty(mUser.getLocation())) {
listItems.put(buildListItem("Location", mUser.getLocation()));
}
listItems.put(buildListItem("Public Activity", "View " + mTarget + "'s public activity"));
listItems.put(buildListItem("Repositories",
Integer.toString(mUser.getPublicRepos()
+ mUser.getTotalPrivateRepos())));
listItems.put(buildListItem("Followers / Following",
Integer.toString(mUser.getFollowers()) + " / "
+ Integer.toString(mUser.getFollowing())));
listItems.put(buildListItem("Gists",
Integer.toString(mUser.getPublicGists()
+ mUser.getPrivateGists())));
if (IsNotNullNorEmpty(mUser.getCreatedAt().toString())) {
listItems.put(buildListItem("Join Date",
mUser.getCreatedAt().toString()));
}
} catch (JSONException e) {
e.printStackTrace();
}
final ListView infoList = (ListView) findViewById(R.id.lv_profile_info);
final InfoListAdapter adapter = new InfoListAdapter(this, infoList);
adapter.loadData(listItems);
adapter.pushData();
infoList.setAdapter(adapter);
infoList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v,
final int position, final long id) {
try {
final String title = ((JSONObject) listItems.get(position))
.getString("title");
final String content = ((JSONObject) listItems.get(position))
.getString("content");
final Intent intent;
if (title.equals("Email")) {
intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, content);
} else if (title.equals("Blog")) {
intent = new Intent("android.intent.action.VIEW", Uri.parse(content));
} else if (title.equals("Public Activity")) {
intent = new Intent(Profile.this, NewsFeed.class);
intent.putExtra("username", mTarget);
} else if (title.equals("Repositories")) {
intent = new Intent(Profile.this, Repositories.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Followers / Following")) {
intent = new Intent(Profile.this, Users.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Gists")) {
intent = new Intent(Profile.this, Gists.class);
intent.putExtra("target", mTarget);
} else {
return;
}
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
| protected void buildUI()
{
if (mUser != null) {
((ImageView) findViewById(R.id.iv_profile_gravatar)).setImageBitmap(mGravatar);
((TextView) findViewById(R.id.tv_profile_username)).setText(mTarget);
final JSONArray listItems = new JSONArray();
try {
if (IsNotNullNorEmpty(mUser.getName())) {
listItems.put(buildListItem("Name", mUser.getName()));
}
if (IsNotNullNorEmpty(mUser.getCompany())) {
listItems.put(buildListItem("Company", mUser.getCompany()));
}
if (IsNotNullNorEmpty(mUser.getEmail())) {
listItems.put(buildListItem("Email", mUser.getEmail()));
}
if (IsNotNullNorEmpty(mUser.getBlog())) {
listItems.put(buildListItem("Blog", mUser.getBlog()));
}
if (IsNotNullNorEmpty(mUser.getLocation())) {
listItems.put(buildListItem("Location", mUser.getLocation()));
}
listItems.put(buildListItem("Public Activity", "View " + mTarget + "'s public activity"));
listItems.put(buildListItem("Repositories",
Integer.toString(mUser.getPublicRepos()
+ mUser.getTotalPrivateRepos())));
listItems.put(buildListItem("Followers / Following",
Integer.toString(mUser.getFollowers()) + " / "
+ Integer.toString(mUser.getFollowing())));
listItems.put(buildListItem("Gists",
Integer.toString(mUser.getPublicGists()
+ mUser.getPrivateGists())));
if (IsNotNullNorEmpty(mUser.getCreatedAt().toString())) {
listItems.put(buildListItem("Join Date",
mUser.getCreatedAt().toString()));
}
} catch (JSONException e) {
e.printStackTrace();
}
final ListView infoList = (ListView) findViewById(R.id.lv_profile_info);
final InfoListAdapter adapter = new InfoListAdapter(this, infoList);
adapter.loadData(listItems);
adapter.pushData();
infoList.setAdapter(adapter);
infoList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v,
final int position, final long id) {
try {
final String title = ((JSONObject) listItems.get(position))
.getString("title");
String content = ((JSONObject) listItems.get(position))
.getString("content");
final Intent intent;
if (title.equals("Email")) {
intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, content);
} else if (title.equals("Blog")) {
if (content.indexOf("://") == -1) {
content = "http://" + content;
}
intent = new Intent("android.intent.action.VIEW", Uri.parse(content));
} else if (title.equals("Public Activity")) {
intent = new Intent(Profile.this, NewsFeed.class);
intent.putExtra("username", mTarget);
} else if (title.equals("Repositories")) {
intent = new Intent(Profile.this, Repositories.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Followers / Following")) {
intent = new Intent(Profile.this, Users.class);
intent.putExtra("target", mTarget);
} else if (title.equals("Gists")) {
intent = new Intent(Profile.this, Gists.class);
intent.putExtra("target", mTarget);
} else {
return;
}
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java b/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
index fb3bef77e..040f992d3 100644
--- a/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
@@ -1,441 +1,443 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.client.gui.plaf.FreeColComboBoxRenderer;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.model.pathfinding.CostDeciders;
import net.sf.freecol.common.model.pathfinding.GoalDecider;
import net.sf.freecol.common.util.Utils;
/**
* Centers the map on a known settlement or colony.
*/
public final class SelectDestinationDialog extends FreeColDialog<Location>
implements ActionListener, ChangeListener, ItemListener {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(SelectDestinationDialog.class.getName());
private static boolean showOnlyMyColonies = true;
private static Comparator<Destination> destinationComparator = null;
private final JCheckBox onlyMyColoniesBox;
private final JComboBox comparatorBox;
private final JList destinationList;
private final List<Destination> destinations = new ArrayList<Destination>();
/**
* The constructor to use.
*/
public SelectDestinationDialog(Canvas parent, Unit unit) {
super(parent);
final Settlement inSettlement = unit.getSettlement();
// Collect the goods the unit is carrying.
List<GoodsType> goodsTypeList = new ArrayList<GoodsType>();
for (Goods goods : unit.getGoodsList()) {
goodsTypeList.add(goods.getType());
}
final List<GoodsType> goodsTypes = goodsTypeList;
// Search for destinations we can reach:
getGame().getMap().search(unit, unit.getTile(), new GoalDecider() {
public PathNode getGoal() {
return null;
}
public boolean check(Unit u, PathNode p) {
Settlement settlement = p.getTile().getSettlement();
if (settlement != null && settlement != inSettlement) {
String extras = (settlement.getOwner() != u.getOwner())
? getExtras(u, settlement, goodsTypes) : "";
destinations.add(new Destination(settlement, p.getTurns(), extras));
}
return false;
}
public boolean hasSubGoals() {
return false;
}
}, CostDeciders.avoidIllegal(), Integer.MAX_VALUE);
if (destinationComparator == null) {
destinationComparator = new DestinationComparator(getMyPlayer());
}
Collections.sort(destinations, destinationComparator);
if (unit.isNaval() && unit.getOwner().canMoveToEurope()) {
PathNode path = unit.findPathToEurope();
- if (path != null) {
+ int turns = (path != null)
+ ? unit.getSailTurns() + path.getTotalTurns()
+ : (unit.getTile() != null
+ && (unit.getTile().canMoveToEurope()
+ || unit.getTile().isAdjacentToMapEdge()))
+ ? unit.getSailTurns()
+ : -1;
+ if (turns >= 0) {
Europe europe = getMyPlayer().getEurope();
- destinations.add(0, new Destination(europe, path.getTotalTurns(),
- getExtras(unit, europe, goodsTypes)));
- } else if (unit.getTile() != null
- && (unit.getTile().canMoveToEurope()
- || unit.getTile().isAdjacentToMapEdge())) {
- Europe europe = getMyPlayer().getEurope();
- destinations.add(0, new Destination(europe, 0,
- getExtras(unit, europe, goodsTypes)));
+ destinations.add(0,
+ new Destination(europe, turns,
+ getExtras(unit, europe, goodsTypes)));
}
}
MigLayout layout = new MigLayout("wrap 1, fill", "[align center]", "");
setLayout(layout);
JLabel header = new JLabel(Messages.message("selectDestination.text"));
header.setFont(smallHeaderFont);
add(header);
DefaultListModel model = new DefaultListModel();
destinationList = new JList(model);
filterDestinations();
destinationList.setCellRenderer(new LocationRenderer());
destinationList.setFixedCellHeight(48);
Action selectAction = new AbstractAction(Messages.message("ok")) {
public void actionPerformed(ActionEvent e) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
};
Action quitAction = new AbstractAction(Messages.message("selectDestination.cancel")) {
public void actionPerformed(ActionEvent e) {
getCanvas().remove(SelectDestinationDialog.this);
}
};
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "select");
destinationList.getActionMap().put("select", selectAction);
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
destinationList.getActionMap().put("quit", quitAction);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
}
};
destinationList.addMouseListener(mouseListener);
JScrollPane listScroller = new JScrollPane(destinationList);
listScroller.setPreferredSize(new Dimension(250, 250));
add(listScroller, "newline 30, growx, growy");
onlyMyColoniesBox = new JCheckBox(Messages.message("selectDestination.onlyMyColonies"),
showOnlyMyColonies);
onlyMyColoniesBox.addChangeListener(this);
add(onlyMyColoniesBox, "left");
comparatorBox = new JComboBox(new String[] {
Messages.message("selectDestination.sortByOwner"),
Messages.message("selectDestination.sortByName"),
Messages.message("selectDestination.sortByDistance")
});
comparatorBox.addItemListener(this);
if (destinationComparator instanceof DestinationComparator) {
comparatorBox.setSelectedIndex(0);
} else if (destinationComparator instanceof NameComparator) {
comparatorBox.setSelectedIndex(1);
} else if (destinationComparator instanceof DistanceComparator) {
comparatorBox.setSelectedIndex(2);
}
add(comparatorBox, "left");
cancelButton.setAction(quitAction);
okButton.setAction(selectAction);
add(okButton, "newline 30, split 2, tag ok");
add(cancelButton, "tag cancel");
setSize(getPreferredSize());
}
@Override
public void requestFocus() {
destinationList.requestFocus();
}
public void stateChanged(ChangeEvent event) {
showOnlyMyColonies = onlyMyColoniesBox.isSelected();
filterDestinations();
}
public void itemStateChanged(ItemEvent event) {
switch(comparatorBox.getSelectedIndex()) {
case 0:
default:
destinationComparator = new DestinationComparator(getMyPlayer());
break;
case 1:
destinationComparator = new NameComparator();
break;
case 2:
destinationComparator = new DistanceComparator();
break;
}
Collections.sort(destinations, destinationComparator);
filterDestinations();
}
/**
* Collected extra annotations of interest to a unit proposing to
* visit a location.
*
* @param unit The <code>Unit</code> proposing to visit.
* @param loc The <code>Location</code> to visit.
* @param goodsTypes A list of goods types the unit is carrying.
* @return A string containing interesting annotations about the visit
* or an empty string if nothing is of interest.
*/
private String getExtras(Unit unit, Location loc, List<GoodsType> goodsTypes) {
if (loc instanceof Europe && !goodsTypes.isEmpty()) {
Market market = unit.getOwner().getMarket();
List<String> sales = new ArrayList<String>();
for (GoodsType goodsType : goodsTypes) {
sales.add(Messages.message(goodsType.getNameKey()) + " "
+ Integer.toString(market.getSalePrice(goodsType, 1)));
}
if (!sales.isEmpty()) {
return "[" + Utils.join(", ", sales) + "]";
}
} else if (loc instanceof Settlement && !goodsTypes.isEmpty()) {
List<String> sales = new ArrayList<String>();
for (GoodsType goodsType : goodsTypes) {
String sale = unit.getOwner().getLastSaleString((Settlement) loc, goodsType);
if (sale != null) {
sales.add(Messages.message(goodsType.getNameKey())
+ " " + sale);
}
}
if (!sales.isEmpty()) {
return "[" + Utils.join(", ", sales) + "]";
}
} else if (loc instanceof IndianSettlement) {
IndianSettlement indianSettlement = (IndianSettlement) loc;
UnitType skill = indianSettlement.getLearnableSkill();
if (skill != null
&& unit.getType().canBeUpgraded(skill, ChangeType.NATIVES)) {
return "[" + Messages.message(skill.getNameKey()) + "]";
}
}
return "";
}
private void filterDestinations() {
DefaultListModel model = (DefaultListModel) destinationList.getModel();
Object selected = destinationList.getSelectedValue();
model.clear();
for (Destination d : destinations) {
if (showOnlyMyColonies) {
if (d.location instanceof Europe
|| (d.location instanceof Colony
&& ((Colony) d.location).getOwner() == getMyPlayer())) {
model.addElement(d);
}
} else {
model.addElement(d);
}
}
destinationList.setSelectedValue(selected, true);
if (destinationList.getSelectedIndex() == -1) {
destinationList.setSelectedIndex(0);
}
}
public int compareNames(Location dest1, Location dest2) {
String name1 = "";
if (dest1 instanceof Settlement) {
name1 = ((Settlement) dest1).getName();
} else if (dest1 instanceof Europe) {
return -1;
}
String name2 = "";
if (dest2 instanceof Settlement) {
name2 = ((Settlement) dest2).getName();
} else if (dest2 instanceof Europe) {
return 1;
}
return name1.compareTo(name2);
}
private class Destination {
public Location location;
public int turns;
public String extras;
public Destination(Location location, int turns, String extras) {
this.location = location;
this.turns = turns;
this.extras = extras;
}
}
private class LocationRenderer extends FreeColComboBoxRenderer {
@Override
public void setLabelValues(JLabel label, Object value) {
Destination d = (Destination) value;
Location location = d.location;
String name = "";
if (location instanceof Europe) {
Europe europe = (Europe) location;
name = Messages.message(europe.getNameKey());
label.setIcon(new ImageIcon(getLibrary().getCoatOfArmsImage(europe.getOwner().getNation())
.getScaledInstance(-1, 48, Image.SCALE_SMOOTH)));
} else if (location instanceof Settlement) {
Settlement settlement = (Settlement) location;
name = settlement.getName();
label.setIcon(new ImageIcon(getLibrary().getSettlementImage(settlement)
.getScaledInstance(64, -1, Image.SCALE_SMOOTH)));
}
label.setText(Messages.message("selectDestination.destinationTurns",
"%location%", name,
"%turns%", String.valueOf(d.turns),
"%extras%", d.extras));
}
}
private class DestinationComparator implements Comparator<Destination> {
private Player owner;
public DestinationComparator(Player player) {
this.owner = player;
}
public int compare(Destination choice1, Destination choice2) {
Location dest1 = choice1.location;
Location dest2 = choice2.location;
int score1 = 100;
if (dest1 instanceof Europe) {
score1 = 10;
} else if (dest1 instanceof Colony) {
if (((Colony) dest1).getOwner() == owner) {
score1 = 20;
} else {
score1 = 30;
}
} else if (dest1 instanceof IndianSettlement) {
score1 = 40;
}
int score2 = 100;
if (dest2 instanceof Europe) {
score2 = 10;
} else if (dest2 instanceof Colony) {
if (((Colony) dest2).getOwner() == owner) {
score2 = 20;
} else {
score2 = 30;
}
} else if (dest2 instanceof IndianSettlement) {
score2 = 40;
}
if (score1 == score2) {
return compareNames(dest1, dest2);
} else {
return score1 - score2;
}
}
}
private class NameComparator implements Comparator<Destination> {
public int compare(Destination choice1, Destination choice2) {
return compareNames(choice1.location, choice2.location);
}
}
private class DistanceComparator implements Comparator<Destination> {
public int compare(Destination choice1, Destination choice2) {
int result = choice1.turns - choice2.turns;
if (result == 0) {
return compareNames(choice1.location, choice2.location);
} else {
return result;
}
}
}
}
| false | true | public SelectDestinationDialog(Canvas parent, Unit unit) {
super(parent);
final Settlement inSettlement = unit.getSettlement();
// Collect the goods the unit is carrying.
List<GoodsType> goodsTypeList = new ArrayList<GoodsType>();
for (Goods goods : unit.getGoodsList()) {
goodsTypeList.add(goods.getType());
}
final List<GoodsType> goodsTypes = goodsTypeList;
// Search for destinations we can reach:
getGame().getMap().search(unit, unit.getTile(), new GoalDecider() {
public PathNode getGoal() {
return null;
}
public boolean check(Unit u, PathNode p) {
Settlement settlement = p.getTile().getSettlement();
if (settlement != null && settlement != inSettlement) {
String extras = (settlement.getOwner() != u.getOwner())
? getExtras(u, settlement, goodsTypes) : "";
destinations.add(new Destination(settlement, p.getTurns(), extras));
}
return false;
}
public boolean hasSubGoals() {
return false;
}
}, CostDeciders.avoidIllegal(), Integer.MAX_VALUE);
if (destinationComparator == null) {
destinationComparator = new DestinationComparator(getMyPlayer());
}
Collections.sort(destinations, destinationComparator);
if (unit.isNaval() && unit.getOwner().canMoveToEurope()) {
PathNode path = unit.findPathToEurope();
if (path != null) {
Europe europe = getMyPlayer().getEurope();
destinations.add(0, new Destination(europe, path.getTotalTurns(),
getExtras(unit, europe, goodsTypes)));
} else if (unit.getTile() != null
&& (unit.getTile().canMoveToEurope()
|| unit.getTile().isAdjacentToMapEdge())) {
Europe europe = getMyPlayer().getEurope();
destinations.add(0, new Destination(europe, 0,
getExtras(unit, europe, goodsTypes)));
}
}
MigLayout layout = new MigLayout("wrap 1, fill", "[align center]", "");
setLayout(layout);
JLabel header = new JLabel(Messages.message("selectDestination.text"));
header.setFont(smallHeaderFont);
add(header);
DefaultListModel model = new DefaultListModel();
destinationList = new JList(model);
filterDestinations();
destinationList.setCellRenderer(new LocationRenderer());
destinationList.setFixedCellHeight(48);
Action selectAction = new AbstractAction(Messages.message("ok")) {
public void actionPerformed(ActionEvent e) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
};
Action quitAction = new AbstractAction(Messages.message("selectDestination.cancel")) {
public void actionPerformed(ActionEvent e) {
getCanvas().remove(SelectDestinationDialog.this);
}
};
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "select");
destinationList.getActionMap().put("select", selectAction);
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
destinationList.getActionMap().put("quit", quitAction);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
}
};
destinationList.addMouseListener(mouseListener);
JScrollPane listScroller = new JScrollPane(destinationList);
listScroller.setPreferredSize(new Dimension(250, 250));
add(listScroller, "newline 30, growx, growy");
onlyMyColoniesBox = new JCheckBox(Messages.message("selectDestination.onlyMyColonies"),
showOnlyMyColonies);
onlyMyColoniesBox.addChangeListener(this);
add(onlyMyColoniesBox, "left");
comparatorBox = new JComboBox(new String[] {
Messages.message("selectDestination.sortByOwner"),
Messages.message("selectDestination.sortByName"),
Messages.message("selectDestination.sortByDistance")
});
comparatorBox.addItemListener(this);
if (destinationComparator instanceof DestinationComparator) {
comparatorBox.setSelectedIndex(0);
} else if (destinationComparator instanceof NameComparator) {
comparatorBox.setSelectedIndex(1);
} else if (destinationComparator instanceof DistanceComparator) {
comparatorBox.setSelectedIndex(2);
}
add(comparatorBox, "left");
cancelButton.setAction(quitAction);
okButton.setAction(selectAction);
add(okButton, "newline 30, split 2, tag ok");
add(cancelButton, "tag cancel");
setSize(getPreferredSize());
}
| public SelectDestinationDialog(Canvas parent, Unit unit) {
super(parent);
final Settlement inSettlement = unit.getSettlement();
// Collect the goods the unit is carrying.
List<GoodsType> goodsTypeList = new ArrayList<GoodsType>();
for (Goods goods : unit.getGoodsList()) {
goodsTypeList.add(goods.getType());
}
final List<GoodsType> goodsTypes = goodsTypeList;
// Search for destinations we can reach:
getGame().getMap().search(unit, unit.getTile(), new GoalDecider() {
public PathNode getGoal() {
return null;
}
public boolean check(Unit u, PathNode p) {
Settlement settlement = p.getTile().getSettlement();
if (settlement != null && settlement != inSettlement) {
String extras = (settlement.getOwner() != u.getOwner())
? getExtras(u, settlement, goodsTypes) : "";
destinations.add(new Destination(settlement, p.getTurns(), extras));
}
return false;
}
public boolean hasSubGoals() {
return false;
}
}, CostDeciders.avoidIllegal(), Integer.MAX_VALUE);
if (destinationComparator == null) {
destinationComparator = new DestinationComparator(getMyPlayer());
}
Collections.sort(destinations, destinationComparator);
if (unit.isNaval() && unit.getOwner().canMoveToEurope()) {
PathNode path = unit.findPathToEurope();
int turns = (path != null)
? unit.getSailTurns() + path.getTotalTurns()
: (unit.getTile() != null
&& (unit.getTile().canMoveToEurope()
|| unit.getTile().isAdjacentToMapEdge()))
? unit.getSailTurns()
: -1;
if (turns >= 0) {
Europe europe = getMyPlayer().getEurope();
destinations.add(0,
new Destination(europe, turns,
getExtras(unit, europe, goodsTypes)));
}
}
MigLayout layout = new MigLayout("wrap 1, fill", "[align center]", "");
setLayout(layout);
JLabel header = new JLabel(Messages.message("selectDestination.text"));
header.setFont(smallHeaderFont);
add(header);
DefaultListModel model = new DefaultListModel();
destinationList = new JList(model);
filterDestinations();
destinationList.setCellRenderer(new LocationRenderer());
destinationList.setFixedCellHeight(48);
Action selectAction = new AbstractAction(Messages.message("ok")) {
public void actionPerformed(ActionEvent e) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
};
Action quitAction = new AbstractAction(Messages.message("selectDestination.cancel")) {
public void actionPerformed(ActionEvent e) {
getCanvas().remove(SelectDestinationDialog.this);
}
};
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "select");
destinationList.getActionMap().put("select", selectAction);
destinationList.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
destinationList.getActionMap().put("quit", quitAction);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Destination d = (Destination) destinationList.getSelectedValue();
if (d != null) {
setResponse((Location) d.location);
}
getCanvas().remove(SelectDestinationDialog.this);
}
}
};
destinationList.addMouseListener(mouseListener);
JScrollPane listScroller = new JScrollPane(destinationList);
listScroller.setPreferredSize(new Dimension(250, 250));
add(listScroller, "newline 30, growx, growy");
onlyMyColoniesBox = new JCheckBox(Messages.message("selectDestination.onlyMyColonies"),
showOnlyMyColonies);
onlyMyColoniesBox.addChangeListener(this);
add(onlyMyColoniesBox, "left");
comparatorBox = new JComboBox(new String[] {
Messages.message("selectDestination.sortByOwner"),
Messages.message("selectDestination.sortByName"),
Messages.message("selectDestination.sortByDistance")
});
comparatorBox.addItemListener(this);
if (destinationComparator instanceof DestinationComparator) {
comparatorBox.setSelectedIndex(0);
} else if (destinationComparator instanceof NameComparator) {
comparatorBox.setSelectedIndex(1);
} else if (destinationComparator instanceof DistanceComparator) {
comparatorBox.setSelectedIndex(2);
}
add(comparatorBox, "left");
cancelButton.setAction(quitAction);
okButton.setAction(selectAction);
add(okButton, "newline 30, split 2, tag ok");
add(cancelButton, "tag cancel");
setSize(getPreferredSize());
}
|
diff --git a/Dashboard/src/dashboard/util/Statistics.java b/Dashboard/src/dashboard/util/Statistics.java
index 56a9d40..8c5ca39 100644
--- a/Dashboard/src/dashboard/util/Statistics.java
+++ b/Dashboard/src/dashboard/util/Statistics.java
@@ -1,379 +1,381 @@
package dashboard.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import dashboard.model.*;
import dashboard.registry.StudentRegistry;
public class Statistics {
/**
* @param course
* the course you ant to get the time from
* @param moments
* the moments you want to use to get the time from
* @return
* the total time studied for that course in seconds
* | for(StudyMoment moment : moments))
* | if(moment.getCourse().getName().equals(course))
* | time += moment.getTime()
*/
public static long getTime(Course course, ArrayList<StudyMoment> moments){
long time = 0;
if(moments!=null){
for(StudyMoment moment : moments)
if(moment.getCourse().equals(course))
time += moment.getTime();
}
return time;
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* returns the total time the student has studied in seconds
* | for(StudyMoment moment : moments)
* | time += moment.getTime()
*/
public static long getTotalTime(ArrayList<StudyMoment> moments) {
long time = 0;
if(moments!=null){
for(StudyMoment moment : moments)
time += moment.getTime();
}
return time;
}
public static int getTotalPages(ArrayList<StudyMoment> moments){
int pages = 0;
for(StudyMoment moment : moments)
if(moment.getKind().equals("Theorie"))
pages += moment.getAmount();
return pages;
}
public static int getTotalExcercices(ArrayList<StudyMoment> moments){
int excercices = 0;
for(StudyMoment moment : moments)
if(moment.getKind().equals("Oefeningen"))
excercices += moment.getAmount();
return excercices;
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* an arrayList with the moments the student studied last week
*/
public static ArrayList<StudyMoment> getMomentsWeek(ArrayList<StudyMoment> moments) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.DAY_OF_WEEK,calendar.MONDAY);
Date start = calendar.getTime();
calendar.add(Calendar.WEEK_OF_YEAR,1);
Date end = calendar.getTime();
return getMomentsPeriod(moments, start, end);
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* an arrayList with the moments the student studied last week
*/
public static ArrayList<StudyMoment> getMomentsMonth(ArrayList<StudyMoment> moments) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.DAY_OF_MONTH,1);
Date start = calendar.getTime();
calendar.add(calendar.MONTH,1);
Date end = calendar.getTime();
return getMomentsPeriod(moments, start, end);
}
public static ArrayList<StudyMoment> getMomentsPeriod(ArrayList<StudyMoment> moments, Date start,Date end){
ArrayList<StudyMoment> goodMoments = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments)
if(moment.getStart().before(end) &&
moment.getStart().after(start))
goodMoments.add(moment);
return goodMoments;
}
public static ArrayList<StudyMoment> getMomentsUntil(ArrayList<StudyMoment> moments,Date end){
ArrayList<StudyMoment> goodMoments = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments)
if(moment.getStart().before(end))
goodMoments.add(moment);
return goodMoments;
}
/**
* @param moments
* the moments of a student
* @param courses
* the courses of a student
* @return
* a hashmap filled with the courses and the percentage of time
* put into those courses based on total time
*/
public static HashMap<String,Long> getCourseTimes(ArrayList<StudyMoment> moments,ArrayList<CourseContract> courses){
HashMap<String,Long> result = new HashMap<String,Long>();
for(CourseContract course: courses){
long part = getTime(course.getCourse(), moments);
result.put(course.getCourse().getName(), part);
}
return result;
}
/**
* @param moments
* the moments of a student
* @param courses
* the courses of a student
* @return
* a hashmap filled with the courses and the percentage of time
* put into those courses based on total time
*/
public static HashMap<String,Long> getCoursePercents(ArrayList<StudyMoment> moments,ArrayList<CourseContract> courses){
HashMap<String,Long> result = new HashMap<String,Long>();
long totTime = getTotalTime(moments);
for(CourseContract course: courses){
long part = getTime(course.getCourse(), moments);
long resTime = (part/totTime)*100;
result.put(course.getCourse().getName(), resTime);
}
return result;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with days and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByDay(ArrayList<StudyMoment> moments){
HashMap<String, Long> results = new HashMap<String, Long>();
String dateString = "geen";
for(StudyMoment moment : moments){
String newDateString = moment.getStart().toString().substring(0, 10);
long time = moment.getTime();
if(dateString.equals(newDateString)){
time += results.get(newDateString);
results.remove(newDateString);
}
results.put(newDateString, time);
}
return results;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with locations and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByLoc(ArrayList<StudyMoment> moments,Student student){
HashMap<String,Long> ret = new HashMap<String,Long>();
Iterator<StudyMoment> it = moments.iterator();
while(it.hasNext()){
StudyMoment moment = it.next();
Integer amount = moment.getAmount();
String name;
if(moment.getLocation()==null)
name = "Geen data";
else{
Location match = student.matchStarredLocation(moment.getLocation(), 1000);
if(match==null)
name = "Overige";
else
name = match.getAlias();
}
if(ret.containsKey(name))
ret.put(name, amount+ret.get(name));
else
ret.put(name, amount.longValue());
}
return ret;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with days and the corresponding relative amount studied
*/
public static long[] getTimeByDayInWeek(ArrayList<StudyMoment> moments){
long[] results = new long[7];
for(StudyMoment moment : moments){
String dayString = moment.getStart().toString().substring(0,3);
if(dayString.equals("Mon"))
results[0] += moment.getTime();
else if(dayString.equals("Tue"))
results[1] += moment.getTime();
else if(dayString.equals("Wed"))
results[2] += moment.getTime();
else if(dayString.equals("Thu"))
results[3] += moment.getTime();
else if(dayString.equals("Fri"))
results[4] += moment.getTime();
else if(dayString.equals("Sat"))
results[5] += moment.getTime();
else if(dayString.equals("Sun"))
results[6] += moment.getTime();
}
return results;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with months and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByMonth(ArrayList<StudyMoment> moments){
HashMap<String, Long> results = new HashMap<String, Long>();
String dateString = "geen";
for(StudyMoment moment : moments){
String newDateString = moment.getStart().toString().substring(4, 7) + moment.getStart().toString().substring(24, 28);
long time = moment.getTime();
if(dateString.equals(newDateString)){
time += results.get(newDateString);
results.remove(newDateString);
} else
dateString = newDateString;
results.put(newDateString, time);
}
return results;
}
/**
* @param moments
* the moments of a student
* @param course
* the course to search for
* @return
* an arraylist containing moments belonging to the course
*/
public static ArrayList<StudyMoment> filterMomentsByCourse(ArrayList<StudyMoment> moments,Course course){
ArrayList<StudyMoment> results = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments){
if(moment.getCourse().equals(course))
results.add(moment);
}
return results;
}
/**
* @param course
* a course of the student
* @param student
* the student
* @return
* the progress in credits, assuming a credit requires 28 hours of work
*/
public static double creditProgress(Course course,Student student){
double done = getTime(course,student.getStudyMoments());
double exp = course.getCredit()*28*60*60;
double div = done/exp;
if(done<exp)
return div;
else
return 1;
}
/**
* @param course
* a course
* @return
* the average progress in credits, assuming a credit requires 28 hours of work
*/
public static double averageCreditProgress(Course course){
List<Student> allStudents = StudentRegistry.getUsers();
double all = 0;
long total = 0;
for(Student student: allStudents){
ArrayList<CourseContract> contracts = student.getCourses();
if(contracts!=null){
for(CourseContract contract : contracts){
if(contract.getCourse().equals(course)){
all += creditProgress(course,student);
total++;
break;
}
}
}
}
double div = all/total;
if(total==0)
return 0;
else
return div;
}
public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
- long time = getTime(course, student.getStudyMoments());
- times.add(time);
- if(time > maxTime)
- maxTime = time;
+ if(student.getCourses().contains(course)){
+ long time = getTime(course, student.getStudyMoments());
+ times.add(time);
+ if(time > maxTime)
+ maxTime = time;
+ }
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
public static long[][] getPeopleStats(int sections){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
long time = getTotalTime(student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
}
| true | true | public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
long time = getTime(course, student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
| public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
if(student.getCourses().contains(course)){
long time = getTime(course, student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java b/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
index 1ed8dd7a3..a6f6b3481 100644
--- a/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
@@ -1,236 +1,238 @@
package org.broadinstitute.sting.gatk.samples;
import net.sf.samtools.SAMReadGroupRecord;
import net.sf.samtools.SAMRecord;
import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.variantcontext.Genotype;
import java.util.*;
/**
*
*/
public class SampleDB {
/**
* This is where Sample objects are stored. Samples are usually accessed by their ID, which is unique, so
* this is stored as a HashMap.
*/
private final HashMap<String, Sample> samples = new HashMap<String, Sample>();
/**
* Constructor takes both a SAM header and sample files because the two must be integrated.
*/
public SampleDB() {
}
/**
* Protected function to add a single sample to the database
*
* @param sample to be added
*/
protected SampleDB addSample(Sample sample) {
Sample prev = samples.get(sample.getID());
if ( prev != null )
sample = Sample.mergeSamples(prev, sample);
samples.put(sample.getID(), sample);
return this;
}
// --------------------------------------------------------------------------------
//
// Functions for getting a sample from the DB
//
// --------------------------------------------------------------------------------
/**
* Get a sample by its ID
* If an alias is passed in, return the main sample object
* @param id
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(String id) {
return samples.get(id);
}
/**
*
* @param read
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final SAMRecord read) {
return getSample(read.getReadGroup());
}
/**
*
* @param rg
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final SAMReadGroupRecord rg) {
return getSample(rg.getSample());
}
/**
* @param g Genotype
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final Genotype g) {
return getSample(g.getSampleName());
}
// --------------------------------------------------------------------------------
//
// Functions for accessing samples in the DB
//
// --------------------------------------------------------------------------------
/**
* Get number of sample objects
* @return size of samples map
*/
public int sampleCount() {
return samples.size();
}
public Set<Sample> getSamples() {
return new HashSet<Sample>(samples.values());
}
public Collection<String> getSampleNames() {
return Collections.unmodifiableCollection(samples.keySet());
}
/**
* Takes a collection of sample names and returns their corresponding sample objects
* Note that, since a set is returned, if you pass in a list with duplicates names there will not be any duplicates in the returned set
* @param sampleNameList Set of sample names
* @return Corresponding set of samples
*/
public Set<Sample> getSamples(Collection<String> sampleNameList) {
HashSet<Sample> samples = new HashSet<Sample>();
for (String name : sampleNameList) {
try {
samples.add(getSample(name));
}
catch (Exception e) {
throw new StingException("Could not get sample with the following ID: " + name, e);
}
}
return samples;
}
// --------------------------------------------------------------------------------
//
// Higher level pedigree functions
//
// --------------------------------------------------------------------------------
/**
* Returns a sorted set of the family IDs in all samples (excluding null ids)
* @return
*/
public final Set<String> getFamilyIDs() {
return getFamilies().keySet();
}
/**
* Returns a map from family ID -> set of family members for all samples with
* non-null family ids
*
* @return
*/
public final Map<String, Set<Sample>> getFamilies() {
return getFamilies(null);
}
/**
* Returns a map from family ID -> set of family members for all samples in sampleIds with
* non-null family ids
*
* @param sampleIds - all samples to include. If null is passed then all samples are returned.
* @return
*/
public final Map<String, Set<Sample>> getFamilies(Collection<String> sampleIds) {
final Map<String, Set<Sample>> families = new TreeMap<String, Set<Sample>>();
for ( final Sample sample : samples.values() ) {
if(sampleIds == null || sampleIds.contains(sample.getID())){
final String famID = sample.getFamilyID();
if ( famID != null ) {
if ( ! families.containsKey(famID) )
families.put(famID, new TreeSet<Sample>());
families.get(famID).add(sample);
}
}
}
return families;
}
/**
* Returns the set of all children that have both of their parents.
* Note that if a family is composed of more than 1 child, each child is
* returned.
* @return - all the children that have both of their parents
*/
public final Set<Sample> getChildrenWithParents(){
return getChildrenWithParents(false);
}
/**
* Returns the set of all children that have both of their parents.
* Note that if triosOnly = false, a family is composed of more than 1 child, each child is
* returned.
*
* This method can be used wherever trios are needed
*
* @param triosOnly - if set to true, only strict trios are returned
* @return - all the children that have both of their parents
*/
public final Set<Sample> getChildrenWithParents(boolean triosOnly) {
Map<String, Set<Sample>> families = getFamilies();
final Set<Sample> childrenWithParents = new HashSet<Sample>();
Iterator<Sample> sampleIterator;
for ( Set<Sample> familyMembers: families.values() ) {
if(triosOnly && familyMembers.size() != 3)
continue;
sampleIterator = familyMembers.iterator();
- for(Sample sample = sampleIterator.next(); sampleIterator.hasNext(); sample = sampleIterator.next()){
+ Sample sample;
+ while(sampleIterator.hasNext()){
+ sample = sampleIterator.next();
if(sample.getParents().size() == 2 && familyMembers.containsAll(sample.getParents()))
childrenWithParents.add(sample);
}
}
return childrenWithParents;
}
/**
* Return all samples with a given family ID
* @param familyId
* @return
*/
public Set<Sample> getFamily(String familyId) {
return getFamilies().get(familyId);
}
/**
* Returns all children of a given sample
* See note on the efficiency of getFamily() - since this depends on getFamily() it's also not efficient
* @param sample
* @return
*/
public Set<Sample> getChildren(Sample sample) {
final HashSet<Sample> children = new HashSet<Sample>();
for ( final Sample familyMember : getFamily(sample.getFamilyID())) {
if ( familyMember.getMother() == sample || familyMember.getFather() == sample ) {
children.add(familyMember);
}
}
return children;
}
}
| true | true | public final Set<Sample> getChildrenWithParents(boolean triosOnly) {
Map<String, Set<Sample>> families = getFamilies();
final Set<Sample> childrenWithParents = new HashSet<Sample>();
Iterator<Sample> sampleIterator;
for ( Set<Sample> familyMembers: families.values() ) {
if(triosOnly && familyMembers.size() != 3)
continue;
sampleIterator = familyMembers.iterator();
for(Sample sample = sampleIterator.next(); sampleIterator.hasNext(); sample = sampleIterator.next()){
if(sample.getParents().size() == 2 && familyMembers.containsAll(sample.getParents()))
childrenWithParents.add(sample);
}
}
return childrenWithParents;
}
| public final Set<Sample> getChildrenWithParents(boolean triosOnly) {
Map<String, Set<Sample>> families = getFamilies();
final Set<Sample> childrenWithParents = new HashSet<Sample>();
Iterator<Sample> sampleIterator;
for ( Set<Sample> familyMembers: families.values() ) {
if(triosOnly && familyMembers.size() != 3)
continue;
sampleIterator = familyMembers.iterator();
Sample sample;
while(sampleIterator.hasNext()){
sample = sampleIterator.next();
if(sample.getParents().size() == 2 && familyMembers.containsAll(sample.getParents()))
childrenWithParents.add(sample);
}
}
return childrenWithParents;
}
|
diff --git a/FactoryControlManager.java b/FactoryControlManager.java
index 6dce7c3..e38894d 100644
--- a/FactoryControlManager.java
+++ b/FactoryControlManager.java
@@ -1,285 +1,285 @@
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
/**
* This class is a parent class for each of the control panels for the
* various devices in the factory
*
*/
@SuppressWarnings("serial")
public class FactoryControlManager extends JFrame implements ActionListener {
Server server;
ImageIcon kitStandImage;
JPanel mainGUIPanel, nestLaneFeederPanel, controlPanel, cardLayoutAndControlPanel, kitQueuePanel;
KitRobotControlPanel kitRobotPanel;
GantryRobotControlPanel gantryRobotPanel;
PartRobotControlPanel partRobotPanel;
NestControlPanel nestPanel;
LaneControlPanel lanePanel;
FeederControlPanel feederPanel;
JButton kitRobotButton, partRobotButton, gantryRobotButton, nestLaneFeederButton;
Dimension mainGUIPanelSize, controlPanelSize, kitQueueSize, controlButtonSize;
CardLayout cl;
ArrayList<Kit> kits; //kits in production queue to be displayed in the kit queue panel
ArrayList<JButton> scheduleButtons;
/**
* Constructor
* @param server pointer to Server object
*/
public FactoryControlManager(Server server) {
//store reference to server
this.server = server;
//Kits
kits = new ArrayList<Kit>();
//ImageIcons
kitStandImage = new ImageIcon( "images/guiserver_thumbs/kit_table_thumb.png" );
//JPanels
mainGUIPanel = new JPanel();
nestLaneFeederPanel = new JPanel();
controlPanel = new JPanel();
cardLayoutAndControlPanel = new JPanel();
kitQueuePanel = new JPanel();
updateSchedule(server.getKits(),server.getStatus());
kitRobotPanel = new KitRobotControlPanel( this );
gantryRobotPanel = new GantryRobotControlPanel( this );
partRobotPanel = new PartRobotControlPanel( this );
nestPanel = new NestControlPanel( this );
lanePanel = new LaneControlPanel( this );
feederPanel = new FeederControlPanel( this );
//Dimensions
mainGUIPanelSize = new Dimension( 750, 532 );
controlPanelSize = new Dimension( 750, 40 );
kitQueueSize = new Dimension( 300, 572 );
controlButtonSize = new Dimension( 160, 30 );
//JButtons
kitRobotButton = new JButton();
kitRobotButton.setText( "Kit Robot" );
kitRobotButton.setPreferredSize( controlButtonSize );
kitRobotButton.setMaximumSize( controlButtonSize );
kitRobotButton.setMinimumSize( controlButtonSize );
kitRobotButton.addActionListener( this );
partRobotButton = new JButton();
partRobotButton.setText( "Part Robot" );
partRobotButton.setPreferredSize( controlButtonSize );
partRobotButton.setMaximumSize( controlButtonSize );
partRobotButton.setMinimumSize( controlButtonSize );
partRobotButton.addActionListener( this );
gantryRobotButton = new JButton();
gantryRobotButton.setText( "Gantry Robot" );
gantryRobotButton.setPreferredSize( controlButtonSize );
gantryRobotButton.setMaximumSize( controlButtonSize );
gantryRobotButton.setMinimumSize( controlButtonSize );
gantryRobotButton.addActionListener( this );
nestLaneFeederButton = new JButton();
nestLaneFeederButton.setText( "Nests Lanes Feeders" );
nestLaneFeederButton.setMargin( new Insets( 0, 0, 0, 0 ) );
nestLaneFeederButton.setPreferredSize( controlButtonSize );
nestLaneFeederButton.setMaximumSize( controlButtonSize );
nestLaneFeederButton.setMinimumSize( controlButtonSize );
nestLaneFeederButton.addActionListener( this );
//Layout
cl = new CardLayout();
nestLaneFeederPanel.setLayout( new BoxLayout( nestLaneFeederPanel, BoxLayout.X_AXIS ) );
nestLaneFeederPanel.add( nestPanel );
nestLaneFeederPanel.add( lanePanel );
nestLaneFeederPanel.add( feederPanel );
mainGUIPanel.setLayout( cl );
mainGUIPanel.setPreferredSize( mainGUIPanelSize );
mainGUIPanel.setMaximumSize( mainGUIPanelSize );
mainGUIPanel.setMinimumSize( mainGUIPanelSize );
mainGUIPanel.add( kitRobotPanel, "kit_robot_panel" );
mainGUIPanel.add( partRobotPanel, "part_robot_panel" );
mainGUIPanel.add( gantryRobotPanel, "gantry_robot_panel" );
mainGUIPanel.add( nestLaneFeederPanel, "nest_lane_feeder_panel" );
controlPanel.setLayout( new BoxLayout( controlPanel, BoxLayout.X_AXIS ) );
controlPanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
controlPanel.setPreferredSize( controlPanelSize );
controlPanel.setMaximumSize( controlPanelSize );
controlPanel.setMinimumSize( controlPanelSize );
controlPanel.add( Box.createGlue() );
controlPanel.add( kitRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( partRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( gantryRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( nestLaneFeederButton );
controlPanel.add( Box.createGlue() );
cardLayoutAndControlPanel.setLayout( new BoxLayout( cardLayoutAndControlPanel, BoxLayout.Y_AXIS ) );
cardLayoutAndControlPanel.add( mainGUIPanel );
cardLayoutAndControlPanel.add( controlPanel );
kitQueuePanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
kitQueuePanel.setPreferredSize( kitQueueSize );
kitQueuePanel.setMaximumSize( kitQueueSize );
kitQueuePanel.setMinimumSize( kitQueueSize );
kitQueuePanel.setLayout(new BoxLayout(kitQueuePanel, BoxLayout.Y_AXIS));
setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) );
add( kitQueuePanel );
add( cardLayoutAndControlPanel );
- setSize( 1050, 572 );
+ setSize( 1056, 600 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setResizable( false );
setVisible( true );
addWindowListener(new WindowCloseListener());
}
public void actionPerformed( ActionEvent ae ) {
if ( ae.getSource() == kitRobotButton ) {
cl.show( mainGUIPanel, "kit_robot_panel" );
}
else if ( ae.getSource() == partRobotButton ) {
cl.show( mainGUIPanel, "part_robot_panel" );
}
else if ( ae.getSource() == gantryRobotButton ) {
cl.show( mainGUIPanel, "gantry_robot_panel" );
}
else if ( ae.getSource() == nestLaneFeederButton ) {
cl.show( mainGUIPanel, "nest_lane_feeder_panel" );
}
else {
// change production status
for (int i = 0; i < scheduleButtons.size(); i++) {
if (ae.getSource() == scheduleButtons.get(i)) {
if (i < server.getStatus().status.size()) {
ProduceStatusMsg.KitStatus kitStatus = server.getStatus().status.get(i);
if (kitStatus == ProduceStatusMsg.KitStatus.QUEUED) {
server.getStatus().status.set(i, ProduceStatusMsg.KitStatus.PRODUCTION);
}
else if (kitStatus == ProduceStatusMsg.KitStatus.PRODUCTION) {
server.getStatus().status.set(i, ProduceStatusMsg.KitStatus.COMPLETE);
}
else if (kitStatus == ProduceStatusMsg.KitStatus.COMPLETE) {
// remove task from list
server.getStatus().cmds.remove(i);
server.getStatus().status.remove(i);
}
server.broadcast(Server.WantsEnum.STATUS);
}
break;
}
}
}
}
/**
* This method calls a method in the kitRobotPanel to reset the move buttons
* for the Kit Robot after its movement is finished
*/
public void enableKitRobotControls() {
kitRobotPanel.resetMoveButtons();
}
/**
* This method calls a method in the partRobotPanel to reset the move buttons
* for the Part Robot after its movement is finished
*/
public void enablePartRobotControls() {
partRobotPanel.resetMoveButtons();
}
/**
* This method calls a method in the gantryRobotPanel to reset the move buttons
* for the Gantry Robot after its movement is finished
*/
public void enableGantryRobotControls() {
gantryRobotPanel.resetMoveButtons();
}
/**
* Turns on a light for the kit inspection.
* Passing a "0" will turn on the red light signifying an incorrectly assembled kit
* Passing a "1" will turn on the yellow light signifying an incomplete kit
* Passing a "2" will turn on the green light signifying a correctly assembled kit
*
* @param status The status of the kit on the inspection stand
*/
public void kitInspectionStatus( int status ) {
if ( status == 0 ) {
kitRobotPanel.redLightOn( true );
}
else if ( status == 1 ) {
kitRobotPanel.yellowLightOn( true );
}
else if ( status == 2 ) {
kitRobotPanel.greenLightOn( true );
}
else
System.out.println( "Invalid Kit Inspection Status Received" );
}
/**
* Turns on a light for the nest inspection.
* Passing a "0" will turn on the red light signifying that the nest pair has 1 or more parts in it that it should not
* Passing a "1" will turn on the yellow light signifying a nest pair that is not full or has not settled completely
* Passing a "2" will turn on the green light signifying a nest pair that is full and has the correct parts
* The PartRobotControlPanel holds a variable that remembers which camera was triggered so specifying the nest pair pair is unnecessary
*
* @param status The status of the nest pair
*/
public void nestInspectionStatus( int status ) {
if ( status == 0 ) {
partRobotPanel.redLightOn( true );
}
else if ( status == 1 ) {
partRobotPanel.yellowLightOn( true );
}
else if ( status == 2 ) {
partRobotPanel.greenLightOn( true );
}
else
System.out.println( "Invalid Nest Inspection Status Received" );
}
public void updateSchedule(ArrayList<Kit> kitList, ProduceStatusMsg status1 ){
ProduceStatusMsg status = status1;
kits = kitList;
String kitname = "";
scheduleButtons = new ArrayList<JButton>();
kitQueuePanel.removeAll();
if (status.cmds.size() > 0) {
for (int i = 0; i < status.cmds.size(); i++) {
for (int j = 0; j < kits.size(); j++) {
kitname = kits.get(j).getName();
if (kits.get(j).getNumber() == status.cmds.get(i).kitNumber) {
scheduleButtons.add(new JButton(kitname + " - "
+ status.cmds.get(i).howMany + " - "
+ status.status.get(i)));
scheduleButtons.get(scheduleButtons.size() - 1).addActionListener(this);
kitQueuePanel.add(scheduleButtons.get(scheduleButtons.size() - 1));
}
}
}
}
validate();
repaint();
}
/** class to handle window close event */
private class WindowCloseListener extends WindowAdapter {
/** handle window close event */
public void windowClosing(WindowEvent e) {
server.saveSettings();
}
}
}
| true | true | public FactoryControlManager(Server server) {
//store reference to server
this.server = server;
//Kits
kits = new ArrayList<Kit>();
//ImageIcons
kitStandImage = new ImageIcon( "images/guiserver_thumbs/kit_table_thumb.png" );
//JPanels
mainGUIPanel = new JPanel();
nestLaneFeederPanel = new JPanel();
controlPanel = new JPanel();
cardLayoutAndControlPanel = new JPanel();
kitQueuePanel = new JPanel();
updateSchedule(server.getKits(),server.getStatus());
kitRobotPanel = new KitRobotControlPanel( this );
gantryRobotPanel = new GantryRobotControlPanel( this );
partRobotPanel = new PartRobotControlPanel( this );
nestPanel = new NestControlPanel( this );
lanePanel = new LaneControlPanel( this );
feederPanel = new FeederControlPanel( this );
//Dimensions
mainGUIPanelSize = new Dimension( 750, 532 );
controlPanelSize = new Dimension( 750, 40 );
kitQueueSize = new Dimension( 300, 572 );
controlButtonSize = new Dimension( 160, 30 );
//JButtons
kitRobotButton = new JButton();
kitRobotButton.setText( "Kit Robot" );
kitRobotButton.setPreferredSize( controlButtonSize );
kitRobotButton.setMaximumSize( controlButtonSize );
kitRobotButton.setMinimumSize( controlButtonSize );
kitRobotButton.addActionListener( this );
partRobotButton = new JButton();
partRobotButton.setText( "Part Robot" );
partRobotButton.setPreferredSize( controlButtonSize );
partRobotButton.setMaximumSize( controlButtonSize );
partRobotButton.setMinimumSize( controlButtonSize );
partRobotButton.addActionListener( this );
gantryRobotButton = new JButton();
gantryRobotButton.setText( "Gantry Robot" );
gantryRobotButton.setPreferredSize( controlButtonSize );
gantryRobotButton.setMaximumSize( controlButtonSize );
gantryRobotButton.setMinimumSize( controlButtonSize );
gantryRobotButton.addActionListener( this );
nestLaneFeederButton = new JButton();
nestLaneFeederButton.setText( "Nests Lanes Feeders" );
nestLaneFeederButton.setMargin( new Insets( 0, 0, 0, 0 ) );
nestLaneFeederButton.setPreferredSize( controlButtonSize );
nestLaneFeederButton.setMaximumSize( controlButtonSize );
nestLaneFeederButton.setMinimumSize( controlButtonSize );
nestLaneFeederButton.addActionListener( this );
//Layout
cl = new CardLayout();
nestLaneFeederPanel.setLayout( new BoxLayout( nestLaneFeederPanel, BoxLayout.X_AXIS ) );
nestLaneFeederPanel.add( nestPanel );
nestLaneFeederPanel.add( lanePanel );
nestLaneFeederPanel.add( feederPanel );
mainGUIPanel.setLayout( cl );
mainGUIPanel.setPreferredSize( mainGUIPanelSize );
mainGUIPanel.setMaximumSize( mainGUIPanelSize );
mainGUIPanel.setMinimumSize( mainGUIPanelSize );
mainGUIPanel.add( kitRobotPanel, "kit_robot_panel" );
mainGUIPanel.add( partRobotPanel, "part_robot_panel" );
mainGUIPanel.add( gantryRobotPanel, "gantry_robot_panel" );
mainGUIPanel.add( nestLaneFeederPanel, "nest_lane_feeder_panel" );
controlPanel.setLayout( new BoxLayout( controlPanel, BoxLayout.X_AXIS ) );
controlPanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
controlPanel.setPreferredSize( controlPanelSize );
controlPanel.setMaximumSize( controlPanelSize );
controlPanel.setMinimumSize( controlPanelSize );
controlPanel.add( Box.createGlue() );
controlPanel.add( kitRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( partRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( gantryRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( nestLaneFeederButton );
controlPanel.add( Box.createGlue() );
cardLayoutAndControlPanel.setLayout( new BoxLayout( cardLayoutAndControlPanel, BoxLayout.Y_AXIS ) );
cardLayoutAndControlPanel.add( mainGUIPanel );
cardLayoutAndControlPanel.add( controlPanel );
kitQueuePanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
kitQueuePanel.setPreferredSize( kitQueueSize );
kitQueuePanel.setMaximumSize( kitQueueSize );
kitQueuePanel.setMinimumSize( kitQueueSize );
kitQueuePanel.setLayout(new BoxLayout(kitQueuePanel, BoxLayout.Y_AXIS));
setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) );
add( kitQueuePanel );
add( cardLayoutAndControlPanel );
setSize( 1050, 572 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setResizable( false );
setVisible( true );
addWindowListener(new WindowCloseListener());
}
| public FactoryControlManager(Server server) {
//store reference to server
this.server = server;
//Kits
kits = new ArrayList<Kit>();
//ImageIcons
kitStandImage = new ImageIcon( "images/guiserver_thumbs/kit_table_thumb.png" );
//JPanels
mainGUIPanel = new JPanel();
nestLaneFeederPanel = new JPanel();
controlPanel = new JPanel();
cardLayoutAndControlPanel = new JPanel();
kitQueuePanel = new JPanel();
updateSchedule(server.getKits(),server.getStatus());
kitRobotPanel = new KitRobotControlPanel( this );
gantryRobotPanel = new GantryRobotControlPanel( this );
partRobotPanel = new PartRobotControlPanel( this );
nestPanel = new NestControlPanel( this );
lanePanel = new LaneControlPanel( this );
feederPanel = new FeederControlPanel( this );
//Dimensions
mainGUIPanelSize = new Dimension( 750, 532 );
controlPanelSize = new Dimension( 750, 40 );
kitQueueSize = new Dimension( 300, 572 );
controlButtonSize = new Dimension( 160, 30 );
//JButtons
kitRobotButton = new JButton();
kitRobotButton.setText( "Kit Robot" );
kitRobotButton.setPreferredSize( controlButtonSize );
kitRobotButton.setMaximumSize( controlButtonSize );
kitRobotButton.setMinimumSize( controlButtonSize );
kitRobotButton.addActionListener( this );
partRobotButton = new JButton();
partRobotButton.setText( "Part Robot" );
partRobotButton.setPreferredSize( controlButtonSize );
partRobotButton.setMaximumSize( controlButtonSize );
partRobotButton.setMinimumSize( controlButtonSize );
partRobotButton.addActionListener( this );
gantryRobotButton = new JButton();
gantryRobotButton.setText( "Gantry Robot" );
gantryRobotButton.setPreferredSize( controlButtonSize );
gantryRobotButton.setMaximumSize( controlButtonSize );
gantryRobotButton.setMinimumSize( controlButtonSize );
gantryRobotButton.addActionListener( this );
nestLaneFeederButton = new JButton();
nestLaneFeederButton.setText( "Nests Lanes Feeders" );
nestLaneFeederButton.setMargin( new Insets( 0, 0, 0, 0 ) );
nestLaneFeederButton.setPreferredSize( controlButtonSize );
nestLaneFeederButton.setMaximumSize( controlButtonSize );
nestLaneFeederButton.setMinimumSize( controlButtonSize );
nestLaneFeederButton.addActionListener( this );
//Layout
cl = new CardLayout();
nestLaneFeederPanel.setLayout( new BoxLayout( nestLaneFeederPanel, BoxLayout.X_AXIS ) );
nestLaneFeederPanel.add( nestPanel );
nestLaneFeederPanel.add( lanePanel );
nestLaneFeederPanel.add( feederPanel );
mainGUIPanel.setLayout( cl );
mainGUIPanel.setPreferredSize( mainGUIPanelSize );
mainGUIPanel.setMaximumSize( mainGUIPanelSize );
mainGUIPanel.setMinimumSize( mainGUIPanelSize );
mainGUIPanel.add( kitRobotPanel, "kit_robot_panel" );
mainGUIPanel.add( partRobotPanel, "part_robot_panel" );
mainGUIPanel.add( gantryRobotPanel, "gantry_robot_panel" );
mainGUIPanel.add( nestLaneFeederPanel, "nest_lane_feeder_panel" );
controlPanel.setLayout( new BoxLayout( controlPanel, BoxLayout.X_AXIS ) );
controlPanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
controlPanel.setPreferredSize( controlPanelSize );
controlPanel.setMaximumSize( controlPanelSize );
controlPanel.setMinimumSize( controlPanelSize );
controlPanel.add( Box.createGlue() );
controlPanel.add( kitRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( partRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( gantryRobotButton );
controlPanel.add( Box.createGlue() );
controlPanel.add( nestLaneFeederButton );
controlPanel.add( Box.createGlue() );
cardLayoutAndControlPanel.setLayout( new BoxLayout( cardLayoutAndControlPanel, BoxLayout.Y_AXIS ) );
cardLayoutAndControlPanel.add( mainGUIPanel );
cardLayoutAndControlPanel.add( controlPanel );
kitQueuePanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
kitQueuePanel.setPreferredSize( kitQueueSize );
kitQueuePanel.setMaximumSize( kitQueueSize );
kitQueuePanel.setMinimumSize( kitQueueSize );
kitQueuePanel.setLayout(new BoxLayout(kitQueuePanel, BoxLayout.Y_AXIS));
setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) );
add( kitQueuePanel );
add( cardLayoutAndControlPanel );
setSize( 1056, 600 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setResizable( false );
setVisible( true );
addWindowListener(new WindowCloseListener());
}
|
diff --git a/app/src/org/gdgankara/app/io/ProgramHandler.java b/app/src/org/gdgankara/app/io/ProgramHandler.java
index 0f413a0..ae7f462 100644
--- a/app/src/org/gdgankara/app/io/ProgramHandler.java
+++ b/app/src/org/gdgankara/app/io/ProgramHandler.java
@@ -1,473 +1,473 @@
package org.gdgankara.app.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.gdgankara.app.model.Announcement;
import org.gdgankara.app.model.Session;
import org.gdgankara.app.model.Speaker;
import org.gdgankara.app.model.Sponsor;
import org.gdgankara.app.model.Tag;
import org.gdgankara.app.services.ImageCacheService;
import org.gdgankara.app.utils.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ProgramHandler extends BaseHandler {
private static final String TAG = ProgramHandler.class.getSimpleName();
private static final String CACHE_FILE = "cache_";
private static final String BASE_URL_PROGRAM = "http://add-2013.appspot.com/api/program/";
protected Context context;
protected String lang;
protected ArrayList<Announcement> announcementList;
protected ArrayList<Sponsor> sponsorList;
protected ArrayList<Session> sessionList;
protected ArrayList<Speaker> speakerList;
protected ArrayList<String> tagList;
public ProgramHandler(Context context) {
super(context);
this.context = context;
}
/**
* API iletişim kurarak verilerde değişiklik olup olmadığını kontrol eder.
* Değişiklik var ise parse ederek verileri dosyada saklar. Değişiklik yok
* ise dosyadan okur.
*
* @param lang
* Session.LANG_TR yada Session.LANG_EN değeri alır
* @return ArrayList
*/
@SuppressWarnings("unchecked")
public void initializeLists(String lang) {
this.lang = lang;
JSONObject jsonObject = null;
try {
sessionList = (ArrayList<Session>) readCacheFile(getCacheFileName(
Session.KIND, lang));
if (sessionList == null) {
tagList = new ArrayList<String>();
jsonObject = doGet(BASE_URL_PROGRAM + lang);
sessionList = parseJSONObjectToSessionList(jsonObject,
"sessions");
writeListToFile(sessionList,
getCacheFileName(Session.KIND, lang));
}else {
tagList = (ArrayList<String>) readCacheFile(getCacheFileName(Tag.KIND, "en"));
}
speakerList = (ArrayList<Speaker>) readCacheFile(getCacheFileName(
Speaker.KIND, lang));
if (speakerList == null) {
if (jsonObject == null) {
jsonObject = doGet(BASE_URL_PROGRAM + lang);
}
speakerList = parseJSONObjectToSpeakerList(jsonObject,
"speakers");
setSpeakerList(speakerList);
// startImageCacheService(ImageCacheService.CACHE_SPEAKER_IMAGES);
writeListToFile(speakerList,getCacheFileName(Speaker.KIND, lang));
}
sponsorList = (ArrayList<Sponsor>) readCacheFile(getCacheFileName(
Sponsor.KIND, "en"));
if (sponsorList == null) {
if (jsonObject == null) {
jsonObject = doGet(BASE_URL_PROGRAM + lang);
}
sponsorList = parseJSONObjectToSponsorList(jsonObject,
"sponsors");
writeListToFile(sponsorList,
getCacheFileName(Sponsor.KIND, lang));
}
announcementList = (ArrayList<Announcement>) readCacheFile(getCacheFileName(
Announcement.KIND, "en"));
if (announcementList == null) {
if (jsonObject == null) {
jsonObject = doGet(BASE_URL_PROGRAM + lang);
}
announcementList = parseJSONObjectToAnnouncementList(
jsonObject, "announcements");
writeListToFile(announcementList,
getCacheFileName(Announcement.KIND, "en"));
}
setAnnouncementList(announcementList);
setSessionList(sessionList);
setSpeakerList(speakerList);
setSponsorList(sponsorList);
setTagList(tagList);
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public ArrayList<Session> updateSessionList(String lang) {
this.lang = lang;
JSONObject jsonObject;
ArrayList<Session> sessionsList = new ArrayList<Session>();
try {
jsonObject = doGet(BASE_URL_PROGRAM + lang);
boolean isVersionUpdated = Util.isVersionUpdated(context,
jsonObject);
if (isVersionUpdated) {
sessionsList = parseJSONObjectToSessionList(jsonObject,
"sessions");
writeListToFile(sessionsList,
getCacheFileName(Session.KIND, lang));
} else {
sessionsList = (ArrayList<Session>) readCacheFile(getCacheFileName(
Session.KIND, lang));
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
setSessionList(sessionsList);
return sessionsList;
}
@SuppressWarnings("unchecked")
public ArrayList<Speaker> updateSpeakerList(String lang) {
this.lang = lang;
JSONObject jsonObject;
ArrayList<Speaker> speakerList = new ArrayList<Speaker>();
try {
jsonObject = doGet(BASE_URL_PROGRAM + lang);
boolean isVersionUpdated = Util.isVersionUpdated(context,
jsonObject);
if (isVersionUpdated) {
speakerList = parseJSONObjectToSpeakerList(jsonObject,
"speakers");
startImageCacheService(ImageCacheService.CACHE_SPEAKER_IMAGES);
writeListToFile(speakerList,
getCacheFileName(Speaker.KIND, lang));
} else {
speakerList = (ArrayList<Speaker>) readCacheFile(getCacheFileName(
Speaker.KIND, lang));
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
setSpeakerList(speakerList);
return speakerList;
}
public void updateSpeakerListCacheFile(String lang) {
try {
writeListToFile(Util.SpeakerList,
getCacheFileName(Speaker.KIND, lang));
} catch (IOException e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
}
private ArrayList<Announcement> parseJSONObjectToAnnouncementList(
JSONObject jsonObject, String objectName) {
JSONArray announcementArray;
ArrayList<Announcement> announcementList = new ArrayList<Announcement>();
try {
announcementArray = jsonObject.getJSONArray(objectName);
int length = announcementArray.length();
Announcement announcement;
for (int i = 0; i < length; i++) {
JSONObject announcementObject = announcementArray
.getJSONObject(i);
announcement = new Announcement();
announcement.setId(announcementObject.getLong("id"));
announcement.setDescription(announcementObject
.getString("description"));
announcement.setImage(announcementObject.getString("image"));
announcement.setLink(announcementObject.getString("link"));
announcement.setSession(announcementObject
.getBoolean("session"));
announcement.setTitle(announcementObject.getString("title"));
if (announcement.isSession()) {
announcement.setSessionId(announcementObject
.getLong("sessionId"));
}
if (announcementObject.getString("lang").equals(
Announcement.LANG_EN)) {
announcement.setLang(Announcement.LANG_EN);
} else {
announcement.setLang(Announcement.LANG_TR);
}
announcementList.add(announcement);
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
return announcementList;
}
private ArrayList<Sponsor> parseJSONObjectToSponsorList(
JSONObject jsonObject, String objectName) {
JSONArray sponsorArray;
ArrayList<Sponsor> sponsorList = new ArrayList<Sponsor>();
try {
sponsorArray = jsonObject.getJSONArray(objectName);
int length = sponsorArray.length();
Sponsor sponsor;
for (int i = 0; i < length; i++) {
JSONObject sponsorObject = sponsorArray.getJSONObject(i);
sponsor = new Sponsor();
sponsor.setId(sponsorObject.getLong("id"));
sponsor.setLogo(sponsorObject.getString("image"));
sponsor.setCategory(sponsorObject.getString("category"));
sponsor.setLink(sponsorObject.getString("link"));
sponsorList.add(sponsor);
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
return sponsorList;
}
private ArrayList<Speaker> parseJSONObjectToSpeakerList(
JSONObject jsonObject, String objectName) {
JSONArray speakerArray;
ArrayList<Speaker> speakerList = new ArrayList<Speaker>();
try {
speakerArray = jsonObject.getJSONArray(objectName);
int length = speakerArray.length();
Speaker speaker;
for (int i = 0; i < length; i++) {
JSONObject speakerObject = (JSONObject) speakerArray.get(i);
speaker = new Speaker();
speaker.setId(speakerObject.getLong("id"));
speaker.setBiography(isObjectNull(speakerObject
.getString("bio")));
speaker.setLanguage(isObjectNull(speakerObject
.getString("lang")));
speaker.setName(isObjectNull(speakerObject.getString("name")));
speaker.setPhoto(isObjectNull(speakerObject.getString("photo")));
JSONArray sessionIDArray;
List<Long> sessionIDList = new ArrayList<Long>();
if (!speakerObject.isNull("sessionIDList")) {
try {
sessionIDList.add(speakerObject
.getLong("sessionIDList"));
} catch (JSONException e) {
// e.printStackTrace();
Log.e(TAG, e.toString());
sessionIDArray = speakerObject
.getJSONArray("sessionIDList");
for (int k = 0; k < sessionIDArray.length(); k++) {
sessionIDList.add(sessionIDArray.getLong(k));
}
}
speaker.setSessionIDList(sessionIDList);
speakerList.add(speaker);
} else {
speaker.setSessionIDList(null);
speakerList.add(speaker);
}
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
System.out.println("size:" + speakerList.size());
return speakerList;
}
private ArrayList<Session> parseJSONObjectToSessionList(
JSONObject jsonObject, String objectName) {
JSONArray sessionArray;
ArrayList<Session> sessionsList = new ArrayList<Session>();
try {
sessionArray = jsonObject.getJSONArray(objectName);
int length = sessionArray.length();
Session session;
for (int i = 0; i < length; i++) {
JSONObject sessionObject = (JSONObject) sessionArray.get(i);
session = new Session();
session.setId(sessionObject.getLong("id"));
session.setBreak(sessionObject.getBoolean("break"));
session.setDate(isObjectNull(sessionObject.getString("day")));
session.setDescription(isObjectNull(sessionObject
.getString("description")));
session.setEnd_hour(isObjectNull(sessionObject
.getString("endHour")));
session.setStart_hour(isObjectNull(sessionObject
.getString("startHour")));
session.setHall(isObjectNull(sessionObject.getString("hall")));
session.setTitle(isObjectNull(sessionObject.getString("title")));
session.setFavorite(false);
if (!session.isBreak()) {
JSONArray speakerIDArray;
List<Long> speakerIDList = new ArrayList<Long>();
try {
if (!sessionObject.isNull("speakerIDList")) {
speakerIDList.add(sessionObject
.getLong("speakerIDList"));
}
} catch (JSONException e) {
// e.printStackTrace();
speakerIDArray = sessionObject
.getJSONArray("speakerIDList");
if (speakerIDArray.get(0) != null) {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add(speakerIDArray.getLong(k));
}
} else {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add((long) 0);
}
}
}
session.setSpeakerIDList(speakerIDList);
if (!sessionObject.isNull("tags")) {
session.setTags(isObjectNull(sessionObject
.getString("tags")));
String[] tags = session.getTags().split(",");
for (String string : tags) {
- if (string != "" && string != null) {
+ if (string != "" && string != null && !tagList.contains(string)) {
tagList.add(string);
}
}
}
}
if (sessionObject.getString("lang").equals(Session.LANG_EN)) {
session.setLanguage(Session.LANG_EN);
} else {
session.setLanguage(Session.LANG_TR);
}
if (session.getDate().contains(
String.valueOf(Session.DAY_FRIDAY))) {
session.setDay(Session.DAY_FRIDAY);
} else {
session.setDay(Session.DAY_SATURDAY);
}
sessionsList.add(session);
}
} catch (JSONException e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
return sessionsList;
}
private void startImageCacheService(String type) {
Intent imageCacheIntent = new Intent(context, ImageCacheService.class);
imageCacheIntent.setAction(ImageCacheService.CACHE_STARTED);
imageCacheIntent.putExtra(ImageCacheService.CACHE_TYPE, type);
context.startService(imageCacheIntent);
}
private void updateFavoriteSessions(ArrayList<Session> sessionList) {
if (Util.FavoritesList != null) {
for (Session session : sessionList) {
for (Long favoriteSessionId : Util.FavoritesList) {
if (session.getId() == favoriteSessionId) {
session.setFavorite(true);
}
}
}
}
}
private String isObjectNull(String value) {
if (value == null || value == "" || value.equals(null)
|| value.equals("")) {
return null;
} else {
return value;
}
}
private String getCacheFileName(String kind, String lang) {
return CACHE_FILE + kind + "_" + lang;
}
public ArrayList<Session> getSessionList() {
return sessionList;
}
public void setSessionList(ArrayList<Session> sessionList) {
updateFavoriteSessions(sessionList);
this.sessionList = sessionList;
Util.SessionList = sessionList;
}
public ArrayList<Speaker> getSpeakerList() {
return speakerList;
}
public void setSpeakerList(ArrayList<Speaker> speakerList) {
this.speakerList = speakerList;
Util.SpeakerList = speakerList;
}
public ArrayList<Announcement> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(ArrayList<Announcement> announcementList) {
this.announcementList = announcementList;
Util.AnnouncementList = announcementList;
}
public ArrayList<Sponsor> getSponsorList() {
return sponsorList;
}
public void setSponsorList(ArrayList<Sponsor> sponsorList) {
this.sponsorList = sponsorList;
Util.SponsorList = sponsorList;
}
public ArrayList<String> getTagList() {
return tagList;
}
public void setTagList(ArrayList<String> tagList) {
this.tagList = tagList;
Util.TagList = tagList;
try {
writeListToFile(tagList,getCacheFileName(Tag.KIND, "en"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public ArrayList<?> parseJSONObject(JSONObject jsonObject, String objectName)
throws JSONException {
return null;
}
}
| true | true | private ArrayList<Session> parseJSONObjectToSessionList(
JSONObject jsonObject, String objectName) {
JSONArray sessionArray;
ArrayList<Session> sessionsList = new ArrayList<Session>();
try {
sessionArray = jsonObject.getJSONArray(objectName);
int length = sessionArray.length();
Session session;
for (int i = 0; i < length; i++) {
JSONObject sessionObject = (JSONObject) sessionArray.get(i);
session = new Session();
session.setId(sessionObject.getLong("id"));
session.setBreak(sessionObject.getBoolean("break"));
session.setDate(isObjectNull(sessionObject.getString("day")));
session.setDescription(isObjectNull(sessionObject
.getString("description")));
session.setEnd_hour(isObjectNull(sessionObject
.getString("endHour")));
session.setStart_hour(isObjectNull(sessionObject
.getString("startHour")));
session.setHall(isObjectNull(sessionObject.getString("hall")));
session.setTitle(isObjectNull(sessionObject.getString("title")));
session.setFavorite(false);
if (!session.isBreak()) {
JSONArray speakerIDArray;
List<Long> speakerIDList = new ArrayList<Long>();
try {
if (!sessionObject.isNull("speakerIDList")) {
speakerIDList.add(sessionObject
.getLong("speakerIDList"));
}
} catch (JSONException e) {
// e.printStackTrace();
speakerIDArray = sessionObject
.getJSONArray("speakerIDList");
if (speakerIDArray.get(0) != null) {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add(speakerIDArray.getLong(k));
}
} else {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add((long) 0);
}
}
}
session.setSpeakerIDList(speakerIDList);
if (!sessionObject.isNull("tags")) {
session.setTags(isObjectNull(sessionObject
.getString("tags")));
String[] tags = session.getTags().split(",");
for (String string : tags) {
if (string != "" && string != null) {
tagList.add(string);
}
}
}
}
if (sessionObject.getString("lang").equals(Session.LANG_EN)) {
session.setLanguage(Session.LANG_EN);
} else {
session.setLanguage(Session.LANG_TR);
}
if (session.getDate().contains(
String.valueOf(Session.DAY_FRIDAY))) {
session.setDay(Session.DAY_FRIDAY);
} else {
session.setDay(Session.DAY_SATURDAY);
}
sessionsList.add(session);
}
} catch (JSONException e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
return sessionsList;
}
| private ArrayList<Session> parseJSONObjectToSessionList(
JSONObject jsonObject, String objectName) {
JSONArray sessionArray;
ArrayList<Session> sessionsList = new ArrayList<Session>();
try {
sessionArray = jsonObject.getJSONArray(objectName);
int length = sessionArray.length();
Session session;
for (int i = 0; i < length; i++) {
JSONObject sessionObject = (JSONObject) sessionArray.get(i);
session = new Session();
session.setId(sessionObject.getLong("id"));
session.setBreak(sessionObject.getBoolean("break"));
session.setDate(isObjectNull(sessionObject.getString("day")));
session.setDescription(isObjectNull(sessionObject
.getString("description")));
session.setEnd_hour(isObjectNull(sessionObject
.getString("endHour")));
session.setStart_hour(isObjectNull(sessionObject
.getString("startHour")));
session.setHall(isObjectNull(sessionObject.getString("hall")));
session.setTitle(isObjectNull(sessionObject.getString("title")));
session.setFavorite(false);
if (!session.isBreak()) {
JSONArray speakerIDArray;
List<Long> speakerIDList = new ArrayList<Long>();
try {
if (!sessionObject.isNull("speakerIDList")) {
speakerIDList.add(sessionObject
.getLong("speakerIDList"));
}
} catch (JSONException e) {
// e.printStackTrace();
speakerIDArray = sessionObject
.getJSONArray("speakerIDList");
if (speakerIDArray.get(0) != null) {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add(speakerIDArray.getLong(k));
}
} else {
for (int k = 0; k < speakerIDArray.length(); k++) {
speakerIDList.add((long) 0);
}
}
}
session.setSpeakerIDList(speakerIDList);
if (!sessionObject.isNull("tags")) {
session.setTags(isObjectNull(sessionObject
.getString("tags")));
String[] tags = session.getTags().split(",");
for (String string : tags) {
if (string != "" && string != null && !tagList.contains(string)) {
tagList.add(string);
}
}
}
}
if (sessionObject.getString("lang").equals(Session.LANG_EN)) {
session.setLanguage(Session.LANG_EN);
} else {
session.setLanguage(Session.LANG_TR);
}
if (session.getDate().contains(
String.valueOf(Session.DAY_FRIDAY))) {
session.setDay(Session.DAY_FRIDAY);
} else {
session.setDay(Session.DAY_SATURDAY);
}
sessionsList.add(session);
}
} catch (JSONException e) {
Log.e(TAG, "Error: " + e);
e.printStackTrace();
}
return sessionsList;
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java
index 63587c611..1d581119e 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java
@@ -1,263 +1,268 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.scenes.scene2d.ui;
import java.io.IOException;
import java.io.Writer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializer;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.SerializationException;
/** @author Nathan Sweet */
public class Skin implements Disposable {
static public class SkinData {
public ObjectMap<Class, ObjectMap<String, Object>> resources = new ObjectMap();
public transient Texture texture;
}
ObjectMap<Class, ObjectMap<String, Object>> styles = new ObjectMap();
final SkinData data;
public Skin () {
data = new SkinData();
}
public Skin (FileHandle skinFile, FileHandle textureFile) {
data = new SkinData();
data.texture = new Texture(textureFile);
try {
getJsonLoader(skinFile).fromJson(Skin.class, skinFile);
} catch (SerializationException ex) {
throw new SerializationException("Error reading file: " + skinFile, ex);
}
}
public Skin (FileHandle skinFile, SkinData data) {
this.data = data;
data.texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
try {
getJsonLoader(skinFile).fromJson(Skin.class, skinFile);
} catch (SerializationException ex) {
throw new SerializationException("Error reading file: " + skinFile, ex);
}
}
public <T> void addResource (String name, T resource) {
if (resource == null) throw new IllegalArgumentException("resource cannot be null.");
ObjectMap<String, Object> typeResources = data.resources.get(resource.getClass());
if (typeResources == null) {
typeResources = new ObjectMap();
data.resources.put(resource.getClass(), typeResources);
}
typeResources.put(name, resource);
}
public <T> T getResource (String name, Class<T> type) {
ObjectMap<String, Object> typeResources = data.resources.get(type);
if (typeResources == null) throw new GdxRuntimeException("No resources registered with type: " + type.getName());
Object resource = typeResources.get(name);
if (resource == null) throw new GdxRuntimeException("No " + type.getName() + " resource registered with name: " + name);
return (T)resource;
}
public <T> void addStyle (String name, T style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
ObjectMap<String, Object> typeStyles = styles.get(style.getClass());
if (typeStyles == null) {
typeStyles = new ObjectMap();
styles.put(style.getClass(), typeStyles);
}
typeStyles.put(name, style);
}
public <T> T getStyle (Class<T> type) {
return getStyle("default", type);
}
public <T> T getStyle (String name, Class<T> type) {
ObjectMap<String, Object> typeStyles = styles.get(type);
if (typeStyles == null) throw new GdxRuntimeException("No styles registered with type: " + type.getName());
Object style = typeStyles.get(name);
if (style == null) throw new GdxRuntimeException("No " + type.getName() + " style registered with name: " + name);
return (T)style;
}
/** Disposes the {@link Texture} and all {@link Disposable} resources of this Skin. */
@Override
public void dispose () {
data.texture.dispose();
for (Object object : data.resources.values())
if (object instanceof Disposable) ((Disposable)object).dispose();
}
public void setTexture (Texture texture) {
data.texture = texture;
}
/** @return the {@link Texture} containing all {@link NinePatch} and {@link TextureRegion} pixels of this Skin. */
public Texture getTexture () {
return data.texture;
}
public void save (FileHandle skinFile) {
String text = getJsonLoader(null).prettyPrint(this, true);
Writer writer = skinFile.writer(false);
try {
writer.write(text);
writer.close();
} catch (IOException ex) {
throw new GdxRuntimeException(ex);
}
}
protected Json getJsonLoader (final FileHandle skinFile) {
final Skin skin = this;
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
class AliasSerializer implements Serializer {
final ObjectMap<String, ?> map;
public AliasSerializer (ObjectMap<String, ?> map) {
this.map = map;
}
public void write (Json json, Object object, Class valueType) {
for (Entry<String, ?> entry : map.entries()) {
if (entry.value.equals(object)) {
json.writeValue(entry.key);
return;
}
}
throw new SerializationException(object.getClass().getSimpleName() + " not found: " + object);
}
public Object read (Json json, Object jsonData, Class type) {
String name = (String)jsonData;
Object object = map.get(name);
if (object != null) return object;
throw new SerializationException("Skin has a " + type.getSimpleName() + " that could not be found in the resources: "
+ jsonData);
}
}
json.setSerializer(Skin.class, new Serializer<Skin>() {
public void write (Json json, Skin skin, Class valueType) {
json.writeObjectStart();
json.writeValue("resources", skin.data.resources);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
json.writeField(skin, "styles");
json.writeObjectEnd();
}
public Skin read (Json json, Object jsonData, Class ignored) {
ObjectMap map = (ObjectMap)jsonData;
readTypeMap(json, (ObjectMap)map.get("resources"), true);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
readTypeMap(json, (ObjectMap)map.get("styles"), false);
return skin;
}
private void readTypeMap (Json json, ObjectMap<String, ObjectMap> typeToValueMap, boolean isResource) {
if (typeToValueMap == null)
throw new SerializationException("Skin file is missing a \"" + (isResource ? "resources" : "styles")
+ "\" section.");
for (Entry<String, ObjectMap> typeEntry : typeToValueMap.entries()) {
Class type;
try {
type = Class.forName(typeEntry.key);
} catch (ClassNotFoundException ex) {
throw new SerializationException(ex);
}
ObjectMap<String, ObjectMap> valueMap = (ObjectMap)typeEntry.value;
for (Entry<String, ObjectMap> valueEntry : valueMap.entries()) {
try {
if (isResource)
addResource(valueEntry.key, json.readValue(type, valueEntry.value));
else
addStyle(valueEntry.key, json.readValue(type, valueEntry.value));
} catch (Exception ex) {
throw new SerializationException("Error reading " + type.getSimpleName() + ": " + valueEntry.key, ex);
}
}
}
}
});
json.setSerializer(TextureRegion.class, new Serializer<TextureRegion>() {
public void write (Json json, TextureRegion region, Class valueType) {
json.writeObjectStart();
json.writeValue("x", region.getRegionX());
json.writeValue("y", region.getRegionY());
json.writeValue("width", region.getRegionWidth());
json.writeValue("height", region.getRegionHeight());
json.writeObjectEnd();
}
public TextureRegion read (Json json, Object jsonData, Class type) {
int x = json.readValue("x", int.class, jsonData);
int y = json.readValue("y", int.class, jsonData);
int width = json.readValue("width", int.class, jsonData);
int height = json.readValue("height", int.class, jsonData);
return new TextureRegion(skin.data.texture, x, y, width, height);
}
});
json.setSerializer(BitmapFont.class, new Serializer<BitmapFont>() {
public void write (Json json, BitmapFont font, Class valueType) {
json.writeValue(font.getData().getFontFile().toString().replace('\\', '/'));
}
public BitmapFont read (Json json, Object jsonData, Class type) {
String path = json.readValue(String.class, jsonData);
FileHandle file = skinFile.parent().child(path);
if (!file.exists()) file = Gdx.files.internal(path);
return new BitmapFont(file, false);
}
});
json.setSerializer(NinePatch.class, new Serializer<NinePatch>() {
public void write (Json json, NinePatch ninePatch, Class valueType) {
- json.writeValue(ninePatch.getPatches());
+ TextureRegion[] patches = ninePatch.getPatches();
+ if (patches[0] == null && patches[1] == null && patches[2] == null && patches[3] == null && patches[4] != null
+ && patches[5] == null && patches[6] == null && patches[7] == null && patches[8] == null)
+ json.writeValue(patches[4]);
+ else
+ json.writeValue(ninePatch.getPatches());
}
public NinePatch read (Json json, Object jsonData, Class type) {
TextureRegion[] regions = json.readValue(TextureRegion[].class, jsonData);
if (regions.length == 1) return new NinePatch(regions[0]);
return new NinePatch(regions);
}
});
return json;
}
}
| true | true | protected Json getJsonLoader (final FileHandle skinFile) {
final Skin skin = this;
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
class AliasSerializer implements Serializer {
final ObjectMap<String, ?> map;
public AliasSerializer (ObjectMap<String, ?> map) {
this.map = map;
}
public void write (Json json, Object object, Class valueType) {
for (Entry<String, ?> entry : map.entries()) {
if (entry.value.equals(object)) {
json.writeValue(entry.key);
return;
}
}
throw new SerializationException(object.getClass().getSimpleName() + " not found: " + object);
}
public Object read (Json json, Object jsonData, Class type) {
String name = (String)jsonData;
Object object = map.get(name);
if (object != null) return object;
throw new SerializationException("Skin has a " + type.getSimpleName() + " that could not be found in the resources: "
+ jsonData);
}
}
json.setSerializer(Skin.class, new Serializer<Skin>() {
public void write (Json json, Skin skin, Class valueType) {
json.writeObjectStart();
json.writeValue("resources", skin.data.resources);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
json.writeField(skin, "styles");
json.writeObjectEnd();
}
public Skin read (Json json, Object jsonData, Class ignored) {
ObjectMap map = (ObjectMap)jsonData;
readTypeMap(json, (ObjectMap)map.get("resources"), true);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
readTypeMap(json, (ObjectMap)map.get("styles"), false);
return skin;
}
private void readTypeMap (Json json, ObjectMap<String, ObjectMap> typeToValueMap, boolean isResource) {
if (typeToValueMap == null)
throw new SerializationException("Skin file is missing a \"" + (isResource ? "resources" : "styles")
+ "\" section.");
for (Entry<String, ObjectMap> typeEntry : typeToValueMap.entries()) {
Class type;
try {
type = Class.forName(typeEntry.key);
} catch (ClassNotFoundException ex) {
throw new SerializationException(ex);
}
ObjectMap<String, ObjectMap> valueMap = (ObjectMap)typeEntry.value;
for (Entry<String, ObjectMap> valueEntry : valueMap.entries()) {
try {
if (isResource)
addResource(valueEntry.key, json.readValue(type, valueEntry.value));
else
addStyle(valueEntry.key, json.readValue(type, valueEntry.value));
} catch (Exception ex) {
throw new SerializationException("Error reading " + type.getSimpleName() + ": " + valueEntry.key, ex);
}
}
}
}
});
json.setSerializer(TextureRegion.class, new Serializer<TextureRegion>() {
public void write (Json json, TextureRegion region, Class valueType) {
json.writeObjectStart();
json.writeValue("x", region.getRegionX());
json.writeValue("y", region.getRegionY());
json.writeValue("width", region.getRegionWidth());
json.writeValue("height", region.getRegionHeight());
json.writeObjectEnd();
}
public TextureRegion read (Json json, Object jsonData, Class type) {
int x = json.readValue("x", int.class, jsonData);
int y = json.readValue("y", int.class, jsonData);
int width = json.readValue("width", int.class, jsonData);
int height = json.readValue("height", int.class, jsonData);
return new TextureRegion(skin.data.texture, x, y, width, height);
}
});
json.setSerializer(BitmapFont.class, new Serializer<BitmapFont>() {
public void write (Json json, BitmapFont font, Class valueType) {
json.writeValue(font.getData().getFontFile().toString().replace('\\', '/'));
}
public BitmapFont read (Json json, Object jsonData, Class type) {
String path = json.readValue(String.class, jsonData);
FileHandle file = skinFile.parent().child(path);
if (!file.exists()) file = Gdx.files.internal(path);
return new BitmapFont(file, false);
}
});
json.setSerializer(NinePatch.class, new Serializer<NinePatch>() {
public void write (Json json, NinePatch ninePatch, Class valueType) {
json.writeValue(ninePatch.getPatches());
}
public NinePatch read (Json json, Object jsonData, Class type) {
TextureRegion[] regions = json.readValue(TextureRegion[].class, jsonData);
if (regions.length == 1) return new NinePatch(regions[0]);
return new NinePatch(regions);
}
});
return json;
}
| protected Json getJsonLoader (final FileHandle skinFile) {
final Skin skin = this;
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
class AliasSerializer implements Serializer {
final ObjectMap<String, ?> map;
public AliasSerializer (ObjectMap<String, ?> map) {
this.map = map;
}
public void write (Json json, Object object, Class valueType) {
for (Entry<String, ?> entry : map.entries()) {
if (entry.value.equals(object)) {
json.writeValue(entry.key);
return;
}
}
throw new SerializationException(object.getClass().getSimpleName() + " not found: " + object);
}
public Object read (Json json, Object jsonData, Class type) {
String name = (String)jsonData;
Object object = map.get(name);
if (object != null) return object;
throw new SerializationException("Skin has a " + type.getSimpleName() + " that could not be found in the resources: "
+ jsonData);
}
}
json.setSerializer(Skin.class, new Serializer<Skin>() {
public void write (Json json, Skin skin, Class valueType) {
json.writeObjectStart();
json.writeValue("resources", skin.data.resources);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
json.writeField(skin, "styles");
json.writeObjectEnd();
}
public Skin read (Json json, Object jsonData, Class ignored) {
ObjectMap map = (ObjectMap)jsonData;
readTypeMap(json, (ObjectMap)map.get("resources"), true);
for (Entry<Class, ObjectMap<String, Object>> entry : data.resources.entries())
json.setSerializer(entry.key, new AliasSerializer(entry.value));
readTypeMap(json, (ObjectMap)map.get("styles"), false);
return skin;
}
private void readTypeMap (Json json, ObjectMap<String, ObjectMap> typeToValueMap, boolean isResource) {
if (typeToValueMap == null)
throw new SerializationException("Skin file is missing a \"" + (isResource ? "resources" : "styles")
+ "\" section.");
for (Entry<String, ObjectMap> typeEntry : typeToValueMap.entries()) {
Class type;
try {
type = Class.forName(typeEntry.key);
} catch (ClassNotFoundException ex) {
throw new SerializationException(ex);
}
ObjectMap<String, ObjectMap> valueMap = (ObjectMap)typeEntry.value;
for (Entry<String, ObjectMap> valueEntry : valueMap.entries()) {
try {
if (isResource)
addResource(valueEntry.key, json.readValue(type, valueEntry.value));
else
addStyle(valueEntry.key, json.readValue(type, valueEntry.value));
} catch (Exception ex) {
throw new SerializationException("Error reading " + type.getSimpleName() + ": " + valueEntry.key, ex);
}
}
}
}
});
json.setSerializer(TextureRegion.class, new Serializer<TextureRegion>() {
public void write (Json json, TextureRegion region, Class valueType) {
json.writeObjectStart();
json.writeValue("x", region.getRegionX());
json.writeValue("y", region.getRegionY());
json.writeValue("width", region.getRegionWidth());
json.writeValue("height", region.getRegionHeight());
json.writeObjectEnd();
}
public TextureRegion read (Json json, Object jsonData, Class type) {
int x = json.readValue("x", int.class, jsonData);
int y = json.readValue("y", int.class, jsonData);
int width = json.readValue("width", int.class, jsonData);
int height = json.readValue("height", int.class, jsonData);
return new TextureRegion(skin.data.texture, x, y, width, height);
}
});
json.setSerializer(BitmapFont.class, new Serializer<BitmapFont>() {
public void write (Json json, BitmapFont font, Class valueType) {
json.writeValue(font.getData().getFontFile().toString().replace('\\', '/'));
}
public BitmapFont read (Json json, Object jsonData, Class type) {
String path = json.readValue(String.class, jsonData);
FileHandle file = skinFile.parent().child(path);
if (!file.exists()) file = Gdx.files.internal(path);
return new BitmapFont(file, false);
}
});
json.setSerializer(NinePatch.class, new Serializer<NinePatch>() {
public void write (Json json, NinePatch ninePatch, Class valueType) {
TextureRegion[] patches = ninePatch.getPatches();
if (patches[0] == null && patches[1] == null && patches[2] == null && patches[3] == null && patches[4] != null
&& patches[5] == null && patches[6] == null && patches[7] == null && patches[8] == null)
json.writeValue(patches[4]);
else
json.writeValue(ninePatch.getPatches());
}
public NinePatch read (Json json, Object jsonData, Class type) {
TextureRegion[] regions = json.readValue(TextureRegion[].class, jsonData);
if (regions.length == 1) return new NinePatch(regions[0]);
return new NinePatch(regions);
}
});
return json;
}
|
diff --git a/jupload2/src/wjhk/jupload2/upload/FileUploadThreadHTTP.java b/jupload2/src/wjhk/jupload2/upload/FileUploadThreadHTTP.java
index ac93d7a..a9e8f75 100644
--- a/jupload2/src/wjhk/jupload2/upload/FileUploadThreadHTTP.java
+++ b/jupload2/src/wjhk/jupload2/upload/FileUploadThreadHTTP.java
@@ -1,962 +1,961 @@
//
// $Id$
//
// jupload - A file upload applet.
// Copyright 2007 The JUpload Team
//
// Created: 2007-03-07
// Creator: etienne_sf
// Last modified: $Date$
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version. This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details. You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation, Inc.,
// 675 Mass Ave, Cambridge, MA 02139, USA.
package wjhk.jupload2.upload;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLSocket;
import javax.swing.JProgressBar;
import wjhk.jupload2.exception.JUploadException;
import wjhk.jupload2.exception.JUploadIOException;
import wjhk.jupload2.filedata.FileData;
import wjhk.jupload2.policies.UploadPolicy;
import wjhk.jupload2.upload.helper.ByteArrayEncoderHTTP;
import wjhk.jupload2.upload.helper.ByteArrayEncoder;
/**
* This class implements the file upload via HTTP POST request.
*
* @author etienne_sf
* @version $Revision$
*/
public class FileUploadThreadHTTP extends DefaultFileUploadThread {
private final static int CHUNKBUF_SIZE = 4096;
private final static Pattern pChunked = Pattern.compile(
"^Transfer-Encoding:\\s+chunked", Pattern.CASE_INSENSITIVE);
private final static Pattern pClose = Pattern.compile(
"^Connection:\\s+close", Pattern.CASE_INSENSITIVE);
private final static Pattern pProxyClose = Pattern.compile(
"^Proxy-Connection:\\s+close", Pattern.CASE_INSENSITIVE);
private final static Pattern pHttpStatus = Pattern
.compile("^HTTP/\\d\\.\\d\\s+((\\d+)\\s+.*)$");
private final static Pattern pContentLen = Pattern.compile(
"^Content-Length:\\s+(\\d+)$", Pattern.CASE_INSENSITIVE);
private final static Pattern pContentTypeCs = Pattern.compile(
"^Content-Type:\\s+.*;\\s*charset=([^;\\s]+).*$",
Pattern.CASE_INSENSITIVE);
private final static Pattern pSetCookie = Pattern.compile(
"^Set-Cookie:\\s+(.*)$", Pattern.CASE_INSENSITIVE);
private final byte chunkbuf[] = new byte[CHUNKBUF_SIZE];
private CookieJar cookies = new CookieJar();
/**
* http boundary, for the posting multipart post.
*/
private String boundary = "-----------------------------"
+ getRandomString();
/**
* local head within the multipart post, for each file. This is
* precalculated for all files, in case the upload is not chunked. The heads
* length are counted in the total upload size, to check that it is less
* than the maxChunkSize. tails are calculated once, as they depend not of
* the file position in the upload.
*/
private ByteArrayEncoder heads[] = null;
/**
* same as heads, for the ... tail in the multipart post, for each file. But
* tails depend on the file position (the boundary is added to the last
* tail). So it's to be calculated fror each upload.
*/
private ByteArrayEncoder tails[] = null;
/**
* This stream is open by {@link #startRequest(long, boolean, int, boolean)}.
* It is closed by the {@link #cleanRequest()} method.
*
* @see #startRequest(long, boolean, int, boolean)
* @see #cleanRequest()
* @see #getOutputStream()
*/
private DataOutputStream httpDataOut = null;
/**
* The network socket where the bytes should be written.
*/
private Socket sock = null;
/**
* This stream allows the applet to get the server response. It is opened
* and closed as the {@link #httpDataOut}.
*/
private InputStream httpDataIn = null;
/**
* This StringBuffer contains the body for the server response. That is: the
* server response without the http header. This the real functionnal
* response from the server application, that would be outputed, for
* instance, by any 'echo' PHP command.
*/
private StringBuffer sbHttpResponseBody = null;
/**
* Creates a new instance.
*
* @param filesDataParam The files to upload.
* @param uploadPolicy The policy to be applied.
* @param progress The progress bar to be updated.
*/
public FileUploadThreadHTTP(FileData[] filesDataParam,
UploadPolicy uploadPolicy, JProgressBar progress) {
super(filesDataParam, uploadPolicy, progress);
uploadPolicy.displayDebug("Upload done by using the "
+ getClass().getName() + " class", 40);
// Name the thread (useful for debugging)
setName("FileUploadThreadHTTP");
this.heads = new ByteArrayEncoder[filesDataParam.length];
this.tails = new ByteArrayEncoder[filesDataParam.length];
}
/** @see DefaultFileUploadThread#beforeRequest(int, int) */
@Override
void beforeRequest(int firstFileToUploadParam, int nbFilesToUploadParam)
throws JUploadException {
setAllHead(firstFileToUploadParam, nbFilesToUploadParam, this.boundary);
setAllTail(firstFileToUploadParam, nbFilesToUploadParam, this.boundary);
}
/** @see DefaultFileUploadThread#getAdditionnalBytesForUpload(int) */
@Override
long getAdditionnalBytesForUpload(int index) throws JUploadIOException {
return this.heads[index].getEncodedLength()
+ this.tails[index].getEncodedLength();
}
/** @see DefaultFileUploadThread#afterFile(int) */
@Override
void afterFile(int index) throws JUploadIOException {
try {
this.httpDataOut.write(tails[index].getEncodedByteArray());
this.uploadPolicy.displayDebug("--- filetail start (len="
+ tails[index].getEncodedLength() + "):", 80);
this.uploadPolicy.displayDebug(quoteCRLF(tails[index].getString()),
80);
this.uploadPolicy.displayDebug("--- filetail end", 80);
} catch (IOException e) {
throw new JUploadIOException(e);
}
}
/** @see DefaultFileUploadThread#beforeFile(int) */
@Override
void beforeFile(int index) throws JUploadException {
// heads[i] contains the header specific for the file, in the multipart
// content.
// It is initialized at the beginning of the run() method. It can be
// override at the beginning
// of this loop, if in chunk mode.
try {
this.httpDataOut.write(this.heads[index].getEncodedByteArray());
// Debug output: always called, so that the debug file is correctly
// filled.
this.uploadPolicy.displayDebug("--- fileheader start (len="
+ this.heads[index].getEncodedLength() + "):", 80);
this.uploadPolicy.displayDebug(quoteCRLF(this.heads[index]
.getString()), 80);
this.uploadPolicy.displayDebug("--- fileheader end", 80);
} catch (Exception e) {
throw new JUploadException(e);
}
}
/** @see DefaultFileUploadThread#cleanAll() */
@SuppressWarnings("unused")
@Override
void cleanAll() throws JUploadException {
// Nothing to do in HTTP mode.
}
/** @see DefaultFileUploadThread#cleanRequest() */
@Override
void cleanRequest() throws JUploadException {
JUploadException localException = null;
try {
// Throws java.io.IOException
this.httpDataOut.close();
} catch (NullPointerException e) {
// httpDataOut is already null ...
} catch (IOException e) {
localException = new JUploadException(e);
this.uploadPolicy.displayErr(this.uploadPolicy
.getString("errDuringUpload"), e);
} finally {
this.httpDataOut = null;
}
try {
// Throws java.io.IOException
this.httpDataIn.close();
} catch (NullPointerException e) {
// httpDataIn is already null ...
} catch (IOException e) {
if (localException != null) {
localException = new JUploadException(e);
this.uploadPolicy.displayErr(this.uploadPolicy
.getString("errDuringUpload"), localException);
}
} finally {
this.httpDataIn = null;
}
try {
// Throws java.io.IOException
this.sock.close();
} catch (NullPointerException e) {
// sock is already null ...
} catch (IOException e) {
if (localException != null) {
localException = new JUploadException(e);
this.uploadPolicy.displayErr(this.uploadPolicy
.getString("errDuringUpload"), e);
}
} finally {
this.sock = null;
}
if (localException != null) {
throw localException;
}
}
@Override
int finishRequest() throws JUploadException {
boolean readingHttpBody = false;
boolean gotClose = false;
boolean gotChunked = false;
boolean gotContentLength = false;
int status = 0;
int clen = 0;
String line = "";
byte[] body = new byte[0];
String charset = "ISO-8859-1";
this.sbHttpResponseBody = new StringBuffer();
try {
// If the user requested abort, we are not going to send
// anymore, so shutdown the outgoing half of the socket.
// This helps the server to speed up with it's response.
if (this.stop && !(this.sock instanceof SSLSocket))
this.sock.shutdownOutput();
// && is evaluated from left to right so !stop must come first!
while (!this.stop && ((!gotContentLength) || (clen > 0))) {
if (readingHttpBody) {
// Read the http body
if (gotChunked) {
// Read the chunk header.
// This is US-ASCII! (See RFC 2616, Section 2.2)
line = readLine(httpDataIn, "US-ASCII", false);
if (null == line)
- throw new JUploadException("unexpected EOF");
+ throw new JUploadException("unexpected EOF (in HTTP Body, chunked mode)");
// Handle a single chunk of the response
// We cut off possible chunk extensions and ignore them.
// The length is hex-encoded (RFC 2616, Section 3.6.1)
int len = Integer.parseInt(line.replaceFirst(";.*", "")
.trim(), 16);
this.uploadPolicy.displayDebug("Chunk: " + line
+ " dec: " + len, 80);
if (len == 0) {
// RFC 2616, Section 3.6.1: A length of 0 denotes
// the last chunk of the body.
// This code wrong if the server sends chunks
// with trailers! (trailers are HTTP Headers that
// are send *after* the body. These are announced
// in the regular HTTP header "Trailer".
// Fritz: Never seen them so far ...
// TODO: Implement trailer-handling.
break;
}
// Loop over the chunk (len == length of the chunk)
while (len > 0) {
int rlen = (len > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: len;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
"unexpected EOF");
len -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf, rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
// Got the whole chunk, read the trailing CRLF.
readLine(httpDataIn, false);
} else {
// Not chunked. Use either content-length (if available)
// or read until EOF.
if (gotContentLength) {
// Got a Content-Length. Read exactly that amount of
// bytes.
while (clen > 0) {
int rlen = (clen > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: clen;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
- "unexpected EOF");
+ "unexpected EOF (in HTTP body, not chunked mode)");
clen -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf,
rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
} else {
// No Content-length available, read until EOF
//
while (true) {
byte[] lbuf = readLine(httpDataIn, true);
if (null == lbuf)
break;
body = byteAppend(body, lbuf);
}
break;
}
}
- } else {
+ } else { // if (readingHttpBody)
// readingHttpBody is false, so we are still in headers.
// Headers are US-ASCII (See RFC 2616, Section 2.2)
String tmp = readLine(httpDataIn, "US-ASCII", false);
if (null == tmp)
- throw new JUploadException("unexpected EOF");
+ throw new JUploadException("unexpected EOF (in header)");
if (status == 0) {
+ // We must be reading the first line of the HTTP header.
this.uploadPolicy.displayDebug(
"-------- Response Headers Start --------", 80);
Matcher m = pHttpStatus.matcher(tmp);
if (m.matches()) {
status = Integer.parseInt(m.group(2));
setResponseMsg(m.group(1));
} else {
// The status line must be the first line of the
// response. (See RFC 2616, Section 6.1) so this
// is an error.
// We first display the wrong line.
this.uploadPolicy
.displayDebug("First line of response: '"
+ tmp + "'", 80);
// Then, we throw the exception.
throw new JUploadException(
"HTTP response did not begin with status line.");
}
}
// Handle folded headers (RFC 2616, Section 2.2). This is
// handled after the status line, because that line may
// not be folded (RFC 2616, Section 6.1).
if (tmp.startsWith(" ") || tmp.startsWith("\t"))
line += " " + tmp.trim();
else
line = tmp;
this.uploadPolicy.displayDebug(line, 80);
if (pClose.matcher(line).matches())
gotClose = true;
if (pProxyClose.matcher(line).matches())
gotClose = true;
if (pChunked.matcher(line).matches())
gotChunked = true;
Matcher m = pContentLen.matcher(line);
if (m.matches()) {
gotContentLength = true;
clen = Integer.parseInt(m.group(1));
}
m = pContentTypeCs.matcher(line);
if (m.matches())
charset = m.group(1);
m = pSetCookie.matcher(line);
if (m.matches())
this.cookies.parseCookieHeader(m.group(1));
if (line.length() == 0) {
// RFC 2616, Section 6. Body is separated by the
// header with an empty line.
readingHttpBody = true;
this.uploadPolicy.displayDebug(
"--------- Response Headers End ---------", 80);
}
}
} // while
if (gotClose) {
// RFC 2868, section 8.1.2.1
cleanRequest();
}
// Convert the whole body according to the charset.
// The default for charset ISO-8859-1, but overridden by
// the charset attribute of the Content-Type header (if any).
// See RFC 2616, Sections 3.4.1 and 3.7.1.
this.sbHttpResponseBody.append(new String(body, charset));
- } catch (JUploadException e) {
- throw e;
} catch (Exception e) {
e.printStackTrace();
throw new JUploadException(e);
}
return status;
}
/** @see DefaultFileUploadThread#getResponseBody() */
@Override
String getResponseBody() {
return this.sbHttpResponseBody.toString();
}
/** @see DefaultFileUploadThread#getOutputStream() */
@SuppressWarnings("unused")
@Override
OutputStream getOutputStream() throws JUploadException {
return this.httpDataOut;
}
/** @see DefaultFileUploadThread#startRequest(long, boolean, int, boolean) */
@Override
void startRequest(long contentLength, boolean bChunkEnabled, int chunkPart,
boolean bLastChunk) throws JUploadException {
ByteArrayEncoder header = new ByteArrayEncoderHTTP(uploadPolicy,
boundary);
try {
String chunkHttpParam = "jupart=" + chunkPart + "&jufinal="
+ (bLastChunk ? "1" : "0");
this.uploadPolicy.displayDebug("chunkHttpParam: " + chunkHttpParam,
40);
URL url = new URL(this.uploadPolicy.getPostURL());
// Add the chunking query params to the URL if there are any
if (bChunkEnabled) {
if (null != url.getQuery() && !"".equals(url.getQuery())) {
url = new URL(url.toExternalForm() + "&" + chunkHttpParam);
} else {
url = new URL(url.toExternalForm() + "?" + chunkHttpParam);
}
}
Proxy proxy = null;
proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
boolean useSSL = url.getProtocol().equals("https");
// Header: Request line
// Let's clear it. Useful only for chunked uploads.
header.append("POST ");
if (useProxy && (!useSSL)) {
// with a proxy we need the absolute URL, but only if not
// using SSL. (with SSL, we first use the proxy CONNECT method,
// and then a plain request.)
header.append(url.getProtocol()).append("://").append(
url.getHost());
}
header.append(url.getPath());
// Append the query params.
// TODO: This probably can be removed as we now
// have everything in POST data. However in order to be
// backwards-compatible, it stays here for now. So we now provide
// *both* GET and POST params.
if (null != url.getQuery() && !"".equals(url.getQuery()))
header.append("?").append(url.getQuery());
header.append(" ").append(this.uploadPolicy.getServerProtocol())
.append("\r\n");
// Header: General
header.append("Host: ").append(url.getHost()).append(
"\r\nAccept: */*\r\n");
// We do not want gzipped or compressed responses, so we must
// specify that here (RFC 2616, Section 14.3)
header.append("Accept-Encoding: identity\r\n");
// Seems like the Keep-alive doesn't work properly, at least on my
// local dev (Etienne).
if (!this.uploadPolicy.getAllowHttpPersistent()) {
header.append("Connection: close\r\n");
} else {
if (!bChunkEnabled
|| bLastChunk
|| useProxy
|| !this.uploadPolicy.getServerProtocol().equals(
"HTTP/1.1")) { // RFC 2086, section 19.7.1
header.append("Connection: close\r\n");
} else {
header.append("Keep-Alive: 300\r\n");
if (useProxy)
header.append("Proxy-Connection: keep-alive\r\n");
else
header.append("Connection: keep-alive\r\n");
}
}
// Get the GET parameters from the URL and convert them to
// post form params
ByteArrayEncoder formParams = getFormParamsForPostRequest(url);
contentLength += formParams.getEncodedLength();
header.append("Content-Type: multipart/form-data; boundary=")
.append(this.boundary.substring(2)).append("\r\n");
header.append("Content-Length: ").append(
String.valueOf(contentLength)).append("\r\n");
// Get specific headers for this upload.
this.uploadPolicy.onAppendHeader(header);
// Blank line (end of header)
header.append("\r\n");
// formParams are not really part of the main header, but we add
// them here anyway. We write directly into the
// ByteArrayOutputStream, as we already encoded them, to get the
// encoded length. We need to flush the writer first, before
// directly writting to the ByteArrayOutputStream.
header.append(formParams);
// Only connect, if sock is null!!
// ... or if we don't persist HTTP connections (patch for IIS, based
// on Marc Reidy's patch)
if (this.sock == null || !uploadPolicy.getAllowHttpPersistent()) {
this.sock = new HttpConnect(this.uploadPolicy).Connect(url,
proxy);
this.httpDataOut = new DataOutputStream(
new BufferedOutputStream(this.sock.getOutputStream()));
this.httpDataIn = this.sock.getInputStream();
}
// The header is now constructed.
header.close();
// Send http request to server
this.httpDataOut.write(header.getEncodedByteArray());
// Debug output: always called, so that the debug file is correctly
// filled.
this.uploadPolicy.displayDebug("=== main header (len="
+ header.getEncodedLength() + "):\n"
+ quoteCRLF(header.getString()), 80);
this.uploadPolicy.displayDebug("=== main header end", 80);
} catch (IOException e) {
throw new JUploadIOException(e);
} catch (KeyManagementException e) {
throw new JUploadException(e);
} catch (UnrecoverableKeyException e) {
throw new JUploadException(e);
} catch (NoSuchAlgorithmException e) {
throw new JUploadException(e);
} catch (KeyStoreException e) {
throw new JUploadException(e);
} catch (CertificateException e) {
throw new JUploadException(e);
} catch (IllegalArgumentException e) {
throw new JUploadException(e);
} catch (URISyntaxException e) {
throw new JUploadException(e);
}
}
// ////////////////////////////////////////////////////////////////////////////////////
// /////////////////////// PRIVATE METHODS
// ///////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////////////
/**
* Construction of a random string, to separate the uploaded files, in the
* HTTP upload request.
*/
private final String getRandomString() {
StringBuffer sbRan = new StringBuffer(11);
String alphaNum = "1234567890abcdefghijklmnopqrstuvwxyz";
int num;
for (int i = 0; i < 11; i++) {
num = (int) (Math.random() * (alphaNum.length() - 1));
sbRan.append(alphaNum.charAt(num));
}
return sbRan.toString();
}
/**
* Creates a mime multipart string snippet, representing a POST variable.
*
* @param bae The ByteArrayEncoder, in which the variable is to be added.
* @param bound The multipart boundary to use.
* @param name The name of the POST variable
* @param value The value of the POST variable
* @throws JUploadIOException An exception that can be thrown while trying
* to encode the given parameter to the current charset.
*
* private final ByteArrayEncoder addPostVariable(ByteArrayEncoder bae,
* String bound, String name, String value) throws JUploadIOException {
* bae.append(bound).append("\r\n"); bae.append("Content-Disposition:
* form-data; name=\"").append(name) .append("\"\r\n");
* bae.append("Content-Transfer-Encoding: 8bit\r\n");
* bae.append("Content-Type: text/plain; UTF-8\r\n"); // An empty line
* before the actual value. bae.append("\r\n"); // And then, the value!
* bae.append(value).append("\r\n");
*
* return bae; }
*/
/**
* Creates a mime multipart string snippet, representing a FORM. Extracts
* all form elements of a given HTML form and assembles a StringBuffer which
* contains a sequence of mime multipart messages which represent the
* elements of that form.
*
* @param bae The ByteArrayEncoder, in which the variable is to be added.
* @param bound The multipart boundary to use.
* @param formname The name of the form to evaluate.
* @return the bae parameter, suitable for appending to the multipart
* content.
* @throws JUploadIOException An exception that can be thrown while trying
* to encode the given parameter to the current charset.
*/
/**
* Returns the header for this file, within the http multipart body.
*
* @param index Index of the file in the array that contains all files to
* upload.
* @param bound The boundary that separate files in the http multipart post
* body.
* @param chunkPart The numero of the current chunk (from 1 to n)
* @return The encoded header for this file. The {@link ByteArrayEncoder} is
* closed within this method.
* @throws JUploadException
*/
private final ByteArrayEncoder getFileHeader(int index, String bound,
@SuppressWarnings("unused")
int chunkPart) throws JUploadException {
String filenameEncoding = this.uploadPolicy.getFilenameEncoding();
String mimetype = this.filesToUpload[index].getMimeType();
String uploadFilename = this.filesToUpload[index]
.getUploadFilename(index);
ByteArrayEncoder bae = new ByteArrayEncoderHTTP(uploadPolicy, bound);
// We'll encode the output stream into UTF-8.
String form = this.uploadPolicy.getFormdata();
if (null != form) {
bae.appendFormVariables(form);
}
// We ask the current FileData to add itself its properties.
this.filesToUpload[index].appendFileProperties(bae);
// boundary.
bae.append(bound).append("\r\n");
// Content-Disposition.
bae.append("Content-Disposition: form-data; name=\"");
bae.append(this.filesToUpload[index].getUploadName(index)).append(
"\"; filename=\"");
if (filenameEncoding == null) {
bae.append(uploadFilename);
} else {
try {
this.uploadPolicy.displayDebug("Encoded filename: "
+ URLEncoder.encode(uploadFilename, filenameEncoding),
99);
bae.append(URLEncoder.encode(uploadFilename, filenameEncoding));
} catch (UnsupportedEncodingException e) {
this.uploadPolicy
.displayWarn(e.getClass().getName() + ": "
+ e.getMessage()
+ " (in UploadFileData.getFileHeader)");
bae.append(uploadFilename);
}
}
bae.append("\"\r\n");
// Line 3: Content-Type.
bae.append("Content-Type: ").append(mimetype).append("\r\n");
// An empty line to finish the header.
bae.append("\r\n");
// The ByteArrayEncoder is now filled.
bae.close();
return bae;
}// getFileHeader
/**
* Construction of the head for each file.
*
* @param firstFileToUpload The index of the first file to upload, in the
* {@link #filesToUpload} area.
* @param nbFilesToUpload Number of file to upload, in the next HTTP upload
* request. These files are taken from the {@link #filesToUpload}
* area
* @param bound The String boundary between the post data in the HTTP
* request.
* @throws JUploadException
*/
private final void setAllHead(int firstFileToUpload, int nbFilesToUpload,
String bound) throws JUploadException {
for (int i = firstFileToUpload; i < firstFileToUpload + nbFilesToUpload; i++) {
this.heads[i] = getFileHeader(i, bound, -1);
}
}
/**
* Construction of the tail for each file.
*
* @param firstFileToUpload The index of the first file to upload, in the
* {@link #filesToUpload} area.
* @param nbFilesToUpload Number of file to upload, in the next HTTP upload
* request. These files are taken from the {@link #filesToUpload}
* area
* @param bound Current boundary, to apply for these tails.
*/
private final void setAllTail(int firstFileToUpload, int nbFilesToUpload,
String bound) throws JUploadException {
for (int i = firstFileToUpload; i < firstFileToUpload + nbFilesToUpload; i++) {
// We'll encode the output stream into UTF-8.
ByteArrayEncoder bae = new ByteArrayEncoderHTTP(uploadPolicy, bound);
bae.append("\r\n");
bae.appendFileProperty("md5sum[]", this.filesToUpload[i].getMD5());
// The last tail gets an additional "--" in order to tell the
// server we have finished.
if (i == firstFileToUpload + nbFilesToUpload - 1) {
bae.append(bound).append("--\r\n");
}
// Let's store this tail.
bae.close();
this.tails[i] = bae;
}
}
/**
* Converts the parameters in GET form to post form
*
* @param url the <code>URL</code> containing the query parameters
* @return the parameters in a string in the correct form for a POST request
* @throws JUploadIOException
*/
private final ByteArrayEncoder getFormParamsForPostRequest(final URL url)
throws JUploadIOException {
// Use a string buffer
// We'll encode the output stream into UTF-8.
ByteArrayEncoder bae = new ByteArrayEncoderHTTP(uploadPolicy,
this.boundary);
// Get the query string
String query = url.getQuery();
if (null != query) {
// Split this into parameters
HashMap<String, String> requestParameters = new HashMap<String, String>();
String[] paramPairs = query.split("&");
String[] oneParamArray;
// Put the parameters correctly to the Hashmap
for (String param : paramPairs) {
if (param.contains("=")) {
oneParamArray = param.split("=");
if (oneParamArray.length > 1) {
// There is a value for this parameter
requestParameters.put(oneParamArray[0],
oneParamArray[1]);
} else {
// There is no value for this parameter
requestParameters.put(oneParamArray[0], "");
}
}
}
// Now add one multipart segment for each
for (String key : requestParameters.keySet())
bae.appendFileProperty(key, requestParameters.get(key));
}
// Return the body content
bae.close();
return bae;
}// getFormParamsForPostRequest
// //////////////////////////////////////////////////////////////////////////////////////
// //////////////////// Various utilities
// //////////////////////////////////////////////////////////////////////////////////////
/**
* Similar like BufferedInputStream#readLine() but operates on raw bytes.
* Line-Ending is <b>always</b> "\r\n".
*
* @param charset The input charset of the stream.
* @param includeCR Set to true, if the terminating CR/LF should be included
* in the returned byte array.
*/
static String readLine(InputStream inputStream, String charset,
boolean includeCR) throws IOException {
byte[] line = readLine(inputStream, includeCR);
return (null == line) ? null : new String(line, charset);
}
/**
* Similar like BufferedInputStream#readLine() but operates on raw bytes.
* Line-Ending is <b>always</b> "\r\n". Update done by TedA (sourceforge
* account: tedaaa). Allows to manage response from web server that send LF
* instead of CRLF ! Here is a part of the RFC: <I>"we recommend that
* applications, when parsing such headers, recognize a single LF as a line
* terminator and ignore the leading CR"</I>.
*
* @param includeCR Set to true, if the terminating CR/LF should be included
* in the returned byte array.
*/
static byte[] readLine(InputStream inputStream, boolean includeCR)
throws IOException {
int len = 0;
int buflen = 128; // average line length
byte[] buf = new byte[buflen];
byte[] ret = null;
int b;
while (true) {
b = inputStream.read();
switch (b) {
case -1:
if (len > 0) {
ret = new byte[len];
System.arraycopy(buf, 0, ret, 0, len);
return ret;
}
return null;
case 10:
if (len > 0) {
if (buf[len - 1] == 13) {
if (includeCR) {
ret = new byte[len + 1];
if (len > 0)
System.arraycopy(buf, 0, ret, 0, len);
ret[len] = 10;
} else {
len--;
ret = new byte[len];
if (len > 0)
System.arraycopy(buf, 0, ret, 0, len);
}
} else {
ret = new byte[len];
if (len > 0)
System.arraycopy(buf, 0, ret, 0, len);
}
} else // line feed for empty line between headers and body
{
ret = new byte[0];
}
return ret;
default:
buf[len++] = (byte) b;
if (len >= buflen) {
buflen *= 2;
byte[] tmp = new byte[buflen];
System.arraycopy(buf, 0, tmp, 0, len);
buf = tmp;
}
}
}
}
/**
* Concatenates two byte arrays.
*
* @param buf1 The first array
* @param buf2 The second array
* @return A byte array, containing buf2 appended to buf2
*/
static byte[] byteAppend(byte[] buf1, byte[] buf2) {
byte[] ret = new byte[buf1.length + buf2.length];
System.arraycopy(buf1, 0, ret, 0, buf1.length);
System.arraycopy(buf2, 0, ret, buf1.length, buf2.length);
return ret;
}
/**
* Concatenates two byte arrays.
*
* @param buf1 The first array
* @param buf2 The second array
* @param len Number of bytes to copy from buf2
* @return A byte array, containing buf2 appended to buf2
*/
static byte[] byteAppend(byte[] buf1, byte[] buf2, int len) {
if (len > buf2.length)
len = buf2.length;
byte[] ret = new byte[buf1.length + len];
System.arraycopy(buf1, 0, ret, 0, buf1.length);
System.arraycopy(buf2, 0, ret, buf1.length, len);
return ret;
}
}
| false | true | int finishRequest() throws JUploadException {
boolean readingHttpBody = false;
boolean gotClose = false;
boolean gotChunked = false;
boolean gotContentLength = false;
int status = 0;
int clen = 0;
String line = "";
byte[] body = new byte[0];
String charset = "ISO-8859-1";
this.sbHttpResponseBody = new StringBuffer();
try {
// If the user requested abort, we are not going to send
// anymore, so shutdown the outgoing half of the socket.
// This helps the server to speed up with it's response.
if (this.stop && !(this.sock instanceof SSLSocket))
this.sock.shutdownOutput();
// && is evaluated from left to right so !stop must come first!
while (!this.stop && ((!gotContentLength) || (clen > 0))) {
if (readingHttpBody) {
// Read the http body
if (gotChunked) {
// Read the chunk header.
// This is US-ASCII! (See RFC 2616, Section 2.2)
line = readLine(httpDataIn, "US-ASCII", false);
if (null == line)
throw new JUploadException("unexpected EOF");
// Handle a single chunk of the response
// We cut off possible chunk extensions and ignore them.
// The length is hex-encoded (RFC 2616, Section 3.6.1)
int len = Integer.parseInt(line.replaceFirst(";.*", "")
.trim(), 16);
this.uploadPolicy.displayDebug("Chunk: " + line
+ " dec: " + len, 80);
if (len == 0) {
// RFC 2616, Section 3.6.1: A length of 0 denotes
// the last chunk of the body.
// This code wrong if the server sends chunks
// with trailers! (trailers are HTTP Headers that
// are send *after* the body. These are announced
// in the regular HTTP header "Trailer".
// Fritz: Never seen them so far ...
// TODO: Implement trailer-handling.
break;
}
// Loop over the chunk (len == length of the chunk)
while (len > 0) {
int rlen = (len > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: len;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
"unexpected EOF");
len -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf, rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
// Got the whole chunk, read the trailing CRLF.
readLine(httpDataIn, false);
} else {
// Not chunked. Use either content-length (if available)
// or read until EOF.
if (gotContentLength) {
// Got a Content-Length. Read exactly that amount of
// bytes.
while (clen > 0) {
int rlen = (clen > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: clen;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
"unexpected EOF");
clen -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf,
rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
} else {
// No Content-length available, read until EOF
//
while (true) {
byte[] lbuf = readLine(httpDataIn, true);
if (null == lbuf)
break;
body = byteAppend(body, lbuf);
}
break;
}
}
} else {
// readingHttpBody is false, so we are still in headers.
// Headers are US-ASCII (See RFC 2616, Section 2.2)
String tmp = readLine(httpDataIn, "US-ASCII", false);
if (null == tmp)
throw new JUploadException("unexpected EOF");
if (status == 0) {
this.uploadPolicy.displayDebug(
"-------- Response Headers Start --------", 80);
Matcher m = pHttpStatus.matcher(tmp);
if (m.matches()) {
status = Integer.parseInt(m.group(2));
setResponseMsg(m.group(1));
} else {
// The status line must be the first line of the
// response. (See RFC 2616, Section 6.1) so this
// is an error.
// We first display the wrong line.
this.uploadPolicy
.displayDebug("First line of response: '"
+ tmp + "'", 80);
// Then, we throw the exception.
throw new JUploadException(
"HTTP response did not begin with status line.");
}
}
// Handle folded headers (RFC 2616, Section 2.2). This is
// handled after the status line, because that line may
// not be folded (RFC 2616, Section 6.1).
if (tmp.startsWith(" ") || tmp.startsWith("\t"))
line += " " + tmp.trim();
else
line = tmp;
this.uploadPolicy.displayDebug(line, 80);
if (pClose.matcher(line).matches())
gotClose = true;
if (pProxyClose.matcher(line).matches())
gotClose = true;
if (pChunked.matcher(line).matches())
gotChunked = true;
Matcher m = pContentLen.matcher(line);
if (m.matches()) {
gotContentLength = true;
clen = Integer.parseInt(m.group(1));
}
m = pContentTypeCs.matcher(line);
if (m.matches())
charset = m.group(1);
m = pSetCookie.matcher(line);
if (m.matches())
this.cookies.parseCookieHeader(m.group(1));
if (line.length() == 0) {
// RFC 2616, Section 6. Body is separated by the
// header with an empty line.
readingHttpBody = true;
this.uploadPolicy.displayDebug(
"--------- Response Headers End ---------", 80);
}
}
} // while
if (gotClose) {
// RFC 2868, section 8.1.2.1
cleanRequest();
}
// Convert the whole body according to the charset.
// The default for charset ISO-8859-1, but overridden by
// the charset attribute of the Content-Type header (if any).
// See RFC 2616, Sections 3.4.1 and 3.7.1.
this.sbHttpResponseBody.append(new String(body, charset));
} catch (JUploadException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
throw new JUploadException(e);
}
return status;
}
| int finishRequest() throws JUploadException {
boolean readingHttpBody = false;
boolean gotClose = false;
boolean gotChunked = false;
boolean gotContentLength = false;
int status = 0;
int clen = 0;
String line = "";
byte[] body = new byte[0];
String charset = "ISO-8859-1";
this.sbHttpResponseBody = new StringBuffer();
try {
// If the user requested abort, we are not going to send
// anymore, so shutdown the outgoing half of the socket.
// This helps the server to speed up with it's response.
if (this.stop && !(this.sock instanceof SSLSocket))
this.sock.shutdownOutput();
// && is evaluated from left to right so !stop must come first!
while (!this.stop && ((!gotContentLength) || (clen > 0))) {
if (readingHttpBody) {
// Read the http body
if (gotChunked) {
// Read the chunk header.
// This is US-ASCII! (See RFC 2616, Section 2.2)
line = readLine(httpDataIn, "US-ASCII", false);
if (null == line)
throw new JUploadException("unexpected EOF (in HTTP Body, chunked mode)");
// Handle a single chunk of the response
// We cut off possible chunk extensions and ignore them.
// The length is hex-encoded (RFC 2616, Section 3.6.1)
int len = Integer.parseInt(line.replaceFirst(";.*", "")
.trim(), 16);
this.uploadPolicy.displayDebug("Chunk: " + line
+ " dec: " + len, 80);
if (len == 0) {
// RFC 2616, Section 3.6.1: A length of 0 denotes
// the last chunk of the body.
// This code wrong if the server sends chunks
// with trailers! (trailers are HTTP Headers that
// are send *after* the body. These are announced
// in the regular HTTP header "Trailer".
// Fritz: Never seen them so far ...
// TODO: Implement trailer-handling.
break;
}
// Loop over the chunk (len == length of the chunk)
while (len > 0) {
int rlen = (len > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: len;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
"unexpected EOF");
len -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf, rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
// Got the whole chunk, read the trailing CRLF.
readLine(httpDataIn, false);
} else {
// Not chunked. Use either content-length (if available)
// or read until EOF.
if (gotContentLength) {
// Got a Content-Length. Read exactly that amount of
// bytes.
while (clen > 0) {
int rlen = (clen > CHUNKBUF_SIZE) ? CHUNKBUF_SIZE
: clen;
int ofs = 0;
if (rlen > 0) {
while (ofs < rlen) {
int res = this.httpDataIn.read(
this.chunkbuf, ofs, rlen - ofs);
if (res < 0)
throw new JUploadException(
"unexpected EOF (in HTTP body, not chunked mode)");
clen -= res;
ofs += res;
}
if (ofs < rlen)
throw new JUploadException("short read");
if (rlen < CHUNKBUF_SIZE)
body = byteAppend(body, this.chunkbuf,
rlen);
else
body = byteAppend(body, this.chunkbuf);
}
}
} else {
// No Content-length available, read until EOF
//
while (true) {
byte[] lbuf = readLine(httpDataIn, true);
if (null == lbuf)
break;
body = byteAppend(body, lbuf);
}
break;
}
}
} else { // if (readingHttpBody)
// readingHttpBody is false, so we are still in headers.
// Headers are US-ASCII (See RFC 2616, Section 2.2)
String tmp = readLine(httpDataIn, "US-ASCII", false);
if (null == tmp)
throw new JUploadException("unexpected EOF (in header)");
if (status == 0) {
// We must be reading the first line of the HTTP header.
this.uploadPolicy.displayDebug(
"-------- Response Headers Start --------", 80);
Matcher m = pHttpStatus.matcher(tmp);
if (m.matches()) {
status = Integer.parseInt(m.group(2));
setResponseMsg(m.group(1));
} else {
// The status line must be the first line of the
// response. (See RFC 2616, Section 6.1) so this
// is an error.
// We first display the wrong line.
this.uploadPolicy
.displayDebug("First line of response: '"
+ tmp + "'", 80);
// Then, we throw the exception.
throw new JUploadException(
"HTTP response did not begin with status line.");
}
}
// Handle folded headers (RFC 2616, Section 2.2). This is
// handled after the status line, because that line may
// not be folded (RFC 2616, Section 6.1).
if (tmp.startsWith(" ") || tmp.startsWith("\t"))
line += " " + tmp.trim();
else
line = tmp;
this.uploadPolicy.displayDebug(line, 80);
if (pClose.matcher(line).matches())
gotClose = true;
if (pProxyClose.matcher(line).matches())
gotClose = true;
if (pChunked.matcher(line).matches())
gotChunked = true;
Matcher m = pContentLen.matcher(line);
if (m.matches()) {
gotContentLength = true;
clen = Integer.parseInt(m.group(1));
}
m = pContentTypeCs.matcher(line);
if (m.matches())
charset = m.group(1);
m = pSetCookie.matcher(line);
if (m.matches())
this.cookies.parseCookieHeader(m.group(1));
if (line.length() == 0) {
// RFC 2616, Section 6. Body is separated by the
// header with an empty line.
readingHttpBody = true;
this.uploadPolicy.displayDebug(
"--------- Response Headers End ---------", 80);
}
}
} // while
if (gotClose) {
// RFC 2868, section 8.1.2.1
cleanRequest();
}
// Convert the whole body according to the charset.
// The default for charset ISO-8859-1, but overridden by
// the charset attribute of the Content-Type header (if any).
// See RFC 2616, Sections 3.4.1 and 3.7.1.
this.sbHttpResponseBody.append(new String(body, charset));
} catch (Exception e) {
e.printStackTrace();
throw new JUploadException(e);
}
return status;
}
|
diff --git a/src/monakhv/android/samlib/data/DataExportImport.java b/src/monakhv/android/samlib/data/DataExportImport.java
index d612cb3..493570d 100644
--- a/src/monakhv/android/samlib/data/DataExportImport.java
+++ b/src/monakhv/android/samlib/data/DataExportImport.java
@@ -1,320 +1,320 @@
/*
* Copyright 2013 Dmitry Monakhov.
*
* 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 monakhv.android.samlib.data;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import monakhv.android.samlib.sql.AuthorController;
import monakhv.android.samlib.sql.SQLController;
import monakhv.android.samlib.sql.entity.Author;
import monakhv.android.samlib.sql.entity.Book;
import monakhv.android.samlib.sql.entity.SamLibConfig;
import monakhv.android.samlib.tasks.AddAuthor;
/**
*
* @author monakhv
*/
public class DataExportImport {
private static final String DATE_FORMAT = "dd-MM-yyyy";
private static final String DATE_FORMAT_DEBUG = "dd-MM-yyyy HH:mm:ss";
private static final String DEBUG_TAG = "DataExportImport";
private static final String BACKUP_DIR = "//SamLib-Info//";
private static final String BOOKS_DIR = "Book//";
private static final String DB_EXT = ".db";
private static final String DB_PREFIX = SQLController.DB_NAME;
private static final String DEBUG_FILE = SQLController.DB_NAME + ".log";
private static final File SD = Environment.getExternalStorageDirectory();
private static final File backupDIR = new File(SD, BACKUP_DIR);
private static final String TXT_PREFIX = "Authors";
private static final String TXT_EXT = ".txt";
private static final String HTM_EXT = ".htm";
private static final String HTML_EXT = ".html";
/**
* Setting file to store book content
* making parent directories if need
*
* @param book
* @return
*/
public static File _getBookFile(Book book){
String ff= BOOKS_DIR +"/"+ book.getUri() + ".html";
File ss = new File(backupDIR, ff);
File pp = ss.getParentFile();
pp.mkdirs();
//Log.d(DEBUG_TAG, "Path: "+ss.getAbsolutePath());
return ss;
}
public static void findDeleteBookFile(SettingsHelper settings) {
findDeleteBookFile( settings, new File(backupDIR,BOOKS_DIR) );
}
private static void findDeleteBookFile(SettingsHelper settings, File dir){
File[] files =dir.listFiles();
if (files == null){
return;
}
for (File file : files){
if ( file.isDirectory()){
findDeleteBookFile(settings, file);
}
else {
settings.checkDeleteBook(file);
}
}
}
public static String exportDB(Context context) {
String backupDBPath = null;
try {
boolean mkres = backupDIR.mkdir();
if (! mkres){
Log.e(DEBUG_TAG, "Can not create directory "+backupDIR.toString() );
}
if (backupDIR.canWrite()) {
backupDBPath = DB_PREFIX + "_" + getTimesuffix() + DB_EXT;
File currentDB = context.getDatabasePath(DB_PREFIX);
File backupDB = new File(backupDIR, backupDBPath);
Log.d(DEBUG_TAG, "Copy to: " + backupDB.getAbsolutePath() + " Can write: " + backupDB.canWrite());
fileCopy(currentDB, backupDB);
}
else {
Log.e(DEBUG_TAG, "Can not write to "+backupDIR.toString() );
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Error to Copy DB: ", e);
return null;
}
return backupDBPath;
}
/**
* Copy list of author's URLs to file and return the file name
*
* @param applicationContext
* @return
*/
public static String exportAuthorList(Context applicationContext) {
String backupTxtPath = null;
try {
backupDIR.mkdir();
if (backupDIR.canWrite()) {
backupTxtPath = TXT_PREFIX + "_" + getTimesuffix() + TXT_EXT;
File backupTxt = new File(backupDIR, backupTxtPath);
BufferedWriter bw = new BufferedWriter(new FileWriter(backupTxt));
AuthorController sql = new AuthorController(applicationContext);
List<Author> authors = sql.getAll();
for (Author a : authors) {
bw.write(a.getUrlForBrowser());
bw.newLine();
}
bw.flush();
bw.close();
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Error export author urls: ", e);
return null;
}
return backupTxtPath;
}
/**
* Scan directory and return all files can be used to import DB from
*
* @param context
* @return arrays of file names
*/
public static String[] getFilesToImportDB(Context context) {
List<String> files = new ArrayList<String>();
backupDIR.mkdir();
for (String file : backupDIR.list()) {
if (file.startsWith(DB_PREFIX) && file.endsWith(DB_EXT)) {
files.add(file);
}
}
String[] res = new String[files.size()];
return files.toArray(res);
}
public static String[] getFilesToImportTxt(Context context) {
List<String> files = new ArrayList<String>();
backupDIR.mkdir();
for (String file : backupDIR.list()) {
if (file.endsWith(TXT_EXT) || file.endsWith(HTM_EXT)|| file.endsWith(HTML_EXT) ) {
files.add(file);
}
}
String[] res = new String[files.size()];
return files.toArray(res);
}
/**
* Just copy file <b>src</b> to file <b>dst</b>
*
* @param srcFile
* @param dstFile
* @throws FileNotFoundException
* @throws IOException
*/
private static void fileCopy(File srcFile, File dstFile) throws FileNotFoundException, IOException {
if (srcFile.exists()) {
FileChannel src = new FileInputStream(srcFile).getChannel();
FileChannel dst = new FileOutputStream(dstFile).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
/**
* Replace working DB by DM from backup
*
* @param context
* @param fileToImport backup db used to import from
* @return
*/
public static boolean importDB(Context context, String fileToImport) {
File currentDB = context.getDatabasePath(DB_PREFIX);
File backupDB = new File(backupDIR, fileToImport);
try {
fileCopy(backupDB, currentDB);
} catch (FileNotFoundException ex) {
Log.e(DEBUG_TAG, "Error to Import DB: ", ex);
return false;
} catch (IOException ex) {
Log.e(DEBUG_TAG, "Error to Import DB: ", ex);
return false;
}
return true;
}
private static String getTimesuffix() {
SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
Date date = Calendar.getInstance().getTime();
return df.format(date);
}
public static boolean importAuthorList(Context applicationContext, String fileToImport) {
File backupTxt = new File(backupDIR, fileToImport);
List<String> urls = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(backupTxt));
String inputLine = in.readLine();
while (inputLine != null) {
String resstr = SamLibConfig.getParsedUrl(inputLine);
if (resstr != null){
- urls.add(inputLine);
+ urls.add(resstr);
}
inputLine = in.readLine();
}
} catch (FileNotFoundException ex) {
Log.e(DEBUG_TAG, "Error Import URL list", ex);
return false;
} catch (IOException ex) {
Log.e(DEBUG_TAG, "Error Import URL list ", ex);
return false;
}
if (!urls.isEmpty()){
AddAuthor adder = new AddAuthor(applicationContext);
adder.execute(urls.toArray(new String[urls.size()]));
}
return true;
}
/**
* Log output - do not take into account DEBUG Flag
*
* @param tag debug tag
* @param msg message
* @param ex Exception
*/
static void log(String tag, String msg, Exception ex) {
SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT_DEBUG);
File save = new File(backupDIR, DEBUG_FILE);
FileOutputStream dst;
Date date = Calendar.getInstance().getTime();
try {
dst = new FileOutputStream(save, true);
PrintStream ps = new PrintStream(dst);
ps.println(df.format(date) + " " + tag + " " + msg);
if (ex != null) {
ex.printStackTrace(ps);
}
ps.flush();
dst.flush();
ps.close();
dst.close();
} catch (Exception ex1) {
Log.e(DEBUG_TAG, "Log save error", ex1);
}
}
static void log(String tag, String msg) {
log(tag, msg, null);
}
}
| true | true | public static boolean importAuthorList(Context applicationContext, String fileToImport) {
File backupTxt = new File(backupDIR, fileToImport);
List<String> urls = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(backupTxt));
String inputLine = in.readLine();
while (inputLine != null) {
String resstr = SamLibConfig.getParsedUrl(inputLine);
if (resstr != null){
urls.add(inputLine);
}
inputLine = in.readLine();
}
} catch (FileNotFoundException ex) {
Log.e(DEBUG_TAG, "Error Import URL list", ex);
return false;
} catch (IOException ex) {
Log.e(DEBUG_TAG, "Error Import URL list ", ex);
return false;
}
if (!urls.isEmpty()){
AddAuthor adder = new AddAuthor(applicationContext);
adder.execute(urls.toArray(new String[urls.size()]));
}
return true;
}
| public static boolean importAuthorList(Context applicationContext, String fileToImport) {
File backupTxt = new File(backupDIR, fileToImport);
List<String> urls = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(backupTxt));
String inputLine = in.readLine();
while (inputLine != null) {
String resstr = SamLibConfig.getParsedUrl(inputLine);
if (resstr != null){
urls.add(resstr);
}
inputLine = in.readLine();
}
} catch (FileNotFoundException ex) {
Log.e(DEBUG_TAG, "Error Import URL list", ex);
return false;
} catch (IOException ex) {
Log.e(DEBUG_TAG, "Error Import URL list ", ex);
return false;
}
if (!urls.isEmpty()){
AddAuthor adder = new AddAuthor(applicationContext);
adder.execute(urls.toArray(new String[urls.size()]));
}
return true;
}
|
diff --git a/lilith/src/main/java/de/huxhorn/lilith/swing/table/renderer/MessageRenderer.java b/lilith/src/main/java/de/huxhorn/lilith/swing/table/renderer/MessageRenderer.java
index e518ccf4..c77d55c9 100644
--- a/lilith/src/main/java/de/huxhorn/lilith/swing/table/renderer/MessageRenderer.java
+++ b/lilith/src/main/java/de/huxhorn/lilith/swing/table/renderer/MessageRenderer.java
@@ -1,119 +1,118 @@
/*
* Lilith - a log event viewer.
* Copyright (C) 2007-2009 Joern Huxhorn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.huxhorn.lilith.swing.table.renderer;
import de.huxhorn.lilith.data.eventsource.EventWrapper;
import de.huxhorn.lilith.data.logging.LoggingEvent;
import de.huxhorn.lilith.data.logging.Message;
import de.huxhorn.lilith.swing.table.Colors;
import de.huxhorn.lilith.swing.table.ColorsProvider;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
public class MessageRenderer
implements TableCellRenderer
{
private LabelCellRenderer renderer;
public MessageRenderer()
{
super();
renderer = new LabelCellRenderer();
renderer.setToolTipText(null);
renderer.setIcon(null);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if(!isSelected)
{
isSelected = rowIndex == LabelCellRenderer.getSelectedRow(table);
}
if(!hasFocus && isSelected)
{
hasFocus = table.isFocusOwner();
}
renderer.setSelected(isSelected);
renderer.setFocused(hasFocus);
Color foreground = Color.BLACK;
String text = "";
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event = (LoggingEvent) eventObj;
Message messageObj = event.getMessage();
if(messageObj != null)
{
text = messageObj.getMessage();
}
if(text != null)
{
int newlineIndex = text.indexOf("\n");
if(newlineIndex > -1)
{
int newlineCounter = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == '\n')
{
newlineCounter++;
}
}
text = text.substring(0, newlineIndex);
- newlineCounter--;
if(newlineCounter > 0)
{
text = text + " [+" + newlineCounter + " lines]";
}
}
}
}
}
renderer.setText(text);
boolean colorsInitialized = false;
if(!hasFocus && !isSelected)
{
if(table instanceof ColorsProvider)
{
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
ColorsProvider cp = (ColorsProvider) table;
Colors colors = cp.resolveColors(wrapper, rowIndex, vColIndex);
colorsInitialized = renderer.updateColors(colors);
}
}
}
if(!colorsInitialized)
{
renderer.setForeground(foreground);
}
renderer.correctRowHeight(table);
return renderer;
}
}
| true | true | public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if(!isSelected)
{
isSelected = rowIndex == LabelCellRenderer.getSelectedRow(table);
}
if(!hasFocus && isSelected)
{
hasFocus = table.isFocusOwner();
}
renderer.setSelected(isSelected);
renderer.setFocused(hasFocus);
Color foreground = Color.BLACK;
String text = "";
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event = (LoggingEvent) eventObj;
Message messageObj = event.getMessage();
if(messageObj != null)
{
text = messageObj.getMessage();
}
if(text != null)
{
int newlineIndex = text.indexOf("\n");
if(newlineIndex > -1)
{
int newlineCounter = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == '\n')
{
newlineCounter++;
}
}
text = text.substring(0, newlineIndex);
newlineCounter--;
if(newlineCounter > 0)
{
text = text + " [+" + newlineCounter + " lines]";
}
}
}
}
}
renderer.setText(text);
boolean colorsInitialized = false;
if(!hasFocus && !isSelected)
{
if(table instanceof ColorsProvider)
{
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
ColorsProvider cp = (ColorsProvider) table;
Colors colors = cp.resolveColors(wrapper, rowIndex, vColIndex);
colorsInitialized = renderer.updateColors(colors);
}
}
}
if(!colorsInitialized)
{
renderer.setForeground(foreground);
}
renderer.correctRowHeight(table);
return renderer;
}
| public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if(!isSelected)
{
isSelected = rowIndex == LabelCellRenderer.getSelectedRow(table);
}
if(!hasFocus && isSelected)
{
hasFocus = table.isFocusOwner();
}
renderer.setSelected(isSelected);
renderer.setFocused(hasFocus);
Color foreground = Color.BLACK;
String text = "";
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event = (LoggingEvent) eventObj;
Message messageObj = event.getMessage();
if(messageObj != null)
{
text = messageObj.getMessage();
}
if(text != null)
{
int newlineIndex = text.indexOf("\n");
if(newlineIndex > -1)
{
int newlineCounter = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == '\n')
{
newlineCounter++;
}
}
text = text.substring(0, newlineIndex);
if(newlineCounter > 0)
{
text = text + " [+" + newlineCounter + " lines]";
}
}
}
}
}
renderer.setText(text);
boolean colorsInitialized = false;
if(!hasFocus && !isSelected)
{
if(table instanceof ColorsProvider)
{
if(value instanceof EventWrapper)
{
EventWrapper wrapper = (EventWrapper) value;
ColorsProvider cp = (ColorsProvider) table;
Colors colors = cp.resolveColors(wrapper, rowIndex, vColIndex);
colorsInitialized = renderer.updateColors(colors);
}
}
}
if(!colorsInitialized)
{
renderer.setForeground(foreground);
}
renderer.correctRowHeight(table);
return renderer;
}
|
diff --git a/src/main/java/com/hacku/swearjar/server/ConvertServlet.java b/src/main/java/com/hacku/swearjar/server/ConvertServlet.java
index e45f535..05a1a0a 100644
--- a/src/main/java/com/hacku/swearjar/server/ConvertServlet.java
+++ b/src/main/java/com/hacku/swearjar/server/ConvertServlet.java
@@ -1,318 +1,318 @@
package com.hacku.swearjar.server;
import com.google.gson.Gson;
import com.hacku.swearjar.speechapi.SpeechResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Servlet implementation class ConvertServlet
*/
@WebServlet(description = "Converts incoming file to .flac format before sending to Google's ASR. Sends json response back to app.",
urlPatterns = {"/convert"})
@MultipartConfig(maxFileSize = 1024 * 1024 * 32) //Accept files upto 32MB
public class ConvertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static void log(String filename, String output) {
FileOutputStream eos = null;
try {
eos = new FileOutputStream("/tmp/" + filename);
IOUtils.copy(IOUtils.toInputStream(output), eos);
eos.flush();
eos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ioe) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ioe);
} finally {
try {
eos.close();
} catch (IOException ex) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Takes an audio file, transcodes it to flac, then performs speech
* recognition. Gives a JSON response containing the recognised speech.
*
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String baseDir = "/tmp";
String baseFilename = "SwearJar_"
+ request.getSession().getCreationTime() //Timestamp
+ "_" + request.getSession().getId(); //Session ID
String inputExt = ".3gp";
String outputExt = ".flac";
String inputFilename = baseDir + "/" + baseFilename + inputExt;
String flacFilename = baseFilename + outputExt;
//Read the wav file sent and store it in a .wav file
Part part = request.getPart("Content");
InputStream inputStream = part.getInputStream();
FileOutputStream fos = new FileOutputStream(inputFilename);
IOUtils.copy(inputStream, fos);
fos.flush();
fos.close();
//encode the file as flac
String[] outputFilenames = transcode(baseDir, baseFilename, inputExt, outputExt);
String filenames = "";
for(String filename: outputFilenames)
filenames = filenames.concat(filename + "\n");
log("outputFilenames", outputFilenames.toString());
//Do speech recogntion and return JSON
SpeechResponse aggregateSpeech = getSpeechResponse(outputFilenames);
response.getOutputStream().print(aggregateSpeech.toJson());
//IOUtils.copy(IOUtils.toInputStream(aggregateSpeech.toJson()), response.getOutputStream());
//Temporary files can be deleted now
/*delete(inputFilename);
for(String filename : outputFilenames)
delete(filename);*/
}
/**
* Gets an aggregate SpeechResponse object based on the speech contained in
* multiple flac files
*
* @param speechFiles
* @return
*/
private static SpeechResponse getSpeechResponse(String[] speechFiles) {
SpeechResponse aggregateSpeech = new SpeechResponse();
//Do speech recogntion and return JSON
for (String filename : speechFiles) {
//TODO create new threads here
SpeechResponse speech = getSpeechResponse(filename);
if (speech != null) {
aggregateSpeech.concat(speech);
}
}
return aggregateSpeech;
}
/**
* Causes the calling thread to wait for a maximum of millis for the File at
* filename to be created
*
* @param millis
* @param filename
* @deprecated
*/
private static File waitForFileCreation(String filename, int millis) {
while (millis > 0) {
try {
File file = new File(filename);
if (file.exists() && file.canRead()) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex);
}
return file;
}
Thread.sleep(1);
millis--;
} catch (InterruptedException ex) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
/**
* Deletes a file if it exists
*
* @param filename
*/
private static void delete(String filename) {
try {
new File(filename).delete();
} catch (NullPointerException ioe) {
System.err.println("Error deleting: " + filename);
}
}
/**
* Transcodes input file to flac
*
* @param inputFile
* @param outputFile
* @return array of files created
*/
private static String[] transcode(String baseDir, String baseFilename, String inputExt, String outputExt) {
Runtime rt = Runtime.getRuntime();
String output = "";
try {
String str = "sox_splitter " + baseDir + " " + baseFilename + " " + inputExt + " " + outputExt;
//"echo test &>> /tmp/output";
/*"ffmpeg -i " + //Location of vlc
inputFile + " -ar 8000 -sample_fmt s16 "//Location of input
+ " " + outputFile;*/
/*"run \"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" -I --dummy-quiet " + //Location of vlc
inputFile + //Location of input
" --sout=\"#transcode{acodec=flac, channels=1 ab=16 samplerate=16000}"
+ ":std{access=file, mux=raw, dst="
+ outputFile + //Location of output
"}\" vlc://quit";*/
Process pr = rt.exec(str);
int exitStatus = pr.waitFor();
- IOUtils.toString(pr.getInputStream(), output);
+ output = IOUtils.toString(pr.getInputStream());
/*FileOutputStream fos = new FileOutputStream("/tmp/output");
IOUtils.copy(pr.getInputStream(), fos);
fos.flush();
fos.close();
*/
FileOutputStream eos = new FileOutputStream("/tmp/errors");
IOUtils.copy(pr.getErrorStream(), eos);
eos.flush();
eos.close();
//output = IOUtils.toString(pr.getInputStream());
System.out.println(System.currentTimeMillis() + " VLC exit code: " + exitStatus);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log("output", output);
return output.split("\n");
}
}
/**
* Takes the audio at the specified path and sends it off to Google via HTTP
* POST. Packages the JSON response from Google into a SpeechResponse
* object.
*
* @param speechFilename path to the audio file
* @return SpeechResponse containing recognised speech, null if error occurs
*/
private static SpeechResponse getSpeechResponse(String speechFilename) {
FileLock lock = null;
try {
//File file = waitForFileCreation(speechFile, 1000);
// Read speech file
File file = new File(speechFilename);
FileInputStream inputStream = new FileInputStream(file);
//Wait for file to become available
FileChannel channel = inputStream.getChannel();
lock = channel.lock(0, Long.MAX_VALUE, true);//channel.lock();
ByteArrayInputStream data = new ByteArrayInputStream(
IOUtils.toByteArray(inputStream));
// Set up the POST request
HttpPost postRequest = getPost(data);
// Do the request to google
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postRequest);
log(speechFilename, packageResponse(response).toJson());
//return the JSON stream
return packageResponse(response);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
lock.release();
} catch (IOException ex) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException npe) {
Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, npe);
}
}
return null;
}
/**
* Sets up the post request =
*
* @param data audio file
* @return HttpPost object with parameters initialised to audio file
*/
private static HttpPost getPost(ByteArrayInputStream data) {
HttpPost postRequest = new HttpPost(
"https://www.google.com/speech-api/v1/recognize"
+ "?xjerr=1&pfilter=0&client=chromium&lang=en-US&maxresults=1");
// Specify Content and Content-Type parameters for POST request
MultipartEntity entity = new MultipartEntity();
entity.addPart("Content", new InputStreamBody(data, "Content"));
postRequest.setHeader("Content-Type", "audio/x-flac; rate=8000");
postRequest.setEntity(entity);
return postRequest;
}
/**
* Uses GSON library to put the returned JSON into a SpeechResponse object
*
* @param response containing JSON to be packaged
* @return SpeechResponse containing recognised speech
* @throws IOException
*/
private static SpeechResponse packageResponse(HttpResponse response) throws IOException {
Gson gson = new Gson();
InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
SpeechResponse speechResponse = gson.fromJson(isr, SpeechResponse.class);
return speechResponse;
}
}
| true | true | private static String[] transcode(String baseDir, String baseFilename, String inputExt, String outputExt) {
Runtime rt = Runtime.getRuntime();
String output = "";
try {
String str = "sox_splitter " + baseDir + " " + baseFilename + " " + inputExt + " " + outputExt;
//"echo test &>> /tmp/output";
/*"ffmpeg -i " + //Location of vlc
inputFile + " -ar 8000 -sample_fmt s16 "//Location of input
+ " " + outputFile;*/
/*"run \"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" -I --dummy-quiet " + //Location of vlc
inputFile + //Location of input
" --sout=\"#transcode{acodec=flac, channels=1 ab=16 samplerate=16000}"
+ ":std{access=file, mux=raw, dst="
+ outputFile + //Location of output
"}\" vlc://quit";*/
Process pr = rt.exec(str);
int exitStatus = pr.waitFor();
IOUtils.toString(pr.getInputStream(), output);
/*FileOutputStream fos = new FileOutputStream("/tmp/output");
IOUtils.copy(pr.getInputStream(), fos);
fos.flush();
fos.close();
*/
FileOutputStream eos = new FileOutputStream("/tmp/errors");
IOUtils.copy(pr.getErrorStream(), eos);
eos.flush();
eos.close();
//output = IOUtils.toString(pr.getInputStream());
System.out.println(System.currentTimeMillis() + " VLC exit code: " + exitStatus);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log("output", output);
return output.split("\n");
}
}
| private static String[] transcode(String baseDir, String baseFilename, String inputExt, String outputExt) {
Runtime rt = Runtime.getRuntime();
String output = "";
try {
String str = "sox_splitter " + baseDir + " " + baseFilename + " " + inputExt + " " + outputExt;
//"echo test &>> /tmp/output";
/*"ffmpeg -i " + //Location of vlc
inputFile + " -ar 8000 -sample_fmt s16 "//Location of input
+ " " + outputFile;*/
/*"run \"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" -I --dummy-quiet " + //Location of vlc
inputFile + //Location of input
" --sout=\"#transcode{acodec=flac, channels=1 ab=16 samplerate=16000}"
+ ":std{access=file, mux=raw, dst="
+ outputFile + //Location of output
"}\" vlc://quit";*/
Process pr = rt.exec(str);
int exitStatus = pr.waitFor();
output = IOUtils.toString(pr.getInputStream());
/*FileOutputStream fos = new FileOutputStream("/tmp/output");
IOUtils.copy(pr.getInputStream(), fos);
fos.flush();
fos.close();
*/
FileOutputStream eos = new FileOutputStream("/tmp/errors");
IOUtils.copy(pr.getErrorStream(), eos);
eos.flush();
eos.close();
//output = IOUtils.toString(pr.getInputStream());
System.out.println(System.currentTimeMillis() + " VLC exit code: " + exitStatus);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log("output", output);
return output.split("\n");
}
}
|
diff --git a/sandbox/tools/src/main/java/org/apache/openejb/tools/examples/Outline.java b/sandbox/tools/src/main/java/org/apache/openejb/tools/examples/Outline.java
index 74ef52adf..a2acc98f1 100644
--- a/sandbox/tools/src/main/java/org/apache/openejb/tools/examples/Outline.java
+++ b/sandbox/tools/src/main/java/org/apache/openejb/tools/examples/Outline.java
@@ -1,245 +1,247 @@
/*
* 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.openejb.tools.examples;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.openejb.tools.util.Files;
import org.apache.openejb.tools.util.IO;
import org.apache.openejb.tools.util.Join;
import org.codehaus.swizzle.stream.StreamLexer;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* @version $Rev$ $Date$
*/
public class Outline {
static {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
root.setLevel(Level.INFO);
}
private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Outline.class);
public void run(String... args) throws Exception {
for (String arg : args) {
final File file = new File(arg);
if (!file.exists()) {
log.error("Does not exist: " + file.getAbsolutePath());
continue;
}
if (!file.isDirectory()) {
log.error("Not a directory: " + file.getAbsolutePath());
continue;
}
generate(file);
}
}
private void generate(File dir) throws Exception {
final File readme = new File(dir, "README.md");
final PrintStream out = new PrintStream(IO.write(readme));
out.print("Title: ");
out.println(title(dir));
out.println();
- out.println("*Help us document this example! Source available in [svn](http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/" + dir.getName() + ") or [git](https://github.com/apache/openejb/tree/trunk/openejb/examples/" + dir.getName() + "). Open a [JIRA](https://issues.apache.org/jira/browse/TOMEE) with patch or pull request*");
+ String path = dir.getAbsolutePath();
+ path = path.substring(0, path.indexOf("examples/") + 10);
+ out.println("*Help us document this example! Source available in [svn](http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/" + path + ") or [git](https://github.com/apache/openejb/tree/trunk/openejb/examples/" + path + "). Open a [JIRA](https://issues.apache.org/jira/browse/TOMEE) with patch or pull request*");
final File main = Files.file(dir, "src", "main");
final File test = Files.file(dir, "src", "test");
printJavaFiles(out, collect(main, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(main, Pattern.compile(".*\\.xml")));
printJavaFiles(out, collect(test, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(test, Pattern.compile(".*\\.xml")));
printBuildOutput(out, new File("/Users/dblevins/examples/"+dir.getName()+"/build.log"));
out.close();
}
private void printBuildOutput(PrintStream out, File file) throws IOException {
if (!file.exists()) return;
final String content = IO.slurp(file);
out.println();
out.println("# Running");
out.println();
for (String line : content.split("\n")) {
if (line.startsWith("[")) continue;
out.println(indent(line));
}
}
private String title(File dir) {
String[] strings = dir.getName().split("-");
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if (string.matches("and|or|to|from|in|on|with|out|the")) continue;
if (string.matches("ejb|cdi|jsf|jsp|mdb|jstl|xml|jpa|jms|ear|rest")) {
strings[i] = strings[i].toUpperCase();
continue;
}
StringBuilder sb = new StringBuilder(string);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
strings[i] = sb.toString();
}
return Join.join(" ", strings);
}
private void printJavaFiles(PrintStream out, List<File> mainJavaFiles) throws IOException {
for (File javaFile : mainJavaFiles) {
out.println();
out.println("## " + javaFile.getName().replace(".java", ""));
out.println();
InputStream read = IO.read(javaFile);
StreamLexer lexer = new StreamLexer(read);
String contents = lexer.read("\npackage", "\n}");
contents = "package" + contents + "\n}";
contents = contents.replaceAll("\n *(\n *})", "$1");
contents = indent(contents);
out.println(contents);
}
}
private void printXmlFiles(PrintStream out, List<File> files) throws IOException {
for (File file : files) {
String xml = "\n" + IO.slurp(file);
final List<Integer> indexes = indexesOf(xml, "\n<");
if (indexes.size() == 0) continue;
if (indexes.size() > 1) {
xml = xml.substring(indexes.get(indexes.size() - 2), xml.length());
}
if (xml.startsWith("\n")) xml = xml.substring(1);
if (xml.matches("<[a-zA-Z-]/>")) continue;
out.println();
out.println("## " + file.getName());
out.println();
out.println(indent(xml));
}
}
private static List<Integer> indexesOf(String xml, String str) {
final List<Integer> indexes = new ArrayList<Integer>();
int index = -1;
while ((index = xml.indexOf(str, index + 1)) != -1) {
indexes.add(index);
}
return indexes;
}
private String indent(String contents) {
String indent = " ";
return indent + contents.replaceAll("\n", "\n" + indent);
}
/*
* Mainstreet
*/
public static List<File> collect(final File dir, final Pattern pattern) {
return collect(dir, new FileFilter() {
@Override
public boolean accept(File file) {
return pattern.matcher(file.getAbsolutePath()).matches();
}
});
}
public static List<File> collect(File dir, FileFilter filter) {
final List<File> accepted = new ArrayList<File>();
if (filter.accept(dir)) accepted.add(dir);
final File[] files = dir.listFiles();
if (files != null) for (File file : files) {
accepted.addAll(collect(file, filter));
}
return accepted;
}
public static void main(String[] args) throws Exception {
args = processSystemProperties(args);
// new Outline().run(args);
process(new File("/Users/dblevins/work/all/trunk/openejb/examples/"));
process(new File("/Users/dblevins/work/all/trunk/openejb/examples/webapps/"));
}
private static void process(File dir) throws Exception {
for (File file : dir.listFiles()) {
if (!file.isDirectory()) continue;
if (!Files.file(file, "src").exists()) continue;
new Outline().run(file.getAbsolutePath());
}
}
public static String[] processSystemProperties(String[] args) {
final ArrayList<String> list = new ArrayList<String>();
// Read in and apply the properties specified on the command line
for (String arg : args) {
if (arg.startsWith("-D")) {
final String name = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("="));
final String value = arg.substring(arg.indexOf("=") + 1);
System.setProperty(name, value);
} else {
list.add(arg);
}
}
return (String[]) list.toArray(new String[list.size()]);
}
}
| true | true | private void generate(File dir) throws Exception {
final File readme = new File(dir, "README.md");
final PrintStream out = new PrintStream(IO.write(readme));
out.print("Title: ");
out.println(title(dir));
out.println();
out.println("*Help us document this example! Source available in [svn](http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/" + dir.getName() + ") or [git](https://github.com/apache/openejb/tree/trunk/openejb/examples/" + dir.getName() + "). Open a [JIRA](https://issues.apache.org/jira/browse/TOMEE) with patch or pull request*");
final File main = Files.file(dir, "src", "main");
final File test = Files.file(dir, "src", "test");
printJavaFiles(out, collect(main, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(main, Pattern.compile(".*\\.xml")));
printJavaFiles(out, collect(test, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(test, Pattern.compile(".*\\.xml")));
printBuildOutput(out, new File("/Users/dblevins/examples/"+dir.getName()+"/build.log"));
out.close();
}
| private void generate(File dir) throws Exception {
final File readme = new File(dir, "README.md");
final PrintStream out = new PrintStream(IO.write(readme));
out.print("Title: ");
out.println(title(dir));
out.println();
String path = dir.getAbsolutePath();
path = path.substring(0, path.indexOf("examples/") + 10);
out.println("*Help us document this example! Source available in [svn](http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/" + path + ") or [git](https://github.com/apache/openejb/tree/trunk/openejb/examples/" + path + "). Open a [JIRA](https://issues.apache.org/jira/browse/TOMEE) with patch or pull request*");
final File main = Files.file(dir, "src", "main");
final File test = Files.file(dir, "src", "test");
printJavaFiles(out, collect(main, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(main, Pattern.compile(".*\\.xml")));
printJavaFiles(out, collect(test, Pattern.compile(".*\\.java")));
printXmlFiles(out, collect(test, Pattern.compile(".*\\.xml")));
printBuildOutput(out, new File("/Users/dblevins/examples/"+dir.getName()+"/build.log"));
out.close();
}
|
diff --git a/edu/cmu/sphinx/decoder/scorer/SimpleAcousticScorer.java b/edu/cmu/sphinx/decoder/scorer/SimpleAcousticScorer.java
index 54905987..a9e8ea1c 100644
--- a/edu/cmu/sphinx/decoder/scorer/SimpleAcousticScorer.java
+++ b/edu/cmu/sphinx/decoder/scorer/SimpleAcousticScorer.java
@@ -1,154 +1,154 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electronic Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.decoder.scorer;
import java.util.Iterator;
import java.util.List;
import java.io.IOException;
import edu.cmu.sphinx.frontend.FrontEnd;
import edu.cmu.sphinx.frontend.FeatureFrame;
import edu.cmu.sphinx.frontend.Feature;
import edu.cmu.sphinx.frontend.Signal;
import edu.cmu.sphinx.decoder.scorer.AcousticScorer;
/**
* A Simple acoustic scorer.
* a certain number of frames have been processed
*
* Note that all scores are maintained in LogMath log base.
*/
public class SimpleAcousticScorer implements AcousticScorer {
private FrontEnd frontEnd;
// TODO: Make this set with a SphinxProperty
private boolean normalizeScores = false;
/**
* Initializes this SimpleAcousticScorer with the given
* context and FrontEnd.
*
* @param context the context to use
* @param frontend the FrontEnd to use
*/
public void initialize(String context, FrontEnd frontend) {
this.frontEnd = frontend;
}
/**
* Starts the scorer
*/
public void start() {
}
/**
* Checks to see if a FeatureFrame is null or if there are Features in it.
*
* @param ff the FeatureFrame to check
*
* @return false if the given FeatureFrame is null or if there
* are no Features in the FeatureFrame; true otherwise.
*/
private boolean hasFeatures(FeatureFrame ff) {
if (ff == null) {
System.out.println("SimpleAcousticScorer: FeatureFrame is null");
return false;
}
if (ff.getFeatures() == null) {
System.out.println
("SimpleAcousticScorer: no features in FeatureFrame");
return false;
}
return true;
}
/**
* Scores the given set of states
*
* @param scoreableList a list containing scoreable objects to
* be scored
*
* @return true if there was a Feature available to score
* false if there was no more Feature available to score
*/
public boolean calculateScores(List scoreableList) {
FeatureFrame ff;
try {
ff = frontEnd.getFeatureFrame(1, null);
Feature feature;
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
if (feature.getSignal() == Signal.UTTERANCE_START) {
ff = frontEnd.getFeatureFrame(1, null);
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
}
if (feature.getSignal() == Signal.UTTERANCE_END) {
return false;
}
if (!feature.hasContent()) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = - Float.MAX_VALUE;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
- if (scoreable.getFrameNumber() != curFeature.getID()) {
+ if (scoreable.getFrameNumber() != feature.getID()) {
throw new Error
("Frame number mismatch: Token: " +
scoreable.getFrameNumber() +
- " Feature: " + curFeature.getID());
+ " Feature: " + feature.getID());
}
float logScore = scoreable.calculateScore(feature);
if (logScore > logMaxScore) {
logMaxScore = logScore;
}
}
if (normalizeScores) {
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
scoreable.normalizeScore(logMaxScore);
}
}
} catch (IOException ioe) {
System.out.println("IO Exception " + ioe);
return false;
}
return true;
}
/**
* Performs post-recognition cleanup.
*/
public void stop() {
}
}
| false | true | public boolean calculateScores(List scoreableList) {
FeatureFrame ff;
try {
ff = frontEnd.getFeatureFrame(1, null);
Feature feature;
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
if (feature.getSignal() == Signal.UTTERANCE_START) {
ff = frontEnd.getFeatureFrame(1, null);
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
}
if (feature.getSignal() == Signal.UTTERANCE_END) {
return false;
}
if (!feature.hasContent()) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = - Float.MAX_VALUE;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
if (scoreable.getFrameNumber() != curFeature.getID()) {
throw new Error
("Frame number mismatch: Token: " +
scoreable.getFrameNumber() +
" Feature: " + curFeature.getID());
}
float logScore = scoreable.calculateScore(feature);
if (logScore > logMaxScore) {
logMaxScore = logScore;
}
}
if (normalizeScores) {
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
scoreable.normalizeScore(logMaxScore);
}
}
} catch (IOException ioe) {
System.out.println("IO Exception " + ioe);
return false;
}
return true;
}
| public boolean calculateScores(List scoreableList) {
FeatureFrame ff;
try {
ff = frontEnd.getFeatureFrame(1, null);
Feature feature;
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
if (feature.getSignal() == Signal.UTTERANCE_START) {
ff = frontEnd.getFeatureFrame(1, null);
if (!hasFeatures(ff)) {
return false;
}
feature = ff.getFeatures()[0];
}
if (feature.getSignal() == Signal.UTTERANCE_END) {
return false;
}
if (!feature.hasContent()) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = - Float.MAX_VALUE;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
if (scoreable.getFrameNumber() != feature.getID()) {
throw new Error
("Frame number mismatch: Token: " +
scoreable.getFrameNumber() +
" Feature: " + feature.getID());
}
float logScore = scoreable.calculateScore(feature);
if (logScore > logMaxScore) {
logMaxScore = logScore;
}
}
if (normalizeScores) {
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
scoreable.normalizeScore(logMaxScore);
}
}
} catch (IOException ioe) {
System.out.println("IO Exception " + ioe);
return false;
}
return true;
}
|
diff --git a/org.dawb.common.ui/src/org/dawb/common/ui/wizard/PlotDataConversionWizard.java b/org.dawb.common.ui/src/org/dawb/common/ui/wizard/PlotDataConversionWizard.java
index b800f0cb..60744a61 100644
--- a/org.dawb.common.ui/src/org/dawb/common/ui/wizard/PlotDataConversionWizard.java
+++ b/org.dawb.common.ui/src/org/dawb/common/ui/wizard/PlotDataConversionWizard.java
@@ -1,145 +1,145 @@
package org.dawb.common.ui.wizard;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import org.dawb.common.services.ServiceManager;
import org.dawb.common.services.conversion.IConversionContext;
import org.dawb.common.services.conversion.IConversionService;
import org.dawb.common.ui.monitor.ProgressMonitorWrapper;
import org.dawb.common.ui.util.EclipseUtils;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
public class PlotDataConversionWizard extends Wizard implements IExportWizard {
public static final String ID = "org.dawb.common.ui.wizard.plotdataconversion";
private IConversionService service;
private IConversionContext context;
private AbstractPlotConversionVisitor visitor;
private PlotDataConversionPage conversionPage;
private IPlottingSystem system;
private static final Logger logger = LoggerFactory.getLogger(PlotDataConversionWizard.class);
public PlotDataConversionWizard() {
super();
setWindowTitle("Convert Data");
// It's an OSGI service, not required to use ServiceManager
try {
this.service = (IConversionService)ServiceManager.getService(IConversionService.class);
} catch (Exception e) {
logger.error("Cannot get conversion service!", e);
return;
}
}
public void addPages() {
if (system == null) system = getPlottingSystem();
if (system == null) {
logger.error("Could not find plotting system to export data from");
return;
}
if (system.is2D()) {
visitor = new Plot2DConversionVisitor(system);
} else {
visitor = new Plot1DConversionVisitor(system);
}
String[] junk = new String[1];
junk[0] = "junk";
context = service.open(junk);
context.setConversionVisitor(visitor);
//HACK - put in a dataset so the conversion class goes straight to iterate
context.setLazyDataset(AbstractDataset.zeros(new int[]{10},AbstractDataset.INT32));
- context.addSliceDimension(0, null);
+ context.addSliceDimension(0, "all");
conversionPage = new PlotDataConversionPage();
conversionPage.setPath(System.getProperty("user.home") +File.separator+ "plotdata."+ visitor.getExtension());
conversionPage.setDescription("Convert plotted data to file");
addPage(conversionPage);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
@Override
public boolean performFinish() {
try {
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
context.setOutputPath(conversionPage.getAbsoluteFilePath());
context.setMonitor(new ProgressMonitorWrapper(monitor));
context.setConversionVisitor(visitor);
// Bit with the juice
monitor.beginTask(visitor.getConversionSchemeName(), context.getWorkSize());
monitor.worked(1);
service.process(context);
} catch (final Exception ne) {
logger.error("Cannot run export process for "+visitor.getConversionSchemeName()+"'", ne);
}
}
});
} catch (Exception ne) {
logger.error("Cannot run export process "+visitor.getConversionSchemeName(), ne);
}
return true;
}
public void setPlottingSystem(IPlottingSystem system) {
this.system = system;
}
private IPlottingSystem getPlottingSystem() {
// Perhaps the plotting system is on a dialog
final Shell[] shells = Display.getDefault().getShells();
if (shells!=null) for (Shell shell : shells) {
final Object o = shell.getData();
if (o!=null && o instanceof IAdaptable) {
IPlottingSystem s = (IPlottingSystem)((IAdaptable)o).getAdapter(IPlottingSystem.class);
if (s!=null) return s;
}
}
final IWorkbenchPart part = EclipseUtils.getPage().getActivePart();
if (part!=null) {
return (IPlottingSystem)part.getAdapter(IPlottingSystem.class);
}
return null;
}
}
| true | true | public void addPages() {
if (system == null) system = getPlottingSystem();
if (system == null) {
logger.error("Could not find plotting system to export data from");
return;
}
if (system.is2D()) {
visitor = new Plot2DConversionVisitor(system);
} else {
visitor = new Plot1DConversionVisitor(system);
}
String[] junk = new String[1];
junk[0] = "junk";
context = service.open(junk);
context.setConversionVisitor(visitor);
//HACK - put in a dataset so the conversion class goes straight to iterate
context.setLazyDataset(AbstractDataset.zeros(new int[]{10},AbstractDataset.INT32));
context.addSliceDimension(0, null);
conversionPage = new PlotDataConversionPage();
conversionPage.setPath(System.getProperty("user.home") +File.separator+ "plotdata."+ visitor.getExtension());
conversionPage.setDescription("Convert plotted data to file");
addPage(conversionPage);
}
| public void addPages() {
if (system == null) system = getPlottingSystem();
if (system == null) {
logger.error("Could not find plotting system to export data from");
return;
}
if (system.is2D()) {
visitor = new Plot2DConversionVisitor(system);
} else {
visitor = new Plot1DConversionVisitor(system);
}
String[] junk = new String[1];
junk[0] = "junk";
context = service.open(junk);
context.setConversionVisitor(visitor);
//HACK - put in a dataset so the conversion class goes straight to iterate
context.setLazyDataset(AbstractDataset.zeros(new int[]{10},AbstractDataset.INT32));
context.addSliceDimension(0, "all");
conversionPage = new PlotDataConversionPage();
conversionPage.setPath(System.getProperty("user.home") +File.separator+ "plotdata."+ visitor.getExtension());
conversionPage.setDescription("Convert plotted data to file");
addPage(conversionPage);
}
|
diff --git a/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java b/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
index ab51980c..de1e70ec 100644
--- a/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
+++ b/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
@@ -1,81 +1,81 @@
package test.cli.cloudify.cloud.services.rackspace;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import test.cli.cloudify.cloud.services.AbstractCloudService;
import framework.tools.SGTestHelper;
import framework.utils.IOUtils;
import framework.utils.ScriptUtils;
public class RackspaceCloudService extends AbstractCloudService {
private String cloudName = "rsopenstack";
private String user = "gsrackspace";
private String apiKey = "1ee2495897b53409f4643926f1968c0c";
private String tenant = "658142";
public String getCloudName() {
return cloudName;
}
public void setCloudName(String cloudName) {
this.cloudName = cloudName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
@Override
public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("USER_NAME", user);
propsToReplace.put("API_KEY", apiKey);
- propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent");
- propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager");
+ propsToReplace.put("machineNamePrefix " + "\"agent\"", this.machinePrefix + "cloudify_agent");
+ propsToReplace.put("managementGroup " + "\"management\"", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace);
}
}
| true | true | public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("USER_NAME", user);
propsToReplace.put("API_KEY", apiKey);
propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent");
propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace);
}
| public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("USER_NAME", user);
propsToReplace.put("API_KEY", apiKey);
propsToReplace.put("machineNamePrefix " + "\"agent\"", this.machinePrefix + "cloudify_agent");
propsToReplace.put("managementGroup " + "\"management\"", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace);
}
|
diff --git a/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicBufferSelect.java b/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicBufferSelect.java
index 7cf640c6..0a567654 100644
--- a/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicBufferSelect.java
+++ b/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicBufferSelect.java
@@ -1,92 +1,92 @@
package powercrystals.minefactoryreloaded.gui.control;
import powercrystals.core.gui.controls.ButtonOption;
import powercrystals.minefactoryreloaded.gui.client.GuiRedNetLogic;
public class ButtonLogicBufferSelect extends ButtonOption
{
private LogicButtonType _buttonType;
private GuiRedNetLogic _logicScreen;
private int _pinIndex;
private boolean _ignoreChanges;
public ButtonLogicBufferSelect(GuiRedNetLogic containerScreen, int x, int y, int pinIndex, LogicButtonType buttonType, int rotation)
{
super(containerScreen, x, y, 30, 14);
_logicScreen = containerScreen;
_buttonType = buttonType;
_pinIndex = pinIndex;
- char[] dir = {'F','R','B','L'};
+ char[] dir = {'L','B','R','F',};
char[] dirMap = new char[4];
for (int i = 0; i < 4; ++i)
dirMap[(i + rotation) & 3] = dir[i];
_ignoreChanges = true;
if(_buttonType == LogicButtonType.Input)
{
setValue(0, "I/O D");
setValue(1, "I/O U");
setValue(2, "I/O " + dirMap[2]);
setValue(3, "I/O " + dirMap[0]);
setValue(4, "I/O " + dirMap[1]);
setValue(5, "I/O " + dirMap[3]);
setValue(12, "CNST");
setValue(13, "VARS");
setSelectedIndex(0);
}
else
{
setValue(6, "I/O D");
setValue(7, "I/O U");
setValue(8, "I/O " + dirMap[2]);
setValue(9, "I/O " + dirMap[0]);
setValue(10, "I/O " + dirMap[1]);
setValue(11, "I/O " + dirMap[3]);
setValue(13, "VARS");
setValue(14, "NULL");
setSelectedIndex(6);
}
_ignoreChanges = false;
setVisible(false);
}
public int getBuffer()
{
return getSelectedIndex();
}
public void setBuffer(int buffer)
{
_ignoreChanges = true;
setSelectedIndex(buffer);
_ignoreChanges = false;
}
@Override
public void onValueChanged(int value, String label)
{
if(_ignoreChanges)
{
return;
}
if(_buttonType == LogicButtonType.Input)
{
_logicScreen.setInputPinMapping(_pinIndex, value, 0);
}
else
{
_logicScreen.setOutputPinMapping(_pinIndex, value, 0);
}
}
@Override
public void drawForeground(int mouseX, int mouseY)
{
if(getValue() == null)
{
System.out.println("Buffer selection of " + getSelectedIndex() + " on " + _buttonType + " has null value!");
}
super.drawForeground(mouseX, mouseY);
}
}
| true | true | public ButtonLogicBufferSelect(GuiRedNetLogic containerScreen, int x, int y, int pinIndex, LogicButtonType buttonType, int rotation)
{
super(containerScreen, x, y, 30, 14);
_logicScreen = containerScreen;
_buttonType = buttonType;
_pinIndex = pinIndex;
char[] dir = {'F','R','B','L'};
char[] dirMap = new char[4];
for (int i = 0; i < 4; ++i)
dirMap[(i + rotation) & 3] = dir[i];
_ignoreChanges = true;
if(_buttonType == LogicButtonType.Input)
{
setValue(0, "I/O D");
setValue(1, "I/O U");
setValue(2, "I/O " + dirMap[2]);
setValue(3, "I/O " + dirMap[0]);
setValue(4, "I/O " + dirMap[1]);
setValue(5, "I/O " + dirMap[3]);
setValue(12, "CNST");
setValue(13, "VARS");
setSelectedIndex(0);
}
else
{
setValue(6, "I/O D");
setValue(7, "I/O U");
setValue(8, "I/O " + dirMap[2]);
setValue(9, "I/O " + dirMap[0]);
setValue(10, "I/O " + dirMap[1]);
setValue(11, "I/O " + dirMap[3]);
setValue(13, "VARS");
setValue(14, "NULL");
setSelectedIndex(6);
}
_ignoreChanges = false;
setVisible(false);
}
| public ButtonLogicBufferSelect(GuiRedNetLogic containerScreen, int x, int y, int pinIndex, LogicButtonType buttonType, int rotation)
{
super(containerScreen, x, y, 30, 14);
_logicScreen = containerScreen;
_buttonType = buttonType;
_pinIndex = pinIndex;
char[] dir = {'L','B','R','F',};
char[] dirMap = new char[4];
for (int i = 0; i < 4; ++i)
dirMap[(i + rotation) & 3] = dir[i];
_ignoreChanges = true;
if(_buttonType == LogicButtonType.Input)
{
setValue(0, "I/O D");
setValue(1, "I/O U");
setValue(2, "I/O " + dirMap[2]);
setValue(3, "I/O " + dirMap[0]);
setValue(4, "I/O " + dirMap[1]);
setValue(5, "I/O " + dirMap[3]);
setValue(12, "CNST");
setValue(13, "VARS");
setSelectedIndex(0);
}
else
{
setValue(6, "I/O D");
setValue(7, "I/O U");
setValue(8, "I/O " + dirMap[2]);
setValue(9, "I/O " + dirMap[0]);
setValue(10, "I/O " + dirMap[1]);
setValue(11, "I/O " + dirMap[3]);
setValue(13, "VARS");
setValue(14, "NULL");
setSelectedIndex(6);
}
_ignoreChanges = false;
setVisible(false);
}
|
diff --git a/sdk/src/com/appnexus/opensdk/AdView.java b/sdk/src/com/appnexus/opensdk/AdView.java
index aebdfe77..8d0c5341 100644
--- a/sdk/src/com/appnexus/opensdk/AdView.java
+++ b/sdk/src/com/appnexus/opensdk/AdView.java
@@ -1,752 +1,756 @@
/*
* Copyright 2013 APPNEXUS 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.appnexus.opensdk;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.appnexus.opensdk.utils.Clog;
import com.appnexus.opensdk.utils.Settings;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* The parent class of InterstitialAdView and BannerAdView. This can not be
* instantiated.
*
* @author jacob
*/
public abstract class AdView extends FrameLayout implements AdViewListener {
AdFetcher mAdFetcher;
String placementID;
boolean opensNativeBrowser = false;
int measuredWidth;
int measuredHeight;
private boolean measured = false;
private int width = -1;
private int height = -1;
boolean shouldServePSAs = true;
private float reserve = 0.00f;
String age;
GENDER gender;
ArrayList<Pair<String, String>> customKeywords = new ArrayList<Pair<String, String>>();
boolean mraid_expand = false;
AdListener adListener;
private BrowserStyle browserStyle;
private LinkedList<MediatedAd> mediatedAds;
final Handler handler = new Handler(Looper.getMainLooper());
private Displayable lastDisplayable;
/**
* Begin Construction *
*/
@SuppressWarnings("javadoc")
AdView(Context context) {
super(context, null);
setup(context, null);
}
AdView(Context context, AttributeSet attrs) {
super(context, attrs);
setup(context, attrs);
}
AdView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup(context, attrs);
}
void setup(Context context, AttributeSet attrs) {
// Store self.context in the settings for errors
Clog.error_context = this.getContext();
Clog.d(Clog.publicFunctionsLogTag, Clog.getString(R.string.new_adview));
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
if (prefs.getBoolean("opensdk_first_launch", true)) {
// This is the first launch, store a value to remember
Clog.v(Clog.baseLogTag,
Clog.getString(R.string.first_opensdk_launch));
Settings.getSettings().first_launch = true;
prefs.edit().putBoolean("opensdk_first_launch", false).commit();
} else {
// Found the stored value, this is NOT the first launch
Clog.v(Clog.baseLogTag,
Clog.getString(R.string.not_first_opensdk_launch));
Settings.getSettings().first_launch = false;
}
// Store the UA in the settings
Settings.getSettings().ua = new WebView(context).getSettings()
.getUserAgentString();
Clog.v(Clog.baseLogTag,
Clog.getString(R.string.ua, Settings.getSettings().ua));
// Store the AppID in the settings
Settings.getSettings().app_id = context.getApplicationContext()
.getPackageName();
Clog.v(Clog.baseLogTag,
Clog.getString(R.string.appid, Settings.getSettings().app_id));
Clog.v(Clog.baseLogTag, Clog.getString(R.string.making_adman));
// Make an AdFetcher - Continue the creation pass
mAdFetcher = new AdFetcher(this);
// Load user variables only if attrs isn't null
if (attrs != null)
loadVariablesFromXML(context, attrs);
// We don't start the ad requesting here, since the view hasn't been
// sized yet.
}
@Override
public void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mraid_expand) {
mraid_expand = false;
return;
}
if (!measured || changed) {
// Convert to dips
float density = getContext().getResources().getDisplayMetrics().density;
measuredWidth = (int) ((right - left) / density + 0.5f);
measuredHeight = (int) ((bottom - top) / density + 0.5f);
if ((measuredHeight < height || measuredWidth < width) && measuredHeight > 0 && measuredWidth > 0) {
Clog.e(Clog.baseLogTag, Clog.getString(R.string.adsize_too_big,
measuredWidth, measuredHeight, width, height));
// Hide the space, since no ad will be loaded due to error
hide();
// Stop any request in progress
if (mAdFetcher != null)
mAdFetcher.stop();
// Returning here allows the SDK to re-request when the layout
// next changes, and maybe the error will be amended.
return;
}
// Hide the adview
if (!measured) {
hide();
}
measured = true;
}
}
boolean isMRAIDExpanded() {
if (this.getChildCount() > 0
&& this.getChildAt(0) instanceof MRAIDWebView
&& ((MRAIDWebView) getChildAt(0)).getImplementation().expanded) {
return true;
}
return false;
}
boolean isReadyToStart() {
if (isMRAIDExpanded()) {
Clog.e(Clog.baseLogTag, Clog.getString(R.string.already_expanded));
return false;
}
if (placementID == null || placementID.isEmpty()) {
Clog.e(Clog.baseLogTag, Clog.getString(R.string.no_placement_id));
return false;
}
return true;
}
/**
* Loads a new ad, if the ad space is visible.
*
* @return true is ad will begin loading, false if ad cannot be loaded
* at this time given the current settings
*/
public boolean loadAd() {
if (!isReadyToStart())
return false;
if (this.getWindowVisibility() == VISIBLE && mAdFetcher != null) {
// Reload Ad Fetcher to get new ad at user's request
mAdFetcher.stop();
mAdFetcher.clearDurations();
mAdFetcher.start();
return true;
}
return false;
}
/**
* Loads a new ad, if the ad space is visible, and sets the placement id
* attribute of the AdView to the supplied parameter.
*
* @param placementID The new placement id to use.
*
* @return true is ad will begin loading, false if ad cannot be loaded
* at this time given the current settings
*/
public boolean loadAd(String placementID) {
this.setPlacementID(placementID);
return loadAd();
}
/**
* Loads a new ad, if the ad space is visible, and sets the placement id, ad
* width, and ad height attribute of the AdView to the supplied parameters.
*
* @param placementID The new placement id to use.
* @param width The new width to use.
* @param height The new height to use.
*
* @return true is ad will begin loading, false if ad cannot be loaded
* at this time given the current settings
*/
public boolean loadAd(String placementID, int width, int height) {
this.setAdHeight(height);
this.setAdWidth(width);
this.setPlacementID(placementID);
return loadAd();
}
public void loadHtml(String content, int width, int height) {
this.mAdFetcher.stop();
AdWebView awv = new AdWebView(this);
awv.loadData(content, "text/html", "UTF-8");
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
height);
awv.setLayoutParams(lp);
this.display(awv);
}
protected abstract void loadVariablesFromXML(Context context,
AttributeSet attrs);
/*
* End Construction
*/
void display(Displayable d) {
if ((d == null) || d.failed()) {
// The displayable has failed to be parsed or turned into a View.
fail();
return;
}
if (lastDisplayable != null) {
if(lastDisplayable instanceof MediatedAdViewController){
lastDisplayable.destroy();
}
lastDisplayable = null;
}
WebView webView = null;
if (getChildAt(0) instanceof WebView) {
webView = (WebView) getChildAt(0);
}
this.removeAllViews();
if (webView != null)
webView.destroy();
if (d.getView() == null) {
return;
}
this.addView(d.getView());
lastDisplayable = d;
unhide();
}
void unhide() {
if (getVisibility() != VISIBLE) {
setVisibility(VISIBLE);
}
}
void hide() {
if (getVisibility() != GONE)
setVisibility(GONE);
}
/**
* @return The current placement id.
*/
public String getPlacementID() {
Clog.d(Clog.publicFunctionsLogTag,
Clog.getString(R.string.get_placement_id, placementID));
return placementID;
}
/**
* Sets the placement id of the AdView.
*
* @param placementID The placement id to use
*/
public void setPlacementID(String placementID) {
Clog.d(Clog.publicFunctionsLogTag,
Clog.getString(R.string.set_placement_id, placementID));
this.placementID = placementID;
}
@Override
protected void finalize() {
try {
super.finalize();
} catch (Throwable e) {
}
// Just in case, kill the adfetcher's service
if (mAdFetcher != null)
mAdFetcher.stop();
}
/**
* Sets the height of the ad to request.
*
* @param h The height, in pixels, to use.
*/
public void setAdHeight(int h) {
Clog.d(Clog.baseLogTag, Clog.getString(R.string.set_height, h));
height = h;
}
/**
* Sets the width of the ad to request.
*
* @param w The width, in pixels, to use.
*/
public void setAdWidth(int w) {
Clog.d(Clog.baseLogTag, Clog.getString(R.string.set_width, w));
width = w;
}
/**
* @return The height of the ad to be requested.
*/
public int getAdHeight() {
Clog.d(Clog.baseLogTag, Clog.getString(R.string.get_height, height));
return height;
}
/**
* @return The width of the ad to be requested.
*/
public int getAdWidth() {
Clog.d(Clog.baseLogTag, Clog.getString(R.string.get_width, width));
return width;
}
int getContainerWidth() {
return measuredWidth;
}
int getContainerHeight() {
return measuredHeight;
}
// Used only by MRAID
ImageButton close_button;
View oldContent;
Activity unexpandedActivity;
protected void close(int w, int h, MRAIDImplementation caller){
//For closing
if(oldContent!= null && oldContent.getParent()!=null){
((ViewGroup)oldContent.getParent()).removeAllViewsInLayout();
}
if(unexpandedActivity!=null){
unexpandedActivity.setContentView(oldContent);
}
if (caller.owner.isFullScreen) {
((FrameLayout)caller.owner.getParent()).removeAllViews();
this.addView(caller.owner);
}
expand(w, h, true, null);
}
protected void expand(int w, int h, boolean custom_close,
final MRAIDImplementation caller) {
mraid_expand = true;
if (getLayoutParams() != null) {
if (getLayoutParams().width > 0)
getLayoutParams().width = w;
if (getLayoutParams().height > 0)
getLayoutParams().height = h;
}
if (!custom_close) {
// Add a stock close_button button to the top right corner
close_button = new ImageButton(this.getContext());
close_button.setImageDrawable(getResources().getDrawable(
android.R.drawable.ic_menu_close_clear_cancel));
FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.TOP);
if(caller.owner.isFullScreen){
//Make a new framelayout to contain webview and button
FrameLayout fslayout = new FrameLayout(this.getContext());
if(this.getChildCount()>0){
this.removeAllViews();
}
fslayout.addView(caller.owner);
fslayout.addView(close_button);
if (this instanceof InterstitialAdView) {
unexpandedActivity = AdActivity.getCurrent_ad_activity();
} else {
unexpandedActivity = (Activity) this.getContext();
}
oldContent= ((ViewGroup)unexpandedActivity.findViewById(android.R.id.content)).getChildAt(0);
unexpandedActivity.setContentView(fslayout);
}else{
if(getChildAt(0)!=null){
blp.rightMargin = (this.getMeasuredWidth() - this.getChildAt(0)
.getMeasuredWidth()) / 2;
}
this.addView(close_button);
}
close_button.setLayoutParams(blp);
close_button.setBackgroundColor(Color.TRANSPARENT);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
caller.close();
}
});
} else if (custom_close && close_button != null) {
close_button.setVisibility(GONE);
}
}
/**
*
* @return true if the AdView is a BannerAdView
*/
abstract boolean isBanner();
/**
*
* @return true if the AdView is an InterstitialAdView
*/
abstract boolean isInterstitial();
/**
* Sets the listener that the InterstitialAdView will call events in.
*
* @param listener The {@link AdListener} object to use.
*/
public void setAdListener(AdListener listener) {
Clog.d(Clog.publicFunctionsLogTag,
Clog.getString(R.string.set_ad_listener));
adListener = listener;
}
/**
* Gets the listener that the InterstitialAdView will call events in.
*
* @return The {@link AdListener} object in use.
*/
public AdListener getAdListener() {
Clog.d(Clog.publicFunctionsLogTag,
Clog.getString(R.string.get_ad_listener));
return adListener;
}
void fail() {
onAdFailed(true);
}
/**
* @return whether or not the native browser is used instead of the in-app
* browser.
*/
public boolean getOpensNativeBrowser() {
Clog.d(Clog.publicFunctionsLogTag, Clog.getString(
R.string.get_opens_native_browser, opensNativeBrowser));
return opensNativeBrowser;
}
/**
* Set this to true to disable the in-app browser.
*
* @param opensNativeBrowser
*/
public void setOpensNativeBrowser(boolean opensNativeBrowser) {
Clog.d(Clog.publicFunctionsLogTag, Clog.getString(
R.string.set_opens_native_browser, opensNativeBrowser));
this.opensNativeBrowser = opensNativeBrowser;
}
BrowserStyle getBrowserStyle() {
return browserStyle;
}
protected void setBrowserStyle(BrowserStyle browserStyle) {
this.browserStyle = browserStyle;
}
/**
* @return Whether this placement accepts PSAs if no ad is served.
*/
public boolean getShouldServePSAs() {
return shouldServePSAs;
}
/**
* @param shouldServePSAs Whether this placement accepts PSAs if no ad is served.
*/
public void setShouldServePSAs(boolean shouldServePSAs) {
this.shouldServePSAs = shouldServePSAs;
}
public void resize(int w, int h, int offset_x, int offset_y, MRAIDImplementation.CUSTOM_CLOSE_POSITION custom_close_position, boolean allow_offscrean,
final MRAIDImplementation caller) {
//TODO: Offsets???
mraid_expand = true;
if (getLayoutParams() != null) {
if (getLayoutParams().width > 0)
getLayoutParams().width = w;
if (getLayoutParams().height > 0)
getLayoutParams().height = h;
}
// Add a stock close_button button to the top right corner
+ if(close_button!=null){
+ ((ViewGroup)close_button.getParent()).removeView(close_button);
+ close_button.setVisibility(GONE);
+ }
close_button = new ImageButton(this.getContext());
close_button.setImageDrawable(getResources().getDrawable(
android.R.drawable.ic_menu_close_clear_cancel));
int grav = Gravity.RIGHT | Gravity.TOP;
switch (custom_close_position) {
case bottom_center:
grav = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
break;
case bottom_left:
grav = Gravity.BOTTOM | Gravity.LEFT;
break;
case bottom_right:
grav = Gravity.BOTTOM | Gravity.RIGHT;
break;
case center:
grav = Gravity.CENTER;
break;
case top_center:
grav = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
break;
case top_left:
grav = Gravity.TOP | Gravity.LEFT;
break;
case top_right:
grav = Gravity.TOP | Gravity.RIGHT;
break;
}
FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, grav);
blp.rightMargin = (this.getMeasuredWidth() - this.getChildAt(0)
.getMeasuredWidth()) / 2;
close_button.setLayoutParams(blp);
close_button.setBackgroundColor(Color.TRANSPARENT);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
caller.close();
}
});
this.addView(close_button);
}
public float getReserve() {
return reserve;
}
public void setReserve(float reserve) {
this.reserve = reserve;
}
public String getAge() {
return age;
}
/**
*
* @param age should be a numerical age, birth year, or hyphenated age range.
* For example: "56", "1974", or "25-35"
*/
public void setAge(String age) {
this.age = age;
}
public enum GENDER {
MALE,
FEMALE
}
public GENDER getGender() {
return gender;
}
/**
*
* @param gender should be either "m" for male or "f" for female
*/
public void setGender(GENDER gender) {
this.gender = gender;
}
/**
* add a custom keyword to the request url for the ad
* @param key keyword name to add, cannot be null or empty
* @param value keyword value, cannot be null
*/
public void addCustomKeywords(String key, String value) {
if ((key == null) || (key.isEmpty()) || (value == null)) {
return;
}
customKeywords.add(new Pair<String, String>(key, value));
}
/**
* remove a custom keyword from the request url for the ad
* @param key keyword name to remove, cannot be null or empty
*/
public void removeCustomKeyword(String key) {
if ((key == null) || (key.isEmpty()))
return;
for (int i = 0; i < customKeywords.size(); i++) {
Pair<String, String> pair = customKeywords.get(i);
if (pair.first.equals(key)) {
customKeywords.remove(i);
break;
}
}
}
public ArrayList<Pair<String, String>> getCustomKeywords() {
return customKeywords;
}
static class BrowserStyle {
public BrowserStyle(Drawable forwardButton, Drawable backButton,
Drawable refreshButton) {
this.forwardButton = forwardButton;
this.backButton = backButton;
this.refreshButton = refreshButton;
}
final Drawable forwardButton;
final Drawable backButton;
final Drawable refreshButton;
static final ArrayList<Pair<String, BrowserStyle>> bridge = new ArrayList<Pair<String, BrowserStyle>>();
}
@Override
public void onAdLoaded(final Displayable d) {
handler.post(new Runnable() {
@Override
public void run() {
display(d);
if (adListener != null)
adListener.onAdLoaded(AdView.this);
}
});
}
@Override
public void onAdFailed(boolean noMoreAds) {
// wait until mediation waterfall is complete before calling adListener
if (!noMoreAds)
return;
handler.post(new Runnable() {
@Override
public void run() {
if (adListener != null)
adListener.onAdRequestFailed(AdView.this);
}
});
}
@Override
public void onAdExpanded() {
handler.post(new Runnable() {
@Override
public void run() {
if (adListener != null)
adListener.onAdExpanded(AdView.this);
}
});
}
@Override
public void onAdCollapsed() {
handler.post(new Runnable() {
@Override
public void run() {
if (adListener != null)
adListener.onAdCollapsed(AdView.this);
}
});
}
@Override
public void onAdClicked() {
handler.post(new Runnable() {
@Override
public void run() {
if (adListener != null)
adListener.onAdClicked(AdView.this);
}
});
}
public LinkedList<MediatedAd> getMediatedAds() {
return mediatedAds;
}
public void setMediatedAds(LinkedList<MediatedAd> mediatedAds) {
this.mediatedAds = mediatedAds;
}
// returns the first mediated ad if available
public MediatedAd popMediatedAd() {
return mediatedAds != null ? mediatedAds.pop() : null;
}
}
| true | true | public void resize(int w, int h, int offset_x, int offset_y, MRAIDImplementation.CUSTOM_CLOSE_POSITION custom_close_position, boolean allow_offscrean,
final MRAIDImplementation caller) {
//TODO: Offsets???
mraid_expand = true;
if (getLayoutParams() != null) {
if (getLayoutParams().width > 0)
getLayoutParams().width = w;
if (getLayoutParams().height > 0)
getLayoutParams().height = h;
}
// Add a stock close_button button to the top right corner
close_button = new ImageButton(this.getContext());
close_button.setImageDrawable(getResources().getDrawable(
android.R.drawable.ic_menu_close_clear_cancel));
int grav = Gravity.RIGHT | Gravity.TOP;
switch (custom_close_position) {
case bottom_center:
grav = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
break;
case bottom_left:
grav = Gravity.BOTTOM | Gravity.LEFT;
break;
case bottom_right:
grav = Gravity.BOTTOM | Gravity.RIGHT;
break;
case center:
grav = Gravity.CENTER;
break;
case top_center:
grav = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
break;
case top_left:
grav = Gravity.TOP | Gravity.LEFT;
break;
case top_right:
grav = Gravity.TOP | Gravity.RIGHT;
break;
}
FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, grav);
blp.rightMargin = (this.getMeasuredWidth() - this.getChildAt(0)
.getMeasuredWidth()) / 2;
close_button.setLayoutParams(blp);
close_button.setBackgroundColor(Color.TRANSPARENT);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
caller.close();
}
});
this.addView(close_button);
}
| public void resize(int w, int h, int offset_x, int offset_y, MRAIDImplementation.CUSTOM_CLOSE_POSITION custom_close_position, boolean allow_offscrean,
final MRAIDImplementation caller) {
//TODO: Offsets???
mraid_expand = true;
if (getLayoutParams() != null) {
if (getLayoutParams().width > 0)
getLayoutParams().width = w;
if (getLayoutParams().height > 0)
getLayoutParams().height = h;
}
// Add a stock close_button button to the top right corner
if(close_button!=null){
((ViewGroup)close_button.getParent()).removeView(close_button);
close_button.setVisibility(GONE);
}
close_button = new ImageButton(this.getContext());
close_button.setImageDrawable(getResources().getDrawable(
android.R.drawable.ic_menu_close_clear_cancel));
int grav = Gravity.RIGHT | Gravity.TOP;
switch (custom_close_position) {
case bottom_center:
grav = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
break;
case bottom_left:
grav = Gravity.BOTTOM | Gravity.LEFT;
break;
case bottom_right:
grav = Gravity.BOTTOM | Gravity.RIGHT;
break;
case center:
grav = Gravity.CENTER;
break;
case top_center:
grav = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
break;
case top_left:
grav = Gravity.TOP | Gravity.LEFT;
break;
case top_right:
grav = Gravity.TOP | Gravity.RIGHT;
break;
}
FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, grav);
blp.rightMargin = (this.getMeasuredWidth() - this.getChildAt(0)
.getMeasuredWidth()) / 2;
close_button.setLayoutParams(blp);
close_button.setBackgroundColor(Color.TRANSPARENT);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
caller.close();
}
});
this.addView(close_button);
}
|
diff --git a/luni/src/main/java/java/net/Socket.java b/luni/src/main/java/java/net/Socket.java
index 26e5ff68a..9297c5381 100644
--- a/luni/src/main/java/java/net/Socket.java
+++ b/luni/src/main/java/java/net/Socket.java
@@ -1,986 +1,995 @@
/*
* 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 java.net;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.SocketChannel;
import libcore.io.IoBridge;
/**
* Provides a client-side TCP socket.
*/
public class Socket {
private static SocketImplFactory factory;
final SocketImpl impl;
private final Proxy proxy;
volatile boolean isCreated = false;
private boolean isBound = false;
private boolean isConnected = false;
private boolean isClosed = false;
private boolean isInputShutdown = false;
private boolean isOutputShutdown = false;
private InetAddress localAddress = Inet4Address.ANY;
private final Object connectLock = new Object();
/**
* Creates a new unconnected socket. When a SocketImplFactory is defined it
* creates the internal socket implementation, otherwise the default socket
* implementation will be used for this socket.
*
* @see SocketImplFactory
* @see SocketImpl
*/
public Socket() {
this.impl = factory != null ? factory.createSocketImpl() : new PlainSocketImpl();
this.proxy = null;
}
/**
* Creates a new unconnected socket using the given proxy type. When a
* {@code SocketImplFactory} is defined it creates the internal socket
* implementation, otherwise the default socket implementation will be used
* for this socket.
* <p>
* Example that will create a socket connection through a {@code SOCKS}
* proxy server: <br>
* {@code Socket sock = new Socket(new Proxy(Proxy.Type.SOCKS, new
* InetSocketAddress("test.domain.org", 2130)));}
*
* @param proxy
* the specified proxy for this socket.
* @throws IllegalArgumentException
* if the argument {@code proxy} is {@code null} or of an
* invalid type.
* @see SocketImplFactory
* @see SocketImpl
*/
public Socket(Proxy proxy) {
if (proxy == null || proxy.type() == Proxy.Type.HTTP) {
throw new IllegalArgumentException("Invalid proxy: " + proxy);
}
this.proxy = proxy;
this.impl = factory != null ? factory.createSocketImpl() : new PlainSocketImpl(proxy);
}
/**
* Tries to connect a socket to all IP addresses of the given hostname.
*
* @param dstName
* the target host name or IP address to connect to.
* @param dstPort
* the port on the target host to connect to.
* @param localAddress
* the address on the local host to bind to.
* @param localPort
* the port on the local host to bind to.
* @param streaming
* if {@code true} a streaming socket is returned, a datagram
* socket otherwise.
* @throws UnknownHostException
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
*/
private void tryAllAddresses(String dstName, int dstPort, InetAddress
localAddress, int localPort, boolean streaming) throws IOException {
InetAddress[] dstAddresses = InetAddress.getAllByName(dstName);
// Loop through all the destination addresses except the last, trying to
// connect to each one and ignoring errors. There must be at least one
// address, or getAllByName would have thrown UnknownHostException.
InetAddress dstAddress;
for (int i = 0; i < dstAddresses.length - 1; i++) {
dstAddress = dstAddresses[i];
try {
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, localAddress, localPort, streaming);
return;
} catch (IOException ex) {
}
}
// Now try to connect to the last address in the array, handing back to
// the caller any exceptions that are thrown.
dstAddress = dstAddresses[dstAddresses.length - 1];
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, localAddress, localPort, streaming);
}
/**
* Creates a new streaming socket connected to the target host specified by
* the parameters {@code dstName} and {@code dstPort}. The socket is bound
* to any available port on the local host.
*
* <p>This implementation tries each IP address for the given hostname (in
* <a href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a> order)
* until it either connects successfully or it exhausts the set.
*
* @param dstName
* the target host name or IP address to connect to.
* @param dstPort
* the port on the target host to connect to.
* @throws UnknownHostException
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
*/
public Socket(String dstName, int dstPort) throws UnknownHostException, IOException {
this(dstName, dstPort, null, 0);
}
/**
* Creates a new streaming socket connected to the target host specified by
* the parameters {@code dstName} and {@code dstPort}. On the local endpoint
* the socket is bound to the given address {@code localAddress} on port
* {@code localPort}. If {@code host} is {@code null} a loopback address is used to connect to.
*
* <p>This implementation tries each IP address for the given hostname (in
* <a href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a> order)
* until it either connects successfully or it exhausts the set.
*
* @param dstName
* the target host name or IP address to connect to.
* @param dstPort
* the port on the target host to connect to.
* @param localAddress
* the address on the local host to bind to.
* @param localPort
* the port on the local host to bind to.
* @throws UnknownHostException
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
*/
public Socket(String dstName, int dstPort, InetAddress localAddress, int localPort) throws IOException {
this();
tryAllAddresses(dstName, dstPort, localAddress, localPort, true);
}
/**
* Creates a new streaming or datagram socket connected to the target host
* specified by the parameters {@code hostName} and {@code port}. The socket
* is bound to any available port on the local host.
*
* <p>This implementation tries each IP address for the given hostname (in
* <a href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a> order)
* until it either connects successfully or it exhausts the set.
*
* @param hostName
* the target host name or IP address to connect to.
* @param port
* the port on the target host to connect to.
* @param streaming
* if {@code true} a streaming socket is returned, a datagram
* socket otherwise.
* @throws UnknownHostException
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
* @deprecated Use {@code Socket(String, int)} instead of this for streaming
* sockets or an appropriate constructor of {@code
* DatagramSocket} for UDP transport.
*/
@Deprecated
public Socket(String hostName, int port, boolean streaming) throws IOException {
this();
tryAllAddresses(hostName, port, null, 0, streaming);
}
/**
* Creates a new streaming socket connected to the target host specified by
* the parameters {@code dstAddress} and {@code dstPort}. The socket is
* bound to any available port on the local host.
*
* @param dstAddress
* the target host address to connect to.
* @param dstPort
* the port on the target host to connect to.
* @throws IOException
* if an error occurs while creating the socket.
*/
public Socket(InetAddress dstAddress, int dstPort) throws IOException {
this();
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, null, 0, true);
}
/**
* Creates a new streaming socket connected to the target host specified by
* the parameters {@code dstAddress} and {@code dstPort}. On the local
* endpoint the socket is bound to the given address {@code localAddress} on
* port {@code localPort}.
*
* @param dstAddress
* the target host address to connect to.
* @param dstPort
* the port on the target host to connect to.
* @param localAddress
* the address on the local host to bind to.
* @param localPort
* the port on the local host to bind to.
* @throws IOException
* if an error occurs while creating the socket.
*/
public Socket(InetAddress dstAddress, int dstPort,
InetAddress localAddress, int localPort) throws IOException {
this();
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, localAddress, localPort, true);
}
/**
* Creates a new streaming or datagram socket connected to the target host
* specified by the parameters {@code addr} and {@code port}. The socket is
* bound to any available port on the local host.
*
* @param addr
* the Internet address to connect to.
* @param port
* the port on the target host to connect to.
* @param streaming
* if {@code true} a streaming socket is returned, a datagram
* socket otherwise.
* @throws IOException
* if an error occurs while creating the socket.
* @deprecated Use {@code Socket(InetAddress, int)} instead of this for
* streaming sockets or an appropriate constructor of {@code
* DatagramSocket} for UDP transport.
*/
@Deprecated
public Socket(InetAddress addr, int port, boolean streaming) throws IOException {
this();
checkDestination(addr, port);
startupSocket(addr, port, null, 0, streaming);
}
/**
* Creates an unconnected socket with the given socket implementation.
*
* @param impl
* the socket implementation to be used.
* @throws SocketException
* if an error occurs while creating the socket.
*/
protected Socket(SocketImpl impl) throws SocketException {
this.impl = impl;
this.proxy = null;
}
/**
* Checks whether the connection destination satisfies the security policy
* and the validity of the port range.
*
* @param destAddr
* the destination host address.
* @param dstPort
* the port on the destination host.
*/
private void checkDestination(InetAddress destAddr, int dstPort) {
if (dstPort < 0 || dstPort > 65535) {
throw new IllegalArgumentException("Port out of range: " + dstPort);
}
}
/**
* Closes the socket. It is not possible to reconnect or rebind to this
* socket thereafter which means a new socket instance has to be created.
*
* @throws IOException
* if an error occurs while closing the socket.
*/
public synchronized void close() throws IOException {
isClosed = true;
// RI compatibility: the RI returns the any address (but the original local port) after close.
localAddress = Inet4Address.ANY;
impl.close();
}
/**
* Returns the IP address of the target host this socket is connected to, or null if this
* socket is not yet connected.
*/
public InetAddress getInetAddress() {
if (!isConnected()) {
return null;
}
return impl.getInetAddress();
}
/**
* Returns an input stream to read data from this socket.
*
* @return the byte-oriented input stream.
* @throws IOException
* if an error occurs while creating the input stream or the
* socket is in an invalid state.
*/
public InputStream getInputStream() throws IOException {
checkOpenAndCreate(false);
if (isInputShutdown()) {
throw new SocketException("Socket input is shutdown");
}
return impl.getInputStream();
}
/**
* Returns this socket's {@link SocketOptions#SO_KEEPALIVE} setting.
*/
public boolean getKeepAlive() throws SocketException {
checkOpenAndCreate(true);
return (Boolean) impl.getOption(SocketOptions.SO_KEEPALIVE);
}
/**
* Returns the local IP address this socket is bound to, or {@code InetAddress.ANY} if
* the socket is unbound.
*/
public InetAddress getLocalAddress() {
return localAddress;
}
/**
* Returns the local port this socket is bound to, or -1 if the socket is unbound.
*/
public int getLocalPort() {
if (!isBound()) {
return -1;
}
return impl.getLocalPort();
}
/**
* Returns an output stream to write data into this socket.
*
* @return the byte-oriented output stream.
* @throws IOException
* if an error occurs while creating the output stream or the
* socket is in an invalid state.
*/
public OutputStream getOutputStream() throws IOException {
checkOpenAndCreate(false);
if (isOutputShutdown()) {
throw new SocketException("Socket output is shutdown");
}
return impl.getOutputStream();
}
/**
* Returns the port number of the target host this socket is connected to, or 0 if this socket
* is not yet connected.
*/
public int getPort() {
if (!isConnected()) {
return 0;
}
return impl.getPort();
}
/**
* Returns this socket's {@link SocketOptions#SO_LINGER linger} timeout in seconds, or -1
* for no linger (i.e. {@code close} will return immediately).
*/
public int getSoLinger() throws SocketException {
checkOpenAndCreate(true);
// The RI explicitly guarantees this idiocy in the SocketOptions.setOption documentation.
Object value = impl.getOption(SocketOptions.SO_LINGER);
if (value instanceof Integer) {
return (Integer) value;
} else {
return -1;
}
}
/**
* Returns this socket's {@link SocketOptions#SO_RCVBUF receive buffer size}.
*/
public synchronized int getReceiveBufferSize() throws SocketException {
checkOpenAndCreate(true);
return (Integer) impl.getOption(SocketOptions.SO_RCVBUF);
}
/**
* Returns this socket's {@link SocketOptions#SO_SNDBUF send buffer size}.
*/
public synchronized int getSendBufferSize() throws SocketException {
checkOpenAndCreate(true);
return (Integer) impl.getOption(SocketOptions.SO_SNDBUF);
}
/**
* Returns this socket's {@link SocketOptions#SO_TIMEOUT receive timeout}.
*/
public synchronized int getSoTimeout() throws SocketException {
checkOpenAndCreate(true);
return (Integer) impl.getOption(SocketOptions.SO_TIMEOUT);
}
/**
* Returns this socket's {@code SocketOptions#TCP_NODELAY} setting.
*/
public boolean getTcpNoDelay() throws SocketException {
checkOpenAndCreate(true);
return (Boolean) impl.getOption(SocketOptions.TCP_NODELAY);
}
/**
* Sets this socket's {@link SocketOptions#SO_KEEPALIVE} option.
*/
public void setKeepAlive(boolean keepAlive) throws SocketException {
if (impl != null) {
checkOpenAndCreate(true);
impl.setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(keepAlive));
}
}
/**
* Sets the internal factory for creating socket implementations. This may
* only be executed once during the lifetime of the application.
*
* @param fac
* the socket implementation factory to be set.
* @throws IOException
* if the factory has been already set.
*/
public static synchronized void setSocketImplFactory(SocketImplFactory fac)
throws IOException {
if (factory != null) {
throw new SocketException("Factory already set");
}
factory = fac;
}
/**
* Sets this socket's {@link SocketOptions#SO_SNDBUF send buffer size}.
*/
public synchronized void setSendBufferSize(int size) throws SocketException {
checkOpenAndCreate(true);
if (size < 1) {
throw new IllegalArgumentException("size < 1");
}
impl.setOption(SocketOptions.SO_SNDBUF, Integer.valueOf(size));
}
/**
* Sets this socket's {@link SocketOptions#SO_SNDBUF receive buffer size}.
*/
public synchronized void setReceiveBufferSize(int size) throws SocketException {
checkOpenAndCreate(true);
if (size < 1) {
throw new IllegalArgumentException("size < 1");
}
impl.setOption(SocketOptions.SO_RCVBUF, Integer.valueOf(size));
}
/**
* Sets this socket's {@link SocketOptions#SO_LINGER linger} timeout in seconds.
* If {@code on} is false, {@code timeout} is irrelevant.
*/
public void setSoLinger(boolean on, int timeout) throws SocketException {
checkOpenAndCreate(true);
// The RI explicitly guarantees this idiocy in the SocketOptions.setOption documentation.
if (on && timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (on) {
impl.setOption(SocketOptions.SO_LINGER, Integer.valueOf(timeout));
} else {
impl.setOption(SocketOptions.SO_LINGER, Boolean.FALSE);
}
}
/**
* Sets this socket's {@link SocketOptions#SO_TIMEOUT read timeout} in milliseconds.
* Use 0 for no timeout.
* To take effect, this option must be set before the blocking method was called.
*/
public synchronized void setSoTimeout(int timeout) throws SocketException {
checkOpenAndCreate(true);
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
impl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(timeout));
}
/**
* Sets this socket's {@link SocketOptions#TCP_NODELAY} option.
*/
public void setTcpNoDelay(boolean on) throws SocketException {
checkOpenAndCreate(true);
impl.setOption(SocketOptions.TCP_NODELAY, Boolean.valueOf(on));
}
/**
* Creates a stream socket, binds it to the nominated local address/port,
* then connects it to the nominated destination address/port.
*
* @param dstAddress
* the destination host address.
* @param dstPort
* the port on the destination host.
* @param localAddress
* the address on the local machine to bind.
* @param localPort
* the port on the local machine to bind.
* @throws IOException
* thrown if an error occurs during the bind or connect
* operations.
*/
private void startupSocket(InetAddress dstAddress, int dstPort,
InetAddress localAddress, int localPort, boolean streaming)
throws IOException {
if (localPort < 0 || localPort > 65535) {
throw new IllegalArgumentException("Local port out of range: " + localPort);
}
InetAddress addr = localAddress == null ? Inet4Address.ANY : localAddress;
synchronized (this) {
impl.create(streaming);
isCreated = true;
try {
if (!streaming || !usingSocks()) {
//
// Bind will happen during connect for INADDR_ANY:0
// Save the system call in the default case
//
if (! addr.isAnyLocalAddress() || 0 != localPort) {
impl.bind(addr, localPort);
}
}
isBound = true;
impl.connect(dstAddress, dstPort);
isConnected = true;
cacheLocalAddress();
} catch (IOException e) {
impl.close();
throw e;
}
}
}
private boolean usingSocks() {
return proxy != null && proxy.type() == Proxy.Type.SOCKS;
}
/**
* Returns a {@code String} containing a concise, human-readable description of the
* socket.
*
* @return the textual representation of this socket.
*/
@Override
public String toString() {
if (!isConnected()) {
return "Socket[unconnected]";
}
return impl.toString();
}
/**
* Closes the input stream of this socket. Any further data sent to this
* socket will be discarded. Reading from this socket after this method has
* been called will return the value {@code EOF}.
*
* @throws IOException
* if an error occurs while closing the socket input stream.
* @throws SocketException
* if the input stream is already closed.
*/
public void shutdownInput() throws IOException {
if (isInputShutdown()) {
throw new SocketException("Socket input is shutdown");
}
checkOpenAndCreate(false);
impl.shutdownInput();
isInputShutdown = true;
}
/**
* Closes the output stream of this socket. All buffered data will be sent
* followed by the termination sequence. Writing to the closed output stream
* will cause an {@code IOException}.
*
* @throws IOException
* if an error occurs while closing the socket output stream.
* @throws SocketException
* if the output stream is already closed.
*/
public void shutdownOutput() throws IOException {
if (isOutputShutdown()) {
throw new SocketException("Socket output is shutdown");
}
checkOpenAndCreate(false);
impl.shutdownOutput();
isOutputShutdown = true;
}
/**
* Checks whether the socket is closed, and throws an exception. Otherwise
* creates the underlying SocketImpl.
*
* @throws SocketException
* if the socket is closed.
*/
private void checkOpenAndCreate(boolean create) throws SocketException {
if (isClosed()) {
throw new SocketException("Socket is closed");
}
if (!create) {
if (!isConnected()) {
throw new SocketException("Socket is not connected");
// a connected socket must be created
}
/*
* return directly to fix a possible bug, if !create, should return
* here
*/
return;
}
if (isCreated) {
return;
}
synchronized (this) {
if (isCreated) {
return;
}
try {
impl.create(true);
} catch (SocketException e) {
throw e;
} catch (IOException e) {
throw new SocketException(e.toString());
}
isCreated = true;
}
}
/**
* Returns the local address and port of this socket as a SocketAddress or
* null if the socket is unbound. This is useful on multihomed
* hosts.
*/
public SocketAddress getLocalSocketAddress() {
if (!isBound()) {
return null;
}
return new InetSocketAddress(getLocalAddress(), getLocalPort());
}
/**
* Returns the remote address and port of this socket as a {@code
* SocketAddress} or null if the socket is not connected.
*
* @return the remote socket address and port.
*/
public SocketAddress getRemoteSocketAddress() {
if (!isConnected()) {
return null;
}
return new InetSocketAddress(getInetAddress(), getPort());
}
/**
* Returns whether this socket is bound to a local address and port.
*
* @return {@code true} if the socket is bound to a local address, {@code
* false} otherwise.
*/
public boolean isBound() {
return isBound;
}
/**
* Returns whether this socket is connected to a remote host.
*
* @return {@code true} if the socket is connected, {@code false} otherwise.
*/
public boolean isConnected() {
return isConnected;
}
/**
* Returns whether this socket is closed.
*
* @return {@code true} if the socket is closed, {@code false} otherwise.
*/
public boolean isClosed() {
return isClosed;
}
/**
* Binds this socket to the given local host address and port specified by
* the SocketAddress {@code localAddr}. If {@code localAddr} is set to
* {@code null}, this socket will be bound to an available local address on
* any free port.
*
* @param localAddr
* the specific address and port on the local machine to bind to.
* @throws IllegalArgumentException
* if the given SocketAddress is invalid or not supported.
* @throws IOException
* if the socket is already bound or an error occurs while
* binding.
*/
public void bind(SocketAddress localAddr) throws IOException {
checkOpenAndCreate(true);
if (isBound()) {
throw new BindException("Socket is already bound");
}
int port = 0;
InetAddress addr = Inet4Address.ANY;
if (localAddr != null) {
if (!(localAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Local address not an InetSocketAddress: " +
localAddr.getClass());
}
InetSocketAddress inetAddr = (InetSocketAddress) localAddr;
if ((addr = inetAddr.getAddress()) == null) {
throw new UnknownHostException("Host is unresolved: " + inetAddr.getHostName());
}
port = inetAddr.getPort();
}
synchronized (this) {
try {
impl.bind(addr, port);
isBound = true;
cacheLocalAddress();
} catch (IOException e) {
impl.close();
throw e;
}
}
}
/**
* Connects this socket to the given remote host address and port specified
* by the SocketAddress {@code remoteAddr}.
*
* @param remoteAddr
* the address and port of the remote host to connect to.
* @throws IllegalArgumentException
* if the given SocketAddress is invalid or not supported.
* @throws IOException
* if the socket is already connected or an error occurs while
* connecting.
*/
public void connect(SocketAddress remoteAddr) throws IOException {
connect(remoteAddr, 0);
}
/**
* Connects this socket to the given remote host address and port specified
* by the SocketAddress {@code remoteAddr} with the specified timeout. The
* connecting method will block until the connection is established or an
* error occurred.
*
* @param remoteAddr
* the address and port of the remote host to connect to.
* @param timeout
* the timeout value in milliseconds or {@code 0} for an infinite
* timeout.
* @throws IllegalArgumentException
* if the given SocketAddress is invalid or not supported or the
* timeout value is negative.
* @throws IOException
* if the socket is already connected or an error occurs while
* connecting.
*/
public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
checkOpenAndCreate(true);
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (isConnected()) {
throw new SocketException("Already connected");
}
if (remoteAddr == null) {
throw new IllegalArgumentException("remoteAddr == null");
}
if (!(remoteAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Remote address not an InetSocketAddress: " +
remoteAddr.getClass());
}
InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
InetAddress addr;
if ((addr = inetAddr.getAddress()) == null) {
throw new UnknownHostException("Host is unresolved: " + inetAddr.getHostName());
}
int port = inetAddr.getPort();
checkDestination(addr, port);
synchronized (connectLock) {
try {
+ if (!isBound()) {
+ // socket already created at this point by earlier call or
+ // checkOpenAndCreate this caused us to lose socket
+ // options on create
+ // impl.create(true);
+ if (!usingSocks()) {
+ impl.bind(Inet4Address.ANY, 0);
+ }
+ isBound = true;
+ }
impl.connect(remoteAddr, timeout);
- isBound = true;
isConnected = true;
cacheLocalAddress();
} catch (IOException e) {
impl.close();
throw e;
}
}
}
/**
* Returns whether the incoming channel of the socket has already been
* closed.
*
* @return {@code true} if reading from this socket is not possible anymore,
* {@code false} otherwise.
*/
public boolean isInputShutdown() {
return isInputShutdown;
}
/**
* Returns whether the outgoing channel of the socket has already been
* closed.
*
* @return {@code true} if writing to this socket is not possible anymore,
* {@code false} otherwise.
*/
public boolean isOutputShutdown() {
return isOutputShutdown;
}
/**
* Sets this socket's {@link SocketOptions#SO_REUSEADDR} option.
*/
public void setReuseAddress(boolean reuse) throws SocketException {
checkOpenAndCreate(true);
impl.setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(reuse));
}
/**
* Returns this socket's {@link SocketOptions#SO_REUSEADDR} setting.
*/
public boolean getReuseAddress() throws SocketException {
checkOpenAndCreate(true);
return (Boolean) impl.getOption(SocketOptions.SO_REUSEADDR);
}
/**
* Sets this socket's {@link SocketOptions#SO_OOBINLINE} option.
*/
public void setOOBInline(boolean oobinline) throws SocketException {
checkOpenAndCreate(true);
impl.setOption(SocketOptions.SO_OOBINLINE, Boolean.valueOf(oobinline));
}
/**
* Returns this socket's {@link SocketOptions#SO_OOBINLINE} setting.
*/
public boolean getOOBInline() throws SocketException {
checkOpenAndCreate(true);
return (Boolean) impl.getOption(SocketOptions.SO_OOBINLINE);
}
/**
* Sets this socket's {@link SocketOptions#IP_TOS} value for every packet sent by this socket.
*/
public void setTrafficClass(int value) throws SocketException {
checkOpenAndCreate(true);
if (value < 0 || value > 255) {
throw new IllegalArgumentException();
}
impl.setOption(SocketOptions.IP_TOS, Integer.valueOf(value));
}
/**
* Returns this socket's {@see SocketOptions#IP_TOS} setting.
*/
public int getTrafficClass() throws SocketException {
checkOpenAndCreate(true);
return (Integer) impl.getOption(SocketOptions.IP_TOS);
}
/**
* Sends the given single byte data which is represented by the lowest octet
* of {@code value} as "TCP urgent data".
*
* @param value
* the byte of urgent data to be sent.
* @throws IOException
* if an error occurs while sending urgent data.
*/
public void sendUrgentData(int value) throws IOException {
impl.sendUrgentData(value);
}
/**
* Set the appropriate flags for a socket created by {@code
* ServerSocket.accept()}.
*
* @see ServerSocket#implAccept
*/
void accepted() {
isCreated = isBound = isConnected = true;
cacheLocalAddress();
}
private void cacheLocalAddress() {
this.localAddress = IoBridge.getSocketLocalAddress(impl.fd);
}
/**
* Returns this socket's {@code SocketChannel}, if one exists. A channel is
* available only if this socket wraps a channel. (That is, you can go from a
* channel to a socket and back again, but you can't go from an arbitrary socket to a channel.)
* In practice, this means that the socket must have been created by
* {@link java.nio.channels.ServerSocketChannel#accept} or
* {@link java.nio.channels.SocketChannel#open}.
*/
public SocketChannel getChannel() {
return null;
}
/**
* @hide internal use only
*/
public FileDescriptor getFileDescriptor$() {
return impl.fd;
}
/**
* Sets performance preferences for connectionTime, latency and bandwidth.
*
* <p>This method does currently nothing.
*
* @param connectionTime
* the value representing the importance of a short connecting
* time.
* @param latency
* the value representing the importance of low latency.
* @param bandwidth
* the value representing the importance of high bandwidth.
*/
public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
// Our socket implementation only provide one protocol: TCP/IP, so
// we do nothing for this method
}
}
| false | true | public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
checkOpenAndCreate(true);
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (isConnected()) {
throw new SocketException("Already connected");
}
if (remoteAddr == null) {
throw new IllegalArgumentException("remoteAddr == null");
}
if (!(remoteAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Remote address not an InetSocketAddress: " +
remoteAddr.getClass());
}
InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
InetAddress addr;
if ((addr = inetAddr.getAddress()) == null) {
throw new UnknownHostException("Host is unresolved: " + inetAddr.getHostName());
}
int port = inetAddr.getPort();
checkDestination(addr, port);
synchronized (connectLock) {
try {
impl.connect(remoteAddr, timeout);
isBound = true;
isConnected = true;
cacheLocalAddress();
} catch (IOException e) {
impl.close();
throw e;
}
}
}
| public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
checkOpenAndCreate(true);
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (isConnected()) {
throw new SocketException("Already connected");
}
if (remoteAddr == null) {
throw new IllegalArgumentException("remoteAddr == null");
}
if (!(remoteAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Remote address not an InetSocketAddress: " +
remoteAddr.getClass());
}
InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
InetAddress addr;
if ((addr = inetAddr.getAddress()) == null) {
throw new UnknownHostException("Host is unresolved: " + inetAddr.getHostName());
}
int port = inetAddr.getPort();
checkDestination(addr, port);
synchronized (connectLock) {
try {
if (!isBound()) {
// socket already created at this point by earlier call or
// checkOpenAndCreate this caused us to lose socket
// options on create
// impl.create(true);
if (!usingSocks()) {
impl.bind(Inet4Address.ANY, 0);
}
isBound = true;
}
impl.connect(remoteAddr, timeout);
isConnected = true;
cacheLocalAddress();
} catch (IOException e) {
impl.close();
throw e;
}
}
}
|
diff --git a/src/main/ed/appserver/AppServer.java b/src/main/ed/appserver/AppServer.java
index aa0686360..8869be4d9 100644
--- a/src/main/ed/appserver/AppServer.java
+++ b/src/main/ed/appserver/AppServer.java
@@ -1,750 +1,759 @@
// AppServer.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 ed.appserver;
import ed.db.JSHook;
import java.io.*;
import java.util.*;
import ed.js.*;
import ed.js.engine.*;
import ed.log.*;
import ed.net.*;
import ed.util.*;
import ed.net.httpserver.*;
import ed.appserver.jxp.*;
/** The server to handle HTTP requests.
*/
public class AppServer implements HttpHandler , MemUtil.MemHaltDisplay {
/** This appserver's default port, 8080 */
private static final int DEFAULT_PORT = 8080;
static boolean D = Boolean.getBoolean( "DEBUG.APP" );
/** Constructs a newly allocated AppServer object for the site <tt>defaultWebRoot</tt>.
* @example If one is running the appserver for the site foo.10gen.com and has the directory structure
*
* gitroot
* |- ed
* | |- master
* | |- 2.1.1
* | |- 2.2.0
* |- foo
* | |-bar1.jxp
* | |-bar2.jxp
*
* And this appserver is started via the commands:
* $ cd gitroot/ed/master
* $ ./runAnt.bash ed.appserver.AppServer ../../foo
*
* Then this appserver's defaultWebRoot will be "../../foo"
*
* @param defaultWebRoot The site that will be run.
* @param root The location in git of sites ("/data/sites").
*/
public AppServer( String defaultWebRoot , String root ){
_contextHolder = new AppContextHolder( defaultWebRoot , root );
}
public void addToServer(){
HttpServer.addGlobalHandler( this );
HttpServer.addGlobalHandler( new HttpMonitor( "appserverstats" ){
public void handle( MonitorRequest mr ){
if ( mr.html() ){
mr.addHeader( "App Server Stats" );
mr.addHeader( "30 second intervals" );
}
List<String> lst = new ArrayList<String>();
lst.addAll( _stats.keySet() );
Collections.sort( lst );
for ( String site : lst ){
_stats.get( site ).displayGraph( mr.getWriter() , _displayOptions );
}
}
}
);
_contextHolder.addToServer();
}
/** Creates a new AppRequest using the given HttpRequest.
* @param request The HTTP request that needs to be processed
* @return The corresponding AppRequest
*/
AppRequest createRequest( HttpRequest request ){
AppContextHolder.Result r = _contextHolder.getContext( request );
if ( r == null || r.context == null )
return null;
return r.context.createRequest( request , r.host , r.uri );
}
/** Checks if the request's uri starts with a "/" and, if so, sets some information about the request.
* Otherwise, <tt>info.fork</tt> is set to true.
* If the URI is "/~~/core/sys", <tt>info.admin</tt> is set to true.
* @param request HTTP request to be processed
* @param info The object to store URI information.
*/
public boolean handles( HttpRequest request , Info info ){
String uri = request.getURI();
if ( ! uri.startsWith( "/" ) )
return false;
info.fork = true;
info.admin = uri.startsWith( "/~~/core/sys/" );
return true;
}
/** Handles an HTTP request and puts the response in the given HTTP response object.
* @param request HTTP request to handle
* @param response to fill in
*/
public boolean handle( HttpRequest request , HttpResponse response ){
try {
_handle( request , response );
}
catch ( Exception e ){
handleError( request , response , e , null );
}
return true;
}
private void _handle( HttpRequest request , HttpResponse response ){
final long start = System.currentTimeMillis();
AppRequest ar = request.getAppRequest();
if ( ar == null ){
ar = createRequest( request );
if ( ar == null ){
handleNoSite( request , response );
return;
}
request.setAppRequest( ar );
}
if ( request.getURI().equals( "/~reset" ) ){
handleReset( ar , request , response );
return;
}
if ( request.getURI().equals( "/~update" ) ){
handleUpdate( ar , request , response );
return;
}
if ( request.getURI().equals( "/~admin" ) ){
handleAdmin( ar , request , response );
return;
}
final AppContext ctxt = ar.getContext();
ar.setResponse( response );
ar.getScope().makeThreadLocal();
ctxt.getLogger().makeThreadLocal();
final UsageTracker usage = ctxt._usage;
final HttpLoadTracker stats = getTracker( ctxt );
{
final int inSize = request.totalSize();
usage.hit( "bytes_in" , inSize );
usage.hit( "requests" , 1 );
}
ctxt.setTLPreferredScope( ar , ar.getScope() );
response.setHeader( "X-ctx" , ctxt._root );
response.setHeader( "X-git" , ctxt.getGitBranch() );
response.setHeader( "X-env" , ctxt._environment );
response.setHeader( "X-ctxhash" , String.valueOf( System.identityHashCode( ctxt ) ) ); // this is kind of tempoary until AppContextHolder is totally vettedx
response.setAppRequest( ar );
ar.turnOnDevFeatures();
final ed.db.DBBase db = ctxt.getDB();
try {
ar.makeThreadLocal();
_requestMonitor.watch( ar );
db.requestStart();
AppSecurityManager.READY = true;
_handle( request , response , ar );
}
finally {
db.requestDone();
ar.unmakeThreadLocal();
Logger.setThreadLocalAppender( null );
final long t = System.currentTimeMillis() - start;
if ( t > 1500 )
ar.getContext().getLogger().getChild( "slow" ).info( request.getURL() + " " + t + "ms" );
ar.done( response );
{
final int outSize = response.totalSize();
usage.hit( "cpu_millis" , t );
usage.hit( "bytes_out" , outSize );
}
stats.hit( request , response );
Scope.clearThreadLocal();
}
}
private void _handle( HttpRequest request , HttpResponse response , AppRequest ar ){
_currentRequests.add( ar );
try {
JSString jsURI = new JSString( ar.getURI() );
if ( ar.getFromInitScope( "allowed" ) != null ){
Object foo = ((JSFunction)ar.getFromInitScope( "allowed" )).call( ar.getScope() , request , response , jsURI );
if ( foo != null ){
if ( response.getResponseCode() == 200 ){
response.setResponseCode( 401 );
response.getJxpWriter().print( "not allowed" );
}
return;
}
}
if ( ar.getURI().equals( "/~f" ) ){
JSFile f = ar.getContext().getJSFile( request.getParameter( "id" ) );
if ( f == null ){
handle404( ar , request , response , null );
return;
}
response.sendFile( f );
return;
}
File f = ar.getFile();
if ( response.getResponseCode() >= 300 )
return;
if ( ar.isStatic() && f.exists() ){
if ( D ) System.out.println( f );
if ( f.isDirectory() ){
response.setResponseCode( 301 );
response.getJxpWriter().print( "listing not allowed\n" );
return;
}
int cacheTime = getCacheTime( ar , jsURI , request , response );
if ( cacheTime >= 0 )
response.setCacheTime( cacheTime );
final String fileString = f.toString();
int idx = fileString.lastIndexOf( "." );
if ( idx > 0 ){
String ext = fileString.substring( idx + 1 );
String type = MimeTypes.get( ext );
if ( type != null )
response.setHeader( "Content-Type" , type );
}
if ( response.getHeader( "Content-Type" ).startsWith( "text/css" ) ){
CSSFixer fixer = new CSSFixer( ar.getURLFixer() );
fixer.fix( new FileInputStream( f ) , response.getJxpWriter() );
}
else {
response.sendFile( f );
}
return;
}
JxpServlet servlet = ar.getServlet( f );
if ( servlet == null ){
handle404( ar , request , response , null );
}
else {
servlet.handle( request , response , ar );
_handleEndOfServlet( request , response , ar );
}
}
+ catch ( StackOverflowError internal ){
+ handleError( request , response , internal , ar.getContext() );
+ }
+ catch ( AssertionError internal ){
+ handleError( request , response , internal , ar.getContext() );
+ }
+ catch ( NoClassDefFoundError internal ){
+ handleError( request , response , internal , ar.getContext() );
+ }
catch ( OutOfMemoryError oom ){
handleOutOfMemoryError( oom , response );
}
catch ( FileNotFoundException fnf ){
handle404( ar , request , response , fnf.getMessage() );
}
catch ( JSException.Quiet q ){
response.setHeader( "X-Exception" , "quiet" );
}
catch ( JSException.Redirect r ){
response.sendRedirectTemporary(r.getTarget());
}
catch ( AppServerError ase ){
ar.getScope().clearToThrow();
handleError( request , response , ase , ar.getContext() );
}
catch ( Exception e ){
handleError( request , response , e , ar.getContext() );
return;
}
finally {
_currentRequests.remove( ar );
}
}
void _handleEndOfServlet( HttpRequest request , HttpResponse response , AppRequest ar ){
if ( response.getHeader( "Content-Type" ).indexOf( "text/html" ) < 0 )
return;
if (request.getHeader(_X10GEN_DEBUG) != null) {
return;
}
// TODO: Eliot, be smarter about this
if ( response.getHeader( "Content-Length" ) != null )
return;
final JSObject user;
{
Object userMaybe = ar.getScope().get( "user" );
if ( userMaybe instanceof JSObject )
user = (JSObject)userMaybe;
else
user = null;
}
final JxpWriter out = response.getJxpWriter();
out.print( "\n<!-- " );
out.print( DNSUtil.getLocalHostString() );
out.print( " " );
out.print( System.currentTimeMillis() - ar._created );
out.print( "ms " );
if ( ar._somethingCompiled )
out.print( " compile " );
out.print( " -->\n" );
if ( ar._profiler != null && showProfilingInfo( request , user ) ){
out.print( "<!--\n" );
out.print( ar._profiler.toString() );
out.print( "\n-->\n" );
}
if ( ar._appenderWriter != null ){
out.print( "<!--\n" );
ar._appenderWriter.flush();
out.print( ar._appenderStream.toString() );
out.print( "\n-->\n" );
}
}
boolean showProfilingInfo( HttpRequest request , JSObject user ){
if ( request.getBoolean( "profile" , false ) )
return true;
if ( user != null &&
( user.get( "permissions" ) instanceof JSArray ) &&
((JSArray)(user.get( "permissions" ) ) ).contains( "admin" ) )
return true;
return false;
}
/** Creates a 404 (page not found) response.
* @param request the HTTP request for the non-existent page
* @param response the HTTP response to send back to the client
* @param extra any extra text to add to the response
*/
void handle404( AppRequest ar , HttpRequest request , HttpResponse response , String extra ){
response.setResponseCode( 404 );
if ( ar.getFromInitScope( "handle404" ) instanceof JSFunction){
JSFunction func = (JSFunction)ar.getFromInitScope( "handle404" );
JxpServlet serv = new JxpServlet( ar.getContext() , func );
serv.handle( request , response , ar );
return;
}
response.getJxpWriter().print( "not found<br>" );
if ( extra != null )
response.getJxpWriter().print( extra + "<BR>" );
response.getJxpWriter().print( request.getRawHeader().replaceAll( "[\r\n]+" , "<br>" ) );
}
/** Kills this appserver if it runs out of memory. Does a garbage collection
* and checks if enough memory was freed. If not, or if the response writer fails,
* the appserver quits with a -3 exit code.
* @param oom The out-of-memory error
* @param response The HTTP response to inform the user of the error
*/
void handleOutOfMemoryError( OutOfMemoryError oom , HttpResponse response ){
// 2 choices here, this request caused all sorts of problems
// or the server is screwed.
MemUtil.checkMemoryAndHalt( "AppServer" , oom , this );
// either this thread was the problem, or whatever
try {
response.setResponseCode( 500 );
JxpWriter writer = response.getJxpWriter();
writer.print( "There was an error handling your request (appsrv 123)<br>" );
writer.print( "ERR 71<br>" );
}
catch ( OutOfMemoryError oom2 ){
// forget it - we're super hosed
Runtime.getRuntime().halt( -3 );
}
}
/** Handles this appserver's errors.
* @param request The request that caused the error
* @param response The response to fill
* @param t The error thrown
* @param ctxt The app context to use for logging
*/
void handleError( HttpRequest request , HttpResponse response , Throwable t , AppContext ctxt ){
if ( t.getCause() instanceof OutOfMemoryError ){
handleOutOfMemoryError( (OutOfMemoryError)t.getCause() , response );
return;
}
if ( ctxt == null )
Logger.getLogger( "appserver.nocontext" ).error( request.getURI() , t );
else
ctxt.getLogger().error( request.getURL() , t );
response.setResponseCode( 500 );
JxpWriter writer = response.getJxpWriter();
if ( t instanceof JSCompileException ){
JSCompileException jce = (JSCompileException)t;
writer.print( "<br><br><hr>" );
writer.print( "<h3>Compile Error</h3>" );
writer.print( "<b>Message:</b> " + jce.getError() + "<BR>" );
writer.print( "<b>File Name:</b> " + jce.getFileName() + "<BR>" );
writer.print( "<b>Line # :</b> " + jce.getLineNumber() + "<BR>" );
writer.print( "<!--\n" );
for ( StackTraceElement element : t.getStackTrace() ){
writer.print( element + "<BR>\n" );
}
writer.print( "-->" );
}
else {
writer.print( "\n<br><br><hr><b>Error</b><br>" );
writer.print("<pre>\n");
StackTraceElement[] parentTrace = new StackTraceElement[0];
while(t != null) {
//message
writer.print( Encoding._escapeHTML(t.toString()) + "\n");
//Compute # frames in common
StackTraceElement[] currentTrace = t.getStackTrace();
int m = currentTrace.length-1, n = parentTrace.length-1;
while (m >= 0 && n >=0 && currentTrace[m].equals(parentTrace[n])) {
m--; n--;
}
int framesInCommon = currentTrace.length - 1 - m;
//print the frames
for(int i=0; i<= m; i++)
writer.print("\tat " + Encoding._escapeHTML(currentTrace[i].toString()) +"\n");
if(framesInCommon != 0)
writer.print("\t... " + framesInCommon + " more\n");
parentTrace = currentTrace;
t = t.getCause();
if(t != null)
writer.print("Caused by: ");
}
writer.print("</pre>\n");
}
}
void handleNoSite( HttpRequest request , HttpResponse response ){
response.setResponseCode( 404 );
response.getJxpWriter().print( "No site for <b>" + request.getHost() + "</b>" );
}
/** Determines how long this response should be cached for.
result is to set Cache-Time and Expires
* @param ar The app request which contains the staticCacheTime function
* @param jsURI The URI to find in the cache
* @param request The HTTP request to process
* @param response The HTTP response to generate
* @return The time, in seconds
*/
int getCacheTime( AppRequest ar , JSString jsURI , HttpRequest request , HttpResponse response ){
if ( ar.getFromInitScope( "staticCacheTime" ) != null ){
JSFunction f = (JSFunction)ar.getFromInitScope( "staticCacheTime" );
if ( f != null ){
Object ret = f.call( ar.getScope() , jsURI , request , response );
if ( ret instanceof Number )
return ((Number)ret).intValue();
}
}
if ( ar.isStatic() && request.getParameter( "lm" ) != null && request.getParameter( "ctxt" ) != null )
return 3600;
return -1;
}
/** This appserver's priority for the HTTP request handler.
* @return 10000
*/
public double priority(){
return 10000;
}
/** Resets the app content.
* @param ar Used to find the context to reset and logger
* @param request
* @param response Set to inform the user what happens
*/
void handleReset( AppRequest ar , HttpRequest request , HttpResponse response ){
response.setHeader( "Content-Type" , "text/plain" );
JxpWriter out = response.getJxpWriter();
out.print( "so, you want to reset?\n" );
if ( _administrativeAllowed( request ) ){
ar.getContext().getLogger().info("creating new context" );
ar.getContext().updateCode();
AppContext newContext = ar.getContext().newCopy();
newContext.getScope();
newContext.getFileSafe( "index.jxp" );
_contextHolder.replace( ar.getContext() , newContext );
ar.getContext().getLogger().info("done creating new context. resetting" );
ar.getContext().reset();
out.print( "you did it!\n" );
out.print( "old hash:" + System.identityHashCode( ar.getContext() ) + "\n" );
out.print( "new hash:" + System.identityHashCode( newContext ) + "\n" );
}
else {
ar.getContext().getLogger().error("Failed attempted context reset via /~reset from " + request.getRemoteIP());
out.print( "you suck!" );
response.setResponseCode(403);
}
}
void handleUpdate( AppRequest ar , HttpRequest request , HttpResponse response ){
response.setHeader( "Content-Type" , "text/plain" );
JxpWriter out = response.getJxpWriter();
out.print( "you are going to update\n" );
if ( _administrativeAllowed( request ) ){
out.print( "you did it!\n" );
ar.getContext().getLogger().info("About to update context via /~update");
try {
String branch = ar.getContext().updateCode();
if ( branch == null )
out.print( "couldn't update." );
else
out.print( "updated to [" + branch + "]" );
}
catch ( Exception e ){
out.print( "Fail : " + e );
}
out.print( "\n" );
}
else {
ar.getContext().getLogger().error("Failed attempted context reset via /~update from " + request.getRemoteIP());
out.print( "you suck!" );
response.setResponseCode(403);
}
}
void handleAdmin( AppRequest ar , HttpRequest request , HttpResponse response ){
JxpWriter out = response.getJxpWriter();
if ( ! _administrativeAllowed( request ) ){
out.print( "you are not allowed here" );
return;
}
out.print( "<html><head>" );
out.print( "<title>admin | " + request.getHost() + "</title>" );
out.print( "</head><body>" );
out.print( "<h1>Quick Admin</h1>" );
out.print( "<table border='1'>" );
out.print( "<tr><th>Created</th><td>" + ar.getContext()._created + "</td></tr>" );
out.print( "<tr><th>Memory (kb)</th><td>" + ( ar.getContext().approxSize() / 1024 ) + "</td></tr>" );
out.print( "</table>" );
out.print( "<h3>Stats</h3>" );
getTracker( ar.getContext() ).displayGraph( out , _displayOptions );
out.print( "<hr>" );
out.print( "<a href='/~update'>Update Code</a> | " );
out.print( "<a href='/~reset'>Reset Site (include code update)</a> | " );
out.print( "</body></html>" );
}
boolean _administrativeAllowed( HttpRequest request ){
return
request.getPhysicalRemoteAddr().equals( "127.0.0.1" ) &&
request.getHeader( "X-Cluster-Cluster-Ip" ) == null;
}
HttpLoadTracker getTracker( final AppContext ctxt ){
final String site = ctxt._name;
final String env = ctxt._environment;
final String name = site + ":" + ( env == null ? "NONE" : env );
HttpLoadTracker t = _stats.get( name );
if ( t != null )
return t;
synchronized ( _stats ){
t = _stats.get( name );
if ( t == null ){
t = new HttpLoadTracker( name , 30 , 30 );
_stats.put( name , t );
}
}
return t;
}
public void printMemInfo(){
System.out.println( "AppServer.printMemInfo" );
for ( AppRequest ar : _currentRequests ){
System.err.print( "\t" );
System.err.print( ar._host );
System.err.print( "\t" );
System.err.print( ar._uri );
System.err.println();
}
}
private final AppContextHolder _contextHolder;
private final Map<String,HttpLoadTracker> _stats = Collections.synchronizedMap( new StringMap<HttpLoadTracker>() );
private final RequestMonitor _requestMonitor = RequestMonitor.getInstance();
private final HttpLoadTracker.GraphOptions _displayOptions = new HttpLoadTracker.GraphOptions( 400 , 100 , true , true , true );
private final IdentitySet<AppRequest> _currentRequests = new IdentitySet<AppRequest>();
protected final static String _X10GEN_DEBUG = "X-10gen-Debug"; // private header - if set, user/profile/timing info won't be appended to response
// ---------
/** @unexpose */
public static void main( String args[] )
throws Exception {
String webRoot = null;
String sitesRoot = "/data/sites";
int portNum = DEFAULT_PORT;
boolean secure = false;
/*
* --port portnum [root]
*/
int aLength = 0;
for ( int i=0; i<args.length; i++ ){
if ( args[i] != null && args[i].trim().length() > 0 )
aLength = i +1;
}
for (int i = 0; i < aLength; i++) {
if ("--port".equals(args[i])) {
portNum = Integer.valueOf(args[++i]);
}
else if ("--root".equals(args[i])) {
portNum = Integer.valueOf(args[++i]);
}
else if ("--serverroot".equals(args[i])) {
JSHook.whereIsEd = args[++i];
}
else if ( "--sitesRoot".equals( args[i] ) ){
sitesRoot = args[++i];
}
else if ( "--secure" .equals( args[i] ) ){
secure = true;
}
else {
if (i != aLength - 1) {
System.out.println("error - unknown param " + args[i]);
System.exit(1);
}
else {
webRoot = args[i];
}
}
}
System.out.println("==================================");
System.out.println(" 10gen AppServer vX");
System.out.println(" listen port = " + portNum);
System.out.println(" server root = " + JSHook.whereIsEd);
System.out.println(" webRoot = " + webRoot);
System.out.println(" sitesRoot = " + sitesRoot);
System.out.println(" listen port = " + portNum);
System.out.println("==================================");
AppServer as = new AppServer( webRoot , sitesRoot );
as.addToServer();
HttpServer hs = new HttpServer(portNum);
if ( secure )
System.setSecurityManager( new AppSecurityManager() );
hs.start();
hs.join();
}
}
| true | true | private void _handle( HttpRequest request , HttpResponse response , AppRequest ar ){
_currentRequests.add( ar );
try {
JSString jsURI = new JSString( ar.getURI() );
if ( ar.getFromInitScope( "allowed" ) != null ){
Object foo = ((JSFunction)ar.getFromInitScope( "allowed" )).call( ar.getScope() , request , response , jsURI );
if ( foo != null ){
if ( response.getResponseCode() == 200 ){
response.setResponseCode( 401 );
response.getJxpWriter().print( "not allowed" );
}
return;
}
}
if ( ar.getURI().equals( "/~f" ) ){
JSFile f = ar.getContext().getJSFile( request.getParameter( "id" ) );
if ( f == null ){
handle404( ar , request , response , null );
return;
}
response.sendFile( f );
return;
}
File f = ar.getFile();
if ( response.getResponseCode() >= 300 )
return;
if ( ar.isStatic() && f.exists() ){
if ( D ) System.out.println( f );
if ( f.isDirectory() ){
response.setResponseCode( 301 );
response.getJxpWriter().print( "listing not allowed\n" );
return;
}
int cacheTime = getCacheTime( ar , jsURI , request , response );
if ( cacheTime >= 0 )
response.setCacheTime( cacheTime );
final String fileString = f.toString();
int idx = fileString.lastIndexOf( "." );
if ( idx > 0 ){
String ext = fileString.substring( idx + 1 );
String type = MimeTypes.get( ext );
if ( type != null )
response.setHeader( "Content-Type" , type );
}
if ( response.getHeader( "Content-Type" ).startsWith( "text/css" ) ){
CSSFixer fixer = new CSSFixer( ar.getURLFixer() );
fixer.fix( new FileInputStream( f ) , response.getJxpWriter() );
}
else {
response.sendFile( f );
}
return;
}
JxpServlet servlet = ar.getServlet( f );
if ( servlet == null ){
handle404( ar , request , response , null );
}
else {
servlet.handle( request , response , ar );
_handleEndOfServlet( request , response , ar );
}
}
catch ( OutOfMemoryError oom ){
handleOutOfMemoryError( oom , response );
}
catch ( FileNotFoundException fnf ){
handle404( ar , request , response , fnf.getMessage() );
}
catch ( JSException.Quiet q ){
response.setHeader( "X-Exception" , "quiet" );
}
catch ( JSException.Redirect r ){
response.sendRedirectTemporary(r.getTarget());
}
catch ( AppServerError ase ){
ar.getScope().clearToThrow();
handleError( request , response , ase , ar.getContext() );
}
catch ( Exception e ){
handleError( request , response , e , ar.getContext() );
return;
}
finally {
_currentRequests.remove( ar );
}
}
| private void _handle( HttpRequest request , HttpResponse response , AppRequest ar ){
_currentRequests.add( ar );
try {
JSString jsURI = new JSString( ar.getURI() );
if ( ar.getFromInitScope( "allowed" ) != null ){
Object foo = ((JSFunction)ar.getFromInitScope( "allowed" )).call( ar.getScope() , request , response , jsURI );
if ( foo != null ){
if ( response.getResponseCode() == 200 ){
response.setResponseCode( 401 );
response.getJxpWriter().print( "not allowed" );
}
return;
}
}
if ( ar.getURI().equals( "/~f" ) ){
JSFile f = ar.getContext().getJSFile( request.getParameter( "id" ) );
if ( f == null ){
handle404( ar , request , response , null );
return;
}
response.sendFile( f );
return;
}
File f = ar.getFile();
if ( response.getResponseCode() >= 300 )
return;
if ( ar.isStatic() && f.exists() ){
if ( D ) System.out.println( f );
if ( f.isDirectory() ){
response.setResponseCode( 301 );
response.getJxpWriter().print( "listing not allowed\n" );
return;
}
int cacheTime = getCacheTime( ar , jsURI , request , response );
if ( cacheTime >= 0 )
response.setCacheTime( cacheTime );
final String fileString = f.toString();
int idx = fileString.lastIndexOf( "." );
if ( idx > 0 ){
String ext = fileString.substring( idx + 1 );
String type = MimeTypes.get( ext );
if ( type != null )
response.setHeader( "Content-Type" , type );
}
if ( response.getHeader( "Content-Type" ).startsWith( "text/css" ) ){
CSSFixer fixer = new CSSFixer( ar.getURLFixer() );
fixer.fix( new FileInputStream( f ) , response.getJxpWriter() );
}
else {
response.sendFile( f );
}
return;
}
JxpServlet servlet = ar.getServlet( f );
if ( servlet == null ){
handle404( ar , request , response , null );
}
else {
servlet.handle( request , response , ar );
_handleEndOfServlet( request , response , ar );
}
}
catch ( StackOverflowError internal ){
handleError( request , response , internal , ar.getContext() );
}
catch ( AssertionError internal ){
handleError( request , response , internal , ar.getContext() );
}
catch ( NoClassDefFoundError internal ){
handleError( request , response , internal , ar.getContext() );
}
catch ( OutOfMemoryError oom ){
handleOutOfMemoryError( oom , response );
}
catch ( FileNotFoundException fnf ){
handle404( ar , request , response , fnf.getMessage() );
}
catch ( JSException.Quiet q ){
response.setHeader( "X-Exception" , "quiet" );
}
catch ( JSException.Redirect r ){
response.sendRedirectTemporary(r.getTarget());
}
catch ( AppServerError ase ){
ar.getScope().clearToThrow();
handleError( request , response , ase , ar.getContext() );
}
catch ( Exception e ){
handleError( request , response , e , ar.getContext() );
return;
}
finally {
_currentRequests.remove( ar );
}
}
|
diff --git a/scc/scc-it/src/main/java/de/atomfrede/android/scc/test/HelloAndroidActivityTest.java b/scc/scc-it/src/main/java/de/atomfrede/android/scc/test/HelloAndroidActivityTest.java
index fd41058..3212c07 100644
--- a/scc/scc-it/src/main/java/de/atomfrede/android/scc/test/HelloAndroidActivityTest.java
+++ b/scc/scc-it/src/main/java/de/atomfrede/android/scc/test/HelloAndroidActivityTest.java
@@ -1,17 +1,17 @@
package de.atomfrede.android.scc.test;
import android.test.ActivityInstrumentationTestCase2;
import de.atomfrede.android.scc.*;
public class HelloAndroidActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
public HelloAndroidActivityTest() {
super(MainActivity.class);
}
public void testActivity() {
- MainActivity activity = getActivity();
- assertNotNull(activity);
+// MainActivity activity = getActivity();
+// assertNotNull(activity);
}
}
| true | true | public void testActivity() {
MainActivity activity = getActivity();
assertNotNull(activity);
}
| public void testActivity() {
// MainActivity activity = getActivity();
// assertNotNull(activity);
}
|
diff --git a/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java b/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java
index 07c93724..9175cc28 100644
--- a/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java
+++ b/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java
@@ -1,433 +1,431 @@
package co.uk.flansmods.common.guns;
import java.util.List;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import co.uk.flansmods.common.FlansMod;
import co.uk.flansmods.common.InfoType;
import co.uk.flansmods.common.RotatedAxes;
import co.uk.flansmods.common.driveables.EntityDriveable;
import co.uk.flansmods.common.teams.TeamsManager;
import co.uk.flansmods.common.vector.Vector3f;
import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
public class EntityGrenade extends Entity implements IEntityAdditionalSpawnData
{
public GrenadeType type;
public EntityLivingBase thrower;
/** Yeah, I want my grenades to have fancy physics */
public RotatedAxes axes = new RotatedAxes();
public Vector3f angularVelocity = new Vector3f(0F, 0F, 0F);
public float prevRotationRoll = 0F;
/** Set to the smoke amount when the grenade detonates and decremented every tick after that */
public int smokeTime = 0;
/** Set to true when smoke grenade detonates */
public boolean smoking = false;
/** Set to true when a sticky grenade sticks. Impedes further movement */
public boolean stuck = false;
/** Stores the position of the block this grenade is stuck to. Used to determine when to unstick */
public int stuckToX, stuckToY, stuckToZ;
/** Stop repeat detonations */
public boolean detonated = false;
public EntityGrenade(World w)
{
super(w);
}
public EntityGrenade(World w, GrenadeType g, EntityLivingBase t)
{
this(w);
setPosition(t.posX, t.posY + t.getEyeHeight(), t.posZ);
type = g;
thrower = t;
setSize(g.hitBoxSize, g.hitBoxSize);
//Set the grenade to be facing the way the player is looking
axes.setAngles(t.rotationYaw + 90F, g.spinWhenThrown ? t.rotationPitch : 0F, 0F);
rotationYaw = prevRotationYaw = g.spinWhenThrown ? t.rotationYaw + 90F : 0F;
rotationPitch = prevRotationPitch = t.rotationPitch;
//Give the grenade velocity in the direction the player is looking
float speed = 0.5F * type.throwSpeed;
motionX = axes.getXAxis().x * speed;
motionY = axes.getXAxis().y * speed;
motionZ = axes.getXAxis().z * speed;
if(type.spinWhenThrown)
angularVelocity = new Vector3f(0F, 0F, 10F);
}
@Override
public void onUpdate()
{
super.onUpdate();
//Quiet despawning
if(type.despawnTime > 0 && ticksExisted > type.despawnTime)
{
detonated = true;
setDead();
return;
}
//Visuals
if(worldObj.isRemote)
{
if(type.trailParticles)
worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F);
//Smoke
if(!smoking)
{
for(int i = 0; i < 20; i++)
worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F);
smokeTime--;
if(smokeTime == 0)
setDead();
}
}
//Detonation conditions
if(!worldObj.isRemote)
{
if(ticksExisted > type.fuse && type.fuse > 0)
detonate();
//If this grenade has a proximity trigger, check for living entities within it's range
if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0)
{
float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius));
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10)
continue;
if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger)
{
//If we are in a gametype and both thrower and triggerer are playing, check for friendly fire
if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer)
{
if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type)))
continue;
}
detonate();
break;
}
if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger)
{
detonate();
break;
}
}
}
}
//If the block we were stuck to is gone, unstick
if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ))
stuck = false;
//Physics and motion (Don't move if stuck)
if(!stuck)
{
prevRotationYaw = axes.getYaw();
prevRotationPitch = axes.getPitch();
prevRotationRoll = axes.getRoll();
if(angularVelocity.lengthSquared() > 0.00000001F)
axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null));
Vector3f posVec = new Vector3f(posX, posY, posZ);
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
Vector3f nextPosVec = Vector3f.add(posVec, motVec, null);
//Raytrace the motion of this grenade
MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3());
//If we hit block
if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE)
{
//Get the blockID and block material
int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ);
Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ);
//If this grenade detonates on impact, do so
if(type.detonateOnImpact)
detonate();
//If we hit glass and can break it, do so
- else if(type.breaksGlass && mat == Material.glass)
+ else if(type.breaksGlass && mat == Material.glass && FlansMod.canBreakGlass)
{
- if(FlansMod.canBreakGlass)
- {
- worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ);
- FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID);
- }
+ worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ);
+ FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID);
}
//If this grenade does not penetrate blocks, hit the block instead
//The grenade cannot bounce if it detonated on impact, so hence the "else" condition
else if(!type.penetratesBlocks)
{
Vector3f hitVec = new Vector3f(hit.hitVec);
//Motion of the grenade pre-hit
Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null);
//Motion of the grenade post-hit
Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null);
//Reflect postHitMotVec based on side hit
int sideHit = hit.sideHit;
switch(sideHit)
{
case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break;
case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break;
case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break;
}
//Calculate the time interval spent post reflection
float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length();
//Scale the post hit motion by the bounciness of the grenade
postHitMotVec.scale(type.bounciness / 2);
//Move the grenade along the new path including reflection
posX += preHitMotVec.x + postHitMotVec.x;
posY += preHitMotVec.y + postHitMotVec.y;
posZ += preHitMotVec.z + postHitMotVec.z;
//Set the motion
motionX = postHitMotVec.x / lambda;
motionY = postHitMotVec.y / lambda;
motionZ = postHitMotVec.z / lambda;
//Reset the motion vector
motVec = new Vector3f(motionX, motionY, motionZ);
//Give it a random spin
float randomSpinner = 90F;
Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity);
//Slow the spin based on the motion
angularVelocity.scale(motVec.lengthSquared());
//Play the bounce sound
if(motVec.lengthSquared() > 0.01D)
playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
//If this grenade is sticky, stick it to the block
if(type.sticky)
{
//Move the grenade to the point of contact
posX = hitVec.x;
posY = hitVec.y;
posZ = hitVec.z;
//Stop all motion of the grenade
motionX = motionY = motionZ = 0;
angularVelocity.set(0F, 0F, 0F);
float yaw = axes.getYaw();
switch(hit.sideHit)
{
case 0 : axes.setAngles(yaw, 180F, 0F); break;
case 1 : axes.setAngles(yaw, 0F, 0F); break;
case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
}
//Set the stuck flag on
stuck = true;
stuckToX = hit.blockX;
stuckToY = hit.blockY;
stuckToZ = hit.blockZ;
}
}
}
//We didn't hit a block, continue as normal
else
{
posX += motionX;
posY += motionY;
posZ += motionZ;
}
//Update the grenade position
setPosition(posX, posY, posZ);
}
//If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so
//(Don't attack entities when stuck to stuff)
if(type.hitEntityDamage > 0 && !stuck)
{
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox);
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D)
continue;
if(obj instanceof EntityLivingBase)
{
+ System.out.println("Damage: " + (type.hitEntityDamage * motVec.lengthSquared() * 3));
((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3);
}
}
}
//Apply gravity
motionY -= 9.81D / 400D * type.fallSpeed;
}
@Override
public boolean attackEntityFrom(DamageSource source, float f)
{
if(type.detonateWhenShot)
detonate();
return type.detonateWhenShot;
}
public void detonate()
{
//Do not detonate before grenade is primed
if(ticksExisted < type.primeDelay)
return;
//Stop repeat detonations
if(detonated)
return;
detonated = true;
//Play detonate sound
playSound(type.detonateSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
//Explode
if(!worldObj.isRemote && type.explosionRadius > 0.1F)
{
if((thrower instanceof EntityPlayer))
new FlansModExplosion(worldObj, this, (EntityPlayer)thrower, type, posX, posY, posZ, type.explosionRadius, FlansMod.explosions && type.explosionBreaksBlocks);
else worldObj.createExplosion(this, posX, posY, posZ, type.explosionRadius, FlansMod.explosions && type.explosionBreaksBlocks);
}
//Make fire
if(type.fireRadius > 0.1F)
{
for(float i = -type.fireRadius; i < type.fireRadius; i++)
{
for(float j = -type.fireRadius; j < type.fireRadius; j++)
{
for(float k = -type.fireRadius; k < type.fireRadius; k++)
{
int x = MathHelper.floor_float(i);
int y = MathHelper.floor_float(j);
int z = MathHelper.floor_float(k);
if(worldObj.getBlockId(x, y, z) == 0)
{
worldObj.setBlock(x, y, z, Block.fire.blockID);
}
}
}
}
}
//Make explosion particles
for(int i = 0; i < type.explodeParticles; i++)
{
worldObj.spawnParticle(type.explodeParticleType, posX, posY, posZ, rand.nextGaussian(), rand.nextGaussian(), rand.nextGaussian());
}
//Drop item upon detonation, after explosions and whatnot
if(!worldObj.isRemote && type.dropItemOnDetonate != null)
{
String itemName = type.dropItemOnDetonate;
int damage = 0;
if (itemName.contains("."))
{
damage = Integer.parseInt(itemName.split("\\.")[1]);
itemName = itemName.split("\\.")[0];
}
ItemStack dropStack = InfoType.getRecipeElement(itemName, damage);
entityDropItem(dropStack, 1.0F);
}
//Start smoke counter
if(type.smokeTime > 0)
{
smoking = true;
smokeTime = type.smokeTime;
}
else
{
setDead();
}
}
@Override
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int i)
{
}
private DamageSource getGrenadeDamage()
{
if(thrower instanceof EntityPlayer)
return (new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type)).setProjectile();
else return (new EntityDamageSourceIndirect(type.shortName, this, thrower)).setProjectile();
}
@Override
protected void entityInit()
{
}
@Override
protected void readEntityFromNBT(NBTTagCompound tags)
{
type = GrenadeType.getGrenade(tags.getString("Type"));
thrower = worldObj.getPlayerEntityByName(tags.getString("Thrower"));
rotationYaw = tags.getFloat("RotationYaw");
rotationPitch = tags.getFloat("RotationPitch");
axes.setAngles(rotationYaw, rotationPitch, 0F);
}
@Override
protected void writeEntityToNBT(NBTTagCompound tags)
{
tags.setString("Type", type.shortName);
if(thrower != null)
tags.setString("Thrower", thrower.getEntityName());
tags.setFloat("RotationYaw", axes.getYaw());
tags.setFloat("RotationPitch", axes.getPitch());
}
@Override
public void writeSpawnData(ByteArrayDataOutput data)
{
data.writeUTF(type.shortName);
data.writeInt(thrower == null ? 0 : thrower.entityId);
data.writeFloat(axes.getYaw());
data.writeFloat(axes.getPitch());
}
@Override
public void readSpawnData(ByteArrayDataInput data)
{
type = GrenadeType.getGrenade(data.readUTF());
thrower = (EntityLivingBase)worldObj.getEntityByID(data.readInt());
setRotation(data.readFloat(), data.readFloat());
prevRotationYaw = rotationYaw;
prevRotationPitch = rotationPitch;
axes.setAngles(rotationYaw, rotationPitch, 0F);
if(type.spinWhenThrown)
angularVelocity = new Vector3f(0F, 0F, 10F);
}
}
| false | true | public void onUpdate()
{
super.onUpdate();
//Quiet despawning
if(type.despawnTime > 0 && ticksExisted > type.despawnTime)
{
detonated = true;
setDead();
return;
}
//Visuals
if(worldObj.isRemote)
{
if(type.trailParticles)
worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F);
//Smoke
if(!smoking)
{
for(int i = 0; i < 20; i++)
worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F);
smokeTime--;
if(smokeTime == 0)
setDead();
}
}
//Detonation conditions
if(!worldObj.isRemote)
{
if(ticksExisted > type.fuse && type.fuse > 0)
detonate();
//If this grenade has a proximity trigger, check for living entities within it's range
if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0)
{
float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius));
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10)
continue;
if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger)
{
//If we are in a gametype and both thrower and triggerer are playing, check for friendly fire
if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer)
{
if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type)))
continue;
}
detonate();
break;
}
if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger)
{
detonate();
break;
}
}
}
}
//If the block we were stuck to is gone, unstick
if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ))
stuck = false;
//Physics and motion (Don't move if stuck)
if(!stuck)
{
prevRotationYaw = axes.getYaw();
prevRotationPitch = axes.getPitch();
prevRotationRoll = axes.getRoll();
if(angularVelocity.lengthSquared() > 0.00000001F)
axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null));
Vector3f posVec = new Vector3f(posX, posY, posZ);
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
Vector3f nextPosVec = Vector3f.add(posVec, motVec, null);
//Raytrace the motion of this grenade
MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3());
//If we hit block
if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE)
{
//Get the blockID and block material
int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ);
Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ);
//If this grenade detonates on impact, do so
if(type.detonateOnImpact)
detonate();
//If we hit glass and can break it, do so
else if(type.breaksGlass && mat == Material.glass)
{
if(FlansMod.canBreakGlass)
{
worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ);
FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID);
}
}
//If this grenade does not penetrate blocks, hit the block instead
//The grenade cannot bounce if it detonated on impact, so hence the "else" condition
else if(!type.penetratesBlocks)
{
Vector3f hitVec = new Vector3f(hit.hitVec);
//Motion of the grenade pre-hit
Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null);
//Motion of the grenade post-hit
Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null);
//Reflect postHitMotVec based on side hit
int sideHit = hit.sideHit;
switch(sideHit)
{
case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break;
case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break;
case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break;
}
//Calculate the time interval spent post reflection
float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length();
//Scale the post hit motion by the bounciness of the grenade
postHitMotVec.scale(type.bounciness / 2);
//Move the grenade along the new path including reflection
posX += preHitMotVec.x + postHitMotVec.x;
posY += preHitMotVec.y + postHitMotVec.y;
posZ += preHitMotVec.z + postHitMotVec.z;
//Set the motion
motionX = postHitMotVec.x / lambda;
motionY = postHitMotVec.y / lambda;
motionZ = postHitMotVec.z / lambda;
//Reset the motion vector
motVec = new Vector3f(motionX, motionY, motionZ);
//Give it a random spin
float randomSpinner = 90F;
Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity);
//Slow the spin based on the motion
angularVelocity.scale(motVec.lengthSquared());
//Play the bounce sound
if(motVec.lengthSquared() > 0.01D)
playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
//If this grenade is sticky, stick it to the block
if(type.sticky)
{
//Move the grenade to the point of contact
posX = hitVec.x;
posY = hitVec.y;
posZ = hitVec.z;
//Stop all motion of the grenade
motionX = motionY = motionZ = 0;
angularVelocity.set(0F, 0F, 0F);
float yaw = axes.getYaw();
switch(hit.sideHit)
{
case 0 : axes.setAngles(yaw, 180F, 0F); break;
case 1 : axes.setAngles(yaw, 0F, 0F); break;
case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
}
//Set the stuck flag on
stuck = true;
stuckToX = hit.blockX;
stuckToY = hit.blockY;
stuckToZ = hit.blockZ;
}
}
}
//We didn't hit a block, continue as normal
else
{
posX += motionX;
posY += motionY;
posZ += motionZ;
}
//Update the grenade position
setPosition(posX, posY, posZ);
}
//If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so
//(Don't attack entities when stuck to stuff)
if(type.hitEntityDamage > 0 && !stuck)
{
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox);
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D)
continue;
if(obj instanceof EntityLivingBase)
{
((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3);
}
}
}
//Apply gravity
motionY -= 9.81D / 400D * type.fallSpeed;
}
| public void onUpdate()
{
super.onUpdate();
//Quiet despawning
if(type.despawnTime > 0 && ticksExisted > type.despawnTime)
{
detonated = true;
setDead();
return;
}
//Visuals
if(worldObj.isRemote)
{
if(type.trailParticles)
worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F);
//Smoke
if(!smoking)
{
for(int i = 0; i < 20; i++)
worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F);
smokeTime--;
if(smokeTime == 0)
setDead();
}
}
//Detonation conditions
if(!worldObj.isRemote)
{
if(ticksExisted > type.fuse && type.fuse > 0)
detonate();
//If this grenade has a proximity trigger, check for living entities within it's range
if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0)
{
float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius));
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10)
continue;
if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger)
{
//If we are in a gametype and both thrower and triggerer are playing, check for friendly fire
if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer)
{
if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type)))
continue;
}
detonate();
break;
}
if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger)
{
detonate();
break;
}
}
}
}
//If the block we were stuck to is gone, unstick
if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ))
stuck = false;
//Physics and motion (Don't move if stuck)
if(!stuck)
{
prevRotationYaw = axes.getYaw();
prevRotationPitch = axes.getPitch();
prevRotationRoll = axes.getRoll();
if(angularVelocity.lengthSquared() > 0.00000001F)
axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null));
Vector3f posVec = new Vector3f(posX, posY, posZ);
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
Vector3f nextPosVec = Vector3f.add(posVec, motVec, null);
//Raytrace the motion of this grenade
MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3());
//If we hit block
if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE)
{
//Get the blockID and block material
int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ);
Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ);
//If this grenade detonates on impact, do so
if(type.detonateOnImpact)
detonate();
//If we hit glass and can break it, do so
else if(type.breaksGlass && mat == Material.glass && FlansMod.canBreakGlass)
{
worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ);
FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID);
}
//If this grenade does not penetrate blocks, hit the block instead
//The grenade cannot bounce if it detonated on impact, so hence the "else" condition
else if(!type.penetratesBlocks)
{
Vector3f hitVec = new Vector3f(hit.hitVec);
//Motion of the grenade pre-hit
Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null);
//Motion of the grenade post-hit
Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null);
//Reflect postHitMotVec based on side hit
int sideHit = hit.sideHit;
switch(sideHit)
{
case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break;
case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break;
case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break;
}
//Calculate the time interval spent post reflection
float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length();
//Scale the post hit motion by the bounciness of the grenade
postHitMotVec.scale(type.bounciness / 2);
//Move the grenade along the new path including reflection
posX += preHitMotVec.x + postHitMotVec.x;
posY += preHitMotVec.y + postHitMotVec.y;
posZ += preHitMotVec.z + postHitMotVec.z;
//Set the motion
motionX = postHitMotVec.x / lambda;
motionY = postHitMotVec.y / lambda;
motionZ = postHitMotVec.z / lambda;
//Reset the motion vector
motVec = new Vector3f(motionX, motionY, motionZ);
//Give it a random spin
float randomSpinner = 90F;
Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity);
//Slow the spin based on the motion
angularVelocity.scale(motVec.lengthSquared());
//Play the bounce sound
if(motVec.lengthSquared() > 0.01D)
playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
//If this grenade is sticky, stick it to the block
if(type.sticky)
{
//Move the grenade to the point of contact
posX = hitVec.x;
posY = hitVec.y;
posZ = hitVec.z;
//Stop all motion of the grenade
motionX = motionY = motionZ = 0;
angularVelocity.set(0F, 0F, 0F);
float yaw = axes.getYaw();
switch(hit.sideHit)
{
case 0 : axes.setAngles(yaw, 180F, 0F); break;
case 1 : axes.setAngles(yaw, 0F, 0F); break;
case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break;
}
//Set the stuck flag on
stuck = true;
stuckToX = hit.blockX;
stuckToY = hit.blockY;
stuckToZ = hit.blockZ;
}
}
}
//We didn't hit a block, continue as normal
else
{
posX += motionX;
posY += motionY;
posZ += motionZ;
}
//Update the grenade position
setPosition(posX, posY, posZ);
}
//If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so
//(Don't attack entities when stuck to stuff)
if(type.hitEntityDamage > 0 && !stuck)
{
Vector3f motVec = new Vector3f(motionX, motionY, motionZ);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox);
for(Object obj : list)
{
if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D)
continue;
if(obj instanceof EntityLivingBase)
{
System.out.println("Damage: " + (type.hitEntityDamage * motVec.lengthSquared() * 3));
((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3);
}
}
}
//Apply gravity
motionY -= 9.81D / 400D * type.fallSpeed;
}
|
diff --git a/src/web/src/main/java/vdi/webinterface/servlet/Screenshot.java b/src/web/src/main/java/vdi/webinterface/servlet/Screenshot.java
index d619077..78df361 100644
--- a/src/web/src/main/java/vdi/webinterface/servlet/Screenshot.java
+++ b/src/web/src/main/java/vdi/webinterface/servlet/Screenshot.java
@@ -1,70 +1,70 @@
package vdi.webinterface.servlet;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.resteasy.client.ProxyFactory;
import vdi.commons.common.Configuration;
import vdi.commons.common.RESTEasyClientExecutor;
import vdi.commons.web.rest.interfaces.ManagementVMService;
/**
* Servlet implementation class Home.
*/
public class Screenshot extends HttpServlet {
private static final long serialVersionUID = 1L;
ManagementVMService mangementVMService;
/**
* @see HttpServlet#HttpServlet()
*/
public Screenshot() {
super();
mangementVMService = ProxyFactory.create(ManagementVMService.class,
Configuration.getProperty("managementserver.uri") + "/vm/",
RESTEasyClientExecutor.get());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
/*
* TODO: Use tudUserUniqueID from SSO
*/
String userId = "123456";
// Get request parameters
- String id = request.getParameter("machine");
+ long id = Long.valueOf(request.getParameter("machine"));
int width = Integer.valueOf(request.getParameter("width"));
int height = Integer.valueOf(request.getParameter("height"));
byte[] screenshot = mangementVMService.getMachineScreenshot(userId, id, width, height);
if (screenshot == null) {
// Image not found
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Set content type
response.setContentType("image/png");
OutputStream output = response.getOutputStream();
// Copy the image to the output stream
output.write(screenshot);
output.close();
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
/*
* TODO: Use tudUserUniqueID from SSO
*/
String userId = "123456";
// Get request parameters
String id = request.getParameter("machine");
int width = Integer.valueOf(request.getParameter("width"));
int height = Integer.valueOf(request.getParameter("height"));
byte[] screenshot = mangementVMService.getMachineScreenshot(userId, id, width, height);
if (screenshot == null) {
// Image not found
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Set content type
response.setContentType("image/png");
OutputStream output = response.getOutputStream();
// Copy the image to the output stream
output.write(screenshot);
output.close();
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
/*
* TODO: Use tudUserUniqueID from SSO
*/
String userId = "123456";
// Get request parameters
long id = Long.valueOf(request.getParameter("machine"));
int width = Integer.valueOf(request.getParameter("width"));
int height = Integer.valueOf(request.getParameter("height"));
byte[] screenshot = mangementVMService.getMachineScreenshot(userId, id, width, height);
if (screenshot == null) {
// Image not found
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Set content type
response.setContentType("image/png");
OutputStream output = response.getOutputStream();
// Copy the image to the output stream
output.write(screenshot);
output.close();
}
|
diff --git a/java/tools/src/com/jopdesign/build/JopMethodInfo.java b/java/tools/src/com/jopdesign/build/JopMethodInfo.java
index e93d7ebb..c4160e3c 100644
--- a/java/tools/src/com/jopdesign/build/JopMethodInfo.java
+++ b/java/tools/src/com/jopdesign/build/JopMethodInfo.java
@@ -1,230 +1,230 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2004,2005, Flavius Gruian
Copyright (C) 2005-2008, Martin Schoeberl ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jopdesign.build;
import java.util.*;
import java.io.PrintWriter;
import java.io.Serializable;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.Type;
/**
* @author Flavius, Martin
*
*/
public class JopMethodInfo extends MethodInfo implements Serializable {
private static final long serialVersionUID = 1L;
static List clinitList;
int codeAddress;
// struct address is ONLY useful for <clinit> methods
// and the boot/main methods!
// Now it's necessary for debugging too.
int structAddress;
CodeException[] exctab;
int mstack, margs, mreallocals;
int len, exclen;
int vtindex;
/**
* Constructor is only used by the ClassInfo visitor
*
* @param jc
* @param mid
*/
protected JopMethodInfo(ClassInfo jc, String mid) {
super(jc, mid);
codeAddress = 0;
structAddress = 0;
}
/**
* Return the correct type of cli
*/
public JopClassInfo getCli() {
return (JopClassInfo) super.getCli();
}
/**
* @param m
*/
public void setInfo(int addr) {
codeAddress = addr;
Method m = getMethod();
margs = 0;
Type at[] = m.getArgumentTypes();
for (int i = 0; i < at.length; ++i) {
margs += at[i].getSize();
}
// FIXME! invokespecial adds an extra objref!!! inits, private, and
// superclass calls
// for now only handle inits
if (!m.isStatic()) {
margs++;
}
if (m.isAbstract()) {
mstack = mreallocals = len = exclen = 0;
exctab = null;
} else {
mstack = m.getCode().getMaxStack();
// the 'real' locals - means without arguments
mreallocals = m.getCode().getMaxLocals() - margs;
// System.err.println(" ++++++++++++ "+methodId+" --> mlocals
// ="+mlocals+" margs ="+margs);
len = (m.getCode().getCode().length + 3) / 4;
exctab = m.getCode().getExceptionTable();
exclen = exctab != null ? exctab.length : 0;
// TODO: couldn't len=JOP...MAX_SIZE/4 be ok?
if (len >= JOPizer.METHOD_MAX_SIZE / 4 || mreallocals > 31
|| margs > 31) {
// we interprete clinit on JOP - no size restriction
if (!m.getName().equals("<clinit>")) {
System.err.println("len(max:"
+ (JOPizer.METHOD_MAX_SIZE / 4) + ")=" + len
+ "mreallocals(max:31)=" + mreallocals
+ " margs(max:31)=" + margs);
System.err.println("wrong size: "
+ getCli().clazz.getClassName() + "." + methodId);
- System.exit(-1);
+ throw new Error();
}
}
// System.out.println((mstack+m.getCode().getMaxLocals())+" "+
// m.getName()+" maxStack="+mstack+"
// locals="+m.getCode().getMaxLocals());
}
}
public int getLength() {
return getMethod().isAbstract() ? 0 : len + 1 + 2 * exclen;
}
public void dumpMethodStruct(PrintWriter out, int addr) {
if (methodId.equals(AppInfo.clinitSig)
&& len >= JOPizer.METHOD_MAX_SIZE / 4) {
out
.println("\t// no size for <clinit> - we iterpret it and allow larger methods!");
}
// java_lang_String
// 0x01 TODO access
// 2 TODO ? stack
// code start:1736
// code length:4
// cp:3647
// locals: 1 args size: 1
String abstr = "";
if (getMethod().isAbstract()) {
abstr = "abstract ";
}
out.println("\t//\t" + addr + ": " + abstr
+ getCli().clazz.getClassName() + "." + methodId);
out.println("\t\t//\tcode start: " + codeAddress);
out.println("\t\t//\tcode length: " + len);
out.println("\t\t//\tcp: " + getCli().cpoolAddress);
out.println("\t\t//\tlocals: " + (mreallocals + margs) + " args size: "
+ margs);
int word1 = codeAddress << 10 | len;
// no length on large <clinit> methods
// get interpreted at start - see Startup.clazzinit()
if (methodId.equals(AppInfo.clinitSig)
&& len >= JOPizer.METHOD_MAX_SIZE / 4) {
word1 = codeAddress << 10;
}
int word2 = getCli().cpoolAddress << 10 | mreallocals << 5 | margs;
if (getMethod().isAbstract()) {
word1 = word2 = 0;
}
out.println("\t\t" + word1 + ",");
out.println("\t\t" + word2 + ",");
}
public void dumpByteCode(PrintWriter out) {
out.println("//\t" + codeAddress + ": " + methodId);
if (getCode() == null) {
out.println("//\tabstract");
return;
}
byte bc[] = getCode().getCode();
String post = "// ";
int i, word, j;
for (j = 0, i = 3, word = 0; j < bc.length; j++) {
word = word << 8 | (bc[j] & 0xFF);
post += (bc[j] & 0xFF) + " ";
if (i == 0) {
out.println("\t" + word + ",\t" + post);
post = "// ";
i = 3;
word = 0;
} else
i--;
}
if (i != 3) {
word = word << (i + 1) * 8;
out.println("\t" + word + ",\t" + post);
}
word = getMethod().isSynchronized() ? 1 : 0;
word = word << 16 | (exclen & 0xFFFF);
out.println("\t" + word
+ ",\t//\tsynchronized?, exception table length");
for (i = 0; i < exclen; i++) {
Integer idx = new Integer(exctab[i].getCatchType());
int pos = getCli().cpoolUsed.indexOf(idx) + 1;
word = exctab[i].getStartPC();
post = "// start: " + exctab[i].getStartPC();
word = word << 16 | exctab[i].getEndPC();
post += "\tend: " + exctab[i].getEndPC();
out.println("\t" + word + ",\t" + post);
word = exctab[i].getHandlerPC();
post = "// target: " + exctab[i].getHandlerPC();
word = word << 16 | pos;
post += "\ttype: " + pos;
out.println("\t" + word + ",\t" + post);
}
}
public int getCodeAddress() {
return codeAddress;
}
public int getStructAddress() {
return structAddress;
}
}
| true | true | public void setInfo(int addr) {
codeAddress = addr;
Method m = getMethod();
margs = 0;
Type at[] = m.getArgumentTypes();
for (int i = 0; i < at.length; ++i) {
margs += at[i].getSize();
}
// FIXME! invokespecial adds an extra objref!!! inits, private, and
// superclass calls
// for now only handle inits
if (!m.isStatic()) {
margs++;
}
if (m.isAbstract()) {
mstack = mreallocals = len = exclen = 0;
exctab = null;
} else {
mstack = m.getCode().getMaxStack();
// the 'real' locals - means without arguments
mreallocals = m.getCode().getMaxLocals() - margs;
// System.err.println(" ++++++++++++ "+methodId+" --> mlocals
// ="+mlocals+" margs ="+margs);
len = (m.getCode().getCode().length + 3) / 4;
exctab = m.getCode().getExceptionTable();
exclen = exctab != null ? exctab.length : 0;
// TODO: couldn't len=JOP...MAX_SIZE/4 be ok?
if (len >= JOPizer.METHOD_MAX_SIZE / 4 || mreallocals > 31
|| margs > 31) {
// we interprete clinit on JOP - no size restriction
if (!m.getName().equals("<clinit>")) {
System.err.println("len(max:"
+ (JOPizer.METHOD_MAX_SIZE / 4) + ")=" + len
+ "mreallocals(max:31)=" + mreallocals
+ " margs(max:31)=" + margs);
System.err.println("wrong size: "
+ getCli().clazz.getClassName() + "." + methodId);
System.exit(-1);
}
}
// System.out.println((mstack+m.getCode().getMaxLocals())+" "+
// m.getName()+" maxStack="+mstack+"
// locals="+m.getCode().getMaxLocals());
}
}
| public void setInfo(int addr) {
codeAddress = addr;
Method m = getMethod();
margs = 0;
Type at[] = m.getArgumentTypes();
for (int i = 0; i < at.length; ++i) {
margs += at[i].getSize();
}
// FIXME! invokespecial adds an extra objref!!! inits, private, and
// superclass calls
// for now only handle inits
if (!m.isStatic()) {
margs++;
}
if (m.isAbstract()) {
mstack = mreallocals = len = exclen = 0;
exctab = null;
} else {
mstack = m.getCode().getMaxStack();
// the 'real' locals - means without arguments
mreallocals = m.getCode().getMaxLocals() - margs;
// System.err.println(" ++++++++++++ "+methodId+" --> mlocals
// ="+mlocals+" margs ="+margs);
len = (m.getCode().getCode().length + 3) / 4;
exctab = m.getCode().getExceptionTable();
exclen = exctab != null ? exctab.length : 0;
// TODO: couldn't len=JOP...MAX_SIZE/4 be ok?
if (len >= JOPizer.METHOD_MAX_SIZE / 4 || mreallocals > 31
|| margs > 31) {
// we interprete clinit on JOP - no size restriction
if (!m.getName().equals("<clinit>")) {
System.err.println("len(max:"
+ (JOPizer.METHOD_MAX_SIZE / 4) + ")=" + len
+ "mreallocals(max:31)=" + mreallocals
+ " margs(max:31)=" + margs);
System.err.println("wrong size: "
+ getCli().clazz.getClassName() + "." + methodId);
throw new Error();
}
}
// System.out.println((mstack+m.getCode().getMaxLocals())+" "+
// m.getName()+" maxStack="+mstack+"
// locals="+m.getCode().getMaxLocals());
}
}
|
diff --git a/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java b/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
index 2ab814d..08de2bf 100644
--- a/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
+++ b/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
@@ -1,144 +1,144 @@
package com.pannous.vaservice.sample;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Handler;
import android.util.Log;
/**
* @author Peter Karich
*/
public class VoiceActionsService extends Handler {
protected int timeout = 5000;
public String text;
public List<String> imageUrls = new ArrayList<String>();
public VoiceActionsService(int timeout) {
this.timeout = timeout;
}
public String getText() {
return text;
}
public String getImageUrl() {
if (imageUrls.isEmpty())
return "";
return imageUrls.get(0);
}
public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
- int timeZoneInMinutes = TimeZone.getDefault().getRawOffset() / 1000 / 60;
+ int timeZoneInMinutes = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60;
// TODO add client features: show-urls, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
- + "&clientTimeZone=" + timeZoneInMinutes
+ + "&timeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
if (firstHandler.has("errorMessage")) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
public void log(String str) {
Log.i("VoiceActions", str);
}
public void err(Exception exc) {
Log.e("VoiceActions", "Problem", exc);
}
public void err(String str) {
Log.e("VoiceActions", str);
}
}
| false | true | public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
int timeZoneInMinutes = TimeZone.getDefault().getRawOffset() / 1000 / 60;
// TODO add client features: show-urls, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
+ "&clientTimeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
if (firstHandler.has("errorMessage")) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
| public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
int timeZoneInMinutes = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60;
// TODO add client features: show-urls, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
+ "&timeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
if (firstHandler.has("errorMessage")) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
|
diff --git a/modules/clear/src/clear/ClearSimulator.java b/modules/clear/src/clear/ClearSimulator.java
index 2f7fceb..40b69e6 100644
--- a/modules/clear/src/clear/ClearSimulator.java
+++ b/modules/clear/src/clear/ClearSimulator.java
@@ -1,173 +1,173 @@
package clear;
import rescuecore2.worldmodel.ChangeSet;
import rescuecore2.worldmodel.EntityID;
import rescuecore2.messages.Command;
import rescuecore2.messages.control.KSCommands;
import rescuecore2.log.Logger;
import rescuecore2.misc.geometry.GeometryTools2D;
import rescuecore2.misc.geometry.Line2D;
import rescuecore2.misc.geometry.Point2D;
import rescuecore2.standard.components.StandardSimulator;
import rescuecore2.standard.entities.Area;
import rescuecore2.standard.entities.Blockade;
import rescuecore2.standard.entities.PoliceForce;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.standard.messages.AKClear;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
The area model clear simulator. This simulator processes AKClear messages.
*/
public class ClearSimulator extends StandardSimulator {
private static final String SIMULATOR_NAME = "Area model clear simulator";
private static final String REPAIR_RATE_KEY = "clear.repair.rate";
private static final String REPAIR_DISTANCE_KEY = "clear.repair.distance";
@Override
public String getName() {
return SIMULATOR_NAME;
}
@Override
protected void processCommands(KSCommands c, ChangeSet changes) {
long start = System.currentTimeMillis();
int time = c.getTime();
Logger.info("Timestep " + time);
Map<Blockade, Integer> partiallyCleared = new HashMap<Blockade, Integer>();
for (Command command : c.getCommands()) {
if (command instanceof AKClear) {
AKClear clear = (AKClear)command;
if (!isValid(clear)) {
continue;
}
Logger.debug("Processing " + clear);
EntityID blockadeID = clear.getTarget();
Blockade blockade = (Blockade)model.getEntity(blockadeID);
Area area = (Area)model.getEntity(blockade.getPosition());
int cost = blockade.getRepairCost();
int rate = config.getIntValue(REPAIR_RATE_KEY);
Logger.debug("Blockade repair cost: " + cost);
Logger.debug("Blockade repair rate: " + rate);
- if (rate > cost) {
+ if (rate >= cost) {
// Remove the blockade entirely
List<EntityID> ids = new ArrayList<EntityID>(area.getBlockades());
ids.remove(blockadeID);
area.setBlockades(ids);
model.removeEntity(blockadeID);
changes.addChange(area, area.getBlockadesProperty());
changes.entityDeleted(blockadeID);
partiallyCleared.remove(blockade);
Logger.debug("Cleared " + blockade);
}
else {
// Update the repair cost
if (!partiallyCleared.containsKey(blockade)) {
partiallyCleared.put(blockade, cost);
}
cost -= rate;
blockade.setRepairCost(cost);
changes.addChange(blockade, blockade.getRepairCostProperty());
}
}
}
// Shrink partially cleared blockades
for (Map.Entry<Blockade, Integer> next : partiallyCleared.entrySet()) {
Blockade b = next.getKey();
double original = next.getValue();
double current = b.getRepairCost();
// d is the new size relative to the old size
double d = current / original;
Logger.debug("Partially cleared " + b);
Logger.debug("Original repair cost: " + original);
Logger.debug("New repair cost: " + current);
Logger.debug("Proportion left: " + d);
int[] apexes = b.getApexes();
double cx = b.getX();
double cy = b.getY();
// Move each apex towards the centre
for (int i = 0; i < apexes.length; i += 2) {
double x = apexes[i];
double y = apexes[i + 1];
double dx = x - cx;
double dy = y - cy;
// Shift both x and y so they are now d * dx from the centre
double newX = cx + (dx * d);
double newY = cy + (dy * d);
apexes[i] = (int)newX;
apexes[i + 1] = (int)newY;
}
b.setApexes(apexes);
changes.addChange(b, b.getApexesProperty());
}
long end = System.currentTimeMillis();
Logger.info("Timestep " + time + " took " + (end - start) + " ms");
}
private boolean isValid(AKClear clear) {
StandardEntity agent = model.getEntity(clear.getAgentID());
StandardEntity target = model.getEntity(clear.getTarget());
if (agent == null) {
Logger.info("Rejecting clear command " + clear + ": agent does not exist");
return false;
}
if (target == null) {
Logger.info("Rejecting clear command " + clear + ": target does not exist");
return false;
}
if (!(agent instanceof PoliceForce)) {
Logger.info("Rejecting clear command " + clear + ": agent is not a police officer");
return false;
}
if (!(target instanceof Blockade)) {
Logger.info("Rejecting clear command " + clear + ": target is not a road");
return false;
}
PoliceForce police = (PoliceForce)agent;
StandardEntity agentPosition = police.getPosition(model);
if (agentPosition == null) {
Logger.info("Rejecting clear command " + clear + ": could not locate agent");
return false;
}
if (!police.isHPDefined() || police.getHP() <= 0) {
Logger.info("Rejecting clear command " + clear + ": agent is dead");
return false;
}
if (police.isBuriednessDefined() && police.getBuriedness() > 0) {
Logger.info("Rejecting clear command " + clear + ": agent is buried");
return false;
}
Blockade targetBlockade = (Blockade)target;
if (!targetBlockade.isPositionDefined()) {
Logger.info("Rejecting clear command " + clear + ": blockade has no position");
return false;
}
if (!targetBlockade.isRepairCostDefined()) {
Logger.info("Rejecting clear command " + clear + ": blockade has no repair cost");
return false;
}
// Check location
// Find the closest point on the blockade to the agent
int range = config.getIntValue(REPAIR_DISTANCE_KEY);
Point2D agentLocation = new Point2D(police.getX(), police.getY());
double bestDistance = Double.MAX_VALUE;
for (Line2D line : GeometryTools2D.pointsToLines(GeometryTools2D.vertexArrayToPoints(targetBlockade.getApexes()), true)) {
Point2D closest = GeometryTools2D.getClosestPointOnSegment(line, agentLocation);
double distance = GeometryTools2D.getDistance(agentLocation, closest);
if (distance < range) {
return true;
}
if (bestDistance > distance) {
bestDistance = distance;
}
}
Logger.info("Rejecting clear command " + clear + ": agent is not adjacent to target: distance is " + bestDistance);
return false;
}
}
| true | true | protected void processCommands(KSCommands c, ChangeSet changes) {
long start = System.currentTimeMillis();
int time = c.getTime();
Logger.info("Timestep " + time);
Map<Blockade, Integer> partiallyCleared = new HashMap<Blockade, Integer>();
for (Command command : c.getCommands()) {
if (command instanceof AKClear) {
AKClear clear = (AKClear)command;
if (!isValid(clear)) {
continue;
}
Logger.debug("Processing " + clear);
EntityID blockadeID = clear.getTarget();
Blockade blockade = (Blockade)model.getEntity(blockadeID);
Area area = (Area)model.getEntity(blockade.getPosition());
int cost = blockade.getRepairCost();
int rate = config.getIntValue(REPAIR_RATE_KEY);
Logger.debug("Blockade repair cost: " + cost);
Logger.debug("Blockade repair rate: " + rate);
if (rate > cost) {
// Remove the blockade entirely
List<EntityID> ids = new ArrayList<EntityID>(area.getBlockades());
ids.remove(blockadeID);
area.setBlockades(ids);
model.removeEntity(blockadeID);
changes.addChange(area, area.getBlockadesProperty());
changes.entityDeleted(blockadeID);
partiallyCleared.remove(blockade);
Logger.debug("Cleared " + blockade);
}
else {
// Update the repair cost
if (!partiallyCleared.containsKey(blockade)) {
partiallyCleared.put(blockade, cost);
}
cost -= rate;
blockade.setRepairCost(cost);
changes.addChange(blockade, blockade.getRepairCostProperty());
}
}
}
// Shrink partially cleared blockades
for (Map.Entry<Blockade, Integer> next : partiallyCleared.entrySet()) {
Blockade b = next.getKey();
double original = next.getValue();
double current = b.getRepairCost();
// d is the new size relative to the old size
double d = current / original;
Logger.debug("Partially cleared " + b);
Logger.debug("Original repair cost: " + original);
Logger.debug("New repair cost: " + current);
Logger.debug("Proportion left: " + d);
int[] apexes = b.getApexes();
double cx = b.getX();
double cy = b.getY();
// Move each apex towards the centre
for (int i = 0; i < apexes.length; i += 2) {
double x = apexes[i];
double y = apexes[i + 1];
double dx = x - cx;
double dy = y - cy;
// Shift both x and y so they are now d * dx from the centre
double newX = cx + (dx * d);
double newY = cy + (dy * d);
apexes[i] = (int)newX;
apexes[i + 1] = (int)newY;
}
b.setApexes(apexes);
changes.addChange(b, b.getApexesProperty());
}
long end = System.currentTimeMillis();
Logger.info("Timestep " + time + " took " + (end - start) + " ms");
}
| protected void processCommands(KSCommands c, ChangeSet changes) {
long start = System.currentTimeMillis();
int time = c.getTime();
Logger.info("Timestep " + time);
Map<Blockade, Integer> partiallyCleared = new HashMap<Blockade, Integer>();
for (Command command : c.getCommands()) {
if (command instanceof AKClear) {
AKClear clear = (AKClear)command;
if (!isValid(clear)) {
continue;
}
Logger.debug("Processing " + clear);
EntityID blockadeID = clear.getTarget();
Blockade blockade = (Blockade)model.getEntity(blockadeID);
Area area = (Area)model.getEntity(blockade.getPosition());
int cost = blockade.getRepairCost();
int rate = config.getIntValue(REPAIR_RATE_KEY);
Logger.debug("Blockade repair cost: " + cost);
Logger.debug("Blockade repair rate: " + rate);
if (rate >= cost) {
// Remove the blockade entirely
List<EntityID> ids = new ArrayList<EntityID>(area.getBlockades());
ids.remove(blockadeID);
area.setBlockades(ids);
model.removeEntity(blockadeID);
changes.addChange(area, area.getBlockadesProperty());
changes.entityDeleted(blockadeID);
partiallyCleared.remove(blockade);
Logger.debug("Cleared " + blockade);
}
else {
// Update the repair cost
if (!partiallyCleared.containsKey(blockade)) {
partiallyCleared.put(blockade, cost);
}
cost -= rate;
blockade.setRepairCost(cost);
changes.addChange(blockade, blockade.getRepairCostProperty());
}
}
}
// Shrink partially cleared blockades
for (Map.Entry<Blockade, Integer> next : partiallyCleared.entrySet()) {
Blockade b = next.getKey();
double original = next.getValue();
double current = b.getRepairCost();
// d is the new size relative to the old size
double d = current / original;
Logger.debug("Partially cleared " + b);
Logger.debug("Original repair cost: " + original);
Logger.debug("New repair cost: " + current);
Logger.debug("Proportion left: " + d);
int[] apexes = b.getApexes();
double cx = b.getX();
double cy = b.getY();
// Move each apex towards the centre
for (int i = 0; i < apexes.length; i += 2) {
double x = apexes[i];
double y = apexes[i + 1];
double dx = x - cx;
double dy = y - cy;
// Shift both x and y so they are now d * dx from the centre
double newX = cx + (dx * d);
double newY = cy + (dy * d);
apexes[i] = (int)newX;
apexes[i + 1] = (int)newY;
}
b.setApexes(apexes);
changes.addChange(b, b.getApexesProperty());
}
long end = System.currentTimeMillis();
Logger.info("Timestep " + time + " took " + (end - start) + " ms");
}
|
diff --git a/src/crawl/DyttCrawler.java b/src/crawl/DyttCrawler.java
index be043c9..ae14cfa 100644
--- a/src/crawl/DyttCrawler.java
+++ b/src/crawl/DyttCrawler.java
@@ -1,213 +1,213 @@
package crawl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import model.Movie_Info;
import util.BasicUtil;
import util.LogUtil;
import witer.DBWriter;
import witer.ImageWriter;
public class DyttCrawler extends BaseCrawler{
private static final String ROOT_URL = "http://www.dytt8.net/";
public static void main(String[] args) {
DyttCrawler dc = new DyttCrawler();
dc.begin();
}
public DyttCrawler(){
movie_src = "Dytt";
CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/china/list_4_%d.html");
CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/rihan/list_6_%d.html");
CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/oumei/list_7_%d.html");
}
protected void begin(){
super.begin();
}
/**
* 获取指定网页内容
* @param surl :网址
* @return 网页源代码
*/
private String getContent(String surl){
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(surl);
URLConnection urlconnection = url.openConnection();
urlconnection.addRequestProperty("User-Agent", AGENT);
urlconnection.setConnectTimeout(TIME_OUT);
InputStream is = url.openStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "GBK"));
String rLine = null;
while((rLine=bReader.readLine())!=null){
sb.append(rLine);
sb.append("/r/n");
}
}catch (IOException e) {
}
return sb.toString();
}
/**
* 获取当前最大页
* @return MAX_PAGE
*/
protected boolean getMaxPage(){
for(int i = 0; i < CRAWLABLE_URLS.size() ; i ++){
String url = CRAWLABLE_URLS.get(i);
String content = getContent(String.format(url, 1));
String regex = "共\\d+页/\\d+条记录";
Pattern pt = Pattern.compile(regex);
Matcher mt = pt.matcher(content);
if(mt.find()){
String str = mt.group();
str = str.substring(1, str.indexOf("/") - 1);
try {
int last_page = Integer.parseInt(str);
CRAWLABLE_MAX_PAGE.add(i, last_page);
System.out.println("last page found: " + last_page);
} catch (NumberFormatException e) {
LogUtil.getInstance().write(this.getClass().getName() + " [error] getting max page at URL : " + url);
e.printStackTrace();
}
}
}
return true;
}
private final static String MOVIE_URL_PATTERN = "<a href=\"/html/gndy/[a-zA-Z]+/[0-9]{1,}/[0-9]{1,}.html\"";
private final static String HAIBAO_PATTERN = "<img[^<]*src=\"http.*?(jpg|gif|JPG|GIF)\"";
private final static String PIANMING_PATTERN = "(◎译 名|◎片 名|◎中 文 名|◎英 文 名|◎译 名|◎片 名|◎中 文 名|◎英 文 名|◎影片原名|◎中文译名)[^<]*<br />";
private final static String XIAZAIMING_PATTERN = "(rmvb|avi|mp4|mkv|RMVB|AVI|PM4|MKV)\">[^<]*(rmvb|avi|mp4|mkv|RMVB|AVI|PM4|MKV)";
private final static String[] MOVIE_PATTERNS = {HAIBAO_PATTERN, PIANMING_PATTERN, XIAZAIMING_PATTERN};
/**
* 获取电影信息
* @param id : 当前线程ID
* @param sUrl : 网页网址
* @return 当前页获取电影数量
*/
protected int crawlMovies(int id, String sUrl){
String s = getContent(sUrl);
int movie_counter = 0;
ArrayList<Movie_Info> movie_list = new ArrayList<Movie_Info>();
Pattern pt = Pattern.compile(MOVIE_URL_PATTERN);
Matcher mt = pt.matcher(s);
while(mt.find()){
String str = mt.group();
str =ROOT_URL + str.substring(10, str.length() - 1);
Movie_Info movie_info = new Movie_Info();
if(DBWriter.getInstance().ifCrawled(str)){
continue;
}
String content = getContent(str);
for(int i = 0; i < MOVIE_PATTERNS.length; i ++){
parsePattern(movie_info, content, i);
}
movie_counter ++;
if(movie_info.getMovieName() != null){
ImageWriter.getInstance().addMovieList(movie_info.clone());
}
movie_list.add(movie_info);
}
DBWriter.getInstance().addMovieList(movie_list);
return movie_counter;
}
/**
* 按照正则表达式解析电影信息
* @param movie_info : 电影类
* @param s : 网页源代码
* @param n : 当前正则表达式. 0 : HAIBAO_PATTERN; 1 : PIANMING_PATTERN; 2 : XIAZAIMING_PATTERN.
*/
private void parsePattern(Movie_Info movie_info, String s, int n){
Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]);
Matcher mt = pt.matcher(s);
while (mt.find()) {
//先去除一些特殊的符号
String str = mt.group();
str = BasicUtil.formatString(str);
//用正则表达式进行匹配,通过字符串处理找到相应内容
switch(n){
case 0:
str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1);
if(!movie_info.hasHaiBaoPath()){
str = str.trim();
movie_info.setHaiBaoPath(str);
}
break;
case 1:
//蛋疼的电影名匹配
if(str.startsWith("◎译 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎译 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎影片原名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中文译名")){
str = str.substring(6, str.lastIndexOf("<"));
}
//去除电影名前的“空格”(trim对此种空格无效)
while(str.startsWith(" ")){
str = str.substring(1, str.length());
}
StringTokenizer st = new StringTokenizer(str, "/");
if(st.countTokens() == 0){
movie_info.setMovieName(str.trim());
}
while(st.hasMoreElements()){
String tmp = st.nextToken().trim();
if(!movie_info.hasName()){
movie_info.setMovieName(tmp);
}else{
movie_info.addName(tmp);
}
}
break;
case 2:
str = str.substring(str.indexOf("\">") + 2).trim();
movie_info.addDownLoadLinks(str, str.substring(str.lastIndexOf("/") + 1));
break;
default:break;
}
}
//部分电影仍旧无法识别电影名,通过title从中提取。
- if(!movie_info.hasName()){
+ if(n == 1 && !movie_info.hasName()){
String title = s.substring(s.indexOf("<title>"), s.indexOf("</title>"));
String name = title.substring(title.indexOf("《") + 1, title.indexOf("》"));
movie_info.setMovieName(name);
}
}
}
| true | true | private void parsePattern(Movie_Info movie_info, String s, int n){
Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]);
Matcher mt = pt.matcher(s);
while (mt.find()) {
//先去除一些特殊的符号
String str = mt.group();
str = BasicUtil.formatString(str);
//用正则表达式进行匹配,通过字符串处理找到相应内容
switch(n){
case 0:
str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1);
if(!movie_info.hasHaiBaoPath()){
str = str.trim();
movie_info.setHaiBaoPath(str);
}
break;
case 1:
//蛋疼的电影名匹配
if(str.startsWith("◎译 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎译 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎影片原名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中文译名")){
str = str.substring(6, str.lastIndexOf("<"));
}
//去除电影名前的“空格”(trim对此种空格无效)
while(str.startsWith(" ")){
str = str.substring(1, str.length());
}
StringTokenizer st = new StringTokenizer(str, "/");
if(st.countTokens() == 0){
movie_info.setMovieName(str.trim());
}
while(st.hasMoreElements()){
String tmp = st.nextToken().trim();
if(!movie_info.hasName()){
movie_info.setMovieName(tmp);
}else{
movie_info.addName(tmp);
}
}
break;
case 2:
str = str.substring(str.indexOf("\">") + 2).trim();
movie_info.addDownLoadLinks(str, str.substring(str.lastIndexOf("/") + 1));
break;
default:break;
}
}
//部分电影仍旧无法识别电影名,通过title从中提取。
if(!movie_info.hasName()){
String title = s.substring(s.indexOf("<title>"), s.indexOf("</title>"));
String name = title.substring(title.indexOf("《") + 1, title.indexOf("》"));
movie_info.setMovieName(name);
}
}
| private void parsePattern(Movie_Info movie_info, String s, int n){
Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]);
Matcher mt = pt.matcher(s);
while (mt.find()) {
//先去除一些特殊的符号
String str = mt.group();
str = BasicUtil.formatString(str);
//用正则表达式进行匹配,通过字符串处理找到相应内容
switch(n){
case 0:
str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1);
if(!movie_info.hasHaiBaoPath()){
str = str.trim();
movie_info.setHaiBaoPath(str);
}
break;
case 1:
//蛋疼的电影名匹配
if(str.startsWith("◎译 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎译 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎片 名")){
str = str.substring(7, str.lastIndexOf("<"));
}else if(str.startsWith("◎中 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎英 文 名")){
str = str.substring(8, str.lastIndexOf("<"));
}else if(str.startsWith("◎影片原名")){
str = str.substring(6, str.lastIndexOf("<"));
}else if(str.startsWith("◎中文译名")){
str = str.substring(6, str.lastIndexOf("<"));
}
//去除电影名前的“空格”(trim对此种空格无效)
while(str.startsWith(" ")){
str = str.substring(1, str.length());
}
StringTokenizer st = new StringTokenizer(str, "/");
if(st.countTokens() == 0){
movie_info.setMovieName(str.trim());
}
while(st.hasMoreElements()){
String tmp = st.nextToken().trim();
if(!movie_info.hasName()){
movie_info.setMovieName(tmp);
}else{
movie_info.addName(tmp);
}
}
break;
case 2:
str = str.substring(str.indexOf("\">") + 2).trim();
movie_info.addDownLoadLinks(str, str.substring(str.lastIndexOf("/") + 1));
break;
default:break;
}
}
//部分电影仍旧无法识别电影名,通过title从中提取。
if(n == 1 && !movie_info.hasName()){
String title = s.substring(s.indexOf("<title>"), s.indexOf("</title>"));
String name = title.substring(title.indexOf("《") + 1, title.indexOf("》"));
movie_info.setMovieName(name);
}
}
|
diff --git a/hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoHelpers.java b/hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoHelpers.java
index 64126e692..81da6f819 100644
--- a/hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoHelpers.java
+++ b/hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoHelpers.java
@@ -1,53 +1,54 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.ogm.dialect.mongodb;
import org.hibernate.ogm.datastore.mongodb.AssociationStorage;
import org.hibernate.ogm.grid.AssociationKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* @author Alan Fitton <alan at eth0.org.uk>
*/
public class MongoHelpers {
public static DBObject associationKeyToObject(AssociationStorage storage,
AssociationKey key) {
Object[] columnValues = key.getColumnValues();
DBObject columns = new BasicDBObject( columnValues.length );
int i = 0;
for ( String name : key.getColumnNames() ) {
columns.put( name, columnValues[i++] );
}
DBObject obj = new BasicDBObject( 1 );
obj.put( MongoDBDialect.COLUMNS_FIELDNAME, columns );
- if (storage == AssociationStorage.GLOBAL_COLLECTION)
+ if ( storage == AssociationStorage.GLOBAL_COLLECTION ) {
obj.put( MongoDBDialect.TABLE_FIELDNAME, key.getTable() );
+ }
return obj;
}
}
| false | true | public static DBObject associationKeyToObject(AssociationStorage storage,
AssociationKey key) {
Object[] columnValues = key.getColumnValues();
DBObject columns = new BasicDBObject( columnValues.length );
int i = 0;
for ( String name : key.getColumnNames() ) {
columns.put( name, columnValues[i++] );
}
DBObject obj = new BasicDBObject( 1 );
obj.put( MongoDBDialect.COLUMNS_FIELDNAME, columns );
if (storage == AssociationStorage.GLOBAL_COLLECTION)
obj.put( MongoDBDialect.TABLE_FIELDNAME, key.getTable() );
return obj;
}
| public static DBObject associationKeyToObject(AssociationStorage storage,
AssociationKey key) {
Object[] columnValues = key.getColumnValues();
DBObject columns = new BasicDBObject( columnValues.length );
int i = 0;
for ( String name : key.getColumnNames() ) {
columns.put( name, columnValues[i++] );
}
DBObject obj = new BasicDBObject( 1 );
obj.put( MongoDBDialect.COLUMNS_FIELDNAME, columns );
if ( storage == AssociationStorage.GLOBAL_COLLECTION ) {
obj.put( MongoDBDialect.TABLE_FIELDNAME, key.getTable() );
}
return obj;
}
|
diff --git a/src/main/java/org/xembly/Directives.java b/src/main/java/org/xembly/Directives.java
index 7b0d77e..ef8d327 100644
--- a/src/main/java/org/xembly/Directives.java
+++ b/src/main/java/org/xembly/Directives.java
@@ -1,455 +1,465 @@
/**
* Copyright (c) 2013, xembly.org
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the xembly.org nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.xembly;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Collection of {@link Directive}s, instantiable from {@link String}.
*
* <p>For example, to fetch directives from a string and apply to the
* DOM document:
*
* <pre> Document dom = DocumentBuilderFactory.newInstance()
* .newDocumentBuilder().newDocument();
* dom.appendChild(dom.createElement("root"));
* new Xembler(
* new Directives("XPATH 'root'; ADD 'employee';")
* ).apply(dom);</pre>
*
* <p>{@link Directives} can be used as a builder of Xembly script:
*
* <pre> Document dom = DocumentBuilderFactory.newInstance()
* .newDocumentBuilder().newDocument();
* dom.appendChild(dom.createElement("root"));
* new Xembler(
* new Directives()
* .xpath("/root")
* .addIf("employees")
* .add("employee")
* .attr("id", 6564)
* .up()
* .xpath("employee[@id='100']")
* .strict(1)
* .remove()
* ).apply(dom);</pre>
*
* <p>The class is mutable and thread-safe.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.1
* @checkstyle ClassDataAbstractionCoupling (500 lines)
* @checkstyle ClassFanOutComplexity (500 lines)
*/
@EqualsAndHashCode(callSuper = false, of = "all")
@SuppressWarnings({ "PMD.TooManyMethods", "PMD.CyclomaticComplexity" })
public final class Directives implements Iterable<Directive> {
/**
* Right margin.
*/
private static final int MARGIN = 80;
/**
* List of directives.
*/
private final transient Collection<Directive> all =
new CopyOnWriteArrayList<Directive>();
/**
* Public ctor.
*/
public Directives() {
this(Collections.<Directive>emptyList());
}
/**
* Public ctor.
* @param text Xembly script
* @throws SyntaxException If syntax is broken
*/
public Directives(@NotNull(message = "xembly script can't be NULL")
final String text) throws SyntaxException {
this(Directives.parse(text));
}
/**
* Public ctor.
* @param dirs Directives
*/
public Directives(@NotNull(message = "directives can't be NULL")
final Iterable<Directive> dirs) {
this.append(dirs);
}
@Override
public String toString() {
final StringBuilder text = new StringBuilder(0);
int width = 0;
for (final Directive dir : this.all) {
final String txt = dir.toString();
text.append(txt).append(';');
width += txt.length();
if (width > Directives.MARGIN) {
text.append('\n');
width = 0;
}
}
return text.toString().trim();
}
@Override
public Iterator<Directive> iterator() {
return this.all.iterator();
}
/**
* Create a collection of directives, which can create a copy
* of provided node.
*
* <p>For example, you already have a node in an XML document,
* which you'd like to add to another XML document:
*
* <pre> Document target = parse("<root/>");
* Node node = parse("<user name='Jeffrey'/>");
* new Xembler(
* new Directives()
* .xpath("/*")
* .add("jeff")
* .append(Directives.copyOf(node))
* ).apply(target);
* assert print(target).equals(
* "<root><jeff name='Jeffrey'></root>"
* );
* </pre>
*
* @param node Node to analyze
* @return Collection of directives
* @since 0.13
* @checkstyle CyclomaticComplexity (50 lines)
*/
public static Iterable<Directive> copyOf(
@NotNull(message = "node can't be NULL") final Node node) {
final Directives dirs = new Directives();
if (node.hasAttributes()) {
final NamedNodeMap attrs = node.getAttributes();
final int len = attrs.getLength();
for (int idx = 0; idx < len; ++idx) {
final Attr attr = Attr.class.cast(attrs.item(idx));
dirs.attr(attr.getNodeName(), attr.getNodeValue());
}
}
if (node.hasChildNodes()) {
final NodeList children = node.getChildNodes();
final int len = children.getLength();
for (int idx = 0; idx < len; ++idx) {
final Node child = children.item(idx);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
dirs.add(child.getNodeName())
.append(Directives.copyOf(child))
.up();
break;
case Node.ATTRIBUTE_NODE:
dirs.attr(child.getNodeName(), child.getNodeValue());
break;
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
- dirs.set(child.getTextContent());
+ if (len == 1) {
+ dirs.set(child.getTextContent());
+ } else if (!child.getTextContent().trim().isEmpty()) {
+ throw new IllegalArgumentException(
+ String.format(
+ // @checkstyle LineLength (1 line)
+ "TEXT node #%d is not allowed together with other %d nodes in %s",
+ idx, len, child.getNodeName()
+ )
+ );
+ }
break;
case Node.PROCESSING_INSTRUCTION_NODE:
dirs.pi(child.getNodeName(), child.getNodeValue());
break;
case Node.ENTITY_NODE:
case Node.COMMENT_NODE:
break;
default:
throw new IllegalArgumentException(
String.format(
"unsupported type %d of node %s",
child.getNodeType(), child.getNodeName()
)
);
}
}
}
return dirs;
}
/**
* Append all directives.
* @param dirs Directives to append
* @return This object
* @since 0.11
*/
public Directives append(
@NotNull(message = "list of directives can't be NULL")
final Iterable<Directive> dirs) {
for (final Directive dir : dirs) {
this.all.add(dir);
}
return this;
}
/**
* Add node to all current nodes.
* @param name Name of the node to add
* @return This object
* @since 0.5
*/
public Directives add(
@NotNull(message = "name can't be NULL") final String name) {
try {
this.all.add(new AddDirective(name));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Add multiple nodes and set their text values.
*
* <p>Every pair in the provided map will be treated as a new
* node name and value. It's a convenient utility method that simplifies
* the process of adding a collection of nodes with pre-set values. For
* example:
*
* <pre> new Directives()
* .add("first", "hello, world!")
* .add(
* new ArrayMap<String, Object>()
* .with("alpha", 1)
* .with("beta", "2")
* .with("gamma", new Date())
* )
* .add("second");
* </pre>
*
* @param <K> Type of key
* @param <V> Type of value
* @param nodes Names and values of nodes to add
* @return This object
* @since 0.8
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public <K, V> Directives add(
@NotNull(message = "map can't be NULL") final Map<K, V> nodes) {
try {
for (final Map.Entry<K, V> entry : nodes.entrySet()) {
this.all.addAll(
Arrays.asList(
new AddDirective(entry.getKey().toString()),
new SetDirective(entry.getValue().toString()),
new UpDirective()
)
);
}
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Add node if it's absent.
* @param name Name of the node to add
* @return This object
* @since 0.5
*/
public Directives addIf(
@NotNull(message = "name can't be NULL") final String name) {
try {
this.all.add(new AddIfDirective(name));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Remove all current nodes and move cursor to their parents.
* @return This object
* @since 0.5
*/
public Directives remove() {
this.all.add(new RemoveDirective());
return this;
}
/**
* Set attribute.
* @param name Name of the attribute
* @param value Value to set
* @return This object
* @since 0.5
*/
public Directives attr(
@NotNull(message = "attr name can't be NULL") final String name,
@NotNull(message = "value can't be NULL") final String value) {
try {
this.all.add(new AttrDirective(name, value));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Add processing instruction.
* @param target PI name
* @param data Data to set
* @return This object
* @since 0.9
* @checkstyle MethodName (3 lines)
*/
@SuppressWarnings("PMD.ShortMethodName")
public Directives pi(
@NotNull(message = "target can't be NULL") final String target,
@NotNull(message = "data can't be NULL") final String data) {
try {
this.all.add(new PiDirective(target, data));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Set text content.
* @param text Text to set
* @return This object
* @since 0.5
*/
public Directives set(
@NotNull(message = "content can't be NULL") final String text) {
try {
this.all.add(new SetDirective(text));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Set text content.
* @param text Text to set
* @return This object
* @since 0.7
*/
public Directives xset(
@NotNull(message = "content can't be NULL") final String text) {
try {
this.all.add(new XsetDirective(text));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Go one node/level up.
* @return This object
* @since 0.5
* @checkstyle MethodName (3 lines)
*/
@SuppressWarnings("PMD.ShortMethodName")
public Directives up() {
this.all.add(new UpDirective());
return this;
}
/**
* Go to XPath.
* @param path Path to go to
* @return This object
* @since 0.5
*/
public Directives xpath(
@NotNull(message = "xpath can't be NULL") final String path) {
try {
this.all.add(new XpathDirective(path));
} catch (XmlContentException ex) {
throw new IllegalArgumentException(ex);
}
return this;
}
/**
* Check that there is exactly this number of current nodes.
* @param number Number of expected nodes
* @return This object
* @since 0.5
*/
public Directives strict(
@NotNull(message = "number can't be NULL") final int number) {
this.all.add(new StrictDirective(number));
return this;
}
/**
* Parse script.
* @param script Script to parse
* @return Collection of directives
* @throws SyntaxException If can't parse
*/
private static Collection<Directive> parse(final String script)
throws SyntaxException {
final CharStream input = new ANTLRStringStream(script);
final XemblyLexer lexer = new XemblyLexer(input);
final TokenStream tokens = new CommonTokenStream(lexer);
final XemblyParser parser = new XemblyParser(tokens);
try {
return parser.directives();
} catch (RecognitionException ex) {
throw new SyntaxException(script, ex);
} catch (ParsingException ex) {
throw new SyntaxException(script, ex);
}
}
}
| true | true | public static Iterable<Directive> copyOf(
@NotNull(message = "node can't be NULL") final Node node) {
final Directives dirs = new Directives();
if (node.hasAttributes()) {
final NamedNodeMap attrs = node.getAttributes();
final int len = attrs.getLength();
for (int idx = 0; idx < len; ++idx) {
final Attr attr = Attr.class.cast(attrs.item(idx));
dirs.attr(attr.getNodeName(), attr.getNodeValue());
}
}
if (node.hasChildNodes()) {
final NodeList children = node.getChildNodes();
final int len = children.getLength();
for (int idx = 0; idx < len; ++idx) {
final Node child = children.item(idx);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
dirs.add(child.getNodeName())
.append(Directives.copyOf(child))
.up();
break;
case Node.ATTRIBUTE_NODE:
dirs.attr(child.getNodeName(), child.getNodeValue());
break;
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
dirs.set(child.getTextContent());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
dirs.pi(child.getNodeName(), child.getNodeValue());
break;
case Node.ENTITY_NODE:
case Node.COMMENT_NODE:
break;
default:
throw new IllegalArgumentException(
String.format(
"unsupported type %d of node %s",
child.getNodeType(), child.getNodeName()
)
);
}
}
}
return dirs;
}
| public static Iterable<Directive> copyOf(
@NotNull(message = "node can't be NULL") final Node node) {
final Directives dirs = new Directives();
if (node.hasAttributes()) {
final NamedNodeMap attrs = node.getAttributes();
final int len = attrs.getLength();
for (int idx = 0; idx < len; ++idx) {
final Attr attr = Attr.class.cast(attrs.item(idx));
dirs.attr(attr.getNodeName(), attr.getNodeValue());
}
}
if (node.hasChildNodes()) {
final NodeList children = node.getChildNodes();
final int len = children.getLength();
for (int idx = 0; idx < len; ++idx) {
final Node child = children.item(idx);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
dirs.add(child.getNodeName())
.append(Directives.copyOf(child))
.up();
break;
case Node.ATTRIBUTE_NODE:
dirs.attr(child.getNodeName(), child.getNodeValue());
break;
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
if (len == 1) {
dirs.set(child.getTextContent());
} else if (!child.getTextContent().trim().isEmpty()) {
throw new IllegalArgumentException(
String.format(
// @checkstyle LineLength (1 line)
"TEXT node #%d is not allowed together with other %d nodes in %s",
idx, len, child.getNodeName()
)
);
}
break;
case Node.PROCESSING_INSTRUCTION_NODE:
dirs.pi(child.getNodeName(), child.getNodeValue());
break;
case Node.ENTITY_NODE:
case Node.COMMENT_NODE:
break;
default:
throw new IllegalArgumentException(
String.format(
"unsupported type %d of node %s",
child.getNodeType(), child.getNodeName()
)
);
}
}
}
return dirs;
}
|
diff --git a/src/main/java/com/solairis/yourcarslife/controller/SaveVehicleFuelLogController.java b/src/main/java/com/solairis/yourcarslife/controller/SaveVehicleFuelLogController.java
index 145b9f6..0af0dbb 100644
--- a/src/main/java/com/solairis/yourcarslife/controller/SaveVehicleFuelLogController.java
+++ b/src/main/java/com/solairis/yourcarslife/controller/SaveVehicleFuelLogController.java
@@ -1,75 +1,76 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.solairis.yourcarslife.controller;
import com.solairis.yourcarslife.command.SaveVehicleFuelLogFormData;
import com.solairis.yourcarslife.data.domain.User;
import com.solairis.yourcarslife.data.domain.Vehicle;
import com.solairis.yourcarslife.data.domain.VehicleFuelLog;
import com.solairis.yourcarslife.service.UserService;
import com.solairis.yourcarslife.service.VehicleFuelLogService;
import java.beans.PropertyEditor;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author josh
*/
@Controller
public class SaveVehicleFuelLogController {
@Autowired
private UserService userService;
@Autowired
private VehicleFuelLogService vehicleFuelLogService;
@Autowired
private org.springframework.validation.Validator saveVehicleFuelLogFormDataValidator;
@Autowired
private PropertyEditor customDateEditor;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(this.saveVehicleFuelLogFormDataValidator);
binder.registerCustomEditor(Date.class, customDateEditor);
}
@RequestMapping(value = "/data/save-vehicle-fuel-log")
public void saveVehicleFuelLog(@Valid SaveVehicleFuelLogFormData saveVehicleFuelLogFormData, BindingResult errors, Model model) {
org.springframework.security.core.userdetails.User securityUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = this.userService.getUser(Long.parseLong(securityUser.getUsername()));
if (!errors.hasFieldErrors()) {
VehicleFuelLog vehicleFuelLog = null;
if (saveVehicleFuelLogFormData.getVehicleFuelLogId() == 0) {
vehicleFuelLog = new VehicleFuelLog();
vehicleFuelLog.setActive(true);
} else {
vehicleFuelLog = this.vehicleFuelLogService.getVehicleFuelLog(saveVehicleFuelLogFormData.getVehicleFuelLogId());
}
vehicleFuelLog.setFuel(saveVehicleFuelLogFormData.getFuel());
vehicleFuelLog.setLogDate(saveVehicleFuelLogFormData.getLogDate());
vehicleFuelLog.setMissedFillup(saveVehicleFuelLogFormData.isMissedFillup());
vehicleFuelLog.setOctane(saveVehicleFuelLogFormData.getOctane());
vehicleFuelLog.setOdometer(saveVehicleFuelLogFormData.getOdometer());
vehicleFuelLog.setVehicleId(saveVehicleFuelLogFormData.getVehicleId());
this.vehicleFuelLogService.saveVehicleFuelLog(vehicleFuelLog);
+ model.addAttribute("vehicleFuelLogId", vehicleFuelLog.getVehicleFuelLogId());
}
model.addAttribute("errors", errors.getFieldErrors());
}
}
| true | true | public void saveVehicleFuelLog(@Valid SaveVehicleFuelLogFormData saveVehicleFuelLogFormData, BindingResult errors, Model model) {
org.springframework.security.core.userdetails.User securityUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = this.userService.getUser(Long.parseLong(securityUser.getUsername()));
if (!errors.hasFieldErrors()) {
VehicleFuelLog vehicleFuelLog = null;
if (saveVehicleFuelLogFormData.getVehicleFuelLogId() == 0) {
vehicleFuelLog = new VehicleFuelLog();
vehicleFuelLog.setActive(true);
} else {
vehicleFuelLog = this.vehicleFuelLogService.getVehicleFuelLog(saveVehicleFuelLogFormData.getVehicleFuelLogId());
}
vehicleFuelLog.setFuel(saveVehicleFuelLogFormData.getFuel());
vehicleFuelLog.setLogDate(saveVehicleFuelLogFormData.getLogDate());
vehicleFuelLog.setMissedFillup(saveVehicleFuelLogFormData.isMissedFillup());
vehicleFuelLog.setOctane(saveVehicleFuelLogFormData.getOctane());
vehicleFuelLog.setOdometer(saveVehicleFuelLogFormData.getOdometer());
vehicleFuelLog.setVehicleId(saveVehicleFuelLogFormData.getVehicleId());
this.vehicleFuelLogService.saveVehicleFuelLog(vehicleFuelLog);
}
model.addAttribute("errors", errors.getFieldErrors());
}
| public void saveVehicleFuelLog(@Valid SaveVehicleFuelLogFormData saveVehicleFuelLogFormData, BindingResult errors, Model model) {
org.springframework.security.core.userdetails.User securityUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = this.userService.getUser(Long.parseLong(securityUser.getUsername()));
if (!errors.hasFieldErrors()) {
VehicleFuelLog vehicleFuelLog = null;
if (saveVehicleFuelLogFormData.getVehicleFuelLogId() == 0) {
vehicleFuelLog = new VehicleFuelLog();
vehicleFuelLog.setActive(true);
} else {
vehicleFuelLog = this.vehicleFuelLogService.getVehicleFuelLog(saveVehicleFuelLogFormData.getVehicleFuelLogId());
}
vehicleFuelLog.setFuel(saveVehicleFuelLogFormData.getFuel());
vehicleFuelLog.setLogDate(saveVehicleFuelLogFormData.getLogDate());
vehicleFuelLog.setMissedFillup(saveVehicleFuelLogFormData.isMissedFillup());
vehicleFuelLog.setOctane(saveVehicleFuelLogFormData.getOctane());
vehicleFuelLog.setOdometer(saveVehicleFuelLogFormData.getOdometer());
vehicleFuelLog.setVehicleId(saveVehicleFuelLogFormData.getVehicleId());
this.vehicleFuelLogService.saveVehicleFuelLog(vehicleFuelLog);
model.addAttribute("vehicleFuelLogId", vehicleFuelLog.getVehicleFuelLogId());
}
model.addAttribute("errors", errors.getFieldErrors());
}
|
diff --git a/ps3mediaserver/net/pms/io/ProcessWrapperImpl.java b/ps3mediaserver/net/pms/io/ProcessWrapperImpl.java
index 6ced664e..c2d6b7ac 100644
--- a/ps3mediaserver/net/pms/io/ProcessWrapperImpl.java
+++ b/ps3mediaserver/net/pms/io/ProcessWrapperImpl.java
@@ -1,206 +1,206 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import net.pms.PMS;
import net.pms.encoders.AviDemuxerInputStream;
import net.pms.util.ProcessUtil;
public class ProcessWrapperImpl extends Thread implements ProcessWrapper {
@Override
public String toString() {
return super.getName();
}
private boolean success;
public boolean isSuccess() {
return success;
}
private String cmdLine;
private Process process;
private OutputConsumer outConsumer;
private OutputTextConsumer stderrConsumer;
private OutputParams params;
private boolean destroyed;
private String [] cmdArray;
private boolean nullable;
private ArrayList<ProcessWrapper> attachedProcesses;
private BufferedOutputFile bo = null;
public ProcessWrapperImpl(String cmdArray [], OutputParams params) {
super(cmdArray[0]);
File exec = new File(cmdArray[0]);
if (exec.exists() && exec.isFile())
cmdArray[0] = exec.getAbsolutePath();
this.cmdArray = cmdArray;
StringBuffer sb = new StringBuffer("");
for(int i=0;i<cmdArray.length;i++) {
if (i>0)
sb.append(" ");
sb.append(cmdArray[i]);
}
cmdLine = sb.toString();
this.params = params;
attachedProcesses = new ArrayList<ProcessWrapper>();
}
public void attachProcess(ProcessWrapper process) {
attachedProcesses.add(process);
}
public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
PMS.info("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory())
pb.directory(params.outputFile.getParentFile());
//process = pb.start();
process = Runtime.getRuntime().exec(cmdArray);
PMS.get().currentProcesses.add(process);
stderrConsumer = new OutputTextConsumer(process.getErrorStream(), true);
outConsumer = null;
if (params.outputFile != null) {
PMS.info("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = new OutputTextConsumer(process.getInputStream(), false);
} else if (params.input_pipes[0] != null) {
PMS.info("Reading pipe: " + params.input_pipes[0].getInputPipe());
//Thread.sleep(150);
bo = params.input_pipes[0].getDirectBuffer();
- if (bo == null) {
+ if (bo == null || params.losslessaudio || params.lossyaudio) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.losslessaudio||params.lossyaudio)?new AviDemuxerInputStream(is, params, attachedProcesses):is, params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextConsumer(process.getInputStream(), true).start();
} else if (params.log) {
outConsumer = new OutputTextConsumer(process.getInputStream(), true);
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
bo.attachThread(this);
}
stderrConsumer.start();
if (outConsumer != null)
outConsumer.start();
process.waitFor();
if (bo != null)
bo.close();
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process.exitValue() != 0) {
PMS.minimal("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occured... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
PMS.error("An error occured", itse);
}
}
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
PMS.get().currentProcesses.remove(process);
} catch (IOException e) {
PMS.error(null, e);
} catch (InterruptedException e) {
PMS.error(null, e);
}
}
public void runInNewThread() {
this.start();
}
public InputStream getInputStream(long seek) throws IOException {
if (bo != null)
return bo.getInputStream(seek);
else if (outConsumer != null && outConsumer.getBuffer() != null)
return outConsumer.getBuffer().getInputStream(seek);
else if (params.outputFile != null) {
BlockerFileInputStream fIn = new BlockerFileInputStream(this, params.outputFile, params.minFileSize);
fIn.skip(seek);
return fIn;
}
return null;
}
public List<String> getOtherResults() {
if (outConsumer == null)
return null;
return outConsumer.getResults();
}
public List<String> getResults() {
try {
stderrConsumer.join(1000);
} catch (InterruptedException e) {}
return stderrConsumer.getResults();
}
public void stopProcess() {
PMS.info("Stopping process: " + this);
destroyed = true;
if (process != null) {
ProcessUtil.destroy(process);
}
/*if (params != null && params.attachedPipeName != null) {
File pipe = new File(params.attachedPipeName);
if (pipe.exists()) {
if (pipe.delete())
pipe.deleteOnExit();
}
}*/
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
if (outConsumer != null && outConsumer.getBuffer() != null)
outConsumer.getBuffer().reset();
}
public boolean isDestroyed() {
return destroyed;
}
public boolean isReadyToStop() {
return nullable;
}
public void setReadyToStop(boolean nullable) {
if (nullable != this.nullable)
PMS.debug("Ready to Stop: " + nullable);
this.nullable = nullable;
}
}
| true | true | public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
PMS.info("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory())
pb.directory(params.outputFile.getParentFile());
//process = pb.start();
process = Runtime.getRuntime().exec(cmdArray);
PMS.get().currentProcesses.add(process);
stderrConsumer = new OutputTextConsumer(process.getErrorStream(), true);
outConsumer = null;
if (params.outputFile != null) {
PMS.info("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = new OutputTextConsumer(process.getInputStream(), false);
} else if (params.input_pipes[0] != null) {
PMS.info("Reading pipe: " + params.input_pipes[0].getInputPipe());
//Thread.sleep(150);
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.losslessaudio||params.lossyaudio)?new AviDemuxerInputStream(is, params, attachedProcesses):is, params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextConsumer(process.getInputStream(), true).start();
} else if (params.log) {
outConsumer = new OutputTextConsumer(process.getInputStream(), true);
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
bo.attachThread(this);
}
stderrConsumer.start();
if (outConsumer != null)
outConsumer.start();
process.waitFor();
if (bo != null)
bo.close();
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process.exitValue() != 0) {
PMS.minimal("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occured... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
PMS.error("An error occured", itse);
}
}
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
PMS.get().currentProcesses.remove(process);
} catch (IOException e) {
PMS.error(null, e);
} catch (InterruptedException e) {
PMS.error(null, e);
}
}
| public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
PMS.info("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory())
pb.directory(params.outputFile.getParentFile());
//process = pb.start();
process = Runtime.getRuntime().exec(cmdArray);
PMS.get().currentProcesses.add(process);
stderrConsumer = new OutputTextConsumer(process.getErrorStream(), true);
outConsumer = null;
if (params.outputFile != null) {
PMS.info("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = new OutputTextConsumer(process.getInputStream(), false);
} else if (params.input_pipes[0] != null) {
PMS.info("Reading pipe: " + params.input_pipes[0].getInputPipe());
//Thread.sleep(150);
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.losslessaudio||params.lossyaudio)?new AviDemuxerInputStream(is, params, attachedProcesses):is, params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextConsumer(process.getInputStream(), true).start();
} else if (params.log) {
outConsumer = new OutputTextConsumer(process.getInputStream(), true);
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
bo.attachThread(this);
}
stderrConsumer.start();
if (outConsumer != null)
outConsumer.start();
process.waitFor();
if (bo != null)
bo.close();
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process.exitValue() != 0) {
PMS.minimal("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occured... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
PMS.error("An error occured", itse);
}
}
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
PMS.get().currentProcesses.remove(process);
} catch (IOException e) {
PMS.error(null, e);
} catch (InterruptedException e) {
PMS.error(null, e);
}
}
|
diff --git a/src/msf/MsgRpcImpl.java b/src/msf/MsgRpcImpl.java
index 34c08a2..50c2a5a 100644
--- a/src/msf/MsgRpcImpl.java
+++ b/src/msf/MsgRpcImpl.java
@@ -1,146 +1,152 @@
package msf;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
import org.msgpack.*;
import org.msgpack.object.*;
/**
* Taken from BSD licensed msfgui by scriptjunkie.
*
* Implements an RPC backend using the MessagePack interface
* @author scriptjunkie
*/
public class MsgRpcImpl extends RpcConnectionImpl {
private URL u;
private URLConnection huc; // new for each call
protected int timeout = 0; /* scriptjunkie likes timeouts, I don't. :) */
/**
* Creates a new URL to use as the basis of a connection.
*/
public MsgRpcImpl(String username, String password, String host, int port, boolean ssl, boolean debugf) throws MalformedURLException {
if (ssl) { // Install the all-trusting trust manager & HostnameVerifier
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
}, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() {
public boolean verify(String string,SSLSession ssls) {
return true;
}
});
}
catch (Exception e) {
}
u = new URL("https", host, port, "/api/1.0/");
}
else {
u = new URL("http", host, port, "/api/1.0/");
}
/* login to msf server */
Object[] params = new Object[]{ username, password };
Map results = exec("auth.login",params);
/* save the temp token (lasts for 5 minutes of inactivity) */
rpcToken = results.get("token").toString();
/* generate a non-expiring token and use that */
params = new Object[]{ rpcToken };
results = exec("auth.token_generate", params);
rpcToken = results.get("token").toString();
}
/**
* Decodes a response recursively from MessagePackObject to a normal Java object
* @param src MessagePack response
* @return decoded object
*/
private static Object unMsg(Object src){
Object out = src;
if (src instanceof ArrayType) {
List l = ((ArrayType)src).asList();
List outList = new ArrayList(l.size());
out = outList;
for(Object o : l)
outList.add(unMsg(o));
}
else if (src instanceof BooleanType) {
out = ((BooleanType)src).asBoolean();
}
else if (src instanceof FloatType) {
out = ((FloatType)src).asFloat();
}
else if (src instanceof IntegerType) {
- out = ((IntegerType)src).asInt();
+ try {
+ out = ((IntegerType)src).asInt();
+ }
+ catch (Exception ex) {
+ /* this is a bandaid until I have a chance to further examine what's happening */
+ out = ((IntegerType)src).asLong();
+ }
}
else if (src instanceof MapType) {
Set ents = ((MapType)src).asMap().entrySet();
out = new HashMap();
for (Object ento : ents) {
Map.Entry ent = (Map.Entry)ento;
Object key = unMsg(ent.getKey());
Object val = ent.getValue();
// Hack - keep bytes of generated or encoded payload
if(ents.size() == 1 && val instanceof RawType && (key.equals("payload") || key.equals("encoded")))
val = ((RawType)val).asByteArray();
else
val = unMsg(val);
((Map)out).put(key + "", val);
}
if (((Map)out).containsKey("error") && ((Map)out).containsKey("error_class")) {
System.out.println(((Map)out).get("error_backtrace"));
throw new RuntimeException(((Map)out).get("error_message").toString());
}
}
else if (src instanceof NilType) {
out = null;
}
else if (src instanceof RawType) {
out = ((RawType)src).asString();
}
return out;
}
/** Creates an XMLRPC call from the given method name and parameters and sends it */
protected void writeCall(String methodName, Object[] args) throws Exception {
huc = u.openConnection();
huc.setDoOutput(true);
huc.setDoInput(true);
huc.setUseCaches(false);
huc.setRequestProperty("Content-Type", "binary/message-pack");
huc.setReadTimeout(0);
OutputStream os = huc.getOutputStream();
Packer pk = new Packer(os);
pk.packArray(args.length+1);
pk.pack(methodName);
for(Object o : args)
pk.pack(o);
os.close();
}
/** Receives an RPC response and converts to an object */
protected Object readResp() throws Exception {
InputStream is = huc.getInputStream();
MessagePackObject mpo = MessagePack.unpack(is);
return unMsg(mpo);
}
}
| true | true | private static Object unMsg(Object src){
Object out = src;
if (src instanceof ArrayType) {
List l = ((ArrayType)src).asList();
List outList = new ArrayList(l.size());
out = outList;
for(Object o : l)
outList.add(unMsg(o));
}
else if (src instanceof BooleanType) {
out = ((BooleanType)src).asBoolean();
}
else if (src instanceof FloatType) {
out = ((FloatType)src).asFloat();
}
else if (src instanceof IntegerType) {
out = ((IntegerType)src).asInt();
}
else if (src instanceof MapType) {
Set ents = ((MapType)src).asMap().entrySet();
out = new HashMap();
for (Object ento : ents) {
Map.Entry ent = (Map.Entry)ento;
Object key = unMsg(ent.getKey());
Object val = ent.getValue();
// Hack - keep bytes of generated or encoded payload
if(ents.size() == 1 && val instanceof RawType && (key.equals("payload") || key.equals("encoded")))
val = ((RawType)val).asByteArray();
else
val = unMsg(val);
((Map)out).put(key + "", val);
}
if (((Map)out).containsKey("error") && ((Map)out).containsKey("error_class")) {
System.out.println(((Map)out).get("error_backtrace"));
throw new RuntimeException(((Map)out).get("error_message").toString());
}
}
else if (src instanceof NilType) {
out = null;
}
else if (src instanceof RawType) {
out = ((RawType)src).asString();
}
return out;
}
| private static Object unMsg(Object src){
Object out = src;
if (src instanceof ArrayType) {
List l = ((ArrayType)src).asList();
List outList = new ArrayList(l.size());
out = outList;
for(Object o : l)
outList.add(unMsg(o));
}
else if (src instanceof BooleanType) {
out = ((BooleanType)src).asBoolean();
}
else if (src instanceof FloatType) {
out = ((FloatType)src).asFloat();
}
else if (src instanceof IntegerType) {
try {
out = ((IntegerType)src).asInt();
}
catch (Exception ex) {
/* this is a bandaid until I have a chance to further examine what's happening */
out = ((IntegerType)src).asLong();
}
}
else if (src instanceof MapType) {
Set ents = ((MapType)src).asMap().entrySet();
out = new HashMap();
for (Object ento : ents) {
Map.Entry ent = (Map.Entry)ento;
Object key = unMsg(ent.getKey());
Object val = ent.getValue();
// Hack - keep bytes of generated or encoded payload
if(ents.size() == 1 && val instanceof RawType && (key.equals("payload") || key.equals("encoded")))
val = ((RawType)val).asByteArray();
else
val = unMsg(val);
((Map)out).put(key + "", val);
}
if (((Map)out).containsKey("error") && ((Map)out).containsKey("error_class")) {
System.out.println(((Map)out).get("error_backtrace"));
throw new RuntimeException(((Map)out).get("error_message").toString());
}
}
else if (src instanceof NilType) {
out = null;
}
else if (src instanceof RawType) {
out = ((RawType)src).asString();
}
return out;
}
|
diff --git a/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetAclRuleByIdTestCases.java b/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetAclRuleByIdTestCases.java
index 9c8b2b02..799d76a7 100644
--- a/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetAclRuleByIdTestCases.java
+++ b/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetAclRuleByIdTestCases.java
@@ -1,93 +1,93 @@
/**
* Mule Google Calendars Cloud Connector
*
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.module.google.calendar.automation.testcases;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mule.api.MuleEvent;
import org.mule.api.processor.MessageProcessor;
import org.mule.module.google.calendar.model.AclRule;
import org.mule.module.google.calendar.model.Calendar;
public class GetAclRuleByIdTestCases extends GoogleCalendarTestParent {
@Before
public void setUp() {
try {
- testObjects = (Map<String, Object>) context.getBean("insertAclRule");
+ testObjects = (Map<String, Object>) context.getBean("getAclRuleById");
// Insert calendar and get reference to retrieved calendar
Calendar calendar = insertCalendar((Calendar) testObjects.get("calendarRef"));
// Replace old calendar instance with new instance
testObjects.put("calendarRef", calendar);
testObjects.put("calendarId", calendar.getId());
// Insert the ACL rule
MessageProcessor flow = lookupFlowConstruct("insert-acl-rule");
MuleEvent event = flow.process(getTestEvent(testObjects));
AclRule returnedAclRule = (AclRule) event.getMessage().getPayload();
testObjects.put("aclRule", returnedAclRule);
testObjects.put("ruleId", returnedAclRule.getId());
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Category({SmokeTests.class, RegressionTests.class})
@Test
public void testGetAclRuleById() {
try {
String ruleIdBefore = testObjects.get("ruleId").toString();
MessageProcessor flow = lookupFlowConstruct("get-acl-rule-by-id");
MuleEvent event = flow.process(getTestEvent(testObjects));
AclRule afterProc = (AclRule) event.getMessage().getPayload();
String ruleIdAfter = afterProc.getId();
assertEquals(ruleIdBefore,ruleIdAfter);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
@After
public void tearDown() {
try {
String calendarId = testObjects.get("calendarId").toString();
deleteCalendar(calendarId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| true | true | public void setUp() {
try {
testObjects = (Map<String, Object>) context.getBean("insertAclRule");
// Insert calendar and get reference to retrieved calendar
Calendar calendar = insertCalendar((Calendar) testObjects.get("calendarRef"));
// Replace old calendar instance with new instance
testObjects.put("calendarRef", calendar);
testObjects.put("calendarId", calendar.getId());
// Insert the ACL rule
MessageProcessor flow = lookupFlowConstruct("insert-acl-rule");
MuleEvent event = flow.process(getTestEvent(testObjects));
AclRule returnedAclRule = (AclRule) event.getMessage().getPayload();
testObjects.put("aclRule", returnedAclRule);
testObjects.put("ruleId", returnedAclRule.getId());
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
| public void setUp() {
try {
testObjects = (Map<String, Object>) context.getBean("getAclRuleById");
// Insert calendar and get reference to retrieved calendar
Calendar calendar = insertCalendar((Calendar) testObjects.get("calendarRef"));
// Replace old calendar instance with new instance
testObjects.put("calendarRef", calendar);
testObjects.put("calendarId", calendar.getId());
// Insert the ACL rule
MessageProcessor flow = lookupFlowConstruct("insert-acl-rule");
MuleEvent event = flow.process(getTestEvent(testObjects));
AclRule returnedAclRule = (AclRule) event.getMessage().getPayload();
testObjects.put("aclRule", returnedAclRule);
testObjects.put("ruleId", returnedAclRule.getId());
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
diff --git a/webapp/app/controllers/modules2/framework/procs/StreamsProcessor.java b/webapp/app/controllers/modules2/framework/procs/StreamsProcessor.java
index 14bbc4fd..6020ec2f 100644
--- a/webapp/app/controllers/modules2/framework/procs/StreamsProcessor.java
+++ b/webapp/app/controllers/modules2/framework/procs/StreamsProcessor.java
@@ -1,182 +1,182 @@
package controllers.modules2.framework.procs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.mvc.results.BadRequest;
import play.mvc.results.NotFound;
import models.StreamAggregation;
import models.message.ChartVarMeta;
import com.alvazan.play.NoSql;
import controllers.modules2.framework.ReadResult;
import controllers.modules2.framework.TSRelational;
import controllers.modules2.framework.VisitorInfo;
public abstract class StreamsProcessor extends PullProcessorAbstract {
protected Long currentTimePointer;
protected List<PullProcessor> children = new ArrayList<PullProcessor>();
protected List<ProxyProcessor> processors = new ArrayList<ProxyProcessor>();
protected List<String> urls;
private List<ReadResult> results = new ArrayList<ReadResult>();
private String aggName;
private static Map<String, ChartVarMeta> parameterMeta = new HashMap<String, ChartVarMeta>();
@Override
public Map<String, ChartVarMeta> getParameterMeta() {
//This needs to be an EMPTY map since there are a few subclasses....if you need stuff in the Map, create your
//own in the subclass so you don't screw up the other modules subclassing this StreamsProcessor
return parameterMeta ;
}
@Override
public String toString() {
String msg = getClass().getSimpleName()+":"+children;
return msg;
}
@Override
protected int getNumParams() {
return 1;
}
@Override
public void start(VisitorInfo visitor) {
for(ProcessorSetup p : children) {
p.start(visitor);
}
}
@Override
public String init(String path, ProcessorSetup nextInChain,
VisitorInfo visitor, HashMap<String, String> options) {
String newPath = super.init(path, nextInChain, visitor, options);
List<String> params2 = params.getParams();
aggName = params2.get(0);
StreamAggregation agg = NoSql.em().find(StreamAggregation.class, aggName);
if(agg == null)
throw new NotFound("Aggregation named="+aggName+" was not found");
urls = agg.getUrls();
if(urls.size() == 0)
throw new NotFound("Aggregation named="+aggName+" has not paths that we can read from");
return newPath;
}
@Override
public List<String> getAggregationList() {
List<String> aggregationList;
if (parent != null)
aggregationList = parent.getAggregationList();
else
aggregationList = new ArrayList<String>();
aggregationList.add(aggName);
return aggregationList;
}
@Override
public ProcessorSetup createPipeline(String path, VisitorInfo visitor, ProcessorSetup useThisChild, boolean alreadyAddedInverter) {
Long start = params.getOriginalStart();
Long end = params.getOriginalEnd();
List<String> aggregationList = parent.getAggregationList();
if (aggregationList.contains(aggName)) {
aggregationList.add(aggName);
- throw new BadRequest("Your aggregation is trying to do an infinite loop back to itself. List of urls:"+visitor.getAggregationList());
+ throw new BadRequest("Your aggregation is trying to do an infinite loop back to itself. List of urls:"+aggregationList);
}
else if (aggregationList.size() > 5) {
aggregationList.add(aggName);
- throw new BadRequest("Your aggregation is trying to do too deep a reference stack. List of urls:"+visitor.getAggregationList());
+ throw new BadRequest("Your aggregation is trying to do too deep a reference stack. List of urls:"+aggregationList);
}
for(String url : urls) {
String newUrl = addTimeStamps(url, start, end);
ProcessorSetup child = super.createPipeline(newUrl, visitor, null, false);
children.add((PullProcessor) child);
processors.add(new ProxyProcessor((PullProcessor)child));
}
return null;
}
private String addTimeStamps(String url, Long start, Long end) {
if(url.startsWith("/"))
url = url.substring(1);
return url+"/"+start+"/"+end;
}
@Override
public ReadResult read() {
List<ReadResult> rows = readAllRows();
if(rows == null)
return null;
long min = calculate(rows);
List<TSRelational> toProcess = find(rows, min);
clearResults();
return process(toProcess);
}
protected void clearResults() {
results.clear();
}
protected List<TSRelational> find(List<ReadResult> rows, long min) {
List<TSRelational> toProcess = new ArrayList<TSRelational>();
for(int i = 0; i < rows.size(); i++) {
ProxyProcessor proxy = processors.get(i);
ReadResult res = rows.get(i);
if(res.getRow() != null) {
long time = getTime(res.getRow());
if(min == time) {
proxy.read(); //make sure we read and discard the value we are about to process
toProcess.add(res.getRow());
} else
toProcess.add(null);
} else
toProcess.add(null);
}
return toProcess;
}
protected long calculate(List<ReadResult> rows) {
long min = Long.MAX_VALUE;
for(ReadResult res : rows) {
if(res.getRow() != null) {
long time = getTime(res.getRow());
min = Math.min(time, min);
}
}
return min;
}
protected List<ReadResult> readAllRows() {
int numChildrenRead = results.size();
//This will pick up where we left off the first time....
for(int i = numChildrenRead; i < children.size(); i++) {
ProxyProcessor proc = processors.get(i);
ReadResult result = proc.peek();
if(result == null)
return null;
results.add(result);
}
return results;
}
protected abstract ReadResult process(List<TSRelational> results);
}
| false | true | public ProcessorSetup createPipeline(String path, VisitorInfo visitor, ProcessorSetup useThisChild, boolean alreadyAddedInverter) {
Long start = params.getOriginalStart();
Long end = params.getOriginalEnd();
List<String> aggregationList = parent.getAggregationList();
if (aggregationList.contains(aggName)) {
aggregationList.add(aggName);
throw new BadRequest("Your aggregation is trying to do an infinite loop back to itself. List of urls:"+visitor.getAggregationList());
}
else if (aggregationList.size() > 5) {
aggregationList.add(aggName);
throw new BadRequest("Your aggregation is trying to do too deep a reference stack. List of urls:"+visitor.getAggregationList());
}
for(String url : urls) {
String newUrl = addTimeStamps(url, start, end);
ProcessorSetup child = super.createPipeline(newUrl, visitor, null, false);
children.add((PullProcessor) child);
processors.add(new ProxyProcessor((PullProcessor)child));
}
return null;
}
| public ProcessorSetup createPipeline(String path, VisitorInfo visitor, ProcessorSetup useThisChild, boolean alreadyAddedInverter) {
Long start = params.getOriginalStart();
Long end = params.getOriginalEnd();
List<String> aggregationList = parent.getAggregationList();
if (aggregationList.contains(aggName)) {
aggregationList.add(aggName);
throw new BadRequest("Your aggregation is trying to do an infinite loop back to itself. List of urls:"+aggregationList);
}
else if (aggregationList.size() > 5) {
aggregationList.add(aggName);
throw new BadRequest("Your aggregation is trying to do too deep a reference stack. List of urls:"+aggregationList);
}
for(String url : urls) {
String newUrl = addTimeStamps(url, start, end);
ProcessorSetup child = super.createPipeline(newUrl, visitor, null, false);
children.add((PullProcessor) child);
processors.add(new ProxyProcessor((PullProcessor)child));
}
return null;
}
|
diff --git a/src/main/java/org/spout/api/plugin/CommonPluginLoader.java b/src/main/java/org/spout/api/plugin/CommonPluginLoader.java
index d1dfe1d96..5228132b2 100644
--- a/src/main/java/org/spout/api/plugin/CommonPluginLoader.java
+++ b/src/main/java/org/spout/api/plugin/CommonPluginLoader.java
@@ -1,322 +1,323 @@
/*
* This file is part of SpoutAPI.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* SpoutAPI is licensed under the SpoutDev License Version 1.
*
* SpoutAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* SpoutAPI 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.api.plugin;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.spout.api.Engine;
import org.spout.api.Spout;
import org.spout.api.UnsafeMethod;
import org.spout.api.event.server.plugin.PluginDisableEvent;
import org.spout.api.event.server.plugin.PluginEnableEvent;
import org.spout.api.exception.InvalidDescriptionFileException;
import org.spout.api.exception.InvalidPluginException;
import org.spout.api.exception.UnknownDependencyException;
import org.spout.api.exception.UnknownSoftDependencyException;
import org.spout.api.plugin.security.CommonSecurityManager;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class CommonPluginLoader implements PluginLoader {
public static final String YAML_SPOUT = "properties.yml";
public static final String YAML_OTHER = "plugin.yml";
protected final Engine engine;
private final Pattern[] patterns;
private final CommonSecurityManager manager;
private final double key;
@SuppressWarnings("unchecked")
private final Map<String, CommonClassLoader> loaders = new CaseInsensitiveMap();
public CommonPluginLoader(final Engine engine, final CommonSecurityManager manager, final double key) {
this.engine = engine;
this.manager = manager;
this.key = key;
patterns = new Pattern[]{Pattern.compile("\\.jar$")};
}
@Override
public Pattern[] getPatterns() {
return patterns;
}
@Override
@UnsafeMethod
public synchronized void enablePlugin(Plugin plugin) {
if (!CommonPlugin.class.isAssignableFrom(plugin.getClass())) {
throw new IllegalArgumentException("Cannot enable plugin with this PluginLoader as it is of the wrong type!");
}
if (!plugin.isEnabled()) {
CommonPlugin cp = (CommonPlugin) plugin;
String name = cp.getDescription().getName();
if (!loaders.containsKey(name)) {
loaders.put(name, (CommonClassLoader) cp.getClassLoader());
}
try {
cp.setEnabled(true);
cp.onEnable();
} catch (Throwable e) {
engine.getLogger().log(Level.SEVERE, "An error occured when enabling '" + plugin.getDescription().getFullName() + "': " + e.getMessage(), e);
}
engine.getEventManager().callEvent(new PluginEnableEvent(cp));
}
}
@Override
@UnsafeMethod
public synchronized void disablePlugin(Plugin paramPlugin) {
if (!CommonPlugin.class.isAssignableFrom(paramPlugin.getClass())) {
throw new IllegalArgumentException("Cannot disable plugin with this PluginLoader as it is of the wrong type!");
}
if (paramPlugin.isEnabled()) {
CommonPlugin cp = (CommonPlugin) paramPlugin;
String name = cp.getDescription().getName();
if (!loaders.containsKey(name)) {
loaders.put(name, (CommonClassLoader) cp.getClassLoader());
}
try {
cp.setEnabled(false);
cp.onDisable();
} catch (Throwable t) {
engine.getLogger().log(Level.SEVERE, "An error occurred when disabling plugin '" + paramPlugin.getDescription().getFullName() + "' : " + t.getMessage(), t);
}
engine.getEventManager().callEvent(new PluginDisableEvent(cp));
}
}
@Override
public synchronized Plugin loadPlugin(File paramFile) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException {
return loadPlugin(paramFile, false);
}
@Override
public synchronized Plugin loadPlugin(File paramFile, boolean ignoresoftdepends) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException {
CommonPlugin result;
PluginDescriptionFile desc;
CommonClassLoader loader;
desc = getDescription(paramFile);
File dataFolder = new File(paramFile.getParentFile(), desc.getName());
processDependencies(desc);
if (!ignoresoftdepends) {
processSoftDependencies(desc);
}
try {
if (engine.getPlatform() == Platform.CLIENT) {
loader = new ClientClassLoader(this, this.getClass().getClassLoader());
} else {
loader = new CommonClassLoader(this, this.getClass().getClassLoader());
}
loader.addURL(paramFile.toURI().toURL());
Class<?> main = Class.forName(desc.getMain(), true, loader);
Class<? extends CommonPlugin> plugin = main.asSubclass(CommonPlugin.class);
boolean locked = manager.lock(key);
Constructor<? extends CommonPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, engine, desc, dataFolder, paramFile, loader);
if (!locked) {
manager.unlock(key);
}
} catch (Exception e) {
throw new InvalidPluginException(e);
} catch (UnsupportedClassVersionError e) {
String version = e.getMessage().replaceFirst("Unsupported major.minor version ", "").split(" ")[0];
Spout.getLogger().severe("Plugin " + desc.getName() + " is built for a newer Java version than your current installation, and cannot be loaded!");
Spout.getLogger().severe("To run " + desc.getName() + ", you need Java version " + version + " or higher!");
+ throw new InvalidPluginException(e);
}
loader.setPlugin(result);
loaders.put(desc.getName(), loader);
return result;
}
/**
* @param description Plugin description element
* @throws UnknownSoftDependencyException
*/
protected synchronized void processSoftDependencies(PluginDescriptionFile description) throws UnknownSoftDependencyException {
List<String> softdepend = description.getSoftDepends();
if (softdepend == null) {
softdepend = new ArrayList<String>();
}
for (String depend : softdepend) {
if (loaders == null) {
throw new UnknownSoftDependencyException(depend);
}
if (!loaders.containsKey(depend)) {
throw new UnknownSoftDependencyException(depend);
}
}
}
/**
* @param desc Plugin description element
* @throws UnknownDependencyException
*/
protected synchronized void processDependencies(PluginDescriptionFile desc) throws UnknownDependencyException {
List<String> depends = desc.getDepends();
if (depends == null) {
depends = new ArrayList<String>();
}
for (String depend : depends) {
if (loaders == null) {
throw new UnknownDependencyException(depend);
}
if (!loaders.containsKey(depend)) {
throw new UnknownDependencyException(depend);
}
}
}
/**
* @param file Plugin file object
* @return The current plugin's description element.
*
* @throws InvalidPluginException
* @throws InvalidDescriptionFileException
*/
protected synchronized PluginDescriptionFile getDescription(File file) throws InvalidPluginException, InvalidDescriptionFileException {
if (!file.exists()) {
throw new InvalidPluginException(file.getName() + " does not exist!");
}
PluginDescriptionFile description = null;
JarFile jar = null;
InputStream in = null;
try {
// Spout plugin properties file
jar = new JarFile(file);
JarEntry entry = jar.getJarEntry(YAML_SPOUT);
// Fallback plugin properties file
if (entry == null) {
entry = jar.getJarEntry(YAML_OTHER);
}
if (entry == null) {
throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
}
in = jar.getInputStream(entry);
description = new PluginDescriptionFile(in);
} catch (IOException e) {
throw new InvalidPluginException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
engine.getLogger().log(Level.WARNING, "Problem closing input stream", e);
}
}
if (jar != null) {
try {
jar.close();
} catch (IOException e) {
engine.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
}
}
}
return description;
}
protected Class<?> getClassByName(final String name, final CommonClassLoader commonLoader) {
CommonPlugin plugin = commonLoader.getPlugin();
Set<String> ignore = new HashSet<String>();
ignore.add(plugin.getName());
if (plugin.getDescription().getDepends() != null) {
for (String dependency : plugin.getDescription().getDepends()) {
try {
Class<?> clazz = loaders.get(dependency).findClass(name, false);
if (clazz != null) {
return clazz;
}
} catch (ClassNotFoundException ignored) {
}
ignore.add(dependency);
}
}
if (plugin.getDescription().getSoftDepends() != null) {
for (String softDependency : plugin.getDescription().getSoftDepends()) {
try {
Class<?> clazz = loaders.get(softDependency).findClass(name, false);
if (clazz != null) {
return clazz;
}
} catch (ClassNotFoundException ignored) {
}
ignore.add(softDependency);
}
}
for (String current : loaders.keySet()) {
if (ignore.contains(current)) {
continue;
}
CommonClassLoader loader = loaders.get(current);
try {
Class<?> clazz = loader.findClass(name, false);
if (clazz != null) {
return clazz;
}
} catch (ClassNotFoundException ignored) {
}
}
return null;
}
}
| true | true | public synchronized Plugin loadPlugin(File paramFile, boolean ignoresoftdepends) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException {
CommonPlugin result;
PluginDescriptionFile desc;
CommonClassLoader loader;
desc = getDescription(paramFile);
File dataFolder = new File(paramFile.getParentFile(), desc.getName());
processDependencies(desc);
if (!ignoresoftdepends) {
processSoftDependencies(desc);
}
try {
if (engine.getPlatform() == Platform.CLIENT) {
loader = new ClientClassLoader(this, this.getClass().getClassLoader());
} else {
loader = new CommonClassLoader(this, this.getClass().getClassLoader());
}
loader.addURL(paramFile.toURI().toURL());
Class<?> main = Class.forName(desc.getMain(), true, loader);
Class<? extends CommonPlugin> plugin = main.asSubclass(CommonPlugin.class);
boolean locked = manager.lock(key);
Constructor<? extends CommonPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, engine, desc, dataFolder, paramFile, loader);
if (!locked) {
manager.unlock(key);
}
} catch (Exception e) {
throw new InvalidPluginException(e);
} catch (UnsupportedClassVersionError e) {
String version = e.getMessage().replaceFirst("Unsupported major.minor version ", "").split(" ")[0];
Spout.getLogger().severe("Plugin " + desc.getName() + " is built for a newer Java version than your current installation, and cannot be loaded!");
Spout.getLogger().severe("To run " + desc.getName() + ", you need Java version " + version + " or higher!");
}
loader.setPlugin(result);
loaders.put(desc.getName(), loader);
return result;
}
| public synchronized Plugin loadPlugin(File paramFile, boolean ignoresoftdepends) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException {
CommonPlugin result;
PluginDescriptionFile desc;
CommonClassLoader loader;
desc = getDescription(paramFile);
File dataFolder = new File(paramFile.getParentFile(), desc.getName());
processDependencies(desc);
if (!ignoresoftdepends) {
processSoftDependencies(desc);
}
try {
if (engine.getPlatform() == Platform.CLIENT) {
loader = new ClientClassLoader(this, this.getClass().getClassLoader());
} else {
loader = new CommonClassLoader(this, this.getClass().getClassLoader());
}
loader.addURL(paramFile.toURI().toURL());
Class<?> main = Class.forName(desc.getMain(), true, loader);
Class<? extends CommonPlugin> plugin = main.asSubclass(CommonPlugin.class);
boolean locked = manager.lock(key);
Constructor<? extends CommonPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, engine, desc, dataFolder, paramFile, loader);
if (!locked) {
manager.unlock(key);
}
} catch (Exception e) {
throw new InvalidPluginException(e);
} catch (UnsupportedClassVersionError e) {
String version = e.getMessage().replaceFirst("Unsupported major.minor version ", "").split(" ")[0];
Spout.getLogger().severe("Plugin " + desc.getName() + " is built for a newer Java version than your current installation, and cannot be loaded!");
Spout.getLogger().severe("To run " + desc.getName() + ", you need Java version " + version + " or higher!");
throw new InvalidPluginException(e);
}
loader.setPlugin(result);
loaders.put(desc.getName(), loader);
return result;
}
|
diff --git a/src/filter/FilterByKeyword.java b/src/filter/FilterByKeyword.java
index 5d1cea0..145ab25 100644
--- a/src/filter/FilterByKeyword.java
+++ b/src/filter/FilterByKeyword.java
@@ -1,41 +1,41 @@
package filter;
import java.util.List;
import java.util.PropertyResourceBundle;
import event.Event;
import exception.TivooEventKeywordNotFound;
public class FilterByKeyword extends FilterDecorator
{
private String myKeyword;
public FilterByKeyword (String keyword)
{
super();
myKeyword = keyword;
}
@Override
public void filter (List<Event> list)
{
List<Event> decoratedList = decoratedFilterWork(list);
for (Event entry : decoratedList)
{
try
{
- if (entry.containsKeyword(entry.get("title"), myKeyword))
+ if (entry.containsKeyword("title", myKeyword))
{
myFilteredList.add(entry);
}
}
catch (TivooEventKeywordNotFound e)
{
myFilteredList.add(entry);
}
}
}
}
| true | true | public void filter (List<Event> list)
{
List<Event> decoratedList = decoratedFilterWork(list);
for (Event entry : decoratedList)
{
try
{
if (entry.containsKeyword(entry.get("title"), myKeyword))
{
myFilteredList.add(entry);
}
}
catch (TivooEventKeywordNotFound e)
{
myFilteredList.add(entry);
}
}
}
| public void filter (List<Event> list)
{
List<Event> decoratedList = decoratedFilterWork(list);
for (Event entry : decoratedList)
{
try
{
if (entry.containsKeyword("title", myKeyword))
{
myFilteredList.add(entry);
}
}
catch (TivooEventKeywordNotFound e)
{
myFilteredList.add(entry);
}
}
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/security/SecurityCleanupEventInspector.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/security/SecurityCleanupEventInspector.java
index da8db3615..2e03f9e92 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/security/SecurityCleanupEventInspector.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/security/SecurityCleanupEventInspector.java
@@ -1,88 +1,89 @@
package org.sonatype.nexus.security;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.sonatype.nexus.jsecurity.realms.TargetPrivilegeDescriptor;
import org.sonatype.nexus.jsecurity.realms.TargetPrivilegeGroupPropertyDescriptor;
import org.sonatype.nexus.jsecurity.realms.TargetPrivilegeRepositoryPropertyDescriptor;
import org.sonatype.nexus.proxy.events.EventInspector;
import org.sonatype.nexus.proxy.events.RepositoryRegistryEventRemove;
import org.sonatype.plexus.appevents.Event;
import org.sonatype.security.SecuritySystem;
import org.sonatype.security.authorization.NoSuchAuthorizationManager;
import org.sonatype.security.authorization.NoSuchPrivilegeException;
import org.sonatype.security.authorization.Privilege;
import org.sonatype.security.authorization.xml.SecurityXmlAuthorizationManager;
import org.sonatype.security.realms.tools.ConfigurationManager;
@Component( role = EventInspector.class, hint = "SecurityCleanupEventInspector" )
public class SecurityCleanupEventInspector
extends AbstractLogEnabled
implements EventInspector
{
@Requirement( hint = "default" )
private ConfigurationManager configManager;
@Requirement
private SecuritySystem security;
public boolean accepts( Event<?> evt )
{
return evt instanceof RepositoryRegistryEventRemove;
}
public void inspect( Event<?> evt )
{
if ( evt instanceof RepositoryRegistryEventRemove )
{
RepositoryRegistryEventRemove rEvt = ( RepositoryRegistryEventRemove ) evt;
String repositoryId = rEvt.getRepository().getId();
try
{
cleanupPrivileges( repositoryId );
}
catch ( NoSuchPrivilegeException e )
{
getLogger().error( "Unable to clean privileges attached to repository", e );
}
catch ( NoSuchAuthorizationManager e )
{
getLogger().error( "Unable to clean privileges attached to repository", e );
}
}
}
protected void cleanupPrivileges( String repositoryId )
throws NoSuchPrivilegeException,
NoSuchAuthorizationManager
{
Set<Privilege> privileges = security.listPrivileges();
Set<String> removedIds = new HashSet<String>();
for ( Privilege privilege : privileges )
{
// Delete target privs that match repo/groupId
- if ( privilege.getType().equals( TargetPrivilegeDescriptor.TYPE )
+ if ( !privilege.isReadOnly()
+ && privilege.getType().equals( TargetPrivilegeDescriptor.TYPE )
&& ( repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeRepositoryPropertyDescriptor.ID ) )
|| repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeGroupPropertyDescriptor.ID ) ) ) )
{
getLogger().debug( "Removing Privilege " + privilege.getName() + " because repository was removed" );
security.getAuthorizationManager( SecurityXmlAuthorizationManager.SOURCE ).deletePrivilege( privilege.getId() );
removedIds.add( privilege.getId() );
}
}
for ( String privilegeId : removedIds )
{
configManager.cleanRemovedPrivilege( privilegeId );
}
configManager.save();
}
}
| true | true | protected void cleanupPrivileges( String repositoryId )
throws NoSuchPrivilegeException,
NoSuchAuthorizationManager
{
Set<Privilege> privileges = security.listPrivileges();
Set<String> removedIds = new HashSet<String>();
for ( Privilege privilege : privileges )
{
// Delete target privs that match repo/groupId
if ( privilege.getType().equals( TargetPrivilegeDescriptor.TYPE )
&& ( repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeRepositoryPropertyDescriptor.ID ) )
|| repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeGroupPropertyDescriptor.ID ) ) ) )
{
getLogger().debug( "Removing Privilege " + privilege.getName() + " because repository was removed" );
security.getAuthorizationManager( SecurityXmlAuthorizationManager.SOURCE ).deletePrivilege( privilege.getId() );
removedIds.add( privilege.getId() );
}
}
for ( String privilegeId : removedIds )
{
configManager.cleanRemovedPrivilege( privilegeId );
}
configManager.save();
}
| protected void cleanupPrivileges( String repositoryId )
throws NoSuchPrivilegeException,
NoSuchAuthorizationManager
{
Set<Privilege> privileges = security.listPrivileges();
Set<String> removedIds = new HashSet<String>();
for ( Privilege privilege : privileges )
{
// Delete target privs that match repo/groupId
if ( !privilege.isReadOnly()
&& privilege.getType().equals( TargetPrivilegeDescriptor.TYPE )
&& ( repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeRepositoryPropertyDescriptor.ID ) )
|| repositoryId.equals( privilege.getPrivilegeProperty( TargetPrivilegeGroupPropertyDescriptor.ID ) ) ) )
{
getLogger().debug( "Removing Privilege " + privilege.getName() + " because repository was removed" );
security.getAuthorizationManager( SecurityXmlAuthorizationManager.SOURCE ).deletePrivilege( privilege.getId() );
removedIds.add( privilege.getId() );
}
}
for ( String privilegeId : removedIds )
{
configManager.cleanRemovedPrivilege( privilegeId );
}
configManager.save();
}
|
diff --git a/play-test-overall-scenario-simulator/src/main/java/org/ow2/play/test/TweetSimulator.java b/play-test-overall-scenario-simulator/src/main/java/org/ow2/play/test/TweetSimulator.java
index 5135786..d615ad4 100644
--- a/play-test-overall-scenario-simulator/src/main/java/org/ow2/play/test/TweetSimulator.java
+++ b/play-test-overall-scenario-simulator/src/main/java/org/ow2/play/test/TweetSimulator.java
@@ -1,92 +1,92 @@
package org.ow2.play.test;
import java.util.Iterator;
import org.event_processing.events.types.TwitterEvent;
import org.ontoware.aifbcommons.collection.ClosableIterator;
import org.ontoware.rdf2go.model.Model;
import org.ontoware.rdf2go.model.QueryResultTable;
import org.ontoware.rdf2go.model.QueryRow;
import org.ontoware.rdf2go.model.node.URI;
import org.ontoware.rdf2go.model.node.Variable;
import org.ontoware.rdf2go.model.node.impl.URIImpl;
import org.ontoware.rdf2go.vocabulary.RDF;
import org.openrdf.rdf2go.RepositoryModelSet;
import eu.play_project.play_commons.constants.Event;
import eu.play_project.play_commons.constants.Namespace;
public class TweetSimulator implements Iterator<Model> {
private final RepositoryModelSet dataSet;
private final ClosableIterator<QueryRow> eventIds;
private final URI eventType;
private URI currentGraphUri;
public TweetSimulator(RepositoryModelSet dataSet, String eventType) {
this.dataSet = dataSet;
this.eventType = new URIImpl(Namespace.TYPES.getUri() + eventType);
/*
- * Get all event IDs from storage, sorted by time for later replay
+ * Count all event IDs in storage
*/
QueryResultTable count = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT (COUNT(?g) AS ?count) " +
"WHERE { GRAPH ?g { " +
- "?s ?p ?o " +
+ "?s :endTime ?time " +
"} " +
"} ");
System.out.format("For keyword '%s' there were %s recorded tweets.\n", eventType, count.iterator().next().getLiteralValue("count"));
/*
* Get all event IDs from storage, sorted by time for later replay
*/
QueryResultTable result = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT ?g " +
"WHERE { GRAPH ?g { " +
"?s :endTime ?time " +
"} " +
"} ORDER BY ASC (?time) ");
this.eventIds = result.iterator();
}
@Override
public boolean hasNext() {
return eventIds.hasNext();
}
@Override
public Model next() {
/*
* Get the complete event (identified by ID) from storage
*/
this.currentGraphUri = eventIds.next().getValue("g").asURI();
Model model = dataSet.getModel(this.currentGraphUri);
/*
* Replace the generic TwitterEvent type a specific one per company keyword
*/
URI eventSubject = new URIImpl(this.currentGraphUri.toString() + Event.EVENT_ID_SUFFIX);
if (model.contains(eventSubject, RDF.type, TwitterEvent.RDFS_CLASS)) {
model.removeStatements(eventSubject, RDF.type, Variable.ANY);
model.addStatement(eventSubject, RDF.type, this.eventType);
}
return model;
}
@Override
public void remove() {
if (this.currentGraphUri == null) {
throw new IllegalStateException("next() was not invoked at least once");
}
else {
dataSet.removeModel(this.currentGraphUri);
}
}
}
| false | true | public TweetSimulator(RepositoryModelSet dataSet, String eventType) {
this.dataSet = dataSet;
this.eventType = new URIImpl(Namespace.TYPES.getUri() + eventType);
/*
* Get all event IDs from storage, sorted by time for later replay
*/
QueryResultTable count = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT (COUNT(?g) AS ?count) " +
"WHERE { GRAPH ?g { " +
"?s ?p ?o " +
"} " +
"} ");
System.out.format("For keyword '%s' there were %s recorded tweets.\n", eventType, count.iterator().next().getLiteralValue("count"));
/*
* Get all event IDs from storage, sorted by time for later replay
*/
QueryResultTable result = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT ?g " +
"WHERE { GRAPH ?g { " +
"?s :endTime ?time " +
"} " +
"} ORDER BY ASC (?time) ");
this.eventIds = result.iterator();
}
| public TweetSimulator(RepositoryModelSet dataSet, String eventType) {
this.dataSet = dataSet;
this.eventType = new URIImpl(Namespace.TYPES.getUri() + eventType);
/*
* Count all event IDs in storage
*/
QueryResultTable count = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT (COUNT(?g) AS ?count) " +
"WHERE { GRAPH ?g { " +
"?s :endTime ?time " +
"} " +
"} ");
System.out.format("For keyword '%s' there were %s recorded tweets.\n", eventType, count.iterator().next().getLiteralValue("count"));
/*
* Get all event IDs from storage, sorted by time for later replay
*/
QueryResultTable result = dataSet.sparqlSelect(
"prefix : <http://events.event-processing.org/types/> " +
"SELECT ?g " +
"WHERE { GRAPH ?g { " +
"?s :endTime ?time " +
"} " +
"} ORDER BY ASC (?time) ");
this.eventIds = result.iterator();
}
|
diff --git a/src/main/java/reindent/Reindent.java b/src/main/java/reindent/Reindent.java
index be29e11..72f4eca 100644
--- a/src/main/java/reindent/Reindent.java
+++ b/src/main/java/reindent/Reindent.java
@@ -1,57 +1,62 @@
/**
*
*/
package reindent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @author Taylor Countryman <[email protected]>
*/
public class Reindent
{
/**
* @param args
*/
public static void main(String[] args)
{
// Argument checking
if(args.length != 2)
{
System.err.println("Usage: java reindent.Reindent INFILE OUTFILE");
System.exit(1);
}
// Input file checking
File inFile = new File(args[0]);
if(!inFile.isFile() || !inFile.canRead() || inFile.length() <= 0)
{
System.err.println( "reindent: " + inFile.getName() + ": Must be a readable file with content");
System.exit(1);
}
// Setup scanner
Scanner inScanner = null;
try
{
inScanner = new Scanner(inFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
+ finally
+ {
+ if(inScanner != null)
+ inScanner.close();
+ }
// Read file line by line
String line;
while(inScanner.hasNextLine())
{
line = inScanner.nextLine();
System.out.println(line);
}
}
}
| true | true | public static void main(String[] args)
{
// Argument checking
if(args.length != 2)
{
System.err.println("Usage: java reindent.Reindent INFILE OUTFILE");
System.exit(1);
}
// Input file checking
File inFile = new File(args[0]);
if(!inFile.isFile() || !inFile.canRead() || inFile.length() <= 0)
{
System.err.println( "reindent: " + inFile.getName() + ": Must be a readable file with content");
System.exit(1);
}
// Setup scanner
Scanner inScanner = null;
try
{
inScanner = new Scanner(inFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
// Read file line by line
String line;
while(inScanner.hasNextLine())
{
line = inScanner.nextLine();
System.out.println(line);
}
}
| public static void main(String[] args)
{
// Argument checking
if(args.length != 2)
{
System.err.println("Usage: java reindent.Reindent INFILE OUTFILE");
System.exit(1);
}
// Input file checking
File inFile = new File(args[0]);
if(!inFile.isFile() || !inFile.canRead() || inFile.length() <= 0)
{
System.err.println( "reindent: " + inFile.getName() + ": Must be a readable file with content");
System.exit(1);
}
// Setup scanner
Scanner inScanner = null;
try
{
inScanner = new Scanner(inFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
finally
{
if(inScanner != null)
inScanner.close();
}
// Read file line by line
String line;
while(inScanner.hasNextLine())
{
line = inScanner.nextLine();
System.out.println(line);
}
}
|
diff --git a/okapi/core/src/test/java/net/sf/okapi/common/filters/RoundTripComparison.java b/okapi/core/src/test/java/net/sf/okapi/common/filters/RoundTripComparison.java
index 825b808ef..58f4970a0 100644
--- a/okapi/core/src/test/java/net/sf/okapi/common/filters/RoundTripComparison.java
+++ b/okapi/core/src/test/java/net/sf/okapi/common/filters/RoundTripComparison.java
@@ -1,268 +1,272 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.common.filters;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.filters.IFilter;
import net.sf.okapi.common.filterwriter.IFilterWriter;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.resource.RawDocument;
public class RoundTripComparison {
private IFilter filter;
private ArrayList<Event> extraction1Events;
private ArrayList<Event> extraction2Events;
private IFilterWriter writer;
private ByteArrayOutputStream writerBuffer;
private String defaultEncoding;
private LocaleId srcLoc;
private LocaleId trgLoc;
public RoundTripComparison() {
extraction1Events = new ArrayList<Event>();
extraction2Events = new ArrayList<Event>();
}
public boolean executeCompare(IFilter filter, List<InputDocument> inputDocs,
String defaultEncoding, LocaleId srcLoc, LocaleId trgLoc) {
String path = null;
this.filter = filter;
this.defaultEncoding = defaultEncoding;
this.srcLoc = srcLoc;
this.trgLoc = trgLoc;
// Create the filter-writer for the provided filter
writer = filter.createFilterWriter();
for (InputDocument doc : inputDocs) {
path = doc.path;
// DEBUG: System.out.println(doc.path);
// Reset the event lists
extraction1Events.clear();
extraction2Events.clear();
// Load parameters if needed
if (doc.paramFile != null && !doc.paramFile.equals("")) {
String root = Util.getDirectoryName(doc.path);
IParameters params = filter.getParameters();
if (params != null) {
params.load(Util.toURI(root + File.separator + doc.paramFile), false);
}
}
// Execute the first extraction and the re-writing
executeFirstExtraction(doc);
// Execute the second extraction from the output of the first
executeSecondExtraction();
// Compare the events
if (!FilterTestDriver.compareEvents(extraction1Events, extraction2Events)) {
throw new RuntimeException("Events are different for " + doc.path);
}
}
return true;
}
public boolean executeCompare(IFilter filter, List<InputDocument> inputDocs,
String defaultEncoding, LocaleId srcLoc, LocaleId trgLoc, String outputDir) {
this.filter = filter;
this.defaultEncoding = defaultEncoding;
this.srcLoc = srcLoc;
this.trgLoc = trgLoc;
// Create the filter-writer for the provided filter
writer = filter.createFilterWriter();
for (InputDocument doc : inputDocs) {
// Reset the event lists
extraction1Events.clear();
extraction2Events.clear();
// Load parameters if needed
if (doc.paramFile == null) {
IParameters params = filter.getParameters();
if (params != null)
params.reset();
} else {
String root = Util.getDirectoryName(doc.path);
IParameters params = filter.getParameters();
if (params != null)
params.load(Util.toURI(root + File.separator + doc.paramFile), false);
}
// Execute the first extraction and the re-writing
String outPath = executeFirstExtractionToFile(doc, outputDir);
// Execute the second extraction from the output of the first
executeSecondExtractionFromFile(outPath);
// Compare the events
if (!FilterTestDriver.compareEvents(extraction1Events, extraction2Events)) {
throw new RuntimeException("Events are different for " + doc.path);
}
}
return true;
}
private void executeFirstExtraction(InputDocument doc) {
try {
// Open the input
filter.open(new RawDocument(Util.toURI(doc.path), defaultEncoding, srcLoc,
trgLoc));
// Prepare the output
writer.setOptions(trgLoc, "UTF-16");
writerBuffer = new ByteArrayOutputStream();
writer.setOutput(writerBuffer);
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction1Events.add(event);
break;
}
writer.handleEvent(event);
}
} finally {
if (filter != null)
filter.close();
if (writer != null)
writer.close();
}
}
private void executeSecondExtraction() {
try {
// Set the input (from the output of first extraction)
String input;
try {
input = new String(writerBuffer.toByteArray(), "UTF-16");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
filter.open(new RawDocument(input, srcLoc, trgLoc));
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction2Events.add(event);
break;
}
}
} finally {
if (filter != null)
filter.close();
}
}
private String executeFirstExtractionToFile(InputDocument doc, String outputDir) {
String outPath = null;
try {
// Open the input
filter.open(new RawDocument(Util.toURI(doc.path), defaultEncoding, srcLoc,
trgLoc));
// Prepare the output
writer.setOptions(trgLoc, "UTF-8");
outPath = Util.getDirectoryName(doc.path);
- outPath += (File.separator + outputDir + File.separator + Util.getFilename(doc.path,
- true));
+ if ( Util.isEmpty(outputDir) ) {
+ outPath += (File.separator + Util.getFilename(doc.path, true));
+ }
+ else {
+ outPath += (File.separator + outputDir + File.separator + Util.getFilename(doc.path, true));
+ }
writer.setOutput(outPath);
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction1Events.add(event);
break;
}
writer.handleEvent(event);
}
} finally {
if (filter != null)
filter.close();
if (writer != null)
writer.close();
}
return outPath;
}
private void executeSecondExtractionFromFile(String input) {
try {
// Set the input (from the output of first extraction)
filter.open(new RawDocument(Util.toURI(input), "UTF-8", srcLoc, trgLoc));
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction2Events.add(event);
break;
}
}
} finally {
if (filter != null)
filter.close();
}
}
}
| true | true | private String executeFirstExtractionToFile(InputDocument doc, String outputDir) {
String outPath = null;
try {
// Open the input
filter.open(new RawDocument(Util.toURI(doc.path), defaultEncoding, srcLoc,
trgLoc));
// Prepare the output
writer.setOptions(trgLoc, "UTF-8");
outPath = Util.getDirectoryName(doc.path);
outPath += (File.separator + outputDir + File.separator + Util.getFilename(doc.path,
true));
writer.setOutput(outPath);
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction1Events.add(event);
break;
}
writer.handleEvent(event);
}
} finally {
if (filter != null)
filter.close();
if (writer != null)
writer.close();
}
return outPath;
}
| private String executeFirstExtractionToFile(InputDocument doc, String outputDir) {
String outPath = null;
try {
// Open the input
filter.open(new RawDocument(Util.toURI(doc.path), defaultEncoding, srcLoc,
trgLoc));
// Prepare the output
writer.setOptions(trgLoc, "UTF-8");
outPath = Util.getDirectoryName(doc.path);
if ( Util.isEmpty(outputDir) ) {
outPath += (File.separator + Util.getFilename(doc.path, true));
}
else {
outPath += (File.separator + outputDir + File.separator + Util.getFilename(doc.path, true));
}
writer.setOutput(outPath);
// Process the document
Event event;
while (filter.hasNext()) {
event = filter.next();
switch (event.getEventType()) {
case START_DOCUMENT:
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
break;
case START_GROUP:
case END_GROUP:
case TEXT_UNIT:
extraction1Events.add(event);
break;
}
writer.handleEvent(event);
}
} finally {
if (filter != null)
filter.close();
if (writer != null)
writer.close();
}
return outPath;
}
|
diff --git a/src/test/java/com/porvak/bracket/utils/builder/RoundBuilder.java b/src/test/java/com/porvak/bracket/utils/builder/RoundBuilder.java
index 61f45fa..f9fbcb9 100644
--- a/src/test/java/com/porvak/bracket/utils/builder/RoundBuilder.java
+++ b/src/test/java/com/porvak/bracket/utils/builder/RoundBuilder.java
@@ -1,60 +1,62 @@
package com.porvak.bracket.utils.builder;
import com.google.common.collect.Lists;
import com.porvak.bracket.domain.Game;
import com.porvak.bracket.domain.Round;
import java.util.List;
public class RoundBuilder {
private int roundId;
private String roundName;
private List<Game> games;
public RoundBuilder(){
init();
}
private void init(){
roundId = 1;
roundName = "Round Name";
games = Lists.newLinkedList();
}
public RoundBuilder withRoundId(int id){
roundId = id;
return this;
}
public RoundBuilder withRoundName(String roundName){
this.roundName = roundName;
return this;
}
public RoundBuilder withGames(List<Game> games){
this.games = games;
return this;
}
public RoundBuilder addGameBuilder(GameBuilder gameBuilder){
games.add(gameBuilder.build());
return this;
}
public RoundBuilder addGame(Game game) {
games.add(game);
return this;
}
public Round build(){
Round round = new Round();
round.setRoundId(roundId);
round.setRoundName(roundName);
if(games != null && !games.isEmpty()){
-// round.setGames(games);
+ for(Game game: games){
+ round.addGame(game);
+ }
}
return round;
}
}
| true | true | public Round build(){
Round round = new Round();
round.setRoundId(roundId);
round.setRoundName(roundName);
if(games != null && !games.isEmpty()){
// round.setGames(games);
}
return round;
}
| public Round build(){
Round round = new Round();
round.setRoundId(roundId);
round.setRoundName(roundName);
if(games != null && !games.isEmpty()){
for(Game game: games){
round.addGame(game);
}
}
return round;
}
|
diff --git a/src/test/java/net/pms/configuration/RendererConfigurationTest.java b/src/test/java/net/pms/configuration/RendererConfigurationTest.java
index e00ab2af5..de3ca79ec 100644
--- a/src/test/java/net/pms/configuration/RendererConfigurationTest.java
+++ b/src/test/java/net/pms/configuration/RendererConfigurationTest.java
@@ -1,254 +1,253 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.configuration;
import ch.qos.logback.classic.LoggerContext;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import static net.pms.configuration.RendererConfiguration.*;
import org.apache.commons.configuration.ConfigurationException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
/**
* Test the RendererConfiguration class
*/
public class RendererConfigurationTest {
private final Map<String, String> testCases = new HashMap<>();
@Before
public void setUp() {
// Silence all log messages from the PMS code that is being tested
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
// Set locale to EN to ignore translations for renderers
Locale.setDefault(Locale.ENGLISH);
// Cases that are too generic should not match anything
testCases.put("User-Agent: UPnP/1.0 DLNADOC/1.50", null);
testCases.put("User-Agent: Unknown Renderer", null);
testCases.put("X-Unknown-Header: Unknown Content", null);
// AirPlayer:
testCases.put("User-Agent: AirPlayer/1.0.09 CFNetwork/485.13.9 Darwin/11.0.0", "AirPlayer");
testCases.put("User-Agent: Lavf52.54.0", "AirPlayer");
// BraviaEX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-32CX520\"; mv=\"1.7\";", "Sony Bravia EX");
// BraviaHX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-55HX750\"; mv=\"1.7\";", "Sony Bravia HX");
// DLinkDSM510:
testCases.put("User-Agent: DLNADOC/1.50 INTEL_NMPR/2.1", "D-Link DSM-510");
// iPad-iPhone:
testCases.put("User-Agent: 8player lite 2.2.3 (iPad; iPhone OS 5.0.1; nl_NL)", "iPad / iPhone");
testCases.put("User-Agent: yxplayer2%20lite/1.2.7 CFNetwork/485.13.9 Darwin/11.0.0", "iPad / iPhone");
testCases.put("User-Agent: MPlayer 1.0rc4-4.2.1", "iPad / iPhone");
testCases.put("User-Agent: NSPlayer/4.1.0.3856", "iPad / iPhone");
// Netgear NeoTV:
- // Need coordination with Vizio here
- //testCases.put("User-Agent: IPI/1.0 UPnP/1.0 DLNADOC/1.50, friendlyName.dlna.org: BD-Player", "Netgear NeoTV");
+ testCases.put("friendlyName.dlna.org: BD-Player", "Netgear NeoTV");
// Philips:
testCases.put("User-Agent: Allegro-Software-WebClient/4.61 DLNADOC/1.00", "Philips Aurea");
// PhilipsPFL:
testCases.put("User-Agent: Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50", "Philips TV");
// PS3:
testCases.put("User-Agent: PLAYSTATION 3", "PlayStation 3");
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Computer Entertainment Inc.\"; mn=\"PLAYSTATION 3\"; mv=\"1.0\"", "PlayStation 3");
// Realtek:
// FIXME: Actual conflict here! Popcorn Hour is returned...
//testCases.put("User-Agent: POSIX UPnP/1.0 Intel MicroStack/1.0.2718, RealtekMediaCenter, DLNADOC/1.50", "Realtek");
testCases.put("User-Agent: RealtekVOD neon/0.27.2", "Realtek");
// SamsungAllShare:
testCases.put("User-Agent: SEC_HHP_[HT]D5500/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_ Family TV/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]PS51D6900/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UN55D6050/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_ Family TV/1.0", "Samsung AllShare");
// Samsung-SMT-G7400:
testCases.put("User-Agent: Linux/2.6.35 UPnP/1.0 NDS_MHF DLNADOC/1.50", "Samsung SMT-G7400");
// Sharp Aquos:
testCases.put("User-Agent: DLNADOC/1.50 SHARP-AQUOS-DMP/1.1W", "Sharp Aquos");
// Showtime 3:
testCases.put("User-Agent: Showtime 3.0", "Showtime 3");
// Showtime 4:
testCases.put("User-Agent: Showtime PS3 4.2", "Showtime 4");
// Telstra T-Box:
// Note: This isn't the full user-agent, just a snippet to find it
testCases.put("User-Agent: telstra", "Telstra T-Box");
// VideoWebTV:
testCases.put("friendlyName.dlna.org: VideoWeb", "VideoWeb TV");
// WDTVLive:
testCases.put("User-Agent: INTEL_NMPR/2.1 DLNADOC/1.50 Intel MicroStack/1.0.1423", "WD TV Live");
// XBMC:
testCases.put("User-Agent: XBMC/10.0 r35648 (Mac OS X; 11.2.0 x86_64; http://www.xbmc.org)", "XBMC");
testCases.put("User-Agent: Platinum/0.5.3.0, DLNADOC/1.50", "XBMC");
}
/**
* Test the RendererConfiguration class and the consistency of the renderer
* .conf files it reads. This is done by feeding it known headers and
* checking whether it recognizes the correct renderer.
*/
@Test
public void testKnownHeaders() {
PmsConfiguration pmsConf = null;
try {
pmsConf = new PmsConfiguration(false);
} catch (IOException | ConfigurationException e) {
// This should be impossible since no configuration file will be loaded.
}
// Initialize the RendererConfiguration
loadRendererConfigurations(pmsConf);
// Test all header test cases
Set<Entry<String, String>> set = testCases.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
while (i.hasNext()) {
Entry<String, String> entry = (Entry<String, String>) i.next();
testHeader(entry.getKey(), entry.getValue());
}
}
/**
* Test recognition with a forced default renderer configured.
*/
@Test
public void testForcedDefault() {
PmsConfiguration pmsConf = null;
try {
pmsConf = new PmsConfiguration(false);
} catch (IOException | ConfigurationException e) {
// This should be impossible since no configuration file will be loaded.
}
// Set default to PlayStation 3
pmsConf.setRendererDefault("PlayStation 3");
pmsConf.setRendererForceDefault(true);
// Initialize the RendererConfiguration
loadRendererConfigurations(pmsConf);
// Known and unknown renderers should always return default
testHeader("User-Agent: AirPlayer/1.0.09 CFNetwork/485.13.9 Darwin/11.0.0", "PlayStation 3");
testHeader("User-Agent: Unknown Renderer", "PlayStation 3");
testHeader("X-Unknown-Header: Unknown Content", "PlayStation 3");
}
/**
* Test recognition with a forced bogus default renderer configured.
*/
@Test
public void testBogusDefault() {
PmsConfiguration pmsConf = null;
try {
pmsConf = new PmsConfiguration(false);
} catch (IOException | ConfigurationException e) {
// This should be impossible since no configuration file will be loaded.
}
// Set default to non existent renderer
pmsConf.setRendererDefault("Bogus Renderer");
pmsConf.setRendererForceDefault(true);
// Initialize the RendererConfiguration
loadRendererConfigurations(pmsConf);
// Known and unknown renderers should return "Unknown renderer"
testHeader("User-Agent: AirPlayer/1.0.09 CFNetwork/485.13.9 Darwin/11.0.0", "Unknown renderer");
testHeader("User-Agent: Unknown Renderer", "Unknown renderer");
testHeader("X-Unknown-Header: Unknown Content", "Unknown renderer");
}
/**
* Test one particular header line to see if it returns the correct
* renderer. Set the correct renderer name to <code>null</code> to require
* that nothing matches at all.
*
* @param headerLine
* The header line to recognize.
* @param correctRendererName
* The name of the renderer.
*/
private void testHeader(String headerLine, String correctRendererName) {
if (correctRendererName != null) {
// Header is supposed to match a particular renderer
if (headerLine != null && headerLine.toLowerCase().startsWith("user-agent")) {
// Match by User-Agent
RendererConfiguration rc = getRendererConfigurationByUA(headerLine);
assertNotNull("Recognized renderer for header \"" + headerLine + "\"", rc);
assertEquals("Expected renderer \"" + correctRendererName + "\", " +
"instead renderer \"" + rc.getRendererName() + "\" was returned for header \"" +
headerLine + "\"", correctRendererName, rc.getRendererName());
} else {
// Match by additional header
RendererConfiguration rc = getRendererConfigurationByUAAHH(headerLine);
assertNotNull("Recognized renderer for header \"" + headerLine + "\"", rc);
assertEquals("Expected renderer \"" + correctRendererName + "\" to be recognized, " +
"instead renderer \"" + rc.getRendererName() + "\" was returned for header \"" +
headerLine + "\"", correctRendererName, rc.getRendererName());
}
} else {
// Header is supposed to match no renderer at all
if (headerLine != null && headerLine.toLowerCase().startsWith("user-agent")) {
// Match by User-Agent
RendererConfiguration rc = getRendererConfigurationByUA(headerLine);
assertEquals("Expected no matching renderer to be found for header \"" + headerLine +
"\", instead renderer \"" + (rc != null ? rc.getRendererName() : "") +
"\" was recognized.", null,
rc);
} else {
// Match by additional header
RendererConfiguration rc = getRendererConfigurationByUAAHH(headerLine);
assertEquals("Expected no matching renderer to be found for header \"" + headerLine +
"\", instead renderer \"" + (rc != null ? rc.getRendererName() : "") +
"\" was recognized.", null, rc);
}
}
}
}
| true | true | public void setUp() {
// Silence all log messages from the PMS code that is being tested
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
// Set locale to EN to ignore translations for renderers
Locale.setDefault(Locale.ENGLISH);
// Cases that are too generic should not match anything
testCases.put("User-Agent: UPnP/1.0 DLNADOC/1.50", null);
testCases.put("User-Agent: Unknown Renderer", null);
testCases.put("X-Unknown-Header: Unknown Content", null);
// AirPlayer:
testCases.put("User-Agent: AirPlayer/1.0.09 CFNetwork/485.13.9 Darwin/11.0.0", "AirPlayer");
testCases.put("User-Agent: Lavf52.54.0", "AirPlayer");
// BraviaEX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-32CX520\"; mv=\"1.7\";", "Sony Bravia EX");
// BraviaHX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-55HX750\"; mv=\"1.7\";", "Sony Bravia HX");
// DLinkDSM510:
testCases.put("User-Agent: DLNADOC/1.50 INTEL_NMPR/2.1", "D-Link DSM-510");
// iPad-iPhone:
testCases.put("User-Agent: 8player lite 2.2.3 (iPad; iPhone OS 5.0.1; nl_NL)", "iPad / iPhone");
testCases.put("User-Agent: yxplayer2%20lite/1.2.7 CFNetwork/485.13.9 Darwin/11.0.0", "iPad / iPhone");
testCases.put("User-Agent: MPlayer 1.0rc4-4.2.1", "iPad / iPhone");
testCases.put("User-Agent: NSPlayer/4.1.0.3856", "iPad / iPhone");
// Netgear NeoTV:
// Need coordination with Vizio here
//testCases.put("User-Agent: IPI/1.0 UPnP/1.0 DLNADOC/1.50, friendlyName.dlna.org: BD-Player", "Netgear NeoTV");
// Philips:
testCases.put("User-Agent: Allegro-Software-WebClient/4.61 DLNADOC/1.00", "Philips Aurea");
// PhilipsPFL:
testCases.put("User-Agent: Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50", "Philips TV");
// PS3:
testCases.put("User-Agent: PLAYSTATION 3", "PlayStation 3");
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Computer Entertainment Inc.\"; mn=\"PLAYSTATION 3\"; mv=\"1.0\"", "PlayStation 3");
// Realtek:
// FIXME: Actual conflict here! Popcorn Hour is returned...
//testCases.put("User-Agent: POSIX UPnP/1.0 Intel MicroStack/1.0.2718, RealtekMediaCenter, DLNADOC/1.50", "Realtek");
testCases.put("User-Agent: RealtekVOD neon/0.27.2", "Realtek");
// SamsungAllShare:
testCases.put("User-Agent: SEC_HHP_[HT]D5500/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_ Family TV/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]PS51D6900/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UN55D6050/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_ Family TV/1.0", "Samsung AllShare");
// Samsung-SMT-G7400:
testCases.put("User-Agent: Linux/2.6.35 UPnP/1.0 NDS_MHF DLNADOC/1.50", "Samsung SMT-G7400");
// Sharp Aquos:
testCases.put("User-Agent: DLNADOC/1.50 SHARP-AQUOS-DMP/1.1W", "Sharp Aquos");
// Showtime 3:
testCases.put("User-Agent: Showtime 3.0", "Showtime 3");
// Showtime 4:
testCases.put("User-Agent: Showtime PS3 4.2", "Showtime 4");
// Telstra T-Box:
// Note: This isn't the full user-agent, just a snippet to find it
testCases.put("User-Agent: telstra", "Telstra T-Box");
// VideoWebTV:
testCases.put("friendlyName.dlna.org: VideoWeb", "VideoWeb TV");
// WDTVLive:
testCases.put("User-Agent: INTEL_NMPR/2.1 DLNADOC/1.50 Intel MicroStack/1.0.1423", "WD TV Live");
// XBMC:
testCases.put("User-Agent: XBMC/10.0 r35648 (Mac OS X; 11.2.0 x86_64; http://www.xbmc.org)", "XBMC");
testCases.put("User-Agent: Platinum/0.5.3.0, DLNADOC/1.50", "XBMC");
}
| public void setUp() {
// Silence all log messages from the PMS code that is being tested
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
// Set locale to EN to ignore translations for renderers
Locale.setDefault(Locale.ENGLISH);
// Cases that are too generic should not match anything
testCases.put("User-Agent: UPnP/1.0 DLNADOC/1.50", null);
testCases.put("User-Agent: Unknown Renderer", null);
testCases.put("X-Unknown-Header: Unknown Content", null);
// AirPlayer:
testCases.put("User-Agent: AirPlayer/1.0.09 CFNetwork/485.13.9 Darwin/11.0.0", "AirPlayer");
testCases.put("User-Agent: Lavf52.54.0", "AirPlayer");
// BraviaEX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-32CX520\"; mv=\"1.7\";", "Sony Bravia EX");
// BraviaHX:
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Corporation\"; mn=\"BRAVIA KDL-55HX750\"; mv=\"1.7\";", "Sony Bravia HX");
// DLinkDSM510:
testCases.put("User-Agent: DLNADOC/1.50 INTEL_NMPR/2.1", "D-Link DSM-510");
// iPad-iPhone:
testCases.put("User-Agent: 8player lite 2.2.3 (iPad; iPhone OS 5.0.1; nl_NL)", "iPad / iPhone");
testCases.put("User-Agent: yxplayer2%20lite/1.2.7 CFNetwork/485.13.9 Darwin/11.0.0", "iPad / iPhone");
testCases.put("User-Agent: MPlayer 1.0rc4-4.2.1", "iPad / iPhone");
testCases.put("User-Agent: NSPlayer/4.1.0.3856", "iPad / iPhone");
// Netgear NeoTV:
testCases.put("friendlyName.dlna.org: BD-Player", "Netgear NeoTV");
// Philips:
testCases.put("User-Agent: Allegro-Software-WebClient/4.61 DLNADOC/1.00", "Philips Aurea");
// PhilipsPFL:
testCases.put("User-Agent: Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50", "Philips TV");
// PS3:
testCases.put("User-Agent: PLAYSTATION 3", "PlayStation 3");
testCases.put("X-AV-Client-Info: av=5.0; cn=\"Sony Computer Entertainment Inc.\"; mn=\"PLAYSTATION 3\"; mv=\"1.0\"", "PlayStation 3");
// Realtek:
// FIXME: Actual conflict here! Popcorn Hour is returned...
//testCases.put("User-Agent: POSIX UPnP/1.0 Intel MicroStack/1.0.2718, RealtekMediaCenter, DLNADOC/1.50", "Realtek");
testCases.put("User-Agent: RealtekVOD neon/0.27.2", "Realtek");
// SamsungAllShare:
testCases.put("User-Agent: SEC_HHP_[HT]D5500/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_ Family TV/1.0", "Samsung AllShare");
testCases.put("User-Agent: SEC_HHP_[TV]PS51D6900/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UE32D5000/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_[TV]UN55D6050/1.0", "Samsung AllShare");
testCases.put("User-Agent: DLNADOC/1.50 SEC_HHP_ Family TV/1.0", "Samsung AllShare");
// Samsung-SMT-G7400:
testCases.put("User-Agent: Linux/2.6.35 UPnP/1.0 NDS_MHF DLNADOC/1.50", "Samsung SMT-G7400");
// Sharp Aquos:
testCases.put("User-Agent: DLNADOC/1.50 SHARP-AQUOS-DMP/1.1W", "Sharp Aquos");
// Showtime 3:
testCases.put("User-Agent: Showtime 3.0", "Showtime 3");
// Showtime 4:
testCases.put("User-Agent: Showtime PS3 4.2", "Showtime 4");
// Telstra T-Box:
// Note: This isn't the full user-agent, just a snippet to find it
testCases.put("User-Agent: telstra", "Telstra T-Box");
// VideoWebTV:
testCases.put("friendlyName.dlna.org: VideoWeb", "VideoWeb TV");
// WDTVLive:
testCases.put("User-Agent: INTEL_NMPR/2.1 DLNADOC/1.50 Intel MicroStack/1.0.1423", "WD TV Live");
// XBMC:
testCases.put("User-Agent: XBMC/10.0 r35648 (Mac OS X; 11.2.0 x86_64; http://www.xbmc.org)", "XBMC");
testCases.put("User-Agent: Platinum/0.5.3.0, DLNADOC/1.50", "XBMC");
}
|
diff --git a/NPCBibtexter/src/main/java/applicationLogic/Generate.java b/NPCBibtexter/src/main/java/applicationLogic/Generate.java
index 9817e89..cbb35b6 100644
--- a/NPCBibtexter/src/main/java/applicationLogic/Generate.java
+++ b/NPCBibtexter/src/main/java/applicationLogic/Generate.java
@@ -1,42 +1,42 @@
package applicationLogic;
import java.util.List;
/**
* Supports Inproceedings for now.
*/
public class Generate {
public static String identifier(String author, int year, String title) {
String toReturn = "";
- String auth = author.toLowerCase().trim();
+ String auth = author.toLowerCase().trim().replaceAll("\\s", "").replaceAll("\\W", "");
if (auth.length() < 6) {
toReturn += auth;
} else {
toReturn += auth.substring(0, 6);
}
toReturn += year;
toReturn += "-";
String tit = title.toLowerCase().trim();
if (tit.length() < 6) {
toReturn += tit;
} else {
toReturn += tit.substring(0, 6);
}
return toReturn;
}
public static boolean isUnique(List<String> citekeys, String citekey) {
for (String string : citekeys) {
if (citekey.equals(string)) {
return false;
}
}
return true;
}
}
| true | true | public static String identifier(String author, int year, String title) {
String toReturn = "";
String auth = author.toLowerCase().trim();
if (auth.length() < 6) {
toReturn += auth;
} else {
toReturn += auth.substring(0, 6);
}
toReturn += year;
toReturn += "-";
String tit = title.toLowerCase().trim();
if (tit.length() < 6) {
toReturn += tit;
} else {
toReturn += tit.substring(0, 6);
}
return toReturn;
}
| public static String identifier(String author, int year, String title) {
String toReturn = "";
String auth = author.toLowerCase().trim().replaceAll("\\s", "").replaceAll("\\W", "");
if (auth.length() < 6) {
toReturn += auth;
} else {
toReturn += auth.substring(0, 6);
}
toReturn += year;
toReturn += "-";
String tit = title.toLowerCase().trim();
if (tit.length() < 6) {
toReturn += tit;
} else {
toReturn += tit.substring(0, 6);
}
return toReturn;
}
|
diff --git a/org.caleydo.view.browser/src/org/caleydo/view/browser/HTMLBrowser.java b/org.caleydo.view.browser/src/org/caleydo/view/browser/HTMLBrowser.java
index 1a14a7e41..1d53c4bae 100644
--- a/org.caleydo.view.browser/src/org/caleydo/view/browser/HTMLBrowser.java
+++ b/org.caleydo.view.browser/src/org/caleydo/view/browser/HTMLBrowser.java
@@ -1,337 +1,337 @@
package org.caleydo.view.browser;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.manager.event.view.browser.ChangeURLEvent;
import org.caleydo.core.manager.id.EManagedObjectType;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.serialize.SerializedDummyView;
import org.caleydo.core.util.logging.Logger;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import org.caleydo.core.view.swt.ASWTView;
import org.caleydo.data.loader.ResourceLoader;
import org.caleydo.view.browser.listener.ChangeURLListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
/**
* Simple HTML browser.
*
* @author Marc Streit
*/
public class HTMLBrowser extends ASWTView {
public final static String VIEW_ID = "org.caleydo.view.browser";
public final static String CALEYDO_HOME = "http://www.caleydo.org";
protected Browser browser;
/**
* Subclasses can add widgets to this composite which appear before the
* browser icons.
*/
protected Composite subContributionComposite;
protected String url = CALEYDO_HOME + "/help/user_interface.html";
protected Text textURL;
// protected IDExtractionLocationListener idExtractionLocationListener;
private ToolItem goButton;
private ToolItem homeButton;
private ToolItem backButton;
private ToolItem stopButton;
private ChangeURLListener changeURLListener;
// private boolean makeRegularScreenshots = false;
private Runnable timer = null;
/**
* Constructor.
*/
public HTMLBrowser(Composite parentComposite) {
super(GeneralManager.get().getIDManager()
.createID(EManagedObjectType.VIEW_SWT_BROWSER_GENERAL), parentComposite);
viewType = VIEW_ID;
}
/**
* Constructor.
*/
public HTMLBrowser(int iViewID, Composite parentComposite) {
super(iViewID, parentComposite);
}
@Override
public void draw() {
Composite browserBarComposite = new Composite(parentComposite, SWT.NONE);
browserBarComposite.setLayout(new GridLayout(3, false));
subContributionComposite = new Composite(browserBarComposite, SWT.NONE);
subContributionComposite.setLayout(new FillLayout());
ToolBar toolbar = new ToolBar(browserBarComposite, SWT.NONE);
GridData data = new GridData(GridData.FILL_VERTICAL);
// toolbar.setLayoutData(data);
ResourceLoader resourceLoader = GeneralManager.get().getResourceLoader();
goButton = new ToolItem(toolbar, SWT.PUSH);
goButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_REFRESH_IMAGE.getFileName()));
backButton = new ToolItem(toolbar, SWT.PUSH);
backButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_BACK_IMAGE.getFileName()));
stopButton = new ToolItem(toolbar, SWT.PUSH);
stopButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_STOP_IMAGE.getFileName()));
homeButton = new ToolItem(toolbar, SWT.PUSH);
homeButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_HOME_IMAGE.getFileName()));
textURL = new Text(browserBarComposite, SWT.BORDER);
if (checkInternetConnection()) {
textURL.setText(url);
}
data = new GridData(GridData.FILL_HORIZONTAL);
data.heightHint = 15;
textURL.setLayoutData(data);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
data.heightHint = 45;
browserBarComposite.setLayoutData(data);
Listener listener = new Listener() {
@Override
public void handleEvent(Event event) {
if (!checkInternetConnection())
return;
ToolItem item = (ToolItem) event.widget;
if (item.equals(backButton)) {
browser.back();
} else if (item.equals(stopButton)) {
browser.stop();
} else if (item.equals(goButton)) {
url = textURL.getText();
} else if (item.equals(homeButton)) {
url = "www.caleydo.org";
textURL.setText(CALEYDO_HOME);
browser.setUrl(url);
}
}
};
goButton.addListener(SWT.Selection, listener);
backButton.addListener(SWT.Selection, listener);
stopButton.addListener(SWT.Selection, listener);
homeButton.addListener(SWT.Selection, listener);
textURL.addListener(SWT.DefaultSelection, new Listener() {
@Override
public void handleEvent(Event e) {
url = textURL.getText();
- draw();
+ browser.setUrl(url);
}
});
parentComposite.getDisplay().addFilter(SWT.FocusIn, new Listener() {
@Override
public void handleEvent(Event event) {
if (!event.widget.getClass().equals(this.getClass()))
return;
}
});
browser = new Browser(parentComposite, SWT.BORDER);
// Mechanism prevents the browser to steal the focus from other views
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
@Override
public void changed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
});
// idExtractionLocationListener = new
// IDExtractionLocationListener(browser, iUniqueID, -1);
// browser.addLocationListener(idExtractionLocationListener);
data = new GridData();
browser.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
Logger.log(new Status(IStatus.INFO, this.toString(), "Load " + url));
try {
parentComposite.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (!checkInternetConnection())
return;
textURL.setText(url);
browser.setUrl(url);
// browser.refresh();
}
});
} catch (SWTException swte) {
Logger.log(new Status(IStatus.INFO, GeneralManager.PLUGIN_ID,
"Error while loading " + url, swte));
}
}
public String getUrl() {
return url;
}
public void setUrl(String sUrl) {
this.url = sUrl;
// idExtractionLocationListener.updateSkipNextChangeEvent(true);
draw();
}
protected boolean checkInternetConnection() {
// Check internet connection
try {
InetAddress.getByName("www.google.at");
} catch (UnknownHostException e) {
textURL.setText("No internet connection available!");
return false;
}
return true;
}
@Override
public void registerEventListeners() {
super.registerEventListeners();
changeURLListener = new ChangeURLListener();
changeURLListener.setHandler(this);
eventPublisher.addListener(ChangeURLEvent.class, changeURLListener);
}
/**
* Registers the listeners for this view to the event system. To release the
* allocated resources unregisterEventListeners() has to be called.
*/
@Override
public void unregisterEventListeners() {
super.unregisterEventListeners();
if (changeURLListener != null) {
eventPublisher.removeListener(ChangeURLEvent.class, changeURLListener);
changeURLListener = null;
}
}
/**
* Unregisters the listeners for this view from the event system. To release
* the allocated resources unregisterEventListenrs() has to be called.
*/
@Override
public ASerializedView getSerializableRepresentation() {
SerializedDummyView serializedForm = new SerializedDummyView();
serializedForm.setViewID(this.getID());
return serializedForm;
}
@Override
public void initFromSerializableRepresentation(ASerializedView ser) {
// this implementation does not initialize anything yet
}
private void makeScreenshot() {
// Make screenshot of browser
Image screenshot = new Image(browser.getShell().getDisplay(), browser.getShell()
.getBounds());
GC gc = new GC(browser.getShell().getDisplay());
gc.copyArea(screenshot, 743, 143);
gc.dispose();
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] { screenshot.getImageData() };
loader.save(GeneralManager.CALEYDO_HOME_PATH + "browser.png", SWT.IMAGE_PNG);
// System.out.println("Write screenshot");
screenshot.dispose();
}
public void makeRegularScreenshots(boolean makeRegularScreenshots) {
if (makeRegularScreenshots) {
final int time = 1000;
if (timer != null) {
browser.getDisplay().timerExec(-1, timer);
timer = null;
}
timer = new Runnable() {
@Override
public void run() {
browser.getDisplay().timerExec(time, this);
makeScreenshot();
}
};
browser.getDisplay().timerExec(time, timer);
} else {
if (timer != null)
browser.getDisplay().timerExec(-1, timer);
}
}
}
| true | true | public void draw() {
Composite browserBarComposite = new Composite(parentComposite, SWT.NONE);
browserBarComposite.setLayout(new GridLayout(3, false));
subContributionComposite = new Composite(browserBarComposite, SWT.NONE);
subContributionComposite.setLayout(new FillLayout());
ToolBar toolbar = new ToolBar(browserBarComposite, SWT.NONE);
GridData data = new GridData(GridData.FILL_VERTICAL);
// toolbar.setLayoutData(data);
ResourceLoader resourceLoader = GeneralManager.get().getResourceLoader();
goButton = new ToolItem(toolbar, SWT.PUSH);
goButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_REFRESH_IMAGE.getFileName()));
backButton = new ToolItem(toolbar, SWT.PUSH);
backButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_BACK_IMAGE.getFileName()));
stopButton = new ToolItem(toolbar, SWT.PUSH);
stopButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_STOP_IMAGE.getFileName()));
homeButton = new ToolItem(toolbar, SWT.PUSH);
homeButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_HOME_IMAGE.getFileName()));
textURL = new Text(browserBarComposite, SWT.BORDER);
if (checkInternetConnection()) {
textURL.setText(url);
}
data = new GridData(GridData.FILL_HORIZONTAL);
data.heightHint = 15;
textURL.setLayoutData(data);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
data.heightHint = 45;
browserBarComposite.setLayoutData(data);
Listener listener = new Listener() {
@Override
public void handleEvent(Event event) {
if (!checkInternetConnection())
return;
ToolItem item = (ToolItem) event.widget;
if (item.equals(backButton)) {
browser.back();
} else if (item.equals(stopButton)) {
browser.stop();
} else if (item.equals(goButton)) {
url = textURL.getText();
} else if (item.equals(homeButton)) {
url = "www.caleydo.org";
textURL.setText(CALEYDO_HOME);
browser.setUrl(url);
}
}
};
goButton.addListener(SWT.Selection, listener);
backButton.addListener(SWT.Selection, listener);
stopButton.addListener(SWT.Selection, listener);
homeButton.addListener(SWT.Selection, listener);
textURL.addListener(SWT.DefaultSelection, new Listener() {
@Override
public void handleEvent(Event e) {
url = textURL.getText();
draw();
}
});
parentComposite.getDisplay().addFilter(SWT.FocusIn, new Listener() {
@Override
public void handleEvent(Event event) {
if (!event.widget.getClass().equals(this.getClass()))
return;
}
});
browser = new Browser(parentComposite, SWT.BORDER);
// Mechanism prevents the browser to steal the focus from other views
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
@Override
public void changed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
});
// idExtractionLocationListener = new
// IDExtractionLocationListener(browser, iUniqueID, -1);
// browser.addLocationListener(idExtractionLocationListener);
data = new GridData();
browser.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
Logger.log(new Status(IStatus.INFO, this.toString(), "Load " + url));
try {
parentComposite.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (!checkInternetConnection())
return;
textURL.setText(url);
browser.setUrl(url);
// browser.refresh();
}
});
} catch (SWTException swte) {
Logger.log(new Status(IStatus.INFO, GeneralManager.PLUGIN_ID,
"Error while loading " + url, swte));
}
}
| public void draw() {
Composite browserBarComposite = new Composite(parentComposite, SWT.NONE);
browserBarComposite.setLayout(new GridLayout(3, false));
subContributionComposite = new Composite(browserBarComposite, SWT.NONE);
subContributionComposite.setLayout(new FillLayout());
ToolBar toolbar = new ToolBar(browserBarComposite, SWT.NONE);
GridData data = new GridData(GridData.FILL_VERTICAL);
// toolbar.setLayoutData(data);
ResourceLoader resourceLoader = GeneralManager.get().getResourceLoader();
goButton = new ToolItem(toolbar, SWT.PUSH);
goButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_REFRESH_IMAGE.getFileName()));
backButton = new ToolItem(toolbar, SWT.PUSH);
backButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_BACK_IMAGE.getFileName()));
stopButton = new ToolItem(toolbar, SWT.PUSH);
stopButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_STOP_IMAGE.getFileName()));
homeButton = new ToolItem(toolbar, SWT.PUSH);
homeButton.setImage(resourceLoader.getImage(parentComposite.getDisplay(),
EIconTextures.BROWSER_HOME_IMAGE.getFileName()));
textURL = new Text(browserBarComposite, SWT.BORDER);
if (checkInternetConnection()) {
textURL.setText(url);
}
data = new GridData(GridData.FILL_HORIZONTAL);
data.heightHint = 15;
textURL.setLayoutData(data);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
data.heightHint = 45;
browserBarComposite.setLayoutData(data);
Listener listener = new Listener() {
@Override
public void handleEvent(Event event) {
if (!checkInternetConnection())
return;
ToolItem item = (ToolItem) event.widget;
if (item.equals(backButton)) {
browser.back();
} else if (item.equals(stopButton)) {
browser.stop();
} else if (item.equals(goButton)) {
url = textURL.getText();
} else if (item.equals(homeButton)) {
url = "www.caleydo.org";
textURL.setText(CALEYDO_HOME);
browser.setUrl(url);
}
}
};
goButton.addListener(SWT.Selection, listener);
backButton.addListener(SWT.Selection, listener);
stopButton.addListener(SWT.Selection, listener);
homeButton.addListener(SWT.Selection, listener);
textURL.addListener(SWT.DefaultSelection, new Listener() {
@Override
public void handleEvent(Event e) {
url = textURL.getText();
browser.setUrl(url);
}
});
parentComposite.getDisplay().addFilter(SWT.FocusIn, new Listener() {
@Override
public void handleEvent(Event event) {
if (!event.widget.getClass().equals(this.getClass()))
return;
}
});
browser = new Browser(parentComposite, SWT.BORDER);
// Mechanism prevents the browser to steal the focus from other views
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
@Override
public void changed(ProgressEvent event) {
// Give the focus back to active view
if (GeneralManager.get().getViewGLCanvasManager().getActiveSWTView() != null) {
GeneralManager.get().getViewGLCanvasManager().getActiveSWTView()
.setFocus();
}
}
});
// idExtractionLocationListener = new
// IDExtractionLocationListener(browser, iUniqueID, -1);
// browser.addLocationListener(idExtractionLocationListener);
data = new GridData();
browser.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
Logger.log(new Status(IStatus.INFO, this.toString(), "Load " + url));
try {
parentComposite.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (!checkInternetConnection())
return;
textURL.setText(url);
browser.setUrl(url);
// browser.refresh();
}
});
} catch (SWTException swte) {
Logger.log(new Status(IStatus.INFO, GeneralManager.PLUGIN_ID,
"Error while loading " + url, swte));
}
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src/org/eclipse/wst/xsd/ui/internal/dialogs/types/xml/XMLComponentSelectionProvider.java b/bundles/org.eclipse.wst.xsd.ui/src/org/eclipse/wst/xsd/ui/internal/dialogs/types/xml/XMLComponentSelectionProvider.java
index 5e6bd7811..613d31a29 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src/org/eclipse/wst/xsd/ui/internal/dialogs/types/xml/XMLComponentSelectionProvider.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src/org/eclipse/wst/xsd/ui/internal/dialogs/types/xml/XMLComponentSelectionProvider.java
@@ -1,142 +1,142 @@
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.xsd.ui.internal.dialogs.types.xml;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.wst.common.core.search.pattern.QualifiedName;
import org.eclipse.wst.xsd.ui.internal.dialogs.types.common.IComponentList;
import org.eclipse.wst.xsd.ui.internal.dialogs.types.common.IComponentSelectionProvider;
public abstract class XMLComponentSelectionProvider implements IComponentSelectionProvider {
public List getQualifiers(Object component) {
List qualifiers = new ArrayList();
if (component != null) {
XMLComponentTreeObject specification = (XMLComponentTreeObject) component;
Iterator it = specification.getXMLComponentSpecification().iterator();
while (it.hasNext()) {
XMLComponentSpecification spec = (XMLComponentSpecification) it.next();
qualifiers.add(createQualifierText(spec));
}
}
return qualifiers;
}
protected String createQualifierText(XMLComponentSpecification spec) {
IPath path = new Path(spec.getFileLocation());
return spec.getTargetNamespace() + " - " + path.lastSegment();
}
protected void addDataItemToTreeNode(IComponentList comps, XMLComponentSpecification dataItem) {
boolean foundMatch = false;
Iterator it = comps.iterator();
XMLComponentTreeObject containingTreeObject = null;
while (it.hasNext()) {
XMLComponentTreeObject treeObject = (XMLComponentTreeObject) it.next();
if (treeObject.getName().equals(dataItem.getAttributeInfo("name"))) {
// If the existing data item and the new data item have the same names
if (treeObject.getXMLComponentSpecification().size() > 0) {
- QualifiedName metaName = ((XMLComponentSpecification) treeObject.getXMLComponentSpecification().get(0)).getMetaName();
- if (metaName.equals(dataItem.getMetaName())) {
+ QualifiedName metaName = ((XMLComponentSpecification) treeObject.getXMLComponentSpecification().get(0)).getMetaName();
+ if (metaName != null && metaName.equals(dataItem.getMetaName())) {
// If they are the same 'type' of items (according to the path value)
containingTreeObject = treeObject;
foundMatch = true;
break;
}
}
}
}
if (!foundMatch) {
containingTreeObject = new XMLComponentTreeObject(dataItem);
comps.addComponent(containingTreeObject);
}
else {
// Only add to the tree object if the qualifier text differs than existing
// qualifier information contained in the tree object.
Iterator existingQualifiers = getQualifiers(containingTreeObject).iterator();
boolean alreadyExists = false;
while (existingQualifiers.hasNext()) {
String existingText = (String) existingQualifiers.next();
String newItemText = createQualifierText(dataItem);
if (existingText.equals(newItemText)) {
alreadyExists = true;
break;
}
}
if (!alreadyExists) {
containingTreeObject.addXMLComponentSpecification(dataItem);
}
}
}
protected String getNormalizedLocation(String location) {
try {
URL url = new URL(location);
URL resolvedURL = Platform.resolve(url);
location = resolvedURL.getPath();
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/*
* Object used to hold components with the same name but different qualifiers.
* This object will contain a list of XMLComponentSpecifications (with the same
* names but different qualifiers).
*/
public class XMLComponentTreeObject {
private String name;
private List xmlComponentSpecifications;
public XMLComponentTreeObject(XMLComponentSpecification spec) {
xmlComponentSpecifications = new ArrayList();
xmlComponentSpecifications.add(spec);
name = (String) spec.getAttributeInfo("name");
}
public String getName() {
return name;
}
public void addXMLComponentSpecification(XMLComponentSpecification spec) {
xmlComponentSpecifications.add(spec);
}
public List getXMLComponentSpecification() {
return xmlComponentSpecifications;
}
}
/*
* Used to provide labels to the ComponentSeletionDialog
*/
public class XMLComponentSelectionLabelProvider extends LabelProvider {
public String getText(Object element) {
XMLComponentTreeObject specification = (XMLComponentTreeObject) element;
return specification.getName();
}
}
}
| true | true | protected void addDataItemToTreeNode(IComponentList comps, XMLComponentSpecification dataItem) {
boolean foundMatch = false;
Iterator it = comps.iterator();
XMLComponentTreeObject containingTreeObject = null;
while (it.hasNext()) {
XMLComponentTreeObject treeObject = (XMLComponentTreeObject) it.next();
if (treeObject.getName().equals(dataItem.getAttributeInfo("name"))) {
// If the existing data item and the new data item have the same names
if (treeObject.getXMLComponentSpecification().size() > 0) {
QualifiedName metaName = ((XMLComponentSpecification) treeObject.getXMLComponentSpecification().get(0)).getMetaName();
if (metaName.equals(dataItem.getMetaName())) {
// If they are the same 'type' of items (according to the path value)
containingTreeObject = treeObject;
foundMatch = true;
break;
}
}
}
}
if (!foundMatch) {
containingTreeObject = new XMLComponentTreeObject(dataItem);
comps.addComponent(containingTreeObject);
}
else {
// Only add to the tree object if the qualifier text differs than existing
// qualifier information contained in the tree object.
Iterator existingQualifiers = getQualifiers(containingTreeObject).iterator();
boolean alreadyExists = false;
while (existingQualifiers.hasNext()) {
String existingText = (String) existingQualifiers.next();
String newItemText = createQualifierText(dataItem);
if (existingText.equals(newItemText)) {
alreadyExists = true;
break;
}
}
if (!alreadyExists) {
containingTreeObject.addXMLComponentSpecification(dataItem);
}
}
}
| protected void addDataItemToTreeNode(IComponentList comps, XMLComponentSpecification dataItem) {
boolean foundMatch = false;
Iterator it = comps.iterator();
XMLComponentTreeObject containingTreeObject = null;
while (it.hasNext()) {
XMLComponentTreeObject treeObject = (XMLComponentTreeObject) it.next();
if (treeObject.getName().equals(dataItem.getAttributeInfo("name"))) {
// If the existing data item and the new data item have the same names
if (treeObject.getXMLComponentSpecification().size() > 0) {
QualifiedName metaName = ((XMLComponentSpecification) treeObject.getXMLComponentSpecification().get(0)).getMetaName();
if (metaName != null && metaName.equals(dataItem.getMetaName())) {
// If they are the same 'type' of items (according to the path value)
containingTreeObject = treeObject;
foundMatch = true;
break;
}
}
}
}
if (!foundMatch) {
containingTreeObject = new XMLComponentTreeObject(dataItem);
comps.addComponent(containingTreeObject);
}
else {
// Only add to the tree object if the qualifier text differs than existing
// qualifier information contained in the tree object.
Iterator existingQualifiers = getQualifiers(containingTreeObject).iterator();
boolean alreadyExists = false;
while (existingQualifiers.hasNext()) {
String existingText = (String) existingQualifiers.next();
String newItemText = createQualifierText(dataItem);
if (existingText.equals(newItemText)) {
alreadyExists = true;
break;
}
}
if (!alreadyExists) {
containingTreeObject.addXMLComponentSpecification(dataItem);
}
}
}
|
diff --git a/src/main/java/me/limebyte/battlenight/core/chat/ListPage.java b/src/main/java/me/limebyte/battlenight/core/chat/ListPage.java
index 0625f93..b9ac13c 100644
--- a/src/main/java/me/limebyte/battlenight/core/chat/ListPage.java
+++ b/src/main/java/me/limebyte/battlenight/core/chat/ListPage.java
@@ -1,17 +1,17 @@
package me.limebyte.battlenight.core.chat;
import java.util.List;
public class ListPage extends StandardPage {
public ListPage(String title, List<String> list) {
super(title, "");
String text = "";
for (String item : list) {
text += item + "\n";
}
- this.text = text.substring(0, text.length() - 2);
+ this.text = text.substring(0, text.length() - 1);
}
}
| true | true | public ListPage(String title, List<String> list) {
super(title, "");
String text = "";
for (String item : list) {
text += item + "\n";
}
this.text = text.substring(0, text.length() - 2);
}
| public ListPage(String title, List<String> list) {
super(title, "");
String text = "";
for (String item : list) {
text += item + "\n";
}
this.text = text.substring(0, text.length() - 1);
}
|
diff --git a/netbout/netbout-rest/src/test/java/com/netbout/rest/BoutRsTest.java b/netbout/netbout-rest/src/test/java/com/netbout/rest/BoutRsTest.java
index 2091fb333..81ea03333 100644
--- a/netbout/netbout-rest/src/test/java/com/netbout/rest/BoutRsTest.java
+++ b/netbout/netbout-rest/src/test/java/com/netbout/rest/BoutRsTest.java
@@ -1,92 +1,92 @@
/**
* Copyright (c) 2009-2012, Netbout.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are PROHIBITED without prior written permission from
* the author. This product may NOT be used anywhere and on any computer
* except the server platform of netBout Inc. located at www.netbout.com.
* Federal copyright law prohibits unauthorized reproduction by any means
* and imposes fines up to $25,000 for violation. If you received
* this code accidentally and without intent to use it, please report this
* incident to the author by email.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package com.netbout.rest;
import com.netbout.hub.HubMocker;
import com.netbout.spi.Bout;
import com.netbout.spi.BoutMocker;
import com.netbout.spi.Identity;
import com.netbout.spi.IdentityMocker;
import com.rexsl.test.XhtmlMatchers;
import javax.ws.rs.core.Response;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test case for {@link BoutRs}.
* @author Yegor Bugayenko ([email protected])
* @version $Id$
*/
public final class BoutRsTest {
/**
* BoutRs can render front page of a bout.
* @throws Exception If there is some problem inside
*/
@Test
public void rendersBoutFrontPage() throws Exception {
final String title = "\u0443\u0440\u0430!";
final Identity identity = new IdentityMocker().mock();
final Bout bout = new BoutMocker()
.withParticipant(identity)
.titledAs(title)
.mock();
Mockito.doReturn(bout).when(identity).start();
Mockito.doReturn(bout).when(identity).bout(Mockito.any(Long.class));
final BoutRs rest = new NbResourceMocker()
.withIdentity(identity)
.withHub(
new HubMocker()
.withIdentity(identity.name(), identity)
.mock()
)
.mock(BoutRs.class);
rest.setNumber(bout.number());
rest.setPeriod("10-20");
rest.setStage(null);
rest.setPlace(null);
rest.setQuery("hello");
rest.setMask(null);
rest.setStageCoords(null);
final Response response = rest.front();
MatcherAssert.assertThat(
NbResourceMocker.the((NbPage) response.getEntity(), rest),
XhtmlMatchers.hasXPaths(
"/page/bout/participants/participant/identity",
String.format("/page/bout[title='%s']", title),
"/page/links/link[@rel='top']",
"/page/links/link[@rel='leave']",
"/page/links/link[@rel='post']",
- "/page[@searcheable='true']",
+ "/page/links/link[@rel='search']",
"/page[query='hello']",
"/page/bout[view='10-20']"
)
);
}
}
| true | true | public void rendersBoutFrontPage() throws Exception {
final String title = "\u0443\u0440\u0430!";
final Identity identity = new IdentityMocker().mock();
final Bout bout = new BoutMocker()
.withParticipant(identity)
.titledAs(title)
.mock();
Mockito.doReturn(bout).when(identity).start();
Mockito.doReturn(bout).when(identity).bout(Mockito.any(Long.class));
final BoutRs rest = new NbResourceMocker()
.withIdentity(identity)
.withHub(
new HubMocker()
.withIdentity(identity.name(), identity)
.mock()
)
.mock(BoutRs.class);
rest.setNumber(bout.number());
rest.setPeriod("10-20");
rest.setStage(null);
rest.setPlace(null);
rest.setQuery("hello");
rest.setMask(null);
rest.setStageCoords(null);
final Response response = rest.front();
MatcherAssert.assertThat(
NbResourceMocker.the((NbPage) response.getEntity(), rest),
XhtmlMatchers.hasXPaths(
"/page/bout/participants/participant/identity",
String.format("/page/bout[title='%s']", title),
"/page/links/link[@rel='top']",
"/page/links/link[@rel='leave']",
"/page/links/link[@rel='post']",
"/page[@searcheable='true']",
"/page[query='hello']",
"/page/bout[view='10-20']"
)
);
}
| public void rendersBoutFrontPage() throws Exception {
final String title = "\u0443\u0440\u0430!";
final Identity identity = new IdentityMocker().mock();
final Bout bout = new BoutMocker()
.withParticipant(identity)
.titledAs(title)
.mock();
Mockito.doReturn(bout).when(identity).start();
Mockito.doReturn(bout).when(identity).bout(Mockito.any(Long.class));
final BoutRs rest = new NbResourceMocker()
.withIdentity(identity)
.withHub(
new HubMocker()
.withIdentity(identity.name(), identity)
.mock()
)
.mock(BoutRs.class);
rest.setNumber(bout.number());
rest.setPeriod("10-20");
rest.setStage(null);
rest.setPlace(null);
rest.setQuery("hello");
rest.setMask(null);
rest.setStageCoords(null);
final Response response = rest.front();
MatcherAssert.assertThat(
NbResourceMocker.the((NbPage) response.getEntity(), rest),
XhtmlMatchers.hasXPaths(
"/page/bout/participants/participant/identity",
String.format("/page/bout[title='%s']", title),
"/page/links/link[@rel='top']",
"/page/links/link[@rel='leave']",
"/page/links/link[@rel='post']",
"/page/links/link[@rel='search']",
"/page[query='hello']",
"/page/bout[view='10-20']"
)
);
}
|
diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java
index a41fd1b5..9403fc36 100644
--- a/Essentials/src/com/earth2me/essentials/User.java
+++ b/Essentials/src/com/earth2me/essentials/User.java
@@ -1,596 +1,596 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.register.payment.Method;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class User extends UserData implements Comparable<User>, IReplyTo, IUser
{
private CommandSender replyTo = null;
private transient User teleportRequester;
private transient boolean teleportRequestHere;
private transient final Teleport teleport;
private transient long teleportRequestTime;
private transient long lastOnlineActivity;
private transient long lastActivity = System.currentTimeMillis();
private boolean hidden = false;
private transient Location afkPosition = null;
private static final Logger logger = Logger.getLogger("Minecraft");
User(final Player base, final IEssentials ess)
{
super(base, ess);
teleport = new Teleport(this, ess);
if (isAfk())
{
afkPosition = getLocation();
}
}
User update(final Player base)
{
setBase(base);
return this;
}
@Override
public boolean isAuthorized(final IEssentialsCommand cmd)
{
return isAuthorized(cmd, "essentials.");
}
@Override
public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix)
{
return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName()));
}
@Override
public boolean isAuthorized(final String node)
{
if (base instanceof OfflinePlayer)
{
return false;
}
if (isOp())
{
return true;
}
if (isJailed())
{
return false;
}
try
{
return ess.getPermissionsHandler().hasPermission(base, node);
}
catch (Exception ex)
{
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
return false;
}
}
public void healCooldown() throws Exception
{
final Calendar now = new GregorianCalendar();
if (getLastHealTimestamp() > 0)
{
final double cooldown = ess.getSettings().getHealCooldown();
final Calendar cooldownTime = new GregorianCalendar();
cooldownTime.setTimeInMillis(getLastHealTimestamp());
cooldownTime.add(Calendar.SECOND, (int)cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass"))
{
throw new Exception(_("timeBeforeHeal", Util.formatDateDiff(cooldownTime.getTimeInMillis())));
}
}
setLastHealTimestamp(now.getTimeInMillis());
}
@Override
public void giveMoney(final double value)
{
giveMoney(value, null);
}
public void giveMoney(final double value, final CommandSender initiator)
{
if (value == 0)
{
return;
}
setMoney(getMoney() + value);
sendMessage(_("addedToAccount", Util.displayCurrency(value, ess)));
if (initiator != null)
{
initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess)));
}
}
public void payUser(final User reciever, final double value) throws Exception
{
if (value == 0)
{
return;
}
if (canAfford(value))
{
setMoney(getMoney() - value);
reciever.setMoney(reciever.getMoney() + value);
sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName()));
reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName()));
}
else
{
throw new Exception(_("notEnoughMoney"));
}
}
@Override
public void takeMoney(final double value)
{
takeMoney(value, null);
}
public void takeMoney(final double value, final CommandSender initiator)
{
if (value == 0)
{
return;
}
setMoney(getMoney() - value);
sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess)));
if (initiator != null)
{
initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess)));
}
}
public boolean canAfford(final double cost)
{
return canAfford(cost, true);
}
public boolean canAfford(final double cost, final boolean permcheck)
{
final double mon = getMoney();
if (!permcheck || isAuthorized("essentials.eco.loan"))
{
return (mon - cost) >= ess.getSettings().getMinMoney();
}
return cost <= mon;
}
public void dispose()
{
this.base = new OfflinePlayer(getName(), ess);
}
@Override
public void setReplyTo(final CommandSender user)
{
replyTo = user;
}
@Override
public CommandSender getReplyTo()
{
return replyTo;
}
@Override
public int compareTo(final User other)
{
return Util.stripColor(this.getDisplayName()).compareToIgnoreCase(Util.stripColor(other.getDisplayName()));
}
@Override
public boolean equals(final Object object)
{
if (!(object instanceof User))
{
return false;
}
return this.getName().equalsIgnoreCase(((User)object).getName());
}
@Override
public int hashCode()
{
return this.getName().hashCode();
}
public Boolean canSpawnItem(final int itemId)
{
return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
}
public Location getHome() throws Exception
{
return getHome(getHomes().get(0));
}
public void setHome()
{
setHome("home", getLocation());
}
public void setHome(final String name)
{
setHome(name, getLocation());
}
@Override
public void setLastLocation()
{
setLastLocation(getLocation());
}
public void requestTeleport(final User player, final boolean here)
{
teleportRequestTime = System.currentTimeMillis();
teleportRequester = player;
teleportRequestHere = here;
}
public User getTeleportRequest()
{
return teleportRequester;
}
public boolean isTpRequestHere()
{
return teleportRequestHere;
}
public String getNick(final boolean addprefixsuffix)
{
final StringBuilder nickname = new StringBuilder();
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName()))
{
nickname.append(getName());
}
else
{
nickname.append(ess.getSettings().getNicknamePrefix()).append(nick);
}
if (addprefixsuffix && isOp())
{
try
{
final String opPrefix = ess.getSettings().getOperatorColor().toString();
if (opPrefix.length() > 0)
{
nickname.insert(0, opPrefix);
nickname.append("§f");
}
}
catch (Exception e)
{
}
}
if (addprefixsuffix && ess.getSettings().addPrefixSuffix())
{
if (!ess.getSettings().disablePrefix())
{
final String prefix = ess.getPermissionsHandler().getPrefix(base).replace('&', '§');
nickname.insert(0, prefix);
if (prefix.length() < 2 || prefix.charAt(0) != '&')
{
- nickname.insert(0, "&f");
+ nickname.insert(0, "§f");
}
}
if (!ess.getSettings().disableSuffix())
{
final String suffix = ess.getPermissionsHandler().getSuffix(base).replace('&', '§');
nickname.append(suffix);
if (suffix.length() < 2 || !suffix.substring(suffix.length() - 2, suffix.length() - 1).equals("§"))
{
nickname.append("§f");
}
}
else
{
nickname.append("§f");
}
}
return nickname.toString();
}
public void setDisplayNick()
{
if (base.isOnline() && ess.getSettings().changeDisplayName())
{
String name = getNick(true);
setDisplayName(name);
if (name.length() > 16)
{
name = getNick(false);
}
if (name.length() > 16)
{
name = Util.stripColor(name);
}
try
{
setPlayerListName(name);
}
catch (IllegalArgumentException e)
{
if (ess.getSettings().isDebug())
{
logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player.");
}
}
}
}
@Override
public String getDisplayName()
{
return super.getDisplayName() == null ? super.getName() : super.getDisplayName();
}
@Override
public Teleport getTeleport()
{
return teleport;
}
public long getLastOnlineActivity()
{
return lastOnlineActivity;
}
public void setLastOnlineActivity(final long timestamp)
{
lastOnlineActivity = timestamp;
}
@Override
public double getMoney()
{
if (ess.getPaymentMethod().hasMethod())
{
try
{
final Method method = ess.getPaymentMethod().getMethod();
if (!method.hasAccount(this.getName()))
{
throw new Exception();
}
final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName());
return account.balance();
}
catch (Throwable ex)
{
}
}
return super.getMoney();
}
@Override
public void setMoney(final double value)
{
if (ess.getPaymentMethod().hasMethod())
{
try
{
final Method method = ess.getPaymentMethod().getMethod();
if (!method.hasAccount(this.getName()))
{
throw new Exception();
}
final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName());
account.set(value);
}
catch (Throwable ex)
{
}
}
super.setMoney(value);
Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess);
}
public void updateMoneyCache(final double value)
{
if (ess.getPaymentMethod().hasMethod() && super.getMoney() != value)
{
super.setMoney(value);
}
}
@Override
public void setAfk(final boolean set)
{
this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set);
if (set && !isAfk())
{
afkPosition = getLocation();
}
else if (!set && isAfk())
{
afkPosition = null;
}
super.setAfk(set);
}
@Override
public boolean toggleAfk()
{
final boolean now = super.toggleAfk();
this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : now);
return now;
}
@Override
public boolean isHidden()
{
return hidden;
}
public void setHidden(final boolean hidden)
{
this.hidden = hidden;
}
//Returns true if status expired during this check
public boolean checkJailTimeout(final long currentTime)
{
if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed())
{
setJailTimeout(0);
setJailed(false);
sendMessage(_("haveBeenReleased"));
setJail(null);
try
{
getTeleport().back();
}
catch (Exception ex)
{
}
return true;
}
return false;
}
//Returns true if status expired during this check
public boolean checkMuteTimeout(final long currentTime)
{
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted())
{
setMuteTimeout(0);
sendMessage(_("canTalkAgain"));
setMuted(false);
return true;
}
return false;
}
//Returns true if status expired during this check
public boolean checkBanTimeout(final long currentTime)
{
if (getBanTimeout() > 0 && getBanTimeout() < currentTime && isBanned())
{
setBanTimeout(0);
setBanned(false);
return true;
}
return false;
}
public void updateActivity(final boolean broadcast)
{
if (isAfk())
{
setAfk(false);
if (broadcast && !isHidden())
{
setDisplayNick();
ess.broadcastMessage(this, _("userIsNotAway", getDisplayName()));
}
}
lastActivity = System.currentTimeMillis();
}
public void checkActivity()
{
final long autoafkkick = ess.getSettings().getAutoAfkKick();
if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt"))
{
final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0;
kickPlayer(kickReason);
for (Player player : ess.getServer().getOnlinePlayers())
{
final User user = ess.getUser(player);
if (user.isAuthorized("essentials.kick.notify"))
{
player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason));
}
}
}
final long autoafk = ess.getSettings().getAutoAfk();
if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk"))
{
setAfk(true);
if (!isHidden())
{
setDisplayNick();
ess.broadcastMessage(this, _("userIsAway", getDisplayName()));
}
}
}
public Location getAfkPosition()
{
return afkPosition;
}
@Override
public boolean toggleGodModeEnabled()
{
if (!isGodModeEnabled())
{
setFoodLevel(20);
}
return super.toggleGodModeEnabled();
}
@Override
public boolean isGodModeEnabled()
{
return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(getLocation().getWorld().getName()))
|| (isAfk() && ess.getSettings().getFreezeAfkPlayers());
}
public boolean isGodModeEnabledRaw()
{
return super.isGodModeEnabled();
}
public String getGroup()
{
return ess.getPermissionsHandler().getGroup(base);
}
public boolean inGroup(final String group)
{
return ess.getPermissionsHandler().inGroup(base, group);
}
public boolean canBuild()
{
if (isOp())
{
return true;
}
return ess.getPermissionsHandler().canBuild(base, getGroup());
}
public long getTeleportRequestTime()
{
return teleportRequestTime;
}
}
| true | true | public String getNick(final boolean addprefixsuffix)
{
final StringBuilder nickname = new StringBuilder();
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName()))
{
nickname.append(getName());
}
else
{
nickname.append(ess.getSettings().getNicknamePrefix()).append(nick);
}
if (addprefixsuffix && isOp())
{
try
{
final String opPrefix = ess.getSettings().getOperatorColor().toString();
if (opPrefix.length() > 0)
{
nickname.insert(0, opPrefix);
nickname.append("§f");
}
}
catch (Exception e)
{
}
}
if (addprefixsuffix && ess.getSettings().addPrefixSuffix())
{
if (!ess.getSettings().disablePrefix())
{
final String prefix = ess.getPermissionsHandler().getPrefix(base).replace('&', '§');
nickname.insert(0, prefix);
if (prefix.length() < 2 || prefix.charAt(0) != '&')
{
nickname.insert(0, "&f");
}
}
if (!ess.getSettings().disableSuffix())
{
final String suffix = ess.getPermissionsHandler().getSuffix(base).replace('&', '§');
nickname.append(suffix);
if (suffix.length() < 2 || !suffix.substring(suffix.length() - 2, suffix.length() - 1).equals("§"))
{
nickname.append("§f");
}
}
else
{
nickname.append("§f");
}
}
return nickname.toString();
}
| public String getNick(final boolean addprefixsuffix)
{
final StringBuilder nickname = new StringBuilder();
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName()))
{
nickname.append(getName());
}
else
{
nickname.append(ess.getSettings().getNicknamePrefix()).append(nick);
}
if (addprefixsuffix && isOp())
{
try
{
final String opPrefix = ess.getSettings().getOperatorColor().toString();
if (opPrefix.length() > 0)
{
nickname.insert(0, opPrefix);
nickname.append("§f");
}
}
catch (Exception e)
{
}
}
if (addprefixsuffix && ess.getSettings().addPrefixSuffix())
{
if (!ess.getSettings().disablePrefix())
{
final String prefix = ess.getPermissionsHandler().getPrefix(base).replace('&', '§');
nickname.insert(0, prefix);
if (prefix.length() < 2 || prefix.charAt(0) != '&')
{
nickname.insert(0, "§f");
}
}
if (!ess.getSettings().disableSuffix())
{
final String suffix = ess.getPermissionsHandler().getSuffix(base).replace('&', '§');
nickname.append(suffix);
if (suffix.length() < 2 || !suffix.substring(suffix.length() - 2, suffix.length() - 1).equals("§"))
{
nickname.append("§f");
}
}
else
{
nickname.append("§f");
}
}
return nickname.toString();
}
|
diff --git a/src/VisibilityTimeoutRunnable.java b/src/VisibilityTimeoutRunnable.java
index 463a1ad..7f36d7a 100644
--- a/src/VisibilityTimeoutRunnable.java
+++ b/src/VisibilityTimeoutRunnable.java
@@ -1,46 +1,46 @@
import com.amazonaws.services.sqs.model.*;
import java.io.IOException;
public class VisibilityTimeoutRunnable {
public static final int MILLISECONDS_IN_MINUTE = 1000 * 60;
private ClientWorker worker;
private boolean done;
private Message message;
private Thread timer;
public void updateVisibilityTimeout() {
worker.parameters.sqs.changeMessageVisibility( new ChangeMessageVisibilityRequest( worker.parameters.param( Parameters.QUEUE_URL_ID ),
message.getReceiptHandle(),
worker.parameters.visibility ) );
}
public VisibilityTimeoutRunnable( final ClientWorker worker, Message message ) {
this.worker = worker;
this.message = message;
timer =
new Thread( new Runnable() {
public void run() {
boolean shouldRun = true;
- while( shouldRun ) {
+ while( shouldRun && !Thread.currentThread().interrupted() ) {
try {
Thread.sleep( worker.parameters.visibility * 1000 - MILLISECONDS_IN_MINUTE );
updateVisibilityTimeout();
} catch ( InterruptedException e ) {
shouldRun = false;
}
}
}
} );
}
public void run() throws IOException {
timer.start();
worker.processFile( message.getBody() );
worker.doneWithFile( message );
timer.interrupt();
try {
timer.join();
} catch ( InterruptedException e ) {}
}
}
| true | true | public VisibilityTimeoutRunnable( final ClientWorker worker, Message message ) {
this.worker = worker;
this.message = message;
timer =
new Thread( new Runnable() {
public void run() {
boolean shouldRun = true;
while( shouldRun ) {
try {
Thread.sleep( worker.parameters.visibility * 1000 - MILLISECONDS_IN_MINUTE );
updateVisibilityTimeout();
} catch ( InterruptedException e ) {
shouldRun = false;
}
}
}
} );
}
| public VisibilityTimeoutRunnable( final ClientWorker worker, Message message ) {
this.worker = worker;
this.message = message;
timer =
new Thread( new Runnable() {
public void run() {
boolean shouldRun = true;
while( shouldRun && !Thread.currentThread().interrupted() ) {
try {
Thread.sleep( worker.parameters.visibility * 1000 - MILLISECONDS_IN_MINUTE );
updateVisibilityTimeout();
} catch ( InterruptedException e ) {
shouldRun = false;
}
}
}
} );
}
|
diff --git a/src/org/coode/dlquery/DLQueryListCellRenderer.java b/src/org/coode/dlquery/DLQueryListCellRenderer.java
index fcffed0..c1d4256 100644
--- a/src/org/coode/dlquery/DLQueryListCellRenderer.java
+++ b/src/org/coode/dlquery/DLQueryListCellRenderer.java
@@ -1,56 +1,55 @@
package org.coode.dlquery;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.renderer.OWLCellRenderer;
import javax.swing.*;
import java.awt.*;
/*
* Copyright (C) 2007, University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate. Authorship
* of the modifications may be determined from the ChangeLog placed at
* the end of this file.
*
* 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
*/
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Bio-Health Informatics Group<br>
* Date: 27-Feb-2007<br><br>
*/
public class DLQueryListCellRenderer extends OWLCellRenderer {
public DLQueryListCellRenderer(OWLEditorKit owlEditorKit) {
super(owlEditorKit);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Object renderableValue = value;
if (value instanceof DLQueryResultsSectionItem) {
DLQueryResultsSectionItem item = (DLQueryResultsSectionItem) value;
renderableValue = item.getOWLObject();
}
setPreferredWidth(list.getWidth());
- setTransparent();
return super.getListCellRendererComponent(list, renderableValue, index, isSelected, cellHasFocus);
}
}
| true | true | public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Object renderableValue = value;
if (value instanceof DLQueryResultsSectionItem) {
DLQueryResultsSectionItem item = (DLQueryResultsSectionItem) value;
renderableValue = item.getOWLObject();
}
setPreferredWidth(list.getWidth());
setTransparent();
return super.getListCellRendererComponent(list, renderableValue, index, isSelected, cellHasFocus);
}
| public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Object renderableValue = value;
if (value instanceof DLQueryResultsSectionItem) {
DLQueryResultsSectionItem item = (DLQueryResultsSectionItem) value;
renderableValue = item.getOWLObject();
}
setPreferredWidth(list.getWidth());
return super.getListCellRendererComponent(list, renderableValue, index, isSelected, cellHasFocus);
}
|
diff --git a/jajc/src/main/java/com/ngdata/CDH3ConfigurationBuilder.java b/jajc/src/main/java/com/ngdata/CDH3ConfigurationBuilder.java
index d0af200..31f35b4 100644
--- a/jajc/src/main/java/com/ngdata/CDH3ConfigurationBuilder.java
+++ b/jajc/src/main/java/com/ngdata/CDH3ConfigurationBuilder.java
@@ -1,133 +1,133 @@
package com.ngdata;
import java.util.HashMap;
import java.util.Map;
import org.jclouds.compute.domain.NodeMetadata;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.ngdata.exception.JajcException;
public class CDH3ConfigurationBuilder {
private static StringBuilder sb;
public static String createConfiguration(Iterable<NodeMetadata> nodes, IConfig config) throws JajcException {
sb = new StringBuilder();
sb.append("class cdh3::environment {");
String jobtracker = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
- return nm.getTags().contains("cdh3::hadoop::namenode");
+ return nm.getTags().contains("cdh3::hadoop::jobtracker");
}
}).iterator().next().getHostname();
StringBuilder namenode = new StringBuilder("hdfs://");
namenode.append(
Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::hadoop::namenode::service")
|| nm.getTags().contains("cdh3::hadoop::namenode::postinstall")
|| nm.getTags().contains("cdh3::hadoop::namenode");
}
}).iterator().next().getHostname());
namenode.append(":8020");
//zookeeper quorum array maken
StringBuilder zk_quorum = new StringBuilder(" [ ");
Iterable<NodeMetadata> zknodes = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::zookeeper");
}});
for (NodeMetadata zknode : zknodes) {
zk_quorum.append(" \"" + zknode.getHostname() + "\" ," );
}
zk_quorum.deleteCharAt(zk_quorum.length()-1);
zk_quorum.append(" ]");
sb.append("\n$namenode = \"").append(namenode).append("\"");
sb.append("\n$zk_quorum = ").append(zk_quorum);
Map<String,Map<String,String>> userConfig = config.getUserConfig();
if (userConfig == null)
userConfig = new HashMap<String, Map<String,String>>();
createNoOverwriteProperty(userConfig, "hdfs", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "core", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "mapred", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "zookeeper", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "hbase", new HashMap<String, String>());
for (String s : userConfig.keySet() ) {
Map<String,String> properties = userConfig.get(s);
if ("hdfs".equals(s)){
createNoOverwriteProperty(properties, "dfs.name.dir", "/data/nn");
createNoOverwriteProperty(properties, "dfs.data.dir", "/data/dn");
}
else if ("mapred".equals(s)) {
createOrOverwriteProperty(properties, "mapred.job.tracker", jobtracker + ":9001");
createNoOverwriteProperty(properties, "mapred.local.dir", "/data/mapred/local");
createNoOverwriteProperty(properties, "mapred.system.dir", "/mapred/system");
}
else if ("core".equals(s)) {
createOrOverwriteProperty(properties, "fs.default.name", "${namenode}" );
}
else if ("zookeeper".equals(s)){
createNoOverwriteProperty(properties, "tickTime", "2000");
createNoOverwriteProperty(properties, "dataDir", "/var/zookeeper");
createNoOverwriteProperty(properties, "clientPort", "2181");
createNoOverwriteProperty(properties, "initLimit", "5");
createNoOverwriteProperty(properties, "syncLimit", "2");
createNoOverwriteProperty(properties, "servers", zk_quorum.toString());
}
else if ("hbase".equals(s)) {
createOrOverwriteProperty(properties, "hbase.cluster.distributed", "true");
createOrOverwriteProperty(properties, "hbase.rootdir", "${namenode}/hbase");
createOrOverwriteProperty(properties, "hbase.zookeeper.quorum", zk_quorum.toString());
}
createHash(s, properties);
}
sb.append("\n}");
return sb.toString();
}
private static void createHash(String name,Map<String,String> properties) {
sb.append("\n\n#").append(name);
sb.append("\n$").append(name).append(" = {");
for (String key : properties.keySet()) {
String value = properties.get(key);
//don't stringify arrays
if (value.indexOf('[') == -1)
sb.append("\n \"").append(key).append("\" => \"").append(properties.get(key)).append("\" ,");
else
sb.append("\n \"").append(key).append("\" => ").append(properties.get(key)).append(" ,");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n}");
}
//properties of which we know the value should overwrite user-defined settings
private static <T> void createOrOverwriteProperty(Map<String,T> properties, String name, T value) {
properties.put(name, value);
}
//only use default if the user didn't set the property
private static <T> void createNoOverwriteProperty(Map<String,T> properties, String name, T value) {
if (properties.get(name) == null)
properties.put(name, value);
}
}
| true | true | public static String createConfiguration(Iterable<NodeMetadata> nodes, IConfig config) throws JajcException {
sb = new StringBuilder();
sb.append("class cdh3::environment {");
String jobtracker = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::hadoop::namenode");
}
}).iterator().next().getHostname();
StringBuilder namenode = new StringBuilder("hdfs://");
namenode.append(
Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::hadoop::namenode::service")
|| nm.getTags().contains("cdh3::hadoop::namenode::postinstall")
|| nm.getTags().contains("cdh3::hadoop::namenode");
}
}).iterator().next().getHostname());
namenode.append(":8020");
//zookeeper quorum array maken
StringBuilder zk_quorum = new StringBuilder(" [ ");
Iterable<NodeMetadata> zknodes = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::zookeeper");
}});
for (NodeMetadata zknode : zknodes) {
zk_quorum.append(" \"" + zknode.getHostname() + "\" ," );
}
zk_quorum.deleteCharAt(zk_quorum.length()-1);
zk_quorum.append(" ]");
sb.append("\n$namenode = \"").append(namenode).append("\"");
sb.append("\n$zk_quorum = ").append(zk_quorum);
Map<String,Map<String,String>> userConfig = config.getUserConfig();
if (userConfig == null)
userConfig = new HashMap<String, Map<String,String>>();
createNoOverwriteProperty(userConfig, "hdfs", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "core", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "mapred", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "zookeeper", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "hbase", new HashMap<String, String>());
for (String s : userConfig.keySet() ) {
Map<String,String> properties = userConfig.get(s);
if ("hdfs".equals(s)){
createNoOverwriteProperty(properties, "dfs.name.dir", "/data/nn");
createNoOverwriteProperty(properties, "dfs.data.dir", "/data/dn");
}
else if ("mapred".equals(s)) {
createOrOverwriteProperty(properties, "mapred.job.tracker", jobtracker + ":9001");
createNoOverwriteProperty(properties, "mapred.local.dir", "/data/mapred/local");
createNoOverwriteProperty(properties, "mapred.system.dir", "/mapred/system");
}
else if ("core".equals(s)) {
createOrOverwriteProperty(properties, "fs.default.name", "${namenode}" );
}
else if ("zookeeper".equals(s)){
createNoOverwriteProperty(properties, "tickTime", "2000");
createNoOverwriteProperty(properties, "dataDir", "/var/zookeeper");
createNoOverwriteProperty(properties, "clientPort", "2181");
createNoOverwriteProperty(properties, "initLimit", "5");
createNoOverwriteProperty(properties, "syncLimit", "2");
createNoOverwriteProperty(properties, "servers", zk_quorum.toString());
}
else if ("hbase".equals(s)) {
createOrOverwriteProperty(properties, "hbase.cluster.distributed", "true");
createOrOverwriteProperty(properties, "hbase.rootdir", "${namenode}/hbase");
createOrOverwriteProperty(properties, "hbase.zookeeper.quorum", zk_quorum.toString());
}
createHash(s, properties);
}
sb.append("\n}");
return sb.toString();
}
| public static String createConfiguration(Iterable<NodeMetadata> nodes, IConfig config) throws JajcException {
sb = new StringBuilder();
sb.append("class cdh3::environment {");
String jobtracker = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::hadoop::jobtracker");
}
}).iterator().next().getHostname();
StringBuilder namenode = new StringBuilder("hdfs://");
namenode.append(
Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::hadoop::namenode::service")
|| nm.getTags().contains("cdh3::hadoop::namenode::postinstall")
|| nm.getTags().contains("cdh3::hadoop::namenode");
}
}).iterator().next().getHostname());
namenode.append(":8020");
//zookeeper quorum array maken
StringBuilder zk_quorum = new StringBuilder(" [ ");
Iterable<NodeMetadata> zknodes = Iterables.filter(nodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata nm) {
return nm.getTags().contains("cdh3::zookeeper");
}});
for (NodeMetadata zknode : zknodes) {
zk_quorum.append(" \"" + zknode.getHostname() + "\" ," );
}
zk_quorum.deleteCharAt(zk_quorum.length()-1);
zk_quorum.append(" ]");
sb.append("\n$namenode = \"").append(namenode).append("\"");
sb.append("\n$zk_quorum = ").append(zk_quorum);
Map<String,Map<String,String>> userConfig = config.getUserConfig();
if (userConfig == null)
userConfig = new HashMap<String, Map<String,String>>();
createNoOverwriteProperty(userConfig, "hdfs", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "core", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "mapred", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "zookeeper", new HashMap<String, String>());
createNoOverwriteProperty(userConfig, "hbase", new HashMap<String, String>());
for (String s : userConfig.keySet() ) {
Map<String,String> properties = userConfig.get(s);
if ("hdfs".equals(s)){
createNoOverwriteProperty(properties, "dfs.name.dir", "/data/nn");
createNoOverwriteProperty(properties, "dfs.data.dir", "/data/dn");
}
else if ("mapred".equals(s)) {
createOrOverwriteProperty(properties, "mapred.job.tracker", jobtracker + ":9001");
createNoOverwriteProperty(properties, "mapred.local.dir", "/data/mapred/local");
createNoOverwriteProperty(properties, "mapred.system.dir", "/mapred/system");
}
else if ("core".equals(s)) {
createOrOverwriteProperty(properties, "fs.default.name", "${namenode}" );
}
else if ("zookeeper".equals(s)){
createNoOverwriteProperty(properties, "tickTime", "2000");
createNoOverwriteProperty(properties, "dataDir", "/var/zookeeper");
createNoOverwriteProperty(properties, "clientPort", "2181");
createNoOverwriteProperty(properties, "initLimit", "5");
createNoOverwriteProperty(properties, "syncLimit", "2");
createNoOverwriteProperty(properties, "servers", zk_quorum.toString());
}
else if ("hbase".equals(s)) {
createOrOverwriteProperty(properties, "hbase.cluster.distributed", "true");
createOrOverwriteProperty(properties, "hbase.rootdir", "${namenode}/hbase");
createOrOverwriteProperty(properties, "hbase.zookeeper.quorum", zk_quorum.toString());
}
createHash(s, properties);
}
sb.append("\n}");
return sb.toString();
}
|
diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/AbstractComponentComposer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/AbstractComponentComposer.java
index ac136de0..bf0b8754 100644
--- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/AbstractComponentComposer.java
+++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/AbstractComponentComposer.java
@@ -1,232 +1,232 @@
package org.codehaus.plexus.component.composition;
/*
* Copyright 2001-2006 Codehaus Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.collections.ComponentList;
import org.codehaus.plexus.component.collections.ComponentMap;
import org.codehaus.plexus.component.repository.ComponentDescriptor;
import org.codehaus.plexus.component.repository.ComponentRequirement;
import org.codehaus.plexus.component.repository.ComponentRequirementList;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.logging.Logger;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Jason van Zyl
* @version $Id$
*/
public abstract class AbstractComponentComposer
extends AbstractLogEnabled
implements ComponentComposer
{
// ----------------------------------------------------------------------
// Composition Life Cycle
// ----------------------------------------------------------------------
public void verifyComponentSuitability( Object component )
throws CompositionException
{
}
public Map createCompositionContext( Object component,
ComponentDescriptor descriptor )
throws CompositionException
{
return Collections.EMPTY_MAP;
}
/** @deprecated */
public void assembleComponent( Object component,
ComponentDescriptor componentDescriptor,
PlexusContainer container )
throws CompositionException
{
assembleComponent( component, componentDescriptor, container, container.getLookupRealm( component ) );
}
public void assembleComponent( Object component,
ComponentDescriptor componentDescriptor,
PlexusContainer container,
ClassRealm lookupRealm )
throws CompositionException
{
// ----------------------------------------------------------------------
// If a ComponentComposer wishes to check any criteria before attempting
// composition it may do so here.
// ----------------------------------------------------------------------
verifyComponentSuitability( component );
Map compositionContext = createCompositionContext( component, componentDescriptor );
// ----------------------------------------------------------------------
// If the ComponentDescriptor is null then we are attempting to autowire
// this component which means that Plexus has just been handled a
// POJO to wire up.
// ----------------------------------------------------------------------
List requirements = componentDescriptor.getRequirements();
for ( Iterator i = requirements.iterator(); i.hasNext(); )
{
ComponentRequirement requirement = (ComponentRequirement) i.next();
assignRequirement( component, componentDescriptor, requirement, container, compositionContext, lookupRealm );
}
}
/** @deprecated */
public final void assignRequirement( Object component,
ComponentDescriptor componentDescriptor,
ComponentRequirement componentRequirement,
PlexusContainer container,
Map compositionContext )
throws CompositionException
{
assignRequirement( component, componentDescriptor, componentRequirement, container, compositionContext,
container.getLookupRealm( component ) );
}
public Requirement findRequirement( Object component,
ComponentDescriptor hostComponentDescriptor,
Class clazz,
PlexusContainer container,
ComponentRequirement requirement,
ClassRealm lookupRealm )
throws CompositionException
{
// We want to find all the requirements for a component and we want to ensure that the
// requirements are pulled from the same realm as the component itself.
try
{
List componentDescriptors;
Object assignment;
String role = requirement.getRole();
List roleHints = null;
if ( requirement instanceof ComponentRequirementList )
{
roleHints = ( (ComponentRequirementList) requirement ).getRoleHints();
}
if ( clazz.isArray() )
{
List dependencies = container.lookupList( role, roleHints, lookupRealm );
- Object[] array = (Object[]) Array.newInstance( clazz, dependencies.size() );
+ Object[] array = (Object[]) Array.newInstance( clazz.getComponentType(), dependencies.size() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
try
{
assignment = dependencies.toArray( array );
}
catch ( ArrayStoreException e )
{
for ( Iterator i = dependencies.iterator(); i.hasNext(); )
{
Class dependencyClass = i.next().getClass();
if ( !clazz.isAssignableFrom( dependencyClass ) )
{
throw new CompositionException( "Dependency of class " + dependencyClass.getName() +
" in requirement " + requirement + " is not assignable in field of class " +
clazz.getComponentType().getName(), e );
}
}
// never gets here
throw e;
}
}
// Map.class.isAssignableFrom( clazz ) doesn't make sense, since Map.class doesn't really
// have a meaningful superclass.
else if ( Map.class.equals( clazz ) )
{
assignment = new ComponentMap( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// List.class.isAssignableFrom( clazz ) doesn't make sense, since List.class doesn't really
// have a meaningful superclass other than Collection.class, which we'll handle next.
else if ( List.class.equals( clazz ) )
{
assignment = new ComponentList( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// Set.class.isAssignableFrom( clazz ) doesn't make sense, since Set.class doesn't really
// have a meaningful superclass other than Collection.class, and that would make this
// if-else cascade unpredictable (both List and Set extend Collection, so we'll put another
// check in for Collection.class.
else if ( Set.class.equals( clazz ) || Collection.class.isAssignableFrom( clazz ) )
{
assignment = container.lookupMap( role, roleHints, lookupRealm );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
else if ( Logger.class.equals( clazz ) )
{
assignment = container.getLoggerManager().getLoggerForComponent( hostComponentDescriptor.getRole() );
componentDescriptors = null;
}
else if ( PlexusContainer.class.equals( clazz ) )
{
assignment = container;
componentDescriptors = null;
}
else
{
String roleHint = requirement.getRoleHint();
assignment = container.lookup( role, roleHint, lookupRealm );
ComponentDescriptor componentDescriptor = container.getComponentDescriptor( role, roleHint, lookupRealm );
componentDescriptors = new ArrayList( 1 );
componentDescriptors.add( componentDescriptor );
}
return new Requirement( assignment, componentDescriptors );
}
catch ( ComponentLookupException e )
{
throw new CompositionException( "Composition failed of field " + requirement.getFieldName() + " " +
"in object of type " + component.getClass().getName() + " because the requirement " + requirement +
" was missing (lookup realm: " + lookupRealm.getId() + ")", e );
}
}
}
| true | true | public Requirement findRequirement( Object component,
ComponentDescriptor hostComponentDescriptor,
Class clazz,
PlexusContainer container,
ComponentRequirement requirement,
ClassRealm lookupRealm )
throws CompositionException
{
// We want to find all the requirements for a component and we want to ensure that the
// requirements are pulled from the same realm as the component itself.
try
{
List componentDescriptors;
Object assignment;
String role = requirement.getRole();
List roleHints = null;
if ( requirement instanceof ComponentRequirementList )
{
roleHints = ( (ComponentRequirementList) requirement ).getRoleHints();
}
if ( clazz.isArray() )
{
List dependencies = container.lookupList( role, roleHints, lookupRealm );
Object[] array = (Object[]) Array.newInstance( clazz, dependencies.size() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
try
{
assignment = dependencies.toArray( array );
}
catch ( ArrayStoreException e )
{
for ( Iterator i = dependencies.iterator(); i.hasNext(); )
{
Class dependencyClass = i.next().getClass();
if ( !clazz.isAssignableFrom( dependencyClass ) )
{
throw new CompositionException( "Dependency of class " + dependencyClass.getName() +
" in requirement " + requirement + " is not assignable in field of class " +
clazz.getComponentType().getName(), e );
}
}
// never gets here
throw e;
}
}
// Map.class.isAssignableFrom( clazz ) doesn't make sense, since Map.class doesn't really
// have a meaningful superclass.
else if ( Map.class.equals( clazz ) )
{
assignment = new ComponentMap( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// List.class.isAssignableFrom( clazz ) doesn't make sense, since List.class doesn't really
// have a meaningful superclass other than Collection.class, which we'll handle next.
else if ( List.class.equals( clazz ) )
{
assignment = new ComponentList( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// Set.class.isAssignableFrom( clazz ) doesn't make sense, since Set.class doesn't really
// have a meaningful superclass other than Collection.class, and that would make this
// if-else cascade unpredictable (both List and Set extend Collection, so we'll put another
// check in for Collection.class.
else if ( Set.class.equals( clazz ) || Collection.class.isAssignableFrom( clazz ) )
{
assignment = container.lookupMap( role, roleHints, lookupRealm );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
else if ( Logger.class.equals( clazz ) )
{
assignment = container.getLoggerManager().getLoggerForComponent( hostComponentDescriptor.getRole() );
componentDescriptors = null;
}
else if ( PlexusContainer.class.equals( clazz ) )
{
assignment = container;
componentDescriptors = null;
}
else
{
String roleHint = requirement.getRoleHint();
assignment = container.lookup( role, roleHint, lookupRealm );
ComponentDescriptor componentDescriptor = container.getComponentDescriptor( role, roleHint, lookupRealm );
componentDescriptors = new ArrayList( 1 );
componentDescriptors.add( componentDescriptor );
}
return new Requirement( assignment, componentDescriptors );
}
catch ( ComponentLookupException e )
{
throw new CompositionException( "Composition failed of field " + requirement.getFieldName() + " " +
"in object of type " + component.getClass().getName() + " because the requirement " + requirement +
" was missing (lookup realm: " + lookupRealm.getId() + ")", e );
}
}
| public Requirement findRequirement( Object component,
ComponentDescriptor hostComponentDescriptor,
Class clazz,
PlexusContainer container,
ComponentRequirement requirement,
ClassRealm lookupRealm )
throws CompositionException
{
// We want to find all the requirements for a component and we want to ensure that the
// requirements are pulled from the same realm as the component itself.
try
{
List componentDescriptors;
Object assignment;
String role = requirement.getRole();
List roleHints = null;
if ( requirement instanceof ComponentRequirementList )
{
roleHints = ( (ComponentRequirementList) requirement ).getRoleHints();
}
if ( clazz.isArray() )
{
List dependencies = container.lookupList( role, roleHints, lookupRealm );
Object[] array = (Object[]) Array.newInstance( clazz.getComponentType(), dependencies.size() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
try
{
assignment = dependencies.toArray( array );
}
catch ( ArrayStoreException e )
{
for ( Iterator i = dependencies.iterator(); i.hasNext(); )
{
Class dependencyClass = i.next().getClass();
if ( !clazz.isAssignableFrom( dependencyClass ) )
{
throw new CompositionException( "Dependency of class " + dependencyClass.getName() +
" in requirement " + requirement + " is not assignable in field of class " +
clazz.getComponentType().getName(), e );
}
}
// never gets here
throw e;
}
}
// Map.class.isAssignableFrom( clazz ) doesn't make sense, since Map.class doesn't really
// have a meaningful superclass.
else if ( Map.class.equals( clazz ) )
{
assignment = new ComponentMap( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// List.class.isAssignableFrom( clazz ) doesn't make sense, since List.class doesn't really
// have a meaningful superclass other than Collection.class, which we'll handle next.
else if ( List.class.equals( clazz ) )
{
assignment = new ComponentList( container, lookupRealm, role, roleHints, hostComponentDescriptor.getHumanReadableKey() );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
// Set.class.isAssignableFrom( clazz ) doesn't make sense, since Set.class doesn't really
// have a meaningful superclass other than Collection.class, and that would make this
// if-else cascade unpredictable (both List and Set extend Collection, so we'll put another
// check in for Collection.class.
else if ( Set.class.equals( clazz ) || Collection.class.isAssignableFrom( clazz ) )
{
assignment = container.lookupMap( role, roleHints, lookupRealm );
componentDescriptors = container.getComponentDescriptorList( role, roleHints, lookupRealm );
}
else if ( Logger.class.equals( clazz ) )
{
assignment = container.getLoggerManager().getLoggerForComponent( hostComponentDescriptor.getRole() );
componentDescriptors = null;
}
else if ( PlexusContainer.class.equals( clazz ) )
{
assignment = container;
componentDescriptors = null;
}
else
{
String roleHint = requirement.getRoleHint();
assignment = container.lookup( role, roleHint, lookupRealm );
ComponentDescriptor componentDescriptor = container.getComponentDescriptor( role, roleHint, lookupRealm );
componentDescriptors = new ArrayList( 1 );
componentDescriptors.add( componentDescriptor );
}
return new Requirement( assignment, componentDescriptors );
}
catch ( ComponentLookupException e )
{
throw new CompositionException( "Composition failed of field " + requirement.getFieldName() + " " +
"in object of type " + component.getClass().getName() + " because the requirement " + requirement +
" was missing (lookup realm: " + lookupRealm.getId() + ")", e );
}
}
|
diff --git a/src/gov/nih/nci/ncicb/cadsr/loader/persister/DECPersister.java b/src/gov/nih/nci/ncicb/cadsr/loader/persister/DECPersister.java
index 84239bcc..34601f1f 100755
--- a/src/gov/nih/nci/ncicb/cadsr/loader/persister/DECPersister.java
+++ b/src/gov/nih/nci/ncicb/cadsr/loader/persister/DECPersister.java
@@ -1,235 +1,235 @@
/*
* Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
*
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. 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.
*
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
*
* "This product includes software developed by Oracle, Inc. and the National Cancer Institute."
*
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear.
*
* 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software.
*
* 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc.
*
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES 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
*/
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import gov.nih.nci.ncicb.cadsr.dao.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import org.apache.log4j.Logger;
import java.util.*;
/**
*
* @author <a href="mailto:[email protected]">Christophe Ludet</a>
*/
public class DECPersister extends UMLPersister {
public static String DEC_PREFERRED_NAME_DELIMITER = "v";
public static String DEC_PREFERRED_NAME_CONCAT_CHAR = ":";
public static String DEC_PREFERRED_DEF_CONCAT_CHAR = "_";
private static Logger logger = Logger.getLogger(DECPersister.class.getName());
public DECPersister() {
}
public void persist() throws PersisterException {
DataElementConcept dec = DomainObjectFactory.newDataElementConcept();
List<DataElementConcept> decs = elements.getElements(dec);
int count = 0;
sendProgressEvent(count++, decs.size(), "DECs");
logger.debug("decs... ");
if (decs != null) {
for (ListIterator<DataElementConcept> it = decs.listIterator(); it.hasNext();) {
DataElementConcept newDec = DomainObjectFactory.newDataElementConcept();
dec = it.next();
sendProgressEvent(count++, decs.size(), "DEC : " + dec.getLongName());
List<Definition> modelDefinitions = dec.getDefinitions();
List<AlternateName> modelAltNames = dec.getAlternateNames();
dec.removeDefinitions();
dec.removeAlternateNames();
String newName = dec.getLongName();
String packageName = getPackageName(dec);
if(!StringUtil.isEmpty(dec.getPublicId()) && dec.getVersion() != null) {
newDec = existingMapping(dec, newName, packageName);
it.set(newDec);
addPackageClassification(newDec, packageName);
logger.info(PropertyAccessor.getProperty("mapped.to.existing.dec"));
continue;
}
// update object class with persisted one
if(dec.getObjectClass().getPublicId() == null)
dec.setObjectClass(LookupUtil.lookupObjectClass(
dec.getObjectClass().getPreferredName()));
else
dec.setObjectClass(LookupUtil.lookupObjectClass
(dec.getObjectClass().getPublicId(),
dec.getObjectClass().getVersion()));
newDec.setObjectClass(dec.getObjectClass());
// update property with persisted one
if(dec.getProperty().getPublicId() == null)
dec.setProperty(LookupUtil.lookupProperty(
dec.getProperty().getPreferredName()));
else
dec.setProperty(LookupUtil.lookupProperty
(dec.getProperty().getPublicId(),
dec.getProperty().getVersion()));
newDec.setProperty(dec.getProperty());
logger.debug("dec name: " + dec.getLongName());
logger.debug("alt Name: " + newName);
List<String> eager = new ArrayList<String>();
eager.add("definitions");
// does this dec exist?
List l = dataElementConceptDAO.find(newDec, eager);
// String newDef = dec.getPreferredDefinition();
if (l.size() == 0) {
dec.setConceptualDomain(defaults.getConceptualDomain());
dec.setContext(defaults.getContext());
dec.setLongName(
dec.getObjectClass().getLongName()
+ " " +
dec.getProperty().getLongName()
);
dec.setPreferredDefinition(
dec.getObjectClass().getPreferredDefinition()
+ DEC_PREFERRED_DEF_CONCAT_CHAR
+ dec.getProperty().getPreferredDefinition()
);
dec.setPreferredName
(ConventionUtil.publicIdVersion(dec.getObjectClass())
+ DEC_PREFERRED_NAME_CONCAT_CHAR
+ ConventionUtil.publicIdVersion(dec.getProperty()));
dec.setVersion(new Float(1.0f));
dec.setWorkflowStatus(defaults.getWorkflowStatus());
dec.setProperty(LookupUtil.lookupProperty(dec.getProperty().getPreferredName()));
// List props = elements.getElements(DomainObjectFactory.newProperty()
// .getClass());
// for (int j = 0; j < props.size(); j++) {
// Property o = (Property) props.get(j);
// if (o.getLongName().equals(dec.getProperty()
// .getLongName())) {
// dec.setProperty(o);
// }
// }
dec.setAudit(defaults.getAudit());
- dec.setLifecycle(defaults.getAudit());
+ dec.setLifecycle(defaults.getLifecycle());
// List altDefs = new ArrayList(dec.getDefinitions());
// List altNames = new ArrayList(dec.getAlternateNames());
newDec = dataElementConceptDAO.create(dec);
// // restore altNames
// for(Iterator it2 = altNames.iterator(); it2.hasNext();) {
// AlternateName an = (AlternateName)it2.next();
// dec.addAlternateName(an);
// }
// // restore altDefs
// for(Iterator it2 = altDefs.iterator(); it2.hasNext();) {
// Definition def = (Definition)it2.next();
// dec.addDefinition(def);
// }
logger.info(PropertyAccessor.getProperty("created.dec"));
} else {
newDec = (DataElementConcept) l.get(0);
logger.info(PropertyAccessor.getProperty("existed.dec"));
/* if DEC alreay exists, check context
* If context is different, add Used_by alt_name
*/
if(!newDec.getContext().getId().equals(defaults.getContext().getId())) {
addAlternateName(newDec, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null);
}
}
addAlternateName(newDec, newName, AlternateName.TYPE_UML_DEC, packageName);
for(Definition def : modelDefinitions) {
addAlternateDefinition(
newDec, def.getDefinition(),
def.getType(), packageName);
}
LogUtil.logAc(newDec, logger);
logger.info("-- Public ID: " + newDec.getPublicId());
logger.info(PropertyAccessor
.getProperty("oc.longName",
newDec.getObjectClass().getLongName()));
logger.info(PropertyAccessor
.getProperty("prop.longName",
newDec.getProperty().getLongName()));
addPackageClassification(newDec, packageName);
it.set(newDec);
// dec still referenced in DE. Need ID to retrieve it in DEPersister.
dec.setId(newDec.getId());
}
}
}
private DataElementConcept existingMapping(DataElementConcept dec, String newName, String packageName) throws PersisterException {
List<String> eager = new ArrayList<String>();
eager.add(EagerConstants.AC_CS_CSI);
List<DataElementConcept> l = dataElementConceptDAO.find(dec, eager);
if(l.size() == 0)
throw new PersisterException(PropertyAccessor.getProperty("dec.existing.error", ConventionUtil.publicIdVersion(dec)));
DataElementConcept existingDec = l.get(0);
addAlternateName(existingDec, newName, AlternateName.TYPE_UML_CLASS ,packageName);
return existingDec;
}
}
| true | true | public void persist() throws PersisterException {
DataElementConcept dec = DomainObjectFactory.newDataElementConcept();
List<DataElementConcept> decs = elements.getElements(dec);
int count = 0;
sendProgressEvent(count++, decs.size(), "DECs");
logger.debug("decs... ");
if (decs != null) {
for (ListIterator<DataElementConcept> it = decs.listIterator(); it.hasNext();) {
DataElementConcept newDec = DomainObjectFactory.newDataElementConcept();
dec = it.next();
sendProgressEvent(count++, decs.size(), "DEC : " + dec.getLongName());
List<Definition> modelDefinitions = dec.getDefinitions();
List<AlternateName> modelAltNames = dec.getAlternateNames();
dec.removeDefinitions();
dec.removeAlternateNames();
String newName = dec.getLongName();
String packageName = getPackageName(dec);
if(!StringUtil.isEmpty(dec.getPublicId()) && dec.getVersion() != null) {
newDec = existingMapping(dec, newName, packageName);
it.set(newDec);
addPackageClassification(newDec, packageName);
logger.info(PropertyAccessor.getProperty("mapped.to.existing.dec"));
continue;
}
// update object class with persisted one
if(dec.getObjectClass().getPublicId() == null)
dec.setObjectClass(LookupUtil.lookupObjectClass(
dec.getObjectClass().getPreferredName()));
else
dec.setObjectClass(LookupUtil.lookupObjectClass
(dec.getObjectClass().getPublicId(),
dec.getObjectClass().getVersion()));
newDec.setObjectClass(dec.getObjectClass());
// update property with persisted one
if(dec.getProperty().getPublicId() == null)
dec.setProperty(LookupUtil.lookupProperty(
dec.getProperty().getPreferredName()));
else
dec.setProperty(LookupUtil.lookupProperty
(dec.getProperty().getPublicId(),
dec.getProperty().getVersion()));
newDec.setProperty(dec.getProperty());
logger.debug("dec name: " + dec.getLongName());
logger.debug("alt Name: " + newName);
List<String> eager = new ArrayList<String>();
eager.add("definitions");
// does this dec exist?
List l = dataElementConceptDAO.find(newDec, eager);
// String newDef = dec.getPreferredDefinition();
if (l.size() == 0) {
dec.setConceptualDomain(defaults.getConceptualDomain());
dec.setContext(defaults.getContext());
dec.setLongName(
dec.getObjectClass().getLongName()
+ " " +
dec.getProperty().getLongName()
);
dec.setPreferredDefinition(
dec.getObjectClass().getPreferredDefinition()
+ DEC_PREFERRED_DEF_CONCAT_CHAR
+ dec.getProperty().getPreferredDefinition()
);
dec.setPreferredName
(ConventionUtil.publicIdVersion(dec.getObjectClass())
+ DEC_PREFERRED_NAME_CONCAT_CHAR
+ ConventionUtil.publicIdVersion(dec.getProperty()));
dec.setVersion(new Float(1.0f));
dec.setWorkflowStatus(defaults.getWorkflowStatus());
dec.setProperty(LookupUtil.lookupProperty(dec.getProperty().getPreferredName()));
// List props = elements.getElements(DomainObjectFactory.newProperty()
// .getClass());
// for (int j = 0; j < props.size(); j++) {
// Property o = (Property) props.get(j);
// if (o.getLongName().equals(dec.getProperty()
// .getLongName())) {
// dec.setProperty(o);
// }
// }
dec.setAudit(defaults.getAudit());
dec.setLifecycle(defaults.getAudit());
// List altDefs = new ArrayList(dec.getDefinitions());
// List altNames = new ArrayList(dec.getAlternateNames());
newDec = dataElementConceptDAO.create(dec);
// // restore altNames
// for(Iterator it2 = altNames.iterator(); it2.hasNext();) {
// AlternateName an = (AlternateName)it2.next();
// dec.addAlternateName(an);
// }
// // restore altDefs
// for(Iterator it2 = altDefs.iterator(); it2.hasNext();) {
// Definition def = (Definition)it2.next();
// dec.addDefinition(def);
// }
logger.info(PropertyAccessor.getProperty("created.dec"));
} else {
newDec = (DataElementConcept) l.get(0);
logger.info(PropertyAccessor.getProperty("existed.dec"));
/* if DEC alreay exists, check context
* If context is different, add Used_by alt_name
*/
if(!newDec.getContext().getId().equals(defaults.getContext().getId())) {
addAlternateName(newDec, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null);
}
}
addAlternateName(newDec, newName, AlternateName.TYPE_UML_DEC, packageName);
for(Definition def : modelDefinitions) {
addAlternateDefinition(
newDec, def.getDefinition(),
def.getType(), packageName);
}
LogUtil.logAc(newDec, logger);
logger.info("-- Public ID: " + newDec.getPublicId());
logger.info(PropertyAccessor
.getProperty("oc.longName",
newDec.getObjectClass().getLongName()));
logger.info(PropertyAccessor
.getProperty("prop.longName",
newDec.getProperty().getLongName()));
addPackageClassification(newDec, packageName);
it.set(newDec);
// dec still referenced in DE. Need ID to retrieve it in DEPersister.
dec.setId(newDec.getId());
}
}
}
| public void persist() throws PersisterException {
DataElementConcept dec = DomainObjectFactory.newDataElementConcept();
List<DataElementConcept> decs = elements.getElements(dec);
int count = 0;
sendProgressEvent(count++, decs.size(), "DECs");
logger.debug("decs... ");
if (decs != null) {
for (ListIterator<DataElementConcept> it = decs.listIterator(); it.hasNext();) {
DataElementConcept newDec = DomainObjectFactory.newDataElementConcept();
dec = it.next();
sendProgressEvent(count++, decs.size(), "DEC : " + dec.getLongName());
List<Definition> modelDefinitions = dec.getDefinitions();
List<AlternateName> modelAltNames = dec.getAlternateNames();
dec.removeDefinitions();
dec.removeAlternateNames();
String newName = dec.getLongName();
String packageName = getPackageName(dec);
if(!StringUtil.isEmpty(dec.getPublicId()) && dec.getVersion() != null) {
newDec = existingMapping(dec, newName, packageName);
it.set(newDec);
addPackageClassification(newDec, packageName);
logger.info(PropertyAccessor.getProperty("mapped.to.existing.dec"));
continue;
}
// update object class with persisted one
if(dec.getObjectClass().getPublicId() == null)
dec.setObjectClass(LookupUtil.lookupObjectClass(
dec.getObjectClass().getPreferredName()));
else
dec.setObjectClass(LookupUtil.lookupObjectClass
(dec.getObjectClass().getPublicId(),
dec.getObjectClass().getVersion()));
newDec.setObjectClass(dec.getObjectClass());
// update property with persisted one
if(dec.getProperty().getPublicId() == null)
dec.setProperty(LookupUtil.lookupProperty(
dec.getProperty().getPreferredName()));
else
dec.setProperty(LookupUtil.lookupProperty
(dec.getProperty().getPublicId(),
dec.getProperty().getVersion()));
newDec.setProperty(dec.getProperty());
logger.debug("dec name: " + dec.getLongName());
logger.debug("alt Name: " + newName);
List<String> eager = new ArrayList<String>();
eager.add("definitions");
// does this dec exist?
List l = dataElementConceptDAO.find(newDec, eager);
// String newDef = dec.getPreferredDefinition();
if (l.size() == 0) {
dec.setConceptualDomain(defaults.getConceptualDomain());
dec.setContext(defaults.getContext());
dec.setLongName(
dec.getObjectClass().getLongName()
+ " " +
dec.getProperty().getLongName()
);
dec.setPreferredDefinition(
dec.getObjectClass().getPreferredDefinition()
+ DEC_PREFERRED_DEF_CONCAT_CHAR
+ dec.getProperty().getPreferredDefinition()
);
dec.setPreferredName
(ConventionUtil.publicIdVersion(dec.getObjectClass())
+ DEC_PREFERRED_NAME_CONCAT_CHAR
+ ConventionUtil.publicIdVersion(dec.getProperty()));
dec.setVersion(new Float(1.0f));
dec.setWorkflowStatus(defaults.getWorkflowStatus());
dec.setProperty(LookupUtil.lookupProperty(dec.getProperty().getPreferredName()));
// List props = elements.getElements(DomainObjectFactory.newProperty()
// .getClass());
// for (int j = 0; j < props.size(); j++) {
// Property o = (Property) props.get(j);
// if (o.getLongName().equals(dec.getProperty()
// .getLongName())) {
// dec.setProperty(o);
// }
// }
dec.setAudit(defaults.getAudit());
dec.setLifecycle(defaults.getLifecycle());
// List altDefs = new ArrayList(dec.getDefinitions());
// List altNames = new ArrayList(dec.getAlternateNames());
newDec = dataElementConceptDAO.create(dec);
// // restore altNames
// for(Iterator it2 = altNames.iterator(); it2.hasNext();) {
// AlternateName an = (AlternateName)it2.next();
// dec.addAlternateName(an);
// }
// // restore altDefs
// for(Iterator it2 = altDefs.iterator(); it2.hasNext();) {
// Definition def = (Definition)it2.next();
// dec.addDefinition(def);
// }
logger.info(PropertyAccessor.getProperty("created.dec"));
} else {
newDec = (DataElementConcept) l.get(0);
logger.info(PropertyAccessor.getProperty("existed.dec"));
/* if DEC alreay exists, check context
* If context is different, add Used_by alt_name
*/
if(!newDec.getContext().getId().equals(defaults.getContext().getId())) {
addAlternateName(newDec, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null);
}
}
addAlternateName(newDec, newName, AlternateName.TYPE_UML_DEC, packageName);
for(Definition def : modelDefinitions) {
addAlternateDefinition(
newDec, def.getDefinition(),
def.getType(), packageName);
}
LogUtil.logAc(newDec, logger);
logger.info("-- Public ID: " + newDec.getPublicId());
logger.info(PropertyAccessor
.getProperty("oc.longName",
newDec.getObjectClass().getLongName()));
logger.info(PropertyAccessor
.getProperty("prop.longName",
newDec.getProperty().getLongName()));
addPackageClassification(newDec, packageName);
it.set(newDec);
// dec still referenced in DE. Need ID to retrieve it in DEPersister.
dec.setId(newDec.getId());
}
}
}
|
diff --git a/src/de/typology/weights/WeightLearner.java b/src/de/typology/weights/WeightLearner.java
index 52bc333e..31f4f7f9 100644
--- a/src/de/typology/weights/WeightLearner.java
+++ b/src/de/typology/weights/WeightLearner.java
@@ -1,44 +1,43 @@
package de.typology.weights;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import de.typology.utils.IOHelper;
public class WeightLearner {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
- File baseDir = new File(
- "/home/rpickhardt/data/source code/git/typology/rawlog/");
+ File baseDir = new File("rawlog/");
for (String log : baseDir.list()) {
if (log.startsWith("learnHMM-")) {
BufferedWriter bw = IOHelper.openWriteFile(baseDir
.getAbsolutePath()
+ "/"
+ log.replace("learnHMM", "HMMWeights"));
File fin = new File(baseDir, log);
System.out.println("Learning Weights for: ");
System.out.println("\t" + log);
for (int prefix = 0; prefix < 10; prefix++) {
System.out.print(prefix + "\t0.0");
bw.write(prefix + "\t0.0");
LogReader reader = new LogReader(fin);
ForwardBackward fb = new ForwardBackward(reader, prefix);
double[] marginal = fb.computeMarginalDistribution();
for (double element : marginal) {
System.out.print("\t" + element);
bw.write("\t" + element);
}
System.out.println();
bw.write("\n");
}
bw.close();
}
}
}
}
| true | true | public static void main(String[] args) throws IOException {
File baseDir = new File(
"/home/rpickhardt/data/source code/git/typology/rawlog/");
for (String log : baseDir.list()) {
if (log.startsWith("learnHMM-")) {
BufferedWriter bw = IOHelper.openWriteFile(baseDir
.getAbsolutePath()
+ "/"
+ log.replace("learnHMM", "HMMWeights"));
File fin = new File(baseDir, log);
System.out.println("Learning Weights for: ");
System.out.println("\t" + log);
for (int prefix = 0; prefix < 10; prefix++) {
System.out.print(prefix + "\t0.0");
bw.write(prefix + "\t0.0");
LogReader reader = new LogReader(fin);
ForwardBackward fb = new ForwardBackward(reader, prefix);
double[] marginal = fb.computeMarginalDistribution();
for (double element : marginal) {
System.out.print("\t" + element);
bw.write("\t" + element);
}
System.out.println();
bw.write("\n");
}
bw.close();
}
}
}
| public static void main(String[] args) throws IOException {
File baseDir = new File("rawlog/");
for (String log : baseDir.list()) {
if (log.startsWith("learnHMM-")) {
BufferedWriter bw = IOHelper.openWriteFile(baseDir
.getAbsolutePath()
+ "/"
+ log.replace("learnHMM", "HMMWeights"));
File fin = new File(baseDir, log);
System.out.println("Learning Weights for: ");
System.out.println("\t" + log);
for (int prefix = 0; prefix < 10; prefix++) {
System.out.print(prefix + "\t0.0");
bw.write(prefix + "\t0.0");
LogReader reader = new LogReader(fin);
ForwardBackward fb = new ForwardBackward(reader, prefix);
double[] marginal = fb.computeMarginalDistribution();
for (double element : marginal) {
System.out.print("\t" + element);
bw.write("\t" + element);
}
System.out.println();
bw.write("\n");
}
bw.close();
}
}
}
|
diff --git a/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java b/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
index 6b0d4cd5..cff4dfa3 100644
--- a/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
+++ b/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
@@ -1,414 +1,415 @@
package com.github.seqware.queryengine.system.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.seqware.queryengine.Benchmarking;
import com.github.seqware.queryengine.Constants;
import com.github.seqware.queryengine.Constants.OVERLAP_STRATEGY;
import com.github.seqware.queryengine.factory.SWQEFactory;
import com.github.seqware.queryengine.model.Reference;
import com.github.seqware.queryengine.system.ReferenceCreator;
import com.github.seqware.queryengine.system.exporters.QueryVCFDumper;
import com.github.seqware.queryengine.system.importers.SOFeatureImporter;
import com.github.seqware.queryengine.util.SGID;
public class QueryVCFDumperBenchmarkTest implements Benchmarking{
private Configuration config;
private static String randomRef = null;
private static Reference reference = null;
private static SGID originalSet = null;
private static List<File> testingFiles = new ArrayList<File>();
private static final String DOWNLOAD_DIR = "/home/seqware/";
private static String FIRST_QUERY;
private static String SECOND_QUERY;
private static String THIRD_QUERY;
private static String FOURTH_QUERY;
private static long start, stop;
private static float diff;
private static List<Float> runQueryTimings = new ArrayList<Float>();
private static HashMap<String, List<Float>> allSingleScanRangeQueryTimings = new HashMap<String,List<Float>>();
private static HashMap<String, List<Float>> allMultiScanRangeQueryTimings = new HashMap<String,List<Float>>();
private static Float importTimingBinning;
private static Float importTimingNaiveOverlaps;
private static File outputFile;
/**Set this to true if you wish to use the smaller file (faster test) or larger file (longer test)**/
private static boolean QUICK_TEST = true;
@BeforeClass
public static void setUpTest(){
try{
if (QUICK_TEST == false){
/**This file contains 1,000,000 lines**/
String vcf = "https://dl.dropboxusercontent.com/u/3238966/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites1MillionLines.vcf.gz";
/**This file contains 2,000,000 lines**/
//String vcf = "https://dl.dropboxusercontent.com/u/3238966/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites.vcf.gz";
/**This file contains 4,000,000 lines**/
//String vcf = "http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase1/analysis_results/consensus_call_sets/indels/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites.vcf.gz";
testingFiles = download(vcf);
FIRST_QUERY = "start>=61800882 && stop <=81800882";
SECOND_QUERY = "start>=61800882 && stop <=81800882 && (seqid==\"X\" || seqid==\"19\")";
THIRD_QUERY = "start>=61800882 && stop <=81800882 || start >= 6180882 && stop <= 9180082";
FOURTH_QUERY = "(start>=61800882 && stop <=81800882 || start >= 6180882 && stop <= 9180082) && (seqid==\"X\" || seqid==\"19\")";
} else if (QUICK_TEST == true){
testingFiles.add(new File("/home/seqware/gitroot/queryengine/seqware-queryengine-backend/src/test/resources/com/github/seqware/queryengine/system/FeatureImporter/consequences_annotated.vcf"));
FIRST_QUERY = "seqid==\"21\" ";
SECOND_QUERY = "seqid==\"21\" && start >= 20000000 && stop <= 30000000";
THIRD_QUERY = "seqid==\"21\" && start >= 20000000 && stop <= 30000000 || start >=40000000 && stop <=40200000";
FOURTH_QUERY = "seqid==\"21\" && (start >= 20000000 && stop <= 30000000 || start >=40000000 && stop <=40200000)";
}
outputFile = null;
try {
outputFile = File.createTempFile("output", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testBinning(){
try{
setOverlapStrategy(Constants.OVERLAP_STRATEGY.BINNING);
System.out.println("Setting OVERLAP_STRATEGY => " + Constants.OVERLAP_STRATEGY.BINNING.toString() + "\n");
start = new Date().getTime();
importToBackend(testingFiles);
stop = new Date().getTime();
diff = ((stop - start) / 1000);
importTimingBinning = diff;
Constants.MULTIPLE_SCAN_RANGES = false;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allSingleScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.BINNING.toString(), runQueryTimings);
Constants.MULTIPLE_SCAN_RANGES = true;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allMultiScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.BINNING.toString(), runQueryTimings);
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testNaiveOverlaps(){
try{
setOverlapStrategy(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS);
System.out.println("Setting OVERLAP_STRATEGY => " + Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString() + "\n");
start = new Date().getTime();
importToBackend(testingFiles);
stop = new Date().getTime();
diff = ((stop - start) / 1000);
importTimingNaiveOverlaps = diff;
Constants.MULTIPLE_SCAN_RANGES = false;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allSingleScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString(), runQueryTimings);
Constants.MULTIPLE_SCAN_RANGES = true;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allMultiScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString(), runQueryTimings);
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testGenerateReport(){
try{
generateReport();
resetAllTables();
System.out.println("Done!");
} catch (Exception e){
e.printStackTrace();
}
}
public void setOverlapStrategy(OVERLAP_STRATEGY strategy){
Constants.OVERLAP_MODE = strategy;
}
public void generateReport(){
int i;
float thisSet = 0;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "s" + "\t (" + importTimingBinning/60 + "min)" + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps)+ "s" + "\t (" + importTimingNaiveOverlaps/60 + "min)" + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
singleTotal += thisSet;
+ thisSet = 0;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = FALSE: " + singleTotal + "s" + "\t (" + singleTotal/60 + "min)");
System.out.println("\n");
- thisSet = 0;
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
multiTotal += thisSet;
+ thisSet = 0;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = TRUE: " + multiTotal + "s" + "\t (" + multiTotal/60 + "min)");
System.out.println("\n");
total = singleTotal + multiTotal;
System.out.println("\t" + "**Time to complete all tests: " + total + "s" + "\t (" + total/60 + "min)");
System.out.println("\n");
}
public void resetAllTables(){
this.config = HBaseConfiguration.create();
try{
System.out.println("Closing tables....");
HBaseAdmin hba = new HBaseAdmin(config);
hba.disableTables("b.*");
hba.deleteTables("b.*");
hba.close();
} catch (Exception e){
e.printStackTrace();
}
}
private static void downloadFile(String file, File downloadDir, List<File> filesToReturnGZCompressed) throws IOException, MalformedURLException, URISyntaxException {
URL newURL = new URL(file);
String name = newURL.toString().substring(newURL.toString().lastIndexOf("/"));
File targetFile = new File(downloadDir, name);
if (!targetFile.exists()){
System.out.println("Downloading " + newURL.getFile() + " to " + targetFile.getAbsolutePath());
FileUtils.copyURLToFile(newURL, targetFile);
}
filesToReturnGZCompressed.add(targetFile);
}
private static List<File> download(String file) {
List<File> filesToReturnGZCompressed = new ArrayList<File>();
List<File> filesToReturnGZUnCompressed = new ArrayList<File>();
// always use the same directory so we do not re-download on repeated runs
File downloadDir = new File(DOWNLOAD_DIR);
try {
downloadFile(file, downloadDir, filesToReturnGZCompressed);
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
for (File thisGZCompressedFile : filesToReturnGZCompressed){
try{
File thisGZUncompressedFile = new File("");
thisGZUncompressedFile = gzDecompressor(thisGZCompressedFile);
Logger.getLogger(QueryVCFDumperBenchmarkTest.class).info("CompressedFile: " + thisGZCompressedFile.getAbsolutePath());
Logger.getLogger(QueryVCFDumperBenchmarkTest.class).info("DeCompressedFile: " + thisGZUncompressedFile.getAbsolutePath());
System.out.println("Done!\n");
filesToReturnGZUnCompressed.add(thisGZUncompressedFile);
} catch (Exception e){
e.printStackTrace();
}
}
return filesToReturnGZUnCompressed;
}
private static void importToBackend(List<File> file){
try{
//Use first file only for now
File f = file.get(0);
Assert.assertTrue("Cannot read VCF file for test", f.exists() && f.canRead());
List<String> argList = new ArrayList<String>();
randomRef = "Random_ref_" + new BigInteger(20, new SecureRandom()).toString(32);
SGID refID = ReferenceCreator.mainMethod(new String[]{randomRef});
reference = SWQEFactory.getQueryInterface().getAtomBySGID(Reference.class, refID);
argList.addAll(Arrays.asList(new String[]{"-w", "VCFVariantImportWorker",
"-i", f.getAbsolutePath(),
"-r", reference.getSGID().getRowKey()}));
System.out.println("Importing " + testingFiles.get(0).getName() + " to database.\n");
originalSet = SOFeatureImporter.runMain(argList.toArray(new String[argList.size()]));
Assert.assertTrue("Could not import VCF for test", originalSet != null);
} catch (Exception e){
e.printStackTrace();
}
}
private static File gzDecompressor(File filePathGZ) throws IOException{
String filename = filePathGZ
.getName()
.substring(0, filePathGZ.getName().lastIndexOf("."));
byte[] buf =
new byte[1024];
int len;
File thisGZUncompressedFile;
String outFilename = DOWNLOAD_DIR + filename;
FileInputStream instream =
new FileInputStream(filePathGZ);
GZIPInputStream ginstream =
new GZIPInputStream(instream);
FileOutputStream outstream =
new FileOutputStream(outFilename);
System.out.println("Decompressing... " + filePathGZ);
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
outstream.close();
ginstream.close();
thisGZUncompressedFile = new File(outFilename);
return thisGZUncompressedFile;
}
private void testFirstQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", FIRST_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testSecondQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", SECOND_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testThirdQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", THIRD_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testFourthQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", FOURTH_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private List<Float> runQueries(){
List<Float> runQueryTimings = new ArrayList<Float>();
System.out.println("Running first query....\n");
start = new Date().getTime();
testFirstQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running second query....\n");
start = new Date().getTime();
testSecondQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running third query....\n");
start = new Date().getTime();
testThirdQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running fourth query....\n");
start = new Date().getTime();
testFourthQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
return runQueryTimings;
}
}
| false | true | public void generateReport(){
int i;
float thisSet = 0;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "s" + "\t (" + importTimingBinning/60 + "min)" + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps)+ "s" + "\t (" + importTimingNaiveOverlaps/60 + "min)" + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
singleTotal += thisSet;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = FALSE: " + singleTotal + "s" + "\t (" + singleTotal/60 + "min)");
System.out.println("\n");
thisSet = 0;
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
multiTotal += thisSet;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = TRUE: " + multiTotal + "s" + "\t (" + multiTotal/60 + "min)");
System.out.println("\n");
total = singleTotal + multiTotal;
System.out.println("\t" + "**Time to complete all tests: " + total + "s" + "\t (" + total/60 + "min)");
System.out.println("\n");
}
| public void generateReport(){
int i;
float thisSet = 0;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "s" + "\t (" + importTimingBinning/60 + "min)" + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps)+ "s" + "\t (" + importTimingNaiveOverlaps/60 + "min)" + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
singleTotal += thisSet;
thisSet = 0;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = FALSE: " + singleTotal + "s" + "\t (" + singleTotal/60 + "min)");
System.out.println("\n");
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println("\t" + "Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println("\t" + "\t" + "Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "\t (" + f/60 + "min)");
thisSet += f;
}
System.out.println("\t" + "Time to complete this set: " + thisSet + "s" + "\t (" + thisSet/60 + "min)");
multiTotal += thisSet;
thisSet = 0;
}
System.out.println("\t" + "Time to complete MULTIPLE SCAN RANGES = TRUE: " + multiTotal + "s" + "\t (" + multiTotal/60 + "min)");
System.out.println("\n");
total = singleTotal + multiTotal;
System.out.println("\t" + "**Time to complete all tests: " + total + "s" + "\t (" + total/60 + "min)");
System.out.println("\n");
}
|
diff --git a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/parser/AcceleoFile.java b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/parser/AcceleoFile.java
index 5744e06f..49cf5d43 100644
--- a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/parser/AcceleoFile.java
+++ b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/parser/AcceleoFile.java
@@ -1,130 +1,130 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.parser;
import java.io.File;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.core.runtime.Path;
/**
* This is an Acceleo file. It creates a mapping between an MTL java.io.File and an unique ID. This ID is the
* full qualified module name. It is used to identify the module, like the NsURI feature in the EPackage
* registry.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
* @since 3.0
*/
public final class AcceleoFile {
/**
* The MTL input IO file.
*/
private File mtlFile;
/**
* The full qualified module name. For example, 'org::eclipse::myGen' is the full module name of the
* 'MyProject/src/org/eclipse/myGen.mtl' file.
*/
private String fullModuleName;
/**
* Constructor.
*
* @param mtlFile
* the MTL input IO file
* @param fullModuleName
* the full qualified module name which can be computed with the following static methods of
* this class : 'javaPackageToFullModuleName', 'simpleModuleName',
* 'relativePathToFullModuleName'...
*/
public AcceleoFile(File mtlFile, String fullModuleName) {
super();
this.mtlFile = mtlFile;
this.fullModuleName = fullModuleName;
}
/**
* Computes the full qualified module name with the java package name and the module name. For example,
* 'org::eclipse::myGen' is the full module name for the 'org.eclipse' java package and the 'myGen' simple
* module name.
*
* @param javaPackageName
* is the name of the enclosing java package
* @param moduleName
* is the simple name of the module (i.e the short name of the MTL file)
* @return a valid full qualified module name that you can use to create an AcceleoFile instance
*/
public static String javaPackageToFullModuleName(String javaPackageName, String moduleName) {
if (javaPackageName != null && javaPackageName.length() > 0) {
return javaPackageName.replaceAll("\\.", IAcceleoConstants.NAMESPACE_SEPARATOR)
+ IAcceleoConstants.NAMESPACE_SEPARATOR + moduleName;
} else {
return moduleName;
}
}
/**
* Computes the full qualified module name with the MTL IO file. The single information available is the
* file name. In this case, the module name isn't relative to the enclosing source folder.
*
* @param mtlFile
* is the MTL IO file
* @return a valid full qualified module name that you can use to create an AcceleoFile instance
*/
public static String simpleModuleName(File mtlFile) {
return new Path(mtlFile.getName()).removeFileExtension().lastSegment();
}
/**
* Computes the full qualified module name with the given relative path. Let's take a simple MTL file with
* the following full path 'MyProject/src/org/eclipse/myGen.mtl'. The relative path of this MTL file must
* be 'org/eclipse/myGen.mtl'. In this case, the method returns 'org::eclipse::myGen' as the full module
* name of the MTL file.
*
* @param relativePath
* is the MTL file path, relative to the enclosing source folder
* @return a valid full qualified module name that you can use to create an AcceleoFile instance
*/
public static String relativePathToFullModuleName(String relativePath) {
StringBuilder fullModuleName = new StringBuilder();
- String[] segments = new Path(relativePath).segments();
+ String[] segments = new Path(relativePath).removeFileExtension().segments();
for (int i = 0; i < segments.length; i++) {
if (i != 0) {
fullModuleName.append(IAcceleoConstants.NAMESPACE_SEPARATOR);
}
fullModuleName.append(segments[i]);
}
return fullModuleName.toString();
}
/**
* Gets the MTL input IO file.
*
* @return the MTL input IO file
*/
public File getMtlFile() {
return mtlFile;
}
/**
* Gets the full qualified module name. This ID is used to identify everywhere the module defined in this
* file, like the NsURI feature in the EPackage registry. This information is also stored in the root
* element of the EMTL resource (Module.nsURI).
*
* @return the full qualified module name
*/
public String getFullModuleName() {
return fullModuleName;
}
}
| true | true | public static String relativePathToFullModuleName(String relativePath) {
StringBuilder fullModuleName = new StringBuilder();
String[] segments = new Path(relativePath).segments();
for (int i = 0; i < segments.length; i++) {
if (i != 0) {
fullModuleName.append(IAcceleoConstants.NAMESPACE_SEPARATOR);
}
fullModuleName.append(segments[i]);
}
return fullModuleName.toString();
}
| public static String relativePathToFullModuleName(String relativePath) {
StringBuilder fullModuleName = new StringBuilder();
String[] segments = new Path(relativePath).removeFileExtension().segments();
for (int i = 0; i < segments.length; i++) {
if (i != 0) {
fullModuleName.append(IAcceleoConstants.NAMESPACE_SEPARATOR);
}
fullModuleName.append(segments[i]);
}
return fullModuleName.toString();
}
|
diff --git a/src/main/java/de/ubercode/javaunitevolution/core/GenericFitnessFunction.java b/src/main/java/de/ubercode/javaunitevolution/core/GenericFitnessFunction.java
index 79abd54..ac0772a 100644
--- a/src/main/java/de/ubercode/javaunitevolution/core/GenericFitnessFunction.java
+++ b/src/main/java/de/ubercode/javaunitevolution/core/GenericFitnessFunction.java
@@ -1,73 +1,73 @@
package de.ubercode.javaunitevolution.core;
import org.apache.log4j.*;
import org.jgap.gp.*;
import org.junit.runner.*;
import org.junit.runner.notification.*;
/**
* A fitness function that will invoke the supplied test case to measure
* program fitness.
*/
class GenericFitnessFunction extends GPFitnessFunction {
private static Logger LOGGER =
Logger.getLogger(GenericFitnessFunction.class);
private static final long serialVersionUID = 1L;
private Class<?> testClass;
/**
* Creates a new fitness function using the supplied test class.
* @param testClass The class containing the test cases used to assess
* the fitness of a program.
*/
public GenericFitnessFunction(Class<?> testClass) {
this.testClass = testClass;
}
@Override
protected double evaluate(IGPProgram subject) {
JavaUnitEvolution.currentProgram = subject;
Result result = JUnitCore.runClasses(testClass);
if (result.getFailureCount() == 0)
return 0.0;
double delta = 0.0;
for (Failure failure : result.getFailures()) {
Throwable t = failure.getException();
if (t instanceof AssertionError)
delta += extractDelta((AssertionError) t);
}
LOGGER.debug("Calculated delta: " + delta);
return delta;
}
/**
* Extracts the delta between the two values of an error.
* @param error The error from which to extract the delta.
* @return The calculated delta.
*/
private double extractDelta(AssertionError error) {
// XXX: Make this more robust.
String message = error.getMessage();
LOGGER.debug("Extracting assertion message: " + message);
String expected = message.substring(message.indexOf("<") + 1,
message.indexOf(">"));
String actual = message.substring(message.lastIndexOf("<") + 1,
message.lastIndexOf(">"));
try {
return Math.abs(Double.valueOf(expected) - Double.valueOf(actual));
} catch (NumberFormatException e1) {
try {
- return Math.abs(Float.valueOf(expected) -
- Float.valueOf(actual));
+ return Math.abs(Float.valueOf(expected)
+ - Float.valueOf(actual));
} catch (NumberFormatException e2) {
try {
- return Math.abs(Integer.valueOf(expected) -
- Integer.valueOf(actual));
+ return Math.abs(Integer.valueOf(expected)
+ - Integer.valueOf(actual));
} catch (NumberFormatException e3) {
// TODO: Try other data types
return 1.0;
}
}
}
}
}
| false | true | private double extractDelta(AssertionError error) {
// XXX: Make this more robust.
String message = error.getMessage();
LOGGER.debug("Extracting assertion message: " + message);
String expected = message.substring(message.indexOf("<") + 1,
message.indexOf(">"));
String actual = message.substring(message.lastIndexOf("<") + 1,
message.lastIndexOf(">"));
try {
return Math.abs(Double.valueOf(expected) - Double.valueOf(actual));
} catch (NumberFormatException e1) {
try {
return Math.abs(Float.valueOf(expected) -
Float.valueOf(actual));
} catch (NumberFormatException e2) {
try {
return Math.abs(Integer.valueOf(expected) -
Integer.valueOf(actual));
} catch (NumberFormatException e3) {
// TODO: Try other data types
return 1.0;
}
}
}
}
| private double extractDelta(AssertionError error) {
// XXX: Make this more robust.
String message = error.getMessage();
LOGGER.debug("Extracting assertion message: " + message);
String expected = message.substring(message.indexOf("<") + 1,
message.indexOf(">"));
String actual = message.substring(message.lastIndexOf("<") + 1,
message.lastIndexOf(">"));
try {
return Math.abs(Double.valueOf(expected) - Double.valueOf(actual));
} catch (NumberFormatException e1) {
try {
return Math.abs(Float.valueOf(expected)
- Float.valueOf(actual));
} catch (NumberFormatException e2) {
try {
return Math.abs(Integer.valueOf(expected)
- Integer.valueOf(actual));
} catch (NumberFormatException e3) {
// TODO: Try other data types
return 1.0;
}
}
}
}
|
diff --git a/test/src/net/sf/freecol/util/test/MockPseudoRandom.java b/test/src/net/sf/freecol/util/test/MockPseudoRandom.java
index 12a1f7d4b..db70ad5f3 100644
--- a/test/src/net/sf/freecol/util/test/MockPseudoRandom.java
+++ b/test/src/net/sf/freecol/util/test/MockPseudoRandom.java
@@ -1,47 +1,55 @@
package net.sf.freecol.util.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.sf.freecol.common.PseudoRandom;
public class MockPseudoRandom implements PseudoRandom {
int pos;
private List<Integer> setNumberList;
private boolean cycleNumbers;
private Random random;
public MockPseudoRandom(){
this(new ArrayList<Integer>(),false);
}
public MockPseudoRandom(List<Integer> setNumbers,boolean toCycle){
pos = 0;
setNumberList = setNumbers;
cycleNumbers = toCycle;
random = null;
}
public void setNextNumbers(List<Integer> setNumbers,boolean toCycle){
pos = 0;
setNumberList = setNumbers;
cycleNumbers = toCycle;
}
@Override
public int nextInt(int n) {
if(pos < setNumberList.size()){
+ int number = setNumberList.get(pos);
+ if(number >= n){
+ throw new IllegalArgumentException("Number in queue is bigger than " + n);
+ }
pos++;
- return setNumberList.get(pos-1);
+ return number;
}
if(cycleNumbers && !setNumberList.isEmpty()){
+ int number = setNumberList.get(0);
pos = 1;
- return setNumberList.get(pos-1);
+ if(number >= n){
+ throw new IllegalArgumentException("Number in queue is bigger than " + n);
+ }
+ return number;
}
if(random == null){
random = new Random(0);
}
- return random.nextInt();
+ return random.nextInt(n);
}
}
| false | true | public int nextInt(int n) {
if(pos < setNumberList.size()){
pos++;
return setNumberList.get(pos-1);
}
if(cycleNumbers && !setNumberList.isEmpty()){
pos = 1;
return setNumberList.get(pos-1);
}
if(random == null){
random = new Random(0);
}
return random.nextInt();
}
| public int nextInt(int n) {
if(pos < setNumberList.size()){
int number = setNumberList.get(pos);
if(number >= n){
throw new IllegalArgumentException("Number in queue is bigger than " + n);
}
pos++;
return number;
}
if(cycleNumbers && !setNumberList.isEmpty()){
int number = setNumberList.get(0);
pos = 1;
if(number >= n){
throw new IllegalArgumentException("Number in queue is bigger than " + n);
}
return number;
}
if(random == null){
random = new Random(0);
}
return random.nextInt(n);
}
|
diff --git a/src/main/java/com/ebay/web/cors/CORSConfiguration.java b/src/main/java/com/ebay/web/cors/CORSConfiguration.java
index 4a28195..df24124 100755
--- a/src/main/java/com/ebay/web/cors/CORSConfiguration.java
+++ b/src/main/java/com/ebay/web/cors/CORSConfiguration.java
@@ -1,398 +1,401 @@
/**
* Copyright 2012-2013 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.ebay.web.cors;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
/**
* The configuration for {@link CORSFilter}.
*
* <ul>
* <li>
* <b>Allowed Origins:</b> A white list of origins, which can send a CORS
* request.</li>
* <li>
* <b>Allowed HTTP Methods:</b> HTTP verbs that can be used to send a CORS
* request.</li>
* <li>
* <b>Allowed HTTP Headers:</b> A list of headers that can be sent with a CORS
* request.</li>
* <li>
* <b>Exposed headers:</b> A list of response headers that can be exposed to JS
* API.</li>
* <li>
* <b>Pre-flight max age:</b> Time duration, in seconds that a client can cache
* pre-flight request.</li>
* </ul>
* <p>
* Defaults:
* </p>
* <ul>
* <li>Allowed HTTP methods: [GET, POST, OPTIONS, HEAD]</li>
* <li>Supports credentials: true</li>
* </ul>
*
* @author <a href="mailto:[email protected]">Mohit Soni</a>
*
*/
public final class CORSConfiguration {
/**
* By default, time duration to cache pre-flight response is 30 mins.
*/
public static final String DEFAULT_PREFLIGHT_MAXAGE = "1800";
/**
* By default, cookie based auth is turned off.
*/
public static final String DEFAULT_SUPPORTS_CREDENTIALS = "false";
/**
* By default, all origins are allowed to make requests.
*/
public static final String DEFAULT_ALLOWED_ORIGINS = "*";
/**
* By default, following methods are supported: GET, POST, HEAD and OPTIONS.
*/
public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS";
/**
* By default, following headers are supported:
* Origin,Accept,X-Requested-With, and Content-Type.
*/
public static final String DEFAULT_ALLOWED_HTTP_HEADERS = "Origin,Accept,X-Requested-With,Content-Type";
/**
* By default, none of the headers are exposed in response.
*/
public static final String DEFAULT_EXPOSED_HEADERS = "";
/**
* Key to retrieve allowed origins from {@link FilterConfig}.
*/
public static final String CORS_ALLOWED_ORIGINS = "cors.allowed.origins";
/**
* Key to retrieve support credentials from {@link FilterConfig}.
*/
public static final String CORS_SUPPORT_CREDENTIALS = "cors.support.credentials";
/**
* Key to retrieve exposed headers from {@link FilterConfig}.
*/
public static final String CORS_EXPOSED_HEADERS = "cors.exposed.headers";
/**
* Key to retrieve allowed headers from {@link FilterConfig}.
*/
public static final String CORS_ALLOWED_HEADERS = "cors.allowed.headers";
/**
* Key to retrieve allowed methods from {@link FilterConfig}.
*/
public static final String CORS_ALLOWED_METHODS = "cors.allowed.methods";
/**
* Key to retrieve preflight max age from {@link FilterConfig}.
*/
public static final String CORS_PREFLIGHT_MAXAGE = "cors.preflight.maxage";
/**
* Set of origin URL that are allowed to make a CORS request.
*/
private final Set<String> allowedOrigins;
/**
* Determines if any origin is allowed to make request.
*/
private boolean anyOriginAllowed;
/**
* Set of allowed HTTP methods, which the CORS filter support.
*/
private final Set<String> allowedHttpMethods;
/**
* Set of allowed headers, which the CORS filter support.
*/
private final Set<String> allowedHttpHeaders;
/**
* Set of exposed headers.
*/
private Set<String> exposedHeaders;
/**
* Does filter supports credentials ?
*/
private boolean supportsCredentials;
/**
* Indicates (in seconds) how long the results of a pre-flight request can
* be cached in a pre-flight result cache.
*/
private long preflightMaxAge;
/**
* Initialize defaults.
*/
public CORSConfiguration() throws ServletException {
this.allowedOrigins = new HashSet<String>();
this.allowedHttpMethods = new HashSet<String>();
this.allowedHttpHeaders = new HashSet<String>();
this.exposedHeaders = new HashSet<String>();
parseAndStore(DEFAULT_ALLOWED_ORIGINS, DEFAULT_ALLOWED_HTTP_METHODS,
DEFAULT_ALLOWED_HTTP_HEADERS, DEFAULT_EXPOSED_HEADERS,
DEFAULT_SUPPORTS_CREDENTIALS, DEFAULT_PREFLIGHT_MAXAGE);
}
/**
* Initialize CORS configuration, by passing in configuration attributes
* from application.
*
* @param allowedOrigins
* A comma separated list of allowed origin for CORS.
* @param allowedHttpMethods
* A comma separated list of allowed HTTP methods.
* @param allowedHttpHeaders
* A comma separated list of allowed HTTP headers.
* @param exposedHeaders
* A comma separated list of HTTP headers in response that we are
* XHR2 object can access.
* @param supportsCredentials
* Is auth required ? Response will contain an allow credentials
* header.
*/
public CORSConfiguration(final String allowedOrigins,
final String allowedHttpMethods, final String allowedHttpHeaders,
final String exposedHeaders, final String supportsCredentials,
final String preflightMaxAge) throws ServletException {
this.allowedOrigins = new HashSet<String>();
this.allowedHttpMethods = new HashSet<String>();
this.allowedHttpHeaders = new HashSet<String>();
this.exposedHeaders = new HashSet<String>();
parseAndStore(allowedOrigins, allowedHttpMethods, allowedHttpHeaders,
exposedHeaders, supportsCredentials, preflightMaxAge);
}
private void parseAndStore(final String allowedOrigins,
final String allowedHttpMethods, final String allowedHttpHeaders,
final String exposedHeaders, final String supportsCredentials,
final String preflightMaxAge) throws ServletException {
if (allowedOrigins != null) {
if (allowedOrigins.trim().equals("*")) {
this.anyOriginAllowed = true;
} else {
this.anyOriginAllowed = false;
Set<String> setAllowedOrigins = parseStringToSet(allowedOrigins);
setAllowedOrigins(setAllowedOrigins);
}
}
Set<String> setAllowedHttpMethods = parseStringToSet(allowedHttpMethods);
setAllowedHttpMethods(setAllowedHttpMethods);
Set<String> setAllowedHttpHeaders = parseStringToSet(allowedHttpHeaders);
setAllowedHttpHeaders(setAllowedHttpHeaders);
Set<String> setExposedHeaders = parseStringToSet(exposedHeaders);
setExposedHeaders(setExposedHeaders);
// For any value other then 'true' this will be false.
boolean isSupportsCredentials = Boolean
.parseBoolean(supportsCredentials);
this.supportsCredentials = isSupportsCredentials;
try {
- this.preflightMaxAge = (preflightMaxAge != null && preflightMaxAge
- .isEmpty() == false) ? Long.parseLong(preflightMaxAge) : 0;
+ if (preflightMaxAge != null && preflightMaxAge.isEmpty() == false) {
+ this.preflightMaxAge = Long.parseLong(preflightMaxAge);
+ } else {
+ this.preflightMaxAge = 0L;
+ }
} catch (NumberFormatException e) {
throw new ServletException("Unable to parse preflightMaxAge", e);
}
}
/**
* Returns an unmodifiable set of allowedOrigins.
*
* @return Set<String>
*/
public Set<String> getAllowedOrigins() {
return Collections.unmodifiableSet(this.allowedOrigins);
}
/**
* Set the allowedOrigins, from which a CORS request can be made.
*
* @param allowedOrigins
* The set of allowed origins.
*/
public void setAllowedOrigins(final Set<String> allowedOrigins) {
this.allowedOrigins.addAll(allowedOrigins);
}
/**
* Returns an unmodifiable set of allowedHttpMethods.
*
* @return Set<String>
*/
public Set<String> getAllowedHttpMethods() {
return Collections.unmodifiableSet(this.allowedHttpMethods);
}
/**
* Set the allowedHttpMethods, with which a CORS request can be made.
*
* @param allowedHttpMethods
* The Set<String> of allowed HTTP methods.
*/
public void setAllowedHttpMethods(final Set<String> allowedHttpMethods) {
this.allowedHttpMethods.addAll(allowedHttpMethods);
}
/**
* Returns an unmodifiable set of exposedHeaders.
*
* @return Set<String>
*/
public Set<String> getExposedHeaders() {
return Collections.unmodifiableSet(this.exposedHeaders);
}
/**
* Set the exposedHeaders, which a CORS response can expose to CORS API.
*
* @param exposedHeaders
* The Set<String> of exposed HTTP headers.
*/
public void setExposedHeaders(final Set<String> exposedHeaders) {
this.exposedHeaders = exposedHeaders;
}
/**
* Returns an unmodifiable set of allowedHttpHeaders.
*
* @return Set<String>
*/
public Set<String> getAllowedHttpHeaders() {
return Collections.unmodifiableSet(this.allowedHttpHeaders);
}
/**
* Set the allowedHttpHeaders, which a simple CORS request can include.
*
* @param allowedHttpHeaders
* The Set<String> of allowed HTTP headers.
*/
public void setAllowedHttpHeaders(final Set<String> allowedHttpHeaders) {
this.allowedHttpHeaders.addAll(allowedHttpHeaders);
}
/**
* Is cookie based auth supported ?
*
* @return boolean
*/
public boolean isSupportsCredentials() {
return this.supportsCredentials;
}
/**
* Takes a comma separated list and returns a Set<String>.
*
* @param data
* A comma separated list of strings.
* @return Set<String>
*/
private Set<String> parseStringToSet(final String data) {
String[] splits = null;
if (data != null && data.length() > 0) {
splits = data.split(",");
} else {
splits = new String[] {};
}
Set<String> set = new HashSet<String>();
if (splits.length > 0) {
for (String split : splits) {
set.add(split.trim());
}
}
return set;
}
/**
* Gets pre-flight response max cache time.
*
* @return long
*/
public long getPreflightMaxAge() {
return preflightMaxAge;
}
/**
* Returns true if any origin is allowed to make CORS request as per
* configuration.
*
* @return <code>true</code> if any origin is allowed; <code>false</code>
* otherwise.
*/
public boolean isAnyOriginAllowed() {
return anyOriginAllowed;
}
/**
* Creates an instance of {@link CORSConfiguration} from the
* {@link FilterConfig} object.
*
* @param filterConfig
* The {@link FilterConfig} object containing filter init
* parameters.
* @return {@link CORSConfiguration} The configuration object.
*/
public static CORSConfiguration loadFromFilterConfig(
FilterConfig filterConfig) throws ServletException {
CORSConfiguration corsConfiguration = null;
if (filterConfig != null) {
String allowedOrigins = filterConfig
.getInitParameter(CORS_ALLOWED_ORIGINS);
String allowedHttpMethods = filterConfig
.getInitParameter(CORS_ALLOWED_METHODS);
String allowedHttpHeaders = filterConfig
.getInitParameter(CORS_ALLOWED_HEADERS);
String exposedHeaders = filterConfig
.getInitParameter(CORS_EXPOSED_HEADERS);
String supportsCredentials = filterConfig
.getInitParameter(CORS_SUPPORT_CREDENTIALS);
String preflightMaxAge = filterConfig
.getInitParameter(CORS_PREFLIGHT_MAXAGE);
corsConfiguration = new CORSConfiguration(allowedOrigins,
allowedHttpMethods, allowedHttpHeaders, exposedHeaders,
supportsCredentials, preflightMaxAge);
}
return corsConfiguration;
}
}
| true | true | private void parseAndStore(final String allowedOrigins,
final String allowedHttpMethods, final String allowedHttpHeaders,
final String exposedHeaders, final String supportsCredentials,
final String preflightMaxAge) throws ServletException {
if (allowedOrigins != null) {
if (allowedOrigins.trim().equals("*")) {
this.anyOriginAllowed = true;
} else {
this.anyOriginAllowed = false;
Set<String> setAllowedOrigins = parseStringToSet(allowedOrigins);
setAllowedOrigins(setAllowedOrigins);
}
}
Set<String> setAllowedHttpMethods = parseStringToSet(allowedHttpMethods);
setAllowedHttpMethods(setAllowedHttpMethods);
Set<String> setAllowedHttpHeaders = parseStringToSet(allowedHttpHeaders);
setAllowedHttpHeaders(setAllowedHttpHeaders);
Set<String> setExposedHeaders = parseStringToSet(exposedHeaders);
setExposedHeaders(setExposedHeaders);
// For any value other then 'true' this will be false.
boolean isSupportsCredentials = Boolean
.parseBoolean(supportsCredentials);
this.supportsCredentials = isSupportsCredentials;
try {
this.preflightMaxAge = (preflightMaxAge != null && preflightMaxAge
.isEmpty() == false) ? Long.parseLong(preflightMaxAge) : 0;
} catch (NumberFormatException e) {
throw new ServletException("Unable to parse preflightMaxAge", e);
}
}
| private void parseAndStore(final String allowedOrigins,
final String allowedHttpMethods, final String allowedHttpHeaders,
final String exposedHeaders, final String supportsCredentials,
final String preflightMaxAge) throws ServletException {
if (allowedOrigins != null) {
if (allowedOrigins.trim().equals("*")) {
this.anyOriginAllowed = true;
} else {
this.anyOriginAllowed = false;
Set<String> setAllowedOrigins = parseStringToSet(allowedOrigins);
setAllowedOrigins(setAllowedOrigins);
}
}
Set<String> setAllowedHttpMethods = parseStringToSet(allowedHttpMethods);
setAllowedHttpMethods(setAllowedHttpMethods);
Set<String> setAllowedHttpHeaders = parseStringToSet(allowedHttpHeaders);
setAllowedHttpHeaders(setAllowedHttpHeaders);
Set<String> setExposedHeaders = parseStringToSet(exposedHeaders);
setExposedHeaders(setExposedHeaders);
// For any value other then 'true' this will be false.
boolean isSupportsCredentials = Boolean
.parseBoolean(supportsCredentials);
this.supportsCredentials = isSupportsCredentials;
try {
if (preflightMaxAge != null && preflightMaxAge.isEmpty() == false) {
this.preflightMaxAge = Long.parseLong(preflightMaxAge);
} else {
this.preflightMaxAge = 0L;
}
} catch (NumberFormatException e) {
throw new ServletException("Unable to parse preflightMaxAge", e);
}
}
|
diff --git a/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/filter/InputFileWrapper.java b/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/filter/InputFileWrapper.java
index 1fbefb008e..ffd9e33c46 100644
--- a/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/filter/InputFileWrapper.java
+++ b/deegree-client/deegree-jsf-core/src/main/java/org/deegree/client/core/filter/InputFileWrapper.java
@@ -1,128 +1,134 @@
//$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.client.core.filter;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* TODO add class documentation here
*
* @author <a href="mailto:[email protected]">Lyn Buesching</a>
* @author last edited by: $Author: lyn $
*
* @version $Revision: $, $Date: $
*/
public class InputFileWrapper extends HttpServletRequestWrapper {
private Map<String, String[]> formParameters;
@SuppressWarnings("unchecked")
public InputFileWrapper( HttpServletRequest request ) throws ServletException {
super( request );
try {
ServletFileUpload upload = new ServletFileUpload();
DiskFileItemFactory factory = new DiskFileItemFactory();
upload.setFileItemFactory( factory );
String encoding = request.getCharacterEncoding();
List<FileItem> fileItems = upload.parseRequest( request );
formParameters = new HashMap<String, String[]>();
for ( int i = 0; i < fileItems.size(); i++ ) {
FileItem item = fileItems.get( i );
if ( item.isFormField() ) {
String[] values;
+ String v;
+ if ( encoding != null ) {
+ v = item.getString( encoding );
+ } else {
+ v = item.getString();
+ }
if ( formParameters.containsKey( item.getFieldName() ) ) {
String[] strings = formParameters.get( item.getFieldName() );
values = new String[strings.length + 1];
for ( int j = 0; j < strings.length; j++ ) {
values[j] = strings[j];
}
- values[strings.length] = item.getString( encoding );
+ values[strings.length] = v;
} else {
- values = new String[] { item.getString( encoding ) };
+ values = new String[] { v };
}
formParameters.put( item.getFieldName(), values );
} else if ( item.getName() != null && item.getName().length() > 0 && item.getSize() > 0 ) {
request.setAttribute( item.getFieldName(), item );
}
}
} catch ( FileUploadException fe ) {
ServletException servletEx = new ServletException();
servletEx.initCause( fe );
throw servletEx;
} catch ( UnsupportedEncodingException e ) {
ServletException servletEx = new ServletException();
servletEx.initCause( e );
throw servletEx;
}
}
@Override
public Map<String, String[]> getParameterMap() {
return formParameters;
}
@Override
public String[] getParameterValues( String name ) {
return (String[]) formParameters.get( name );
}
@Override
public String getParameter( String name ) {
String[] params = getParameterValues( name );
if ( params == null )
return null;
return params[0];
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration( formParameters.keySet() );
}
}
| false | true | public InputFileWrapper( HttpServletRequest request ) throws ServletException {
super( request );
try {
ServletFileUpload upload = new ServletFileUpload();
DiskFileItemFactory factory = new DiskFileItemFactory();
upload.setFileItemFactory( factory );
String encoding = request.getCharacterEncoding();
List<FileItem> fileItems = upload.parseRequest( request );
formParameters = new HashMap<String, String[]>();
for ( int i = 0; i < fileItems.size(); i++ ) {
FileItem item = fileItems.get( i );
if ( item.isFormField() ) {
String[] values;
if ( formParameters.containsKey( item.getFieldName() ) ) {
String[] strings = formParameters.get( item.getFieldName() );
values = new String[strings.length + 1];
for ( int j = 0; j < strings.length; j++ ) {
values[j] = strings[j];
}
values[strings.length] = item.getString( encoding );
} else {
values = new String[] { item.getString( encoding ) };
}
formParameters.put( item.getFieldName(), values );
} else if ( item.getName() != null && item.getName().length() > 0 && item.getSize() > 0 ) {
request.setAttribute( item.getFieldName(), item );
}
}
} catch ( FileUploadException fe ) {
ServletException servletEx = new ServletException();
servletEx.initCause( fe );
throw servletEx;
} catch ( UnsupportedEncodingException e ) {
ServletException servletEx = new ServletException();
servletEx.initCause( e );
throw servletEx;
}
}
| public InputFileWrapper( HttpServletRequest request ) throws ServletException {
super( request );
try {
ServletFileUpload upload = new ServletFileUpload();
DiskFileItemFactory factory = new DiskFileItemFactory();
upload.setFileItemFactory( factory );
String encoding = request.getCharacterEncoding();
List<FileItem> fileItems = upload.parseRequest( request );
formParameters = new HashMap<String, String[]>();
for ( int i = 0; i < fileItems.size(); i++ ) {
FileItem item = fileItems.get( i );
if ( item.isFormField() ) {
String[] values;
String v;
if ( encoding != null ) {
v = item.getString( encoding );
} else {
v = item.getString();
}
if ( formParameters.containsKey( item.getFieldName() ) ) {
String[] strings = formParameters.get( item.getFieldName() );
values = new String[strings.length + 1];
for ( int j = 0; j < strings.length; j++ ) {
values[j] = strings[j];
}
values[strings.length] = v;
} else {
values = new String[] { v };
}
formParameters.put( item.getFieldName(), values );
} else if ( item.getName() != null && item.getName().length() > 0 && item.getSize() > 0 ) {
request.setAttribute( item.getFieldName(), item );
}
}
} catch ( FileUploadException fe ) {
ServletException servletEx = new ServletException();
servletEx.initCause( fe );
throw servletEx;
} catch ( UnsupportedEncodingException e ) {
ServletException servletEx = new ServletException();
servletEx.initCause( e );
throw servletEx;
}
}
|
diff --git a/src/main/java/org/kabeja/ui/Demo.java b/src/main/java/org/kabeja/ui/Demo.java
index c824cc5..8da44d7 100644
--- a/src/main/java/org/kabeja/ui/Demo.java
+++ b/src/main/java/org/kabeja/ui/Demo.java
@@ -1,59 +1,59 @@
/*
Copyright 2008 Simon Mieth
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.kabeja.ui;
import java.awt.Dimension;
import javax.swing.JFrame;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.dxf.DXFEntity;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.ui.SVGViewUIComponent;
import dk.abj.svg.action.HighlightAction;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Parser p = ParserBuilder.createDefaultParser();
try {
- p.parse("/home/simon/Desktop/kabeja/problemDXF/t6.dxf");
+ p.parse("samples/dxf/draft4.dxf");
DXFDocument doc = p.getDocument();
DXFEntity e = doc.getDXFEntityByID("406F");
// Bounds b = e.getBounds();
System.out.println("e=" + e);
SVGViewUIComponent ui = new SVGViewUIComponent();
ui.addAction(new HighlightAction("GG"));
JFrame f = new JFrame("Demo");
f.add(ui.getView());
f.setSize(new Dimension(640, 480));
f.setVisible(true);
ui.showDXFDocument(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
Parser p = ParserBuilder.createDefaultParser();
try {
p.parse("/home/simon/Desktop/kabeja/problemDXF/t6.dxf");
DXFDocument doc = p.getDocument();
DXFEntity e = doc.getDXFEntityByID("406F");
// Bounds b = e.getBounds();
System.out.println("e=" + e);
SVGViewUIComponent ui = new SVGViewUIComponent();
ui.addAction(new HighlightAction("GG"));
JFrame f = new JFrame("Demo");
f.add(ui.getView());
f.setSize(new Dimension(640, 480));
f.setVisible(true);
ui.showDXFDocument(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
Parser p = ParserBuilder.createDefaultParser();
try {
p.parse("samples/dxf/draft4.dxf");
DXFDocument doc = p.getDocument();
DXFEntity e = doc.getDXFEntityByID("406F");
// Bounds b = e.getBounds();
System.out.println("e=" + e);
SVGViewUIComponent ui = new SVGViewUIComponent();
ui.addAction(new HighlightAction("GG"));
JFrame f = new JFrame("Demo");
f.add(ui.getView());
f.setSize(new Dimension(640, 480));
f.setVisible(true);
ui.showDXFDocument(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/de/_13ducks/cor/networks/client/behaviour/impl/ClientBehaviourMove.java b/src/de/_13ducks/cor/networks/client/behaviour/impl/ClientBehaviourMove.java
index cff53e3..cbad8c8 100644
--- a/src/de/_13ducks/cor/networks/client/behaviour/impl/ClientBehaviourMove.java
+++ b/src/de/_13ducks/cor/networks/client/behaviour/impl/ClientBehaviourMove.java
@@ -1,228 +1,231 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Centuries of Rage is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.networks.client.behaviour.impl;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.client.ClientCore;
import de._13ducks.cor.game.server.movement.Vector;
import de._13ducks.cor.networks.client.behaviour.ClientBehaviour;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Der Clientmover bewegt die Einheiten gemäß den Befehlen des Servers auf dem Client.
* Jede Einheit hat ihren eingenen Clientmover.
*
*/
public class ClientBehaviourMove extends ClientBehaviour {
/**
* Um wieviele Millisekunden das Clientbehaviour eingehende Bewegungs-
* befehle absichtlich verzögert, um flakern beim Stoppen zu verhindern.
*/
private int CLIENT_DELAY = 100;
/**
* Das derzeitige Bewegungsziel der Einheit.
*/
private FloatingPointPosition target;
/**
* Die Einheit, die von diesem Behaviour verwaltet wird
*/
protected Unit caster2;
/**
* Die derzeitige Bewegungsgeschwindigkeit
*/
private double speed;
/**
* Stoppen?
*/
private FloatingPointPosition stopPos = null;
/**
* Wann wurde die Bewegung zuletzt berechnet? (in nanosekunden)
*/
private long lastTick;
private ConcurrentLinkedQueue<MoveTask> queue;
public ClientBehaviourMove(ClientCore.InnerClient rgi, Unit caster2) {
super(rgi, caster2, 1, 5, false);
this.caster2 = caster2;
queue = new ConcurrentLinkedQueue<MoveTask>();
}
@Override
public synchronized void execute() {
// Eingehende Signale verarbeiten:
if (!queue.isEmpty()) {
MoveTask task = queue.peek();
if (System.currentTimeMillis() >= task.execTime) {
queue.remove().perform();
if (!queue.isEmpty()) {
// Noch mehr da? Dann gleich nochmal:
trigger();
}
} else {
// Es ist was da, aber wir müssen noch etwas warten.
trigger();
}
+ } else {
+ // Auto-Ende:
+ if (target == null || speed <= 0) {
+ deactivate();
+ return;
+ }
}
- // Auto-Ende:
+ // Es gibt nichts zu tun...
if (target == null || speed <= 0) {
- deactivate();
return;
}
if (stopPos == null) {
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (!newpos.toVector().isValid()) {
// Das geht so nicht, abbrechen und gleich nochmal!
System.out.println("CLIENT-Move: Evil params: " + caster2 + " " + oldPos + " " + target + " " + vec + " " + ticktime + " " + lastTick + "-->" + newpos);
trigger();
return;
}
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target);
target = null;
stopPos = null; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
- deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
} else {
caster2.setMainPosition(stopPos);
target = null;
stopPos = null;
- deactivate();
}
}
@Override
public synchronized void gotSignal(byte[] packet) {
if (packet[0] == 24) {
// Anhalten ist normalerweise kein neuer Task, sondern das Ziel des vorhergehenden wird geändert.
if (!queue.isEmpty()) {
MoveTask task = queue.peek();
task.pos = rgi.readFloatingPointPosition(packet, 2);
} else {
// Es läuft schon, live ändern
if (target != null) {
target = rgi.readFloatingPointPosition(packet, 2);
} else {
// Wir laufen gar nicht und werden auch in Zukunft nicht loslaufen
// Dann als normalen Task adden, damit die Position mit Gewalt
// gesetzt wird. Ist zwar hässlich, verhindert aber asyncs.
FloatingPointPosition pos = rgi.readFloatingPointPosition(packet, 2);
MoveTask task = new MoveTask(0, pos, 0);
queue.add(task);
}
}
} else if (packet[0] == 23) {
// Move
float moveSpeed = Float.intBitsToFloat(rgi.readInt(packet, 2));
FloatingPointPosition pos = new FloatingPointPosition(Float.intBitsToFloat(rgi.readInt(packet, 3)), Float.intBitsToFloat(rgi.readInt(packet, 4)));
MoveTask task = new MoveTask(1, pos, moveSpeed);
queue.add(task);
}
// Schnell verarbeiten
activate();
}
@Override
public void pause() {
}
@Override
public void unpause() {
}
private synchronized void newMoveVec(double speed, FloatingPointPosition target) {
this.speed = speed;
this.target = target;
lastTick = System.nanoTime();
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
/**
* Stoppt die Einheit sofort auf der angegeben Position
* (innerhalb eines Ticks)
* @param pos
*/
private synchronized void stopAt(FloatingPointPosition pos) {
stopPos = pos;
}
/**
* Jedes Signal vom Server wird in ein solches Objekt gesteckt.
* Der Client verarbeitet diese Aufaben der Reihe nach.
*/
private class MoveTask {
int mode;
FloatingPointPosition pos;
double speed;
long execTime;
public MoveTask(int mode, FloatingPointPosition pos, double speed) {
this.mode = mode;
this.pos = pos;
this.speed = speed;
execTime = System.currentTimeMillis() + CLIENT_DELAY;
}
void perform() {
System.out.println("QUEUE-TASK: " + caster2 + " " + mode + " " + pos + " " + speed);
if (mode == 0) {
// STOP
stopAt(pos);
} else if (mode == 1) {
newMoveVec(speed, pos);
}
}
}
}
| false | true | public synchronized void execute() {
// Eingehende Signale verarbeiten:
if (!queue.isEmpty()) {
MoveTask task = queue.peek();
if (System.currentTimeMillis() >= task.execTime) {
queue.remove().perform();
if (!queue.isEmpty()) {
// Noch mehr da? Dann gleich nochmal:
trigger();
}
} else {
// Es ist was da, aber wir müssen noch etwas warten.
trigger();
}
}
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
if (stopPos == null) {
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (!newpos.toVector().isValid()) {
// Das geht so nicht, abbrechen und gleich nochmal!
System.out.println("CLIENT-Move: Evil params: " + caster2 + " " + oldPos + " " + target + " " + vec + " " + ticktime + " " + lastTick + "-->" + newpos);
trigger();
return;
}
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target);
target = null;
stopPos = null; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
} else {
caster2.setMainPosition(stopPos);
target = null;
stopPos = null;
deactivate();
}
}
| public synchronized void execute() {
// Eingehende Signale verarbeiten:
if (!queue.isEmpty()) {
MoveTask task = queue.peek();
if (System.currentTimeMillis() >= task.execTime) {
queue.remove().perform();
if (!queue.isEmpty()) {
// Noch mehr da? Dann gleich nochmal:
trigger();
}
} else {
// Es ist was da, aber wir müssen noch etwas warten.
trigger();
}
} else {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
}
// Es gibt nichts zu tun...
if (target == null || speed <= 0) {
return;
}
if (stopPos == null) {
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (!newpos.toVector().isValid()) {
// Das geht so nicht, abbrechen und gleich nochmal!
System.out.println("CLIENT-Move: Evil params: " + caster2 + " " + oldPos + " " + target + " " + vec + " " + ticktime + " " + lastTick + "-->" + newpos);
trigger();
return;
}
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target);
target = null;
stopPos = null; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
} else {
caster2.setMainPosition(stopPos);
target = null;
stopPos = null;
}
}
|
diff --git a/ChessFeudServer/src/se/chalmers/chessfeudserver/TestServlet.java b/ChessFeudServer/src/se/chalmers/chessfeudserver/TestServlet.java
index c8f47ea..b7c89c6 100644
--- a/ChessFeudServer/src/se/chalmers/chessfeudserver/TestServlet.java
+++ b/ChessFeudServer/src/se/chalmers/chessfeudserver/TestServlet.java
@@ -1,69 +1,65 @@
package se.chalmers.chessfeudserver;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TestServlet() {
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
final ServletOutputStream out = response.getOutputStream();
try {
- String userName = request.getParameter("userName");
+ String userName = request.getParameter("username");
String password = request.getParameter("password");
boolean authenticated = login(userName, password);
- if (authenticated) {
- out.println("<login><status>SUCSESS</status></login>");
- } else {
- out.println("<login><status>FAIL</status></login>");
- }
+ out.print(authenticated);
} catch(Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
public boolean login(String userName, String password) {
if(userName == null || password == null) {
return false;
}
if (userName.equals("twister") && password.equals("awesomeness")) {
return true;
} else {
return false;
}
}
}
| false | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
final ServletOutputStream out = response.getOutputStream();
try {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
boolean authenticated = login(userName, password);
if (authenticated) {
out.println("<login><status>SUCSESS</status></login>");
} else {
out.println("<login><status>FAIL</status></login>");
}
} catch(Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
final ServletOutputStream out = response.getOutputStream();
try {
String userName = request.getParameter("username");
String password = request.getParameter("password");
boolean authenticated = login(userName, password);
out.print(authenticated);
} catch(Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
}
|
diff --git a/src/ceid/netcins/json/ContentCatalogEntryJSONConvertor.java b/src/ceid/netcins/json/ContentCatalogEntryJSONConvertor.java
index 5c05277..c22897f 100644
--- a/src/ceid/netcins/json/ContentCatalogEntryJSONConvertor.java
+++ b/src/ceid/netcins/json/ContentCatalogEntryJSONConvertor.java
@@ -1,37 +1,37 @@
package ceid.netcins.json;
import java.util.Map;
import org.eclipse.jetty.util.ajax.JSON.Convertor;
import org.eclipse.jetty.util.ajax.JSON.Output;
import ceid.netcins.catalog.ContentCatalogEntry;
import ceid.netcins.catalog.UserCatalogEntry;
import ceid.netcins.content.ContentProfile;
public class ContentCatalogEntryJSONConvertor implements Convertor {
protected static final UserCatalogEntryJSONConvertor ucjc = new UserCatalogEntryJSONConvertor();
protected static final ContentProfileJSONConvertor cpjc = new ContentProfileJSONConvertor();
public ContentCatalogEntryJSONConvertor() {
}
@Override
public void toJSON(Object obj, Output out) {
if (obj == null) {
out.add(null);
return;
}
- UserCatalogEntry uce = (UserCatalogEntry)obj;
+ ContentCatalogEntry uce = (ContentCatalogEntry)obj;
ucjc.toJSON(uce, out);
- cpjc.toJSON(uce.getUserProfile(), out);
+ cpjc.toJSON(uce.getContentProfile(), out);
}
@Override
@SuppressWarnings("rawtypes")
public Object fromJSON(Map object) {
UserCatalogEntry uce = (UserCatalogEntry)ucjc.fromJSON(object);
ContentProfile cp = (ContentProfile)cpjc.fromJSON(object);
return new ContentCatalogEntry(uce.getUID(), cp, uce.getUserProfile());
}
}
| false | true | public void toJSON(Object obj, Output out) {
if (obj == null) {
out.add(null);
return;
}
UserCatalogEntry uce = (UserCatalogEntry)obj;
ucjc.toJSON(uce, out);
cpjc.toJSON(uce.getUserProfile(), out);
}
| public void toJSON(Object obj, Output out) {
if (obj == null) {
out.add(null);
return;
}
ContentCatalogEntry uce = (ContentCatalogEntry)obj;
ucjc.toJSON(uce, out);
cpjc.toJSON(uce.getContentProfile(), out);
}
|
diff --git a/openxc/src/main/java/com/openxc/sources/bluetooth/BluetoothVehicleDataSource.java b/openxc/src/main/java/com/openxc/sources/bluetooth/BluetoothVehicleDataSource.java
index 8ad85b70..caa79528 100644
--- a/openxc/src/main/java/com/openxc/sources/bluetooth/BluetoothVehicleDataSource.java
+++ b/openxc/src/main/java/com/openxc/sources/bluetooth/BluetoothVehicleDataSource.java
@@ -1,182 +1,184 @@
package com.openxc.sources.bluetooth;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import com.openxc.controllers.VehicleController;
import com.openxc.remote.RawMeasurement;
import com.openxc.sources.ContextualVehicleDataSource;
import com.openxc.sources.DataSourceException;
import com.openxc.sources.SourceCallback;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;
public class BluetoothVehicleDataSource extends ContextualVehicleDataSource
implements Runnable, VehicleController {
private static final String TAG = "BluetoothVehicleDataSource";
private boolean mRunning = false;
private DeviceManager mDeviceManager;
private PrintWriter mOutStream;
private BufferedReader mInStream;
private BluetoothSocket mSocket;
private String mAddress;
public BluetoothVehicleDataSource(SourceCallback callback, Context context,
String address) throws DataSourceException {
super(callback, context);
try {
mDeviceManager = new DeviceManager(getContext());
} catch(BluetoothException e) {
throw new DataSourceException(
"Unable to open Bluetooth device manager", e);
}
mAddress = address;
start();
}
public BluetoothVehicleDataSource(Context context, String address)
throws DataSourceException {
this(null, context, address);
}
public synchronized void start() {
if(!mRunning) {
mRunning = true;
new Thread(this).start();
}
}
public void stop() {
super.stop();
Log.d(TAG, "Stopping Bluetooth source");
if(!mRunning) {
Log.d(TAG, "Already stopped.");
return;
}
mRunning = false;
}
public void close() {
stop();
disconnect();
}
public void run() {
while(mRunning) {
try {
waitForDeviceConnection();
} catch(BluetoothException e) {
Log.i(TAG, "Unable to connect to target device -- " +
"sleeping for awhile before trying again");
try {
Thread.sleep(5000);
} catch(InterruptedException e2){
stop();
}
continue;
}
String line = null;
try {
line = mInStream.readLine();
} catch(IOException e) {
Log.e(TAG, "Unable to read response");
+ disconnect();
continue;
}
if(line == null){
Log.e(TAG, "Device has dropped offline");
+ disconnect();
continue;
}
handleMessage(line);
}
Log.d(TAG, "Stopped Bluetooth listener");
}
public void set(RawMeasurement command) {
String message = command.serialize() + "\u0000";
Log.d(TAG, "Writing message to Bluetooth: " + message);
try {
write(message);
} catch(BluetoothException e) {
Log.w(TAG, "Unable to write message", e);
}
}
private void disconnect() {
if(mSocket == null) {
Log.w(TAG, "Unable to disconnect -- not connected");
return;
}
Log.d(TAG, "Disconnecting from the socket " + mSocket);
mOutStream.close();
try {
mInStream.close();
} catch(IOException e) {
Log.w(TAG, "Unable to close the input stream", e);
}
if(mSocket != null) {
try {
mSocket.close();
} catch(IOException e) {
Log.w(TAG, "Unable to close the socket", e);
}
}
mSocket = null;
Log.d(TAG, "Disconnected from the socket");
}
private synchronized void write(String message) throws BluetoothException {
if(mSocket == null) {
Log.w(TAG, "Unable to write -- not connected");
throw new BluetoothException();
}
mOutStream.write(message);
mOutStream.flush();
}
private void waitForDeviceConnection() throws BluetoothException {
if(mSocket == null) {
try {
mSocket = mDeviceManager.connect(mAddress);
connectStreams();
} catch(BluetoothException e) {
Log.w(TAG, "Unable to connect to device at address " +
mAddress, e);
throw e;
}
}
}
private void connectStreams() throws BluetoothException {
try {
mOutStream = new PrintWriter(new OutputStreamWriter(
mSocket.getOutputStream()));
mInStream = new BufferedReader(new InputStreamReader(
mSocket.getInputStream()));
Log.i(TAG, "Socket stream to CAN translator opened successfully");
} catch(IOException e) {
// We are expecting to see "host is down" when repeatedly
// autoconnecting
if(!(e.toString().contains("Host is Down"))){
Log.d(TAG, "Error opening streams "+e);
} else {
Log.e(TAG, "Error opening streams "+e);
}
mSocket = null;
throw new BluetoothException();
}
}
}
| false | true | public void run() {
while(mRunning) {
try {
waitForDeviceConnection();
} catch(BluetoothException e) {
Log.i(TAG, "Unable to connect to target device -- " +
"sleeping for awhile before trying again");
try {
Thread.sleep(5000);
} catch(InterruptedException e2){
stop();
}
continue;
}
String line = null;
try {
line = mInStream.readLine();
} catch(IOException e) {
Log.e(TAG, "Unable to read response");
continue;
}
if(line == null){
Log.e(TAG, "Device has dropped offline");
continue;
}
handleMessage(line);
}
Log.d(TAG, "Stopped Bluetooth listener");
}
| public void run() {
while(mRunning) {
try {
waitForDeviceConnection();
} catch(BluetoothException e) {
Log.i(TAG, "Unable to connect to target device -- " +
"sleeping for awhile before trying again");
try {
Thread.sleep(5000);
} catch(InterruptedException e2){
stop();
}
continue;
}
String line = null;
try {
line = mInStream.readLine();
} catch(IOException e) {
Log.e(TAG, "Unable to read response");
disconnect();
continue;
}
if(line == null){
Log.e(TAG, "Device has dropped offline");
disconnect();
continue;
}
handleMessage(line);
}
Log.d(TAG, "Stopped Bluetooth listener");
}
|
diff --git a/ProjectGammon/src/test/java/fr/ujm/tse/info4/pgammon/test/gui/TestDesignPlateau.java b/ProjectGammon/src/test/java/fr/ujm/tse/info4/pgammon/test/gui/TestDesignPlateau.java
index fd526e4..2870199 100644
--- a/ProjectGammon/src/test/java/fr/ujm/tse/info4/pgammon/test/gui/TestDesignPlateau.java
+++ b/ProjectGammon/src/test/java/fr/ujm/tse/info4/pgammon/test/gui/TestDesignPlateau.java
@@ -1,74 +1,74 @@
package fr.ujm.tse.info4.pgammon.test.gui;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import fr.ujm.tse.info4.pgammon.gui.TriangleCaseButton;
import fr.ujm.tse.info4.pgammon.models.Case;
import fr.ujm.tse.info4.pgammon.models.CouleurCase;
public class TestDesignPlateau {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Design");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
Container panel = frame.getContentPane();
panel.setLayout(new FlowLayout());
panel.setBackground(new Color(0x00000));
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,3), CouleurCase.BLANC);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,3,3), CouleurCase.BLANC);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,4), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,4,4), CouleurCase.NOIR);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,5), CouleurCase.BLANC);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,5,5), CouleurCase.BLANC);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,6), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,6,6), CouleurCase.NOIR);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,7), CouleurCase.BLANC);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,7,7), CouleurCase.BLANC);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,8), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,8,8), CouleurCase.NOIR);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,9), CouleurCase.BLANC);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,9,9), CouleurCase.BLANC);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,10), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,10,10), CouleurCase.NOIR);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,11), CouleurCase.BLANC);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,11,1), CouleurCase.BLANC);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,12), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,12,12), CouleurCase.NOIR);
panel.add(t);
}
{
- TriangleCaseButton t = new TriangleCaseButton(new Case(12), CouleurCase.NOIR);
+ TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,0,13), CouleurCase.NOIR);
panel.add(t);
}
frame.setVisible(true);
}
}
| false | true | public static void main(String[] args) {
JFrame frame = new JFrame("Test Design");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
Container panel = frame.getContentPane();
panel.setLayout(new FlowLayout());
panel.setBackground(new Color(0x00000));
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,3), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,4), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,5), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,6), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,7), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,8), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,9), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.BLANC,10), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,11), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12,CouleurCase.NOIR,12), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(12), CouleurCase.NOIR);
panel.add(t);
}
frame.setVisible(true);
}
| public static void main(String[] args) {
JFrame frame = new JFrame("Test Design");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
Container panel = frame.getContentPane();
panel.setLayout(new FlowLayout());
panel.setBackground(new Color(0x00000));
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,3,3), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,4,4), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,5,5), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,6,6), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,7,7), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,8,8), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,9,9), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.BLANC,10,10), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,11,1), CouleurCase.BLANC);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,12,12), CouleurCase.NOIR);
panel.add(t);
}
{
TriangleCaseButton t = new TriangleCaseButton(new Case(CouleurCase.NOIR,0,13), CouleurCase.NOIR);
panel.add(t);
}
frame.setVisible(true);
}
|
diff --git a/components/bio-formats/src/loci/formats/in/BDReader.java b/components/bio-formats/src/loci/formats/in/BDReader.java
index 33842212d..62659de33 100644
--- a/components/bio-formats/src/loci/formats/in/BDReader.java
+++ b/components/bio-formats/src/loci/formats/in/BDReader.java
@@ -1,375 +1,375 @@
//
// BDReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
Copyright (C) 2009-@year@ Vanderbilt Integrative Cancer Center.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.util.*;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.XMLTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
/**
* BDReader is the file format reader for BD Pathway datasets.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/BDReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/BDReader.java">SVN</a></dd></dl>
*
* @author Shawn Garbett Shawn.Garbett a t Vanderbilt.edu
*/
public class BDReader extends FormatReader {
// -- Constants --
private static final String EXPERIMENT_FILE = "Experiment.exp";
private static final String[] META_EXT = {"drt","dye","exp","plt"};
// -- Fields --
private Vector<String> metadataFiles = new Vector<String>();
private Vector<String> channelNames = new Vector<String>();
private Vector<String> wellLabels = new Vector<String>();
private String plateName;
private String[] tiffs;
private MinimalTiffReader reader;
// -- Constructor --
/** Constructs a new ScanR reader. */
public BDReader() {
super("BD Pathway", new String[] {"exp", "tif"});
domains = new String[] {FormatTools.HCS_DOMAIN};
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
String id = new Location(name).getAbsolutePath();
try {
id = locateExperimentFile(id);
}
catch (FormatException f) {
return false;
}
catch (IOException f) {
return false;
}
if (id.endsWith(EXPERIMENT_FILE)) { return true; }
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser p = new TiffParser(stream);
IFD ifd = p.getFirstIFD();
if (ifd == null) return false;
String software = ifd.getIFDTextValue(IFD.SOFTWARE);
return software.trim().startsWith("MATROX Imaging Library");
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
for (String file : metadataFiles) {
if (file != null) files.add(file);
}
if (!noPixels && tiffs != null) {
int offset = getSeries() * getImageCount();
for (int i = 0; i<getImageCount(); i++) {
if (tiffs[offset + i] != null) { files.add(tiffs[offset + i]); }
}
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
if (reader != null) reader.close();
reader = null;
tiffs = null;
plateName = null;
channelNames.clear();
metadataFiles.clear();
wellLabels.clear();
}
}
/* @see IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int index = getSeries() * getImageCount() + no;
if (tiffs[index] != null) {
reader.setId(tiffs[index]);
reader.openBytes(0, buf, x, y, w, h);
reader.close();
}
return buf;
}
// -- Internal FormatReader API methods --
public IniList readMetaData(String id) throws IOException {
IniList exp = (new IniParser()).parseINI(
new BufferedReader(new FileReader(id)));
IniList plate = null;
// Read Plate File
for (String filename : metadataFiles) {
if (filename.endsWith(".plt")) {
plate = (new IniParser()).parseINI(
new BufferedReader(new FileReader(filename)));
break;
}
}
if (plate == null) throw new IOException("No Plate File");
plateName = plate.getTable("PlateType").get("Brand");
Location dir = new Location(id).getParentFile();
for (String filename : dir.list()) {
if (filename.startsWith("Well ")) {
wellLabels.add(filename.substring(5,8));
}
}
core = new CoreMetadata[wellLabels.size()];
core[0] = new CoreMetadata();
// Hack for current testing/development purposes
// Not all channels have the same Z!!! How to handle???
// FIXME FIXME FIXME
core[0].sizeZ=1;
// FIXME FIXME FIXME
// END OF HACK
core[0].sizeC = Integer.parseInt(exp.getTable("General").get("Dyes"));
for (int i=1; i<=core[0].sizeC; i++) {
channelNames.add(exp.getTable("Dyes").get(Integer.toString(i)));
}
// Count Images
core[0].sizeT = 0;
Location well = new Location(dir.getAbsolutePath(),
"Well " + wellLabels.get(1));
for (String filename : well.list()) {
if (filename.startsWith(channelNames.get(0)) &&
filename.endsWith(".tif"))
{
core[0].sizeT++;
}
}
return exp;
}
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
// make sure we have the experiment file
id = locateExperimentFile(id);
super.initFile(id);
Location dir = new Location(id).getAbsoluteFile().getParentFile();
for (String file : dir.list(true)) {
Location f = new Location(dir, file);
if (!f.isDirectory()) {
for (String ext : META_EXT) {
if (checkSuffix(id, ext)) {
metadataFiles.add(f.getAbsolutePath());
}
}
}
}
// parse Experiment metadata
IniList experiment = readMetaData(id);
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels) {
String row = well.substring(0, 1).trim();
String column = well.substring(1, 3).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellLabels.size();
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
tiffs = getTiffs(dir.getAbsoluteFile().toString());
// [] files = new String[nChannels * nWells * nTimepoints * nSlices];
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX;
core[i].sizeY = sizeY;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYZTC";
core[i].imageCount = nSlices * nTimepoints * nChannels;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
for (int c=0; c<getSizeC(); c++) {
store.setLogicalChannelName(channelNames.get(c), i, c);
}
}
store.setPlateRowNamingConvention("A", 0);
store.setPlateColumnNamingConvention("01", 0);
store.setPlateName(plateName, 0);
for (int i=0; i<getSeriesCount(); i++) {
MetadataTools.setDefaultCreationDate(store, id, i);
String name = wellLabels.get(i);
String row = name.substring(0, 1);
Integer col = Integer.parseInt(name.substring(1, 3));
store.setWellColumn(col, 0, i);
store.setWellRow(row.charAt(0)-'A', 0, i);
store.setWellSampleIndex(new Integer(i), 0, i, 0);
- String imageID = MetadataTools.creatLSID("Image", i);
+ String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, i, 0);
store.setImageID(imageID, i);
store.setImageName(name, i);
}
}
/* Locate the experiment file given any file in set */
private String locateExperimentFile(String id)
throws FormatException, IOException
{
if (!checkSuffix(id, "exp")) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif")) parent = parent.getParentFile();
for (String file : parent.list()) {
if (file.equals(EXPERIMENT_FILE)) {
id = new Location(parent, file).getAbsolutePath();
break;
}
}
if (!checkSuffix(id, "exp")) {
throw new FormatException("Could not find " + EXPERIMENT_FILE +
" in " + parent.getAbsolutePath());
}
}
return id;
}
public String[] getTiffs(String dir) {
LinkedList<String> files = new LinkedList<String>();
FileFilter wellDirFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() && file.getName().startsWith("Well ");
}
};
FileFilter tiffFilter = new FileFilter() {
public boolean accept(File file) {
return file.getName().matches(".* - n\\d\\d\\d\\d\\d\\d\\.tif");
}
};
File[] dirs = (new File(dir)).listFiles(wellDirFilter);
Arrays.sort(dirs);
for (File well : dirs) {
File[] found = well.listFiles(tiffFilter);
Arrays.sort(found);
for (File file : found) {
files.add(file.getAbsolutePath());
}
}
return files.toArray(new String[files.size()]);
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
// make sure we have the experiment file
id = locateExperimentFile(id);
super.initFile(id);
Location dir = new Location(id).getAbsoluteFile().getParentFile();
for (String file : dir.list(true)) {
Location f = new Location(dir, file);
if (!f.isDirectory()) {
for (String ext : META_EXT) {
if (checkSuffix(id, ext)) {
metadataFiles.add(f.getAbsolutePath());
}
}
}
}
// parse Experiment metadata
IniList experiment = readMetaData(id);
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels) {
String row = well.substring(0, 1).trim();
String column = well.substring(1, 3).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellLabels.size();
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
tiffs = getTiffs(dir.getAbsoluteFile().toString());
// [] files = new String[nChannels * nWells * nTimepoints * nSlices];
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX;
core[i].sizeY = sizeY;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYZTC";
core[i].imageCount = nSlices * nTimepoints * nChannels;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
for (int c=0; c<getSizeC(); c++) {
store.setLogicalChannelName(channelNames.get(c), i, c);
}
}
store.setPlateRowNamingConvention("A", 0);
store.setPlateColumnNamingConvention("01", 0);
store.setPlateName(plateName, 0);
for (int i=0; i<getSeriesCount(); i++) {
MetadataTools.setDefaultCreationDate(store, id, i);
String name = wellLabels.get(i);
String row = name.substring(0, 1);
Integer col = Integer.parseInt(name.substring(1, 3));
store.setWellColumn(col, 0, i);
store.setWellRow(row.charAt(0)-'A', 0, i);
store.setWellSampleIndex(new Integer(i), 0, i, 0);
String imageID = MetadataTools.creatLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, i, 0);
store.setImageID(imageID, i);
store.setImageName(name, i);
}
}
| protected void initFile(String id) throws FormatException, IOException {
// make sure we have the experiment file
id = locateExperimentFile(id);
super.initFile(id);
Location dir = new Location(id).getAbsoluteFile().getParentFile();
for (String file : dir.list(true)) {
Location f = new Location(dir, file);
if (!f.isDirectory()) {
for (String ext : META_EXT) {
if (checkSuffix(id, ext)) {
metadataFiles.add(f.getAbsolutePath());
}
}
}
}
// parse Experiment metadata
IniList experiment = readMetaData(id);
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels) {
String row = well.substring(0, 1).trim();
String column = well.substring(1, 3).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellLabels.size();
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
tiffs = getTiffs(dir.getAbsoluteFile().toString());
// [] files = new String[nChannels * nWells * nTimepoints * nSlices];
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX;
core[i].sizeY = sizeY;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYZTC";
core[i].imageCount = nSlices * nTimepoints * nChannels;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
for (int c=0; c<getSizeC(); c++) {
store.setLogicalChannelName(channelNames.get(c), i, c);
}
}
store.setPlateRowNamingConvention("A", 0);
store.setPlateColumnNamingConvention("01", 0);
store.setPlateName(plateName, 0);
for (int i=0; i<getSeriesCount(); i++) {
MetadataTools.setDefaultCreationDate(store, id, i);
String name = wellLabels.get(i);
String row = name.substring(0, 1);
Integer col = Integer.parseInt(name.substring(1, 3));
store.setWellColumn(col, 0, i);
store.setWellRow(row.charAt(0)-'A', 0, i);
store.setWellSampleIndex(new Integer(i), 0, i, 0);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, i, 0);
store.setImageID(imageID, i);
store.setImageName(name, i);
}
}
|
diff --git a/src/main/java/com/eli/web/action/MainSearch.java b/src/main/java/com/eli/web/action/MainSearch.java
index 771bc68..b79b933 100644
--- a/src/main/java/com/eli/web/action/MainSearch.java
+++ b/src/main/java/com/eli/web/action/MainSearch.java
@@ -1,98 +1,102 @@
package com.eli.web.action;
import com.eli.index.manager.MultiNRTSearcherAgent;
import com.eli.index.manager.ZhihuIndexManager;
import com.eli.web.BasicAction;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainSearch extends BasicAction {
private static final Logger logger = Logger.getLogger(MainSearch.class);
private static Analyzer analyzer= new CJKAnalyzer(Version.LUCENE_36);
@Override
protected void execute() throws IOException {
String token = super.getParam("q", "");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+9)/10)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
- content = highlighter.getBestFragment(stream, content);
+ String hContent = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
- title = highlighter.getBestFragment(stream, title);
- if (title == null)
- title = "无标题";
- if (content == null)
- content = "无内容";
+ String hTitle = highlighter.getBestFragment(stream, title);
+ if (hTitle == null && title.length() == 0)
+ hTitle = "无标题";
+ else
+ hTitle = title;
+ if (hContent == null && (content == null || content.length() == 0))
+ hContent = "无内容";
+ else
+ hContent = content.substring(0, Math.min(60, content.length()));
if (type.equals("topic"))
- title = "板块:";
+ hTitle = "板块:" + hTitle;
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
- map.put("content", content);
- map.put("title", title);
+ map.put("content", hContent);
+ map.put("title", hTitle);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
}
| false | true | protected void execute() throws IOException {
String token = super.getParam("q", "");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+9)/10)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
content = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
title = highlighter.getBestFragment(stream, title);
if (title == null)
title = "无标题";
if (content == null)
content = "无内容";
if (type.equals("topic"))
title = "板块:";
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
map.put("content", content);
map.put("title", title);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
| protected void execute() throws IOException {
String token = super.getParam("q", "");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+9)/10)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
String hContent = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
String hTitle = highlighter.getBestFragment(stream, title);
if (hTitle == null && title.length() == 0)
hTitle = "无标题";
else
hTitle = title;
if (hContent == null && (content == null || content.length() == 0))
hContent = "无内容";
else
hContent = content.substring(0, Math.min(60, content.length()));
if (type.equals("topic"))
hTitle = "板块:" + hTitle;
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
map.put("content", hContent);
map.put("title", hTitle);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
|
diff --git a/src/java/fedora/client/utility/ingest/Ingest.java b/src/java/fedora/client/utility/ingest/Ingest.java
index 90c326c1b..d4b1a2c80 100755
--- a/src/java/fedora/client/utility/ingest/Ingest.java
+++ b/src/java/fedora/client/utility/ingest/Ingest.java
@@ -1,611 +1,611 @@
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package fedora.client.utility.ingest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.StringTokenizer;
import fedora.client.FedoraClient;
import fedora.client.utility.AutoFinder;
import fedora.client.utility.export.AutoExporter;
import fedora.common.Constants;
import fedora.server.access.FedoraAPIA;
import fedora.server.management.FedoraAPIM;
import fedora.server.types.gen.ComparisonOperator;
import fedora.server.types.gen.Condition;
import fedora.server.types.gen.FieldSearchQuery;
import fedora.server.types.gen.FieldSearchResult;
import fedora.server.types.gen.ObjectFields;
import fedora.server.types.gen.RepositoryInfo;
import fedora.utilities.FileComparator;
/**
* Initiates ingest of one or more objects. This class provides static utility
* methods, and it is also called by command line utilities.
*
* @version $Id$
*/
public class Ingest
implements Constants {
public static String LAST_PATH;
private static FileComparator _FILE_COMPARATOR = new FileComparator();
// if logMessage is null, will use original path in logMessage
public static String oneFromFile(File file,
String ingestFormat,
FedoraAPIA targetRepoAPIA,
FedoraAPIM targetRepoAPIM,
String logMessage) throws Exception {
LAST_PATH = file.getPath();
String pid =
AutoIngestor.ingestAndCommit(targetRepoAPIA,
targetRepoAPIM,
new FileInputStream(file),
ingestFormat,
getMessage(logMessage, file));
return pid;
}
/***************************************************************************
* Ingest from directory
**************************************************************************/
public static void multiFromDirectory(File dir,
String ingestFormat,
FedoraAPIA targetRepoAPIA,
FedoraAPIM targetRepoAPIM,
String logMessage,
PrintStream log,
IngestCounter c) throws Exception {
File[] files = dir.listFiles();
if (files == null) {
throw new RuntimeException("Could not read files from directory "
+ dir.getPath());
}
Arrays.sort(files, _FILE_COMPARATOR);
for (File element : files) {
if (!element.isHidden() && !element.getName().startsWith(".")) {
if (element.isDirectory()) {
multiFromDirectory(element,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
c);
} else {
try {
String pid =
oneFromFile(element,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage);
c.successes++;
IngestLogger.logFromFile(log, element, pid);
} catch (Exception e) {
// failed... just log it and continue
c.failures++;
IngestLogger.logFailedFromFile(log, element, e);
}
}
}
}
}
/***************************************************************************
* Ingest from repository
**************************************************************************/
// if logMessage is null, will make informative one up
public static String oneFromRepository(FedoraAPIA sourceRepoAPIA,
FedoraAPIM sourceRepoAPIM,
String sourceExportFormat,
String pid,
FedoraAPIA targetRepoAPIA,
FedoraAPIM targetRepoAPIM,
String logMessage) throws Exception {
// EXPORT from source repository
// The export context is set to "migrate" since the intent
// of ingest from repository is to migrate an object from
// one repository to another. The "migrate" option will
// ensure that URLs that were relative to the "exporting"
// repository are made relative to the "importing" repository.
ByteArrayOutputStream out = new ByteArrayOutputStream();
AutoExporter.export(sourceRepoAPIA,
sourceRepoAPIM,
pid,
sourceExportFormat,
"migrate",
out);
// Convert old format values to URIs for ingest
String ingestFormat = sourceExportFormat;
if (sourceExportFormat.equals(METS_EXT1_0_LEGACY)) {
ingestFormat = METS_EXT1_0.uri;
} else if (sourceExportFormat.equals(FOXML1_0_LEGACY)) {
ingestFormat = FOXML1_0.uri;
}
// INGEST into target repository
String realLogMessage = logMessage;
if (realLogMessage == null) {
realLogMessage = "Ingested from source repository with pid " + pid;
}
return AutoIngestor.ingestAndCommit(targetRepoAPIA,
targetRepoAPIM,
new ByteArrayInputStream(out
.toByteArray()),
ingestFormat,
realLogMessage);
}
public static void multiFromRepository(String sourceProtocol,
String sourceHost,
int sourcePort,
FedoraAPIA sourceRepoAPIA,
FedoraAPIM sourceRepoAPIM,
String sourceExportFormat,
FedoraAPIA targetRepoAPIA,
FedoraAPIM targetRepoAPIM,
String logMessage,
PrintStream log,
IngestCounter c) throws Exception {
// prepare the FieldSearch query
FieldSearchQuery query = new FieldSearchQuery();
Condition cond = new Condition();
cond.setProperty("pid");
cond.setOperator(ComparisonOperator.fromValue("has"));
Condition[] conditions = new Condition[1];
conditions[0] = cond;
query.setConditions(conditions);
query.setTerms(null);
String[] resultFields = new String[1];
resultFields[0] = "pid";
// get the first chunk of search results
FieldSearchResult result =
AutoFinder
.findObjects(sourceRepoAPIA, resultFields, 100, query);
while (result != null) {
ObjectFields[] ofs = result.getResultList();
// ingest all objects from this chunk of search results
for (ObjectFields element : ofs) {
String pid = element.getPid();
try {
String newPID =
oneFromRepository(sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
pid,
targetRepoAPIA,
targetRepoAPIM,
logMessage);
c.successes++;
IngestLogger.logFromRepos(log, pid, newPID);
} catch (Exception e) {
// failed... just log it and continue
c.failures++;
IngestLogger.logFailedFromRepos(log, pid, e);
}
}
// get the next chunk of search results, if any
String token = null;
try {
token = result.getListSession().getToken();
} catch (Throwable th) {
}
if (token != null) {
result = AutoFinder.resumeFindObjects(sourceRepoAPIA, token);
} else {
result = null;
}
}
}
/**
* Determine the default export format of the source repository. For
* backward compatibility: with pre-2.0 repositories assume the
* "metslikefedora1" format
*/
public static String getExportFormat(RepositoryInfo repoinfo)
throws Exception {
String sourceExportFormat = null;
StringTokenizer stoken =
new StringTokenizer(repoinfo.getRepositoryVersion(), ".");
int majorVersion = new Integer(stoken.nextToken()).intValue();
if (majorVersion < 2) {
sourceExportFormat = METS_EXT1_0_LEGACY;
} else {
sourceExportFormat = repoinfo.getDefaultExportFormat();
}
return sourceExportFormat;
}
private static String getMessage(String logMessage, File file) {
if (logMessage != null) {
return logMessage;
}
return "Ingested from local file " + file.getPath();
}
// FIXME: this isn't ingest-specific... it doesn't belong here
public static String getDuration(long millis) {
long tsec = millis / 1000;
long h = tsec / 60 / 60;
long m = (tsec - h * 60 * 60) / 60;
long s = tsec - h * 60 * 60 - m * 60;
StringBuffer out = new StringBuffer();
if (h > 0) {
out.append(h + " hour");
if (h > 1) {
out.append('s');
}
}
if (m > 0) {
if (h > 0) {
out.append(", ");
}
out.append(m + " minute");
if (m > 1) {
out.append('s');
}
}
if (s > 0 || h == 0 && m == 0) {
if (h > 0 || m > 0) {
out.append(", ");
}
out.append(s + " second");
if (s != 1) {
out.append('s');
}
}
return out.toString();
}
/**
* Print error message and show usage for command-line interface.
*/
public static void badArgs(String msg) {
System.err.println("Command: fedora-ingest");
System.err.println();
System.err.println("Summary: Ingests one or more objects into a Fedora repository, from either");
System.err.println(" the local filesystem or another Fedora repository.");
System.err.println();
System.err.println("Syntax:");
System.err.println(" fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS TPROTOCOL [LOG] [CTX]");
System.err.println(" fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS TPROTOCOL [LOG] [CTX]");
System.err.println(" fedora-ingest r[epos] SHST:SPRT SUSR SPSS PID|* THST:TPRT TUSR TPSS SPROTOCOL TPROTOCOL [LOG] [CTX]");
System.err.println();
System.err.println("Where:");
System.err.println(" INPATH is the local file or directory name that is ingest source.");
System.err.println(" FORMAT is a string value which indicates the XML format of the ingest file(s)");
System.err.println(" ('" + FOXML1_1.uri + "',");
System.err.println(" '" + FOXML1_0.uri + "',");
System.err.println(" '" + METS_EXT1_1.uri + "',");
System.err.println(" '" + METS_EXT1_0.uri + "',");
System.err.println(" '" + ATOM1_1.uri + "',");
System.err.println(" or '" + ATOM_ZIP1_1.uri + "')");
System.err.println(" PID is the id of the object to ingest from the source repository.");
System.err.println(" SHST/THST is the source or target repository's hostname.");
System.err.println(" SPRT/TPRT is the source or target repository's port number.");
System.err.println(" SUSR/TUSR is the id of the source or target repository user.");
System.err.println(" SPSS/TPSS is the password of the source or target repository user.");
System.err.println(" SPROTOCOL is the protocol to communicate with source repository (http or https)");
System.err.println(" TPROTOCOL is the protocol to communicate with target repository (http or https)");
System.err.println(" LOG is the optional log message. If unspecified, the log message");
System.err.println(" will indicate the source filename or repository of the object(s).");
System.err.println(" CTX is the optional parameter for specifying the context name under which ");
System.err.println(" the Fedora server is deployed. The default is fedora.");
System.err.println();
System.err.println("Examples:");
System.err.println("fedora-ingest f obj1.xml " + FOXML1_1.uri + " myrepo.com:8443 jane jpw https");
System.err.println();
System.err.println(" Ingests obj1.xml (encoded in FOXML 1.1 format) from the");
System.err.println(" current directory into the repository at myrepo.com:80");
System.err.println(" as user 'jane' with password 'jpw' using the secure https protocol (SSL).");
System.err.println(" The logmessage will be system-generated, indicating");
System.err.println(" the source path+filename.");
System.err.println();
System.err.println("fedora-ingest d c:\\archive " + FOXML1_1.uri + " myrepo.com:80 jane janepw http \"\"");
System.err.println();
System.err.println(" Traverses entire directory structure of c:\\archive, and ingests any file.");
System.err.println(" It assumes all files will be in the FOXML 1.1 format");
System.err.println(" and will fail on ingests of files that are not of this format.");
System.err.println(" All log messages will be the quoted string.");
System.err.println();
System.err.println("fedora-ingest d c:\\archive " + FOXML1_1.uri + " myrepo.com:80 jane janepw http \"\" my-personal-fedora");
System.err.println(" Traverses entire directory structure of c:\\archive, and ingests any file.");
System.err.println(" It assumes all files will be in the FOXML 1.1 format");
System.err.println(" and will fail on ingests of files that are not of this format.");
System.err.println(" All log messages will be the quoted string.");
System.err.println(" Additionally the Fedora server is assumed to be running under the context name ");
System.err.println(" http://myrepo:80/my-personal-fedora instead of http://myrepo:80/fedora ");
System.err.println();
System.err.println("fedora-ingest r jrepo.com:8081 mike mpw demo:1 myrepo.com:8443 jane jpw http https \"\"");
System.err.println();
System.err.println(" Ingests the object whose pid is 'demo:1' from the source repository");
System.err.println(" 'srcrepo.com:8081' into the target repository 'myrepo.com:80'.");
System.err.println(" The object will be exported from the source repository in the default");
System.err.println(" export format configured at the source.");
System.err.println(" All log messages will be empty.");
System.err.println();
System.err.println("fedora-ingest r jrepo.com:8081 mike mpw O myrepo.com:8443 jane jpw http https \"\"");
System.err.println();
System.err.println(" Same as above, but ingests all data objects (type O).");
System.err.println();
System.err.println("ERROR : " + msg);
System.exit(1);
}
private static void summarize(IngestCounter counter, File logFile) {
System.out.println();
if (counter.failures > 0) {
System.out.println("WARNING: " + counter.failures + " of "
+ counter.getTotal() + " objects failed. Check log.");
} else {
System.out.println("SUCCESS: All " + counter.getTotal()
+ " objects were ingested.");
}
System.out.println();
System.out.println("A detailed log is at " + logFile.getPath());
}
/**
* Command-line interface for doing ingests.
*/
public static void main(String[] args) {
try {
if (args.length < 1) {
Ingest.badArgs("No arguments entered!");
}
String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
PrintStream log = null;
File logFile = null;
String logRootName = null;
IngestCounter counter = new IngestCounter();
char kind = args[0].toLowerCase().charAt(0);
if (kind == 'f') {
// USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]
if (args.length < 7 || args.length > 9) {
Ingest
.badArgs("Wrong number of arguments for file ingest.");
System.out
.println("USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File f = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
- if (args.length == 9) {
+ if (args.length == 9 && !args[8].equals("")) {
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
String pid =
Ingest.oneFromFile(f,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (pid == null) {
System.out.print("ERROR: ingest failed for file: "
+ args[1]);
} else {
System.out.println("Ingested PID: " + pid);
}
} else if (kind == 'd') {
// USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG]
if (args.length < 7 || args.length > 9) {
Ingest.badArgs("Wrong number of arguments (" + args.length
+ ") for directory ingest.");
System.out
.println("USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File d = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
- if (args.length == 9){
+ if (args.length == 9 && !args[8].equals("")) {
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
logRootName = "ingest-from-dir";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromDirectory(d,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
} else if (kind == 'r') {
// USAGE: fedora-ingest r[epos] SHST:SPRT SUSR SPSS PID|* THST:TPRT TUSR TPSS SPROTOCOL TPROTOCOL [LOG] [CTX]
if (args.length < 10 || args.length > 12) {
Ingest
.badArgs("Wrong number of arguments for repository ingest.");
}
String logMessage = null;
if (args.length == 11){
logMessage=args[10];
}
- if (args.length == 12){
+ if (args.length == 12 && !args[11].equals("")){
context = args[11];
}
//Source repository
String[] shp = args[1].split(":");
String source_host = shp[0];
String source_port = shp[1];
String source_user = args[2];
String source_password = args[3];
String source_protocol = args[8];
// ******************************************
// NEW: use new client utility class
String sourceBaseURL =
source_protocol + "://" + source_host + ":"
+ Integer.parseInt(source_port) + "/" + context;
FedoraClient sfc =
new FedoraClient(sourceBaseURL,
source_user,
source_password);
FedoraAPIA sourceRepoAPIA = sfc.getAPIA();
FedoraAPIM sourceRepoAPIM = sfc.getAPIM();
//*******************************************
//Target repository
String[] thp = args[5].split(":");
String target_host = thp[0];
String target_port = thp[1];
String target_user = args[6];
String target_password = args[7];
String target_protocol = args[9];
// ******************************************
// NEW: use new client utility class
String targetBaseURL =
target_protocol + "://" + target_host + ":"
+ Integer.parseInt(target_port) + "/" + context;
FedoraClient tfc =
new FedoraClient(targetBaseURL,
target_user,
target_password);
FedoraAPIA targetRepoAPIA = tfc.getAPIA();
FedoraAPIM targetRepoAPIM = tfc.getAPIM();
//*******************************************
// Determine export format
RepositoryInfo repoinfo = sourceRepoAPIA.describeRepository();
System.out
.println("Ingest: exporting from a source repo version "
+ repoinfo.getRepositoryVersion());
String sourceExportFormat = getExportFormat(repoinfo);
System.out.println("Ingest: source repo is using "
+ sourceExportFormat + " export format.");
if (args[4].indexOf(":") != -1) {
// single object
String successfulPID =
Ingest.oneFromRepository(sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
args[4],
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (successfulPID == null) {
System.out
.print("ERROR: ingest from repo failed for PID="
+ args[4]);
} else {
System.out.println("Ingested PID: " + successfulPID);
}
} else {
// multi-object
//hp=args[1].split(":");
logRootName = "ingest-from-repository";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromRepository(source_protocol,
source_host,
Integer.parseInt(source_port),
sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
}
} else {
Ingest.badArgs("First argument must start with f, d, or r.");
}
} catch (Exception e) {
System.err.print("Error : ");
if (e.getMessage() == null) {
e.printStackTrace();
} else {
System.err.print(e.getMessage());
}
System.err.println();
if (Ingest.LAST_PATH != null) {
System.out.println("(Last attempted file was "
+ Ingest.LAST_PATH + ")");
}
}
}
}
| false | true | public static void main(String[] args) {
try {
if (args.length < 1) {
Ingest.badArgs("No arguments entered!");
}
String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
PrintStream log = null;
File logFile = null;
String logRootName = null;
IngestCounter counter = new IngestCounter();
char kind = args[0].toLowerCase().charAt(0);
if (kind == 'f') {
// USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]
if (args.length < 7 || args.length > 9) {
Ingest
.badArgs("Wrong number of arguments for file ingest.");
System.out
.println("USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File f = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
if (args.length == 9) {
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
String pid =
Ingest.oneFromFile(f,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (pid == null) {
System.out.print("ERROR: ingest failed for file: "
+ args[1]);
} else {
System.out.println("Ingested PID: " + pid);
}
} else if (kind == 'd') {
// USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG]
if (args.length < 7 || args.length > 9) {
Ingest.badArgs("Wrong number of arguments (" + args.length
+ ") for directory ingest.");
System.out
.println("USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File d = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
if (args.length == 9){
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
logRootName = "ingest-from-dir";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromDirectory(d,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
} else if (kind == 'r') {
// USAGE: fedora-ingest r[epos] SHST:SPRT SUSR SPSS PID|* THST:TPRT TUSR TPSS SPROTOCOL TPROTOCOL [LOG] [CTX]
if (args.length < 10 || args.length > 12) {
Ingest
.badArgs("Wrong number of arguments for repository ingest.");
}
String logMessage = null;
if (args.length == 11){
logMessage=args[10];
}
if (args.length == 12){
context = args[11];
}
//Source repository
String[] shp = args[1].split(":");
String source_host = shp[0];
String source_port = shp[1];
String source_user = args[2];
String source_password = args[3];
String source_protocol = args[8];
// ******************************************
// NEW: use new client utility class
String sourceBaseURL =
source_protocol + "://" + source_host + ":"
+ Integer.parseInt(source_port) + "/" + context;
FedoraClient sfc =
new FedoraClient(sourceBaseURL,
source_user,
source_password);
FedoraAPIA sourceRepoAPIA = sfc.getAPIA();
FedoraAPIM sourceRepoAPIM = sfc.getAPIM();
//*******************************************
//Target repository
String[] thp = args[5].split(":");
String target_host = thp[0];
String target_port = thp[1];
String target_user = args[6];
String target_password = args[7];
String target_protocol = args[9];
// ******************************************
// NEW: use new client utility class
String targetBaseURL =
target_protocol + "://" + target_host + ":"
+ Integer.parseInt(target_port) + "/" + context;
FedoraClient tfc =
new FedoraClient(targetBaseURL,
target_user,
target_password);
FedoraAPIA targetRepoAPIA = tfc.getAPIA();
FedoraAPIM targetRepoAPIM = tfc.getAPIM();
//*******************************************
// Determine export format
RepositoryInfo repoinfo = sourceRepoAPIA.describeRepository();
System.out
.println("Ingest: exporting from a source repo version "
+ repoinfo.getRepositoryVersion());
String sourceExportFormat = getExportFormat(repoinfo);
System.out.println("Ingest: source repo is using "
+ sourceExportFormat + " export format.");
if (args[4].indexOf(":") != -1) {
// single object
String successfulPID =
Ingest.oneFromRepository(sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
args[4],
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (successfulPID == null) {
System.out
.print("ERROR: ingest from repo failed for PID="
+ args[4]);
} else {
System.out.println("Ingested PID: " + successfulPID);
}
} else {
// multi-object
//hp=args[1].split(":");
logRootName = "ingest-from-repository";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromRepository(source_protocol,
source_host,
Integer.parseInt(source_port),
sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
}
} else {
Ingest.badArgs("First argument must start with f, d, or r.");
}
} catch (Exception e) {
System.err.print("Error : ");
if (e.getMessage() == null) {
e.printStackTrace();
} else {
System.err.print(e.getMessage());
}
System.err.println();
if (Ingest.LAST_PATH != null) {
System.out.println("(Last attempted file was "
+ Ingest.LAST_PATH + ")");
}
}
}
| public static void main(String[] args) {
try {
if (args.length < 1) {
Ingest.badArgs("No arguments entered!");
}
String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
PrintStream log = null;
File logFile = null;
String logRootName = null;
IngestCounter counter = new IngestCounter();
char kind = args[0].toLowerCase().charAt(0);
if (kind == 'f') {
// USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]
if (args.length < 7 || args.length > 9) {
Ingest
.badArgs("Wrong number of arguments for file ingest.");
System.out
.println("USAGE: fedora-ingest f[ile] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File f = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
if (args.length == 9 && !args[8].equals("")) {
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
String pid =
Ingest.oneFromFile(f,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (pid == null) {
System.out.print("ERROR: ingest failed for file: "
+ args[1]);
} else {
System.out.println("Ingested PID: " + pid);
}
} else if (kind == 'd') {
// USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG]
if (args.length < 7 || args.length > 9) {
Ingest.badArgs("Wrong number of arguments (" + args.length
+ ") for directory ingest.");
System.out
.println("USAGE: fedora-ingest d[ir] INPATH FORMAT THST:TPRT TUSR TPSS PROTOCOL [LOG] [CTX]");
}
File d = new File(args[1]);
String ingestFormat = args[2];
String logMessage = null;
if (args.length == 8){
logMessage = args[7];
}
if (args.length == 9 && !args[8].equals("")) {
context = args[8];
}
String protocol = args[6];
String[] hp = args[3].split(":");
// ******************************************
// NEW: use new client utility class
String baseURL =
protocol + "://" + hp[0] + ":"
+ Integer.parseInt(hp[1]) + "/" + context;
FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
FedoraAPIA targetRepoAPIA = fc.getAPIA();
FedoraAPIM targetRepoAPIM = fc.getAPIM();
//*******************************************
logRootName = "ingest-from-dir";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromDirectory(d,
ingestFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
} else if (kind == 'r') {
// USAGE: fedora-ingest r[epos] SHST:SPRT SUSR SPSS PID|* THST:TPRT TUSR TPSS SPROTOCOL TPROTOCOL [LOG] [CTX]
if (args.length < 10 || args.length > 12) {
Ingest
.badArgs("Wrong number of arguments for repository ingest.");
}
String logMessage = null;
if (args.length == 11){
logMessage=args[10];
}
if (args.length == 12 && !args[11].equals("")){
context = args[11];
}
//Source repository
String[] shp = args[1].split(":");
String source_host = shp[0];
String source_port = shp[1];
String source_user = args[2];
String source_password = args[3];
String source_protocol = args[8];
// ******************************************
// NEW: use new client utility class
String sourceBaseURL =
source_protocol + "://" + source_host + ":"
+ Integer.parseInt(source_port) + "/" + context;
FedoraClient sfc =
new FedoraClient(sourceBaseURL,
source_user,
source_password);
FedoraAPIA sourceRepoAPIA = sfc.getAPIA();
FedoraAPIM sourceRepoAPIM = sfc.getAPIM();
//*******************************************
//Target repository
String[] thp = args[5].split(":");
String target_host = thp[0];
String target_port = thp[1];
String target_user = args[6];
String target_password = args[7];
String target_protocol = args[9];
// ******************************************
// NEW: use new client utility class
String targetBaseURL =
target_protocol + "://" + target_host + ":"
+ Integer.parseInt(target_port) + "/" + context;
FedoraClient tfc =
new FedoraClient(targetBaseURL,
target_user,
target_password);
FedoraAPIA targetRepoAPIA = tfc.getAPIA();
FedoraAPIM targetRepoAPIM = tfc.getAPIM();
//*******************************************
// Determine export format
RepositoryInfo repoinfo = sourceRepoAPIA.describeRepository();
System.out
.println("Ingest: exporting from a source repo version "
+ repoinfo.getRepositoryVersion());
String sourceExportFormat = getExportFormat(repoinfo);
System.out.println("Ingest: source repo is using "
+ sourceExportFormat + " export format.");
if (args[4].indexOf(":") != -1) {
// single object
String successfulPID =
Ingest.oneFromRepository(sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
args[4],
targetRepoAPIA,
targetRepoAPIM,
logMessage);
if (successfulPID == null) {
System.out
.print("ERROR: ingest from repo failed for PID="
+ args[4]);
} else {
System.out.println("Ingested PID: " + successfulPID);
}
} else {
// multi-object
//hp=args[1].split(":");
logRootName = "ingest-from-repository";
logFile = IngestLogger.newLogFile(logRootName);
log =
new PrintStream(new FileOutputStream(logFile),
true,
"UTF-8");
IngestLogger.openLog(log, logRootName);
Ingest.multiFromRepository(source_protocol,
source_host,
Integer.parseInt(source_port),
sourceRepoAPIA,
sourceRepoAPIM,
sourceExportFormat,
targetRepoAPIA,
targetRepoAPIM,
logMessage,
log,
counter);
IngestLogger.closeLog(log, logRootName);
summarize(counter, logFile);
}
} else {
Ingest.badArgs("First argument must start with f, d, or r.");
}
} catch (Exception e) {
System.err.print("Error : ");
if (e.getMessage() == null) {
e.printStackTrace();
} else {
System.err.print(e.getMessage());
}
System.err.println();
if (Ingest.LAST_PATH != null) {
System.out.println("(Last attempted file was "
+ Ingest.LAST_PATH + ")");
}
}
}
|
diff --git a/src/org/openmrs/module/clinicalsummary/rule/RuleUtils.java b/src/org/openmrs/module/clinicalsummary/rule/RuleUtils.java
index 0123c7d..401ca35 100644
--- a/src/org/openmrs/module/clinicalsummary/rule/RuleUtils.java
+++ b/src/org/openmrs/module/clinicalsummary/rule/RuleUtils.java
@@ -1,119 +1,119 @@
/**
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.clinicalsummary.rule;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.logic.result.Result;
import org.openmrs.logic.result.Result.Datatype;
import org.openmrs.util.OpenmrsUtil;
/**
*
*/
public class RuleUtils {
private static final Log log = LogFactory.getLog(RuleUtils.class);
/**
* This class will never gets instantiated
*/
private RuleUtils() {
}
/**
* Cut a result to a certain size
*
* @param obsResults original result object
* @param codedValues optional parameter for coded obs to only include obs with the specified
* values
* @param maxElement total number element in the output
* @return sliced result. Slicing will happen in the middle. So, the element are: first ...
* E(maxElement - 2), E(maxElement - 1)
*/
public static Result sliceResult(Result obsResults, int maxElement) {
Result slicedObservations = new Result();
// get (maxElement - 1) number of observations from the descending observations list
int descCounter = 0;
while (descCounter < obsResults.size() && slicedObservations.size() < maxElement - 1) {
Result obsResult = obsResults.get(descCounter++);
slicedObservations.add(obsResult);
}
if (!obsResults.isEmpty()) {
// get one from the descending observations list (get the earliest)
int ascCounter = obsResults.size();
while (ascCounter > 0 && slicedObservations.size() < maxElement) {
Result obsResult = obsResults.get(--ascCounter);
if (!slicedObservations.isEmpty()) {
Result lastResult = slicedObservations.get(slicedObservations.size() - 1);
// remove if we already have the earliest
if (OpenmrsUtil.nullSafeEquals(obsResult.toNumber(), lastResult.toNumber())
&& OpenmrsUtil.nullSafeEquals(obsResult.getResultDate(), lastResult.getResultDate())
&& OpenmrsUtil.nullSafeEquals(obsResult.toString(), lastResult.toString())
&& OpenmrsUtil.nullSafeEquals(obsResult.toConcept(), lastResult.toConcept()))
slicedObservations.remove(slicedObservations.size() - 1);
}
slicedObservations.add(obsResult);
// if we found the earliest obs that we needed than we should stop and get out
break;
}
}
return slicedObservations;
}
/**
* @param obsResults
* @return
*/
public static Result consolidate(Result obsResults) {
Result consolidatedResult = new Result();
if (!obsResults.isEmpty()) {
Result prevResult = obsResults.get(0);
for (int i = 1; i < obsResults.size(); i++) {
Result currentResult = obsResults.get(i);
// skip when they are the same result :)
if (log.isDebugEnabled())
log.debug("current: " + currentResult.getResultDate() + " prev: " + prevResult.getResultDate());
if (DateUtils.isSameDay(prevResult.getResultDate(), currentResult.getResultDate())
&& OpenmrsUtil.nullSafeEquals(prevResult.getDatatype(), currentResult.getDatatype())) {
if (log.isDebugEnabled())
log.debug("prev number: " + prevResult.toNumber() + ", current number: " + currentResult.toNumber());
if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.NUMERIC)
&& OpenmrsUtil.nullSafeEquals(prevResult.toNumber(), currentResult.toNumber()))
continue;
if (log.isDebugEnabled())
log.debug("prev concept: " + prevResult.toConcept() + ", current concept: " + currentResult.toConcept());
- if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.NUMERIC)
+ if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.CODED)
&& OpenmrsUtil.nullSafeEquals(prevResult.toConcept(), currentResult.toConcept()))
continue;
}
consolidatedResult.add(prevResult);
prevResult = currentResult;
}
consolidatedResult.add(prevResult);
}
return consolidatedResult;
}
}
| true | true | public static Result consolidate(Result obsResults) {
Result consolidatedResult = new Result();
if (!obsResults.isEmpty()) {
Result prevResult = obsResults.get(0);
for (int i = 1; i < obsResults.size(); i++) {
Result currentResult = obsResults.get(i);
// skip when they are the same result :)
if (log.isDebugEnabled())
log.debug("current: " + currentResult.getResultDate() + " prev: " + prevResult.getResultDate());
if (DateUtils.isSameDay(prevResult.getResultDate(), currentResult.getResultDate())
&& OpenmrsUtil.nullSafeEquals(prevResult.getDatatype(), currentResult.getDatatype())) {
if (log.isDebugEnabled())
log.debug("prev number: " + prevResult.toNumber() + ", current number: " + currentResult.toNumber());
if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.NUMERIC)
&& OpenmrsUtil.nullSafeEquals(prevResult.toNumber(), currentResult.toNumber()))
continue;
if (log.isDebugEnabled())
log.debug("prev concept: " + prevResult.toConcept() + ", current concept: " + currentResult.toConcept());
if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.NUMERIC)
&& OpenmrsUtil.nullSafeEquals(prevResult.toConcept(), currentResult.toConcept()))
continue;
}
consolidatedResult.add(prevResult);
prevResult = currentResult;
}
consolidatedResult.add(prevResult);
}
return consolidatedResult;
}
| public static Result consolidate(Result obsResults) {
Result consolidatedResult = new Result();
if (!obsResults.isEmpty()) {
Result prevResult = obsResults.get(0);
for (int i = 1; i < obsResults.size(); i++) {
Result currentResult = obsResults.get(i);
// skip when they are the same result :)
if (log.isDebugEnabled())
log.debug("current: " + currentResult.getResultDate() + " prev: " + prevResult.getResultDate());
if (DateUtils.isSameDay(prevResult.getResultDate(), currentResult.getResultDate())
&& OpenmrsUtil.nullSafeEquals(prevResult.getDatatype(), currentResult.getDatatype())) {
if (log.isDebugEnabled())
log.debug("prev number: " + prevResult.toNumber() + ", current number: " + currentResult.toNumber());
if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.NUMERIC)
&& OpenmrsUtil.nullSafeEquals(prevResult.toNumber(), currentResult.toNumber()))
continue;
if (log.isDebugEnabled())
log.debug("prev concept: " + prevResult.toConcept() + ", current concept: " + currentResult.toConcept());
if (OpenmrsUtil.nullSafeEquals(currentResult.getDatatype(), Datatype.CODED)
&& OpenmrsUtil.nullSafeEquals(prevResult.toConcept(), currentResult.toConcept()))
continue;
}
consolidatedResult.add(prevResult);
prevResult = currentResult;
}
consolidatedResult.add(prevResult);
}
return consolidatedResult;
}
|
diff --git a/java/com/delcyon/capo/xml/XPath.java b/java/com/delcyon/capo/xml/XPath.java
index 813b907..3121370 100644
--- a/java/com/delcyon/capo/xml/XPath.java
+++ b/java/com/delcyon/capo/xml/XPath.java
@@ -1,538 +1,539 @@
/**
Copyright (C) 2012 Delcyon, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.delcyon.capo.xml;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
import javax.xml.xpath.XPathFunctionResolver;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import com.delcyon.capo.CapoApplication;
import com.delcyon.capo.datastream.NullOutputStream;
import com.delcyon.capo.datastream.stream_attribute_filter.MD5FilterOutputStream;
import com.delcyon.capo.server.CapoServer;
import com.delcyon.capo.util.NamespaceContextMap;
import com.delcyon.capo.xml.cdom.CDocument;
/**
* @author jeremiah
*
*/
public class XPath
{
private static XPathFactory xPathFactory = null;;
static
{
try
{
//try local class loader first, then downgrade to system, then do it the old way...
xPathFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI, "net.sf.saxon.xpath.XPathFactoryImpl", XPath.class.getClassLoader());
}
catch (Throwable e)
{
System.err.println(e);
try
{
xPathFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI, "net.sf.saxon.xpath.XPathFactoryImpl", ClassLoader.getSystemClassLoader());
} catch (Throwable e2)
{
System.err.println(e);
try
{
xPathFactory = XPathFactory.newInstance();
} catch (Exception e3)
{
e3.printStackTrace();
}
}
}
}
public static void setXPathFunctionResolver(XPathFunctionResolver xPathFunctionResolver)
{
xPathFactory.setXPathFunctionResolver(xPathFunctionResolver);
}
public static Node selectSingleNode(Node node, String path) throws Exception
{
return selectSingleNode(node, path, null);
}
public static boolean evaluate(Node node,String path) throws Exception
{
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
namespaceContextMap.addNamespace("server", CapoApplication.SERVER_NAMESPACE_URI);
namespaceContextMap.addNamespace("client", CapoApplication.CLIENT_NAMESPACE_URI);
xPath.setNamespaceContext(namespaceContextMap);
//String parsedXpath = processFunctions(path,prefix);
XPathExpression xPathExpression = xPath.compile(path);
return (Boolean) xPathExpression.evaluate(node,XPathConstants.BOOLEAN);
}
public static Node selectSingleNode(Node node, String path,String prefix) throws Exception
{
try
{
//dumpNode(node.getOwnerDocument(), System.err);
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
namespaceContextMap.addNamespace("server", CapoApplication.SERVER_NAMESPACE_URI);
namespaceContextMap.addNamespace("client", CapoApplication.CLIENT_NAMESPACE_URI);
namespaceContextMap.addNamespace("resource", CapoApplication.RESOURCE_NAMESPACE_URI);
xPath.setNamespaceContext(namespaceContextMap);
//String parsedXpath = processFunctions(path,prefix);
XPathExpression xPathExpression = xPath.compile(path);
return (Node) xPathExpression.evaluate(node,XPathConstants.NODE);
} catch (Exception exception)
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating '"+path+"' on "+getPathToRoot(node));
throw exception;
}
}
public static NodeList selectNodes(Node node, String path) throws Exception
{
return selectNodes(node, path, null);
}
public static Node selectNSNode(Node node, String path,String... namespaces) throws Exception
{
try
{
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
for (String namespace : namespaces)
{
String[] namespaceDecl = namespace.split("=");
namespaceContextMap.addNamespace(namespaceDecl[0], namespaceDecl[1]);
}
xPath.setNamespaceContext(namespaceContextMap);
XPathExpression xPathExpression = xPath.compile(path);
return (Node) xPathExpression.evaluate(node,XPathConstants.NODE);
} catch (Exception exception)
{
if (CapoServer.logger != null)
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"' on "+getPathToRoot(node));
}
throw exception;
}
}
public static NodeList selectNSNodes(Node node, String path,String... namespaces) throws Exception
{
try
{
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
for (String namespace : namespaces)
{
String[] namespaceDecl = namespace.split("=");
namespaceContextMap.addNamespace(namespaceDecl[0], namespaceDecl[1]);
}
xPath.setNamespaceContext(namespaceContextMap);
XPathExpression xPathExpression = xPath.compile(path);
return (NodeList) xPathExpression.evaluate(node,XPathConstants.NODESET);
} catch (Exception exception)
{
if (CapoServer.logger != null)
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"' on "+getPathToRoot(node));
}
throw exception;
}
}
public static void removeNamespaceDeclarations(Node node,String... namespaces)
{
NamedNodeMap namedNodeMap = ((Element)node).getAttributes();
for(int nameIndex = 0; nameIndex < namedNodeMap.getLength(); nameIndex++)
{
Node namedNode = namedNodeMap.item(nameIndex);
String uri = namedNode.getNamespaceURI();
String localName = namedNode.getLocalName();
if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/"))
{
for (String removeableNamespace : namespaces)
{
if (namedNode.getNodeValue().equals(removeableNamespace))
{
((Element)node).removeAttributeNS("http://www.w3.org/2000/xmlns/",localName);
nameIndex--;
}
}
}
}
}
public static NodeList selectNodes(Node node, String path,String prefix) throws Exception
{
try
{
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
namespaceContextMap.addNamespace("server", CapoApplication.SERVER_NAMESPACE_URI);
namespaceContextMap.addNamespace("client", CapoApplication.CLIENT_NAMESPACE_URI);
namespaceContextMap.addNamespace("resource", CapoApplication.RESOURCE_NAMESPACE_URI);
xPath.setNamespaceContext(namespaceContextMap);
XPathExpression xPathExpression = xPath.compile(path);
return (NodeList) xPathExpression.evaluate(node,XPathConstants.NODESET);
} catch (Exception exception)
{
exception.printStackTrace();
if (CapoServer.logger != null) //TODO this shouldn't have a dependency on CapoServer!
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"' on "+getPathToRoot(node));
}
throw exception;
}
}
public static String selectSingleNodeValue(Element node, String path,String... namespaces) throws Exception
{
return selectSingleNodeValue(node, path, null,namespaces);
}
public static String selectSingleNodeValue(Element node, String path, String prefix,String... namespaces) throws Exception
{
try
{
javax.xml.xpath.XPath xPath = xPathFactory.newXPath();
NamespaceContextMap namespaceContextMap = new NamespaceContextMap();
namespaceContextMap.addNamespace("server", CapoApplication.SERVER_NAMESPACE_URI);
namespaceContextMap.addNamespace("client", CapoApplication.CLIENT_NAMESPACE_URI);
namespaceContextMap.addNamespace("resource", CapoApplication.RESOURCE_NAMESPACE_URI);
for (String namespace : namespaces)
{
String[] namespaceDecl = namespace.split("=");
namespaceContextMap.addNamespace(namespaceDecl[0], namespaceDecl[1]);
}
xPath.setNamespaceContext(namespaceContextMap);
XPathExpression xPathExpression = xPath.compile(path);
return xPathExpression.evaluate(node);
} catch (Exception exception)
{
exception.printStackTrace();
//keep this from looping out of control when things are weird
if (exception.getCause() == null || exception.getCause().getMessage() == null)
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"'");
throw exception;
}
if (exception.getCause().getMessage().matches(".*context.*item.*for.*axis.*step.*is.*undefined.*"))
{
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"'");
throw exception;
}
CapoServer.logger.log(Level.SEVERE, "Error evaluating xpath '"+path+"' on "+getPathToRoot(node));
throw exception;
}
}
public static String getXPath(Node node) throws Exception
{
//example
// /server:Capo/server:group[1]/server:choose[1]/server:when[1]
return getPathToRoot(node);
}
private static String getPathToRoot(Node node) throws Exception
{
if(node.getOwnerDocument() == null)
{
Document tempDocument = new CDocument();
node = tempDocument.adoptNode(node.cloneNode(true));
}
String name = node.getNodeName();
if (node instanceof Element)
{
String nameAttributeValue = ((Element) node).getAttribute("name");
if (nameAttributeValue.isEmpty() == true )
{
if (node.getParentNode() != null)
{
String[] nameSpace = new String[0];
if(node.getNamespaceURI() != null)
{
nameSpace = new String[]{node.getPrefix()+"="+node.getNamespaceURI()};
}
- String position = selectSingleNodeValue((Element) node, "count(preceding-sibling::"+name+")+1",nameSpace);
+ //if we're in the default namespace, makeup a prefix aka 'null:' in this current case
+ String position = selectSingleNodeValue((Element) node, "count(preceding-sibling::"+(node.getPrefix() == null && node.getNamespaceURI() != null? node.getPrefix()+":" :"")+name+")+1",nameSpace);
name += "["+position+"]";
}
else //this node does not belong to a document. It must have just been created.
{
name += "[ORPHAN_NODE]";
}
}
else
{
name += "[@name = '"+nameAttributeValue+"']";
}
}
if(node instanceof Attr)
{
name = "@"+name;
}
if (node.getParentNode() != null && node.getParentNode().getNodeName() != null && node.getParentNode() instanceof Element)
{
return getPathToRoot(node.getParentNode())+"/"+name;
}
else
{
return "/"+name;
}
}
// private static String processFunctions(String varString,String prefix)
// {
// StringBuffer stringBuffer = new StringBuffer(varString);
// processFunctions(stringBuffer,prefix);
// return stringBuffer.toString();
// }
// private static void processFunctions(StringBuffer varStringBuffer,String prefix)
// {
// if (prefix == null)
// {
// prefix = "";
// }
// else
// {
// prefix = prefix +":";
// }
//
// Set<String> keySet = xpathFunctionProcessorHashMap.keySet();
//
// for (String functionName : keySet)
// {
// //TODO deal with nested functions and quotes in quotes
// //TODO look into cache this matches function, since it's got the greatest number of allocations in the system.
// if (varStringBuffer != null)
// {
// String varString = varStringBuffer.toString();
// if( varString.matches(".*"+functionName.toString()+functionMatcher))
// {
// String argument = varString.replaceFirst(".*"+functionName.toString()+functionMatcher, "$1");
// String originalFunctionDeclaration = functionName.toString()+"("+argument+")";
// //strip of any quotes
// argument = argument.replaceAll("'", "");
// int startIndex = varStringBuffer.indexOf(originalFunctionDeclaration);
// String[] arguments = argument.split(",");
//
// String value = xpathFunctionProcessorHashMap.get(functionName).processFunction(prefix, functionName, arguments);
//
// varStringBuffer.replace(startIndex, startIndex+originalFunctionDeclaration.length(), value);
// }
// }
// }
//
// if (CapoServer.logger != null)
// {
// CapoServer.logger.log(Level.FINE,"final function replacement = '"+varStringBuffer+"'");
// }
//
// }
public static void dumpNode(Node node, OutputStream outputStream) throws Exception
{
TransformerFactory tFactory = TransformerFactory.newInstance();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document indentityTransforDocument = documentBuilder.parse(XPath.class.getClassLoader().getResourceAsStream("defaults/identity_transform.xsl"));
Transformer transformer = tFactory.newTransformer(new DOMSource(indentityTransforDocument));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//transformer.setOutputProperty(SaxonOutputKeys.INDENT_SPACES,"4");
// if(node.getOwnerDocument() == null)
// {
// Document tempDocument = documentBuilder.newDocument();
// node = tempDocument.adoptNode(node.cloneNode(true));
// }
transformer.transform(new DOMSource(node), new StreamResult(outputStream));
if(outputStream == System.out || outputStream == System.err)
{
outputStream.write(new String("\n").getBytes());
}
}
/**
*
* @param node
* @param xpath
* @return list of nodes removed
* @throws Exception
*/
public static NodeList removeNodes(Node node, String xpath) throws Exception
{
NodeList nodeList = selectNodes(node, xpath);
for (int nodeListIndex = 0; nodeListIndex < nodeList.getLength(); nodeListIndex++)
{
Node removeableNode = nodeList.item(nodeListIndex);
Node parentNode = removeableNode.getParentNode();
if (parentNode != null)
{
parentNode.removeChild(removeableNode);
}
}
return nodeList;
}
/**
*
* @param wrappedDocument
* @param useAdoption - controls whether or not we can use the quicker adoption method, as opposed to making a copy of the document first.
* @return document with first root elements child as document element of new document.
* @throws Exception
*/
public static Document unwrapDocument(Document wrappedDocument,boolean useAdoption) throws Exception
{
//unwrap document
Document unwrappedDocument = CapoApplication.getDocumentBuilder().newDocument();
NodeList nodeList = wrappedDocument.getDocumentElement().getElementsByTagName("*");
if (nodeList.getLength() != 0)
{
if(useAdoption == false)
{
unwrappedDocument.appendChild(unwrappedDocument.importNode(nodeList.item(0),true));
}
else
{
unwrappedDocument.appendChild(unwrappedDocument.adoptNode(nodeList.item(0)));
}
}
else
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XPath.dumpNode(wrappedDocument, byteArrayOutputStream);
throw new Exception("No root element child found:"+new String(byteArrayOutputStream.toByteArray()));
}
return unwrappedDocument;
}
public static Document wrapDocument(Document parentDocument, Document childDocument) throws Exception
{
parentDocument.getDocumentElement().appendChild(parentDocument.importNode(childDocument.getDocumentElement(), true));
return parentDocument;
}
public static void removeContent(Element element)
{
NodeList nodeList = element.getChildNodes();
while(nodeList.getLength() > 0)
{
element.removeChild(nodeList.item(0));
}
}
public static void removeAttributes(Element element)
{
NamedNodeMap namedNodeMap = element.getAttributes();
while (namedNodeMap.getLength() > 0)
{
element.removeAttributeNode((Attr) namedNodeMap.item(0));
}
}
public static String getElementMD5(Element element) throws Exception
{
String md5 = "";
MD5FilterOutputStream md5FilterOutputStream = new MD5FilterOutputStream(new NullOutputStream());
getElementMD5(element, md5FilterOutputStream);
md5FilterOutputStream.close();
md5 = md5FilterOutputStream.getMD5();
return md5;
}
private static void getElementMD5(Element element, MD5FilterOutputStream md5FilterOutputStream) throws Exception
{
//process attributes first
NamedNodeMap attributeList = element.getAttributes();
for (int currentAttribute = 0; currentAttribute < attributeList.getLength(); currentAttribute++)
{
Node attributeNode = attributeList.item(currentAttribute);
if (attributeNode instanceof Attr)
{
Attr attr = (Attr) attributeNode;
md5FilterOutputStream.write(attr.getName());
md5FilterOutputStream.write(attr.getValue());
}
}
//then process children
NodeList nodeList = element.getChildNodes();
for (int currentNode = 0; currentNode < nodeList.getLength(); currentNode++)
{
Node node = nodeList.item(currentNode);
if (node instanceof Element)
{
getElementMD5((Element) node, md5FilterOutputStream);
}
else if (node instanceof Text)
{
if (node.getNodeValue().trim().isEmpty() == false)
{
md5FilterOutputStream.write(node.getNodeValue());
}
}
}
}
}
| true | true | private static String getPathToRoot(Node node) throws Exception
{
if(node.getOwnerDocument() == null)
{
Document tempDocument = new CDocument();
node = tempDocument.adoptNode(node.cloneNode(true));
}
String name = node.getNodeName();
if (node instanceof Element)
{
String nameAttributeValue = ((Element) node).getAttribute("name");
if (nameAttributeValue.isEmpty() == true )
{
if (node.getParentNode() != null)
{
String[] nameSpace = new String[0];
if(node.getNamespaceURI() != null)
{
nameSpace = new String[]{node.getPrefix()+"="+node.getNamespaceURI()};
}
String position = selectSingleNodeValue((Element) node, "count(preceding-sibling::"+name+")+1",nameSpace);
name += "["+position+"]";
}
else //this node does not belong to a document. It must have just been created.
{
name += "[ORPHAN_NODE]";
}
}
else
{
name += "[@name = '"+nameAttributeValue+"']";
}
}
if(node instanceof Attr)
{
name = "@"+name;
}
if (node.getParentNode() != null && node.getParentNode().getNodeName() != null && node.getParentNode() instanceof Element)
{
return getPathToRoot(node.getParentNode())+"/"+name;
}
else
{
return "/"+name;
}
}
| private static String getPathToRoot(Node node) throws Exception
{
if(node.getOwnerDocument() == null)
{
Document tempDocument = new CDocument();
node = tempDocument.adoptNode(node.cloneNode(true));
}
String name = node.getNodeName();
if (node instanceof Element)
{
String nameAttributeValue = ((Element) node).getAttribute("name");
if (nameAttributeValue.isEmpty() == true )
{
if (node.getParentNode() != null)
{
String[] nameSpace = new String[0];
if(node.getNamespaceURI() != null)
{
nameSpace = new String[]{node.getPrefix()+"="+node.getNamespaceURI()};
}
//if we're in the default namespace, makeup a prefix aka 'null:' in this current case
String position = selectSingleNodeValue((Element) node, "count(preceding-sibling::"+(node.getPrefix() == null && node.getNamespaceURI() != null? node.getPrefix()+":" :"")+name+")+1",nameSpace);
name += "["+position+"]";
}
else //this node does not belong to a document. It must have just been created.
{
name += "[ORPHAN_NODE]";
}
}
else
{
name += "[@name = '"+nameAttributeValue+"']";
}
}
if(node instanceof Attr)
{
name = "@"+name;
}
if (node.getParentNode() != null && node.getParentNode().getNodeName() != null && node.getParentNode() instanceof Element)
{
return getPathToRoot(node.getParentNode())+"/"+name;
}
else
{
return "/"+name;
}
}
|
diff --git a/src/com/android/gallery3d/app/ActivityState.java b/src/com/android/gallery3d/app/ActivityState.java
index 1563a09..48ee9fe 100644
--- a/src/com/android/gallery3d/app/ActivityState.java
+++ b/src/com/android/gallery3d/app/ActivityState.java
@@ -1,202 +1,203 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.app;
import com.android.gallery3d.ui.GLView;
import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
abstract public class ActivityState {
public static final int FLAG_HIDE_ACTION_BAR = 1;
public static final int FLAG_HIDE_STATUS_BAR = 2;
public static final int FLAG_SCREEN_ON = 3;
private static final int SCREEN_ON_FLAGS = (
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
);
protected GalleryActivity mActivity;
protected Bundle mData;
protected int mFlags;
protected ResultEntry mReceivedResults;
protected ResultEntry mResult;
protected static class ResultEntry {
public int requestCode;
public int resultCode = Activity.RESULT_CANCELED;
public Intent resultData;
ResultEntry next;
}
private boolean mDestroyed = false;
private boolean mPlugged = false;
protected ActivityState() {
}
protected void setContentPane(GLView content) {
mActivity.getGLRoot().setContentPane(content);
}
void initialize(GalleryActivity activity, Bundle data) {
mActivity = activity;
mData = data;
}
public Bundle getData() {
return mData;
}
protected void onBackPressed() {
mActivity.getStateManager().finishState(this);
}
protected void setStateResult(int resultCode, Intent data) {
if (mResult == null) return;
mResult.resultCode = resultCode;
mResult.resultData = data;
}
protected void onConfigurationChanged(Configuration config) {
}
protected void onSaveState(Bundle outState) {
}
protected void onStateResult(int requestCode, int resultCode, Intent data) {
}
protected void onCreate(Bundle data, Bundle storedState) {
}
BroadcastReceiver mPowerIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
boolean plugged = (0 != intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0));
if (plugged != mPlugged) {
mPlugged = plugged;
final Window win = ((Activity) mActivity).getWindow();
final WindowManager.LayoutParams params = win.getAttributes();
setScreenOnFlags(params);
win.setAttributes(params);
}
}
}
};
void setScreenOnFlags(WindowManager.LayoutParams params) {
if (mPlugged && 0 != (mFlags & FLAG_SCREEN_ON)) {
params.flags |= SCREEN_ON_FLAGS;
} else {
params.flags &= ~SCREEN_ON_FLAGS;
}
}
protected void onPause() {
if (0 != (mFlags & FLAG_SCREEN_ON)) {
((Activity) mActivity).unregisterReceiver(mPowerIntentReceiver);
}
}
// should only be called by StateManager
void resume() {
Activity activity = (Activity) mActivity;
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
if ((mFlags & FLAG_HIDE_ACTION_BAR) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
int stateCount = mActivity.getStateManager().getStateCount();
actionBar.setDisplayOptions(
stateCount == 1 ? 0 : ActionBar.DISPLAY_HOME_AS_UP,
ActionBar.DISPLAY_HOME_AS_UP);
- actionBar.setHomeButtonEnabled(true);
+ actionBar.setHomeButtonEnabled(
+ (actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0);
}
activity.invalidateOptionsMenu();
final Window win = activity.getWindow();
final WindowManager.LayoutParams params = win.getAttributes();
if ((mFlags & FLAG_HIDE_STATUS_BAR) != 0) {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
} else {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
}
setScreenOnFlags(params);
win.setAttributes(params);
ResultEntry entry = mReceivedResults;
if (entry != null) {
mReceivedResults = null;
onStateResult(entry.requestCode, entry.resultCode, entry.resultData);
}
if (0 != (mFlags & FLAG_SCREEN_ON)) {
// we need to know whether the device is plugged in to do this correctly
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
activity.registerReceiver(mPowerIntentReceiver, filter);
}
onResume();
}
// a subclass of ActivityState should override the method to resume itself
protected void onResume() {
}
protected boolean onCreateActionBar(Menu menu) {
// TODO: we should return false if there is no menu to show
// this is a workaround for a bug in system
return true;
}
protected boolean onItemSelected(MenuItem item) {
return false;
}
protected void onDestroy() {
mDestroyed = true;
}
boolean isDestroyed() {
return mDestroyed;
}
}
| true | true | void resume() {
Activity activity = (Activity) mActivity;
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
if ((mFlags & FLAG_HIDE_ACTION_BAR) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
int stateCount = mActivity.getStateManager().getStateCount();
actionBar.setDisplayOptions(
stateCount == 1 ? 0 : ActionBar.DISPLAY_HOME_AS_UP,
ActionBar.DISPLAY_HOME_AS_UP);
actionBar.setHomeButtonEnabled(true);
}
activity.invalidateOptionsMenu();
final Window win = activity.getWindow();
final WindowManager.LayoutParams params = win.getAttributes();
if ((mFlags & FLAG_HIDE_STATUS_BAR) != 0) {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
} else {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
}
setScreenOnFlags(params);
win.setAttributes(params);
ResultEntry entry = mReceivedResults;
if (entry != null) {
mReceivedResults = null;
onStateResult(entry.requestCode, entry.resultCode, entry.resultData);
}
if (0 != (mFlags & FLAG_SCREEN_ON)) {
// we need to know whether the device is plugged in to do this correctly
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
activity.registerReceiver(mPowerIntentReceiver, filter);
}
onResume();
}
| void resume() {
Activity activity = (Activity) mActivity;
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
if ((mFlags & FLAG_HIDE_ACTION_BAR) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
int stateCount = mActivity.getStateManager().getStateCount();
actionBar.setDisplayOptions(
stateCount == 1 ? 0 : ActionBar.DISPLAY_HOME_AS_UP,
ActionBar.DISPLAY_HOME_AS_UP);
actionBar.setHomeButtonEnabled(
(actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0);
}
activity.invalidateOptionsMenu();
final Window win = activity.getWindow();
final WindowManager.LayoutParams params = win.getAttributes();
if ((mFlags & FLAG_HIDE_STATUS_BAR) != 0) {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
} else {
params.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
}
setScreenOnFlags(params);
win.setAttributes(params);
ResultEntry entry = mReceivedResults;
if (entry != null) {
mReceivedResults = null;
onStateResult(entry.requestCode, entry.resultCode, entry.resultData);
}
if (0 != (mFlags & FLAG_SCREEN_ON)) {
// we need to know whether the device is plugged in to do this correctly
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
activity.registerReceiver(mPowerIntentReceiver, filter);
}
onResume();
}
|
diff --git a/src/net/azib/ipscan/config/Version.java b/src/net/azib/ipscan/config/Version.java
index 5039881..0be7b60 100755
--- a/src/net/azib/ipscan/config/Version.java
+++ b/src/net/azib/ipscan/config/Version.java
@@ -1,82 +1,82 @@
/**
* This is a part of Angry IP Scanner source.
*/
package net.azib.ipscan.config;
import java.net.URI;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.logging.Level;
/**
* Class with accessors to version information of the program.
*
* @author Anton Keks
*/
public class Version {
public static final String NAME = "Angry IP Scanner";
public static final String COPYLEFT = "© 2014 Anton Keks";
public static final String WEBSITE = "http://angryip.org/";
public static final String MAILTO = "[email protected]";
public static final String FAQ_URL = WEBSITE + "/faq/";
public static final String PRIVACY_URL = WEBSITE + "/about/privacy.html";
public static final String FULL_LICENSE_URL = "http://www.gnu.org/licenses/gpl-2.0.html";
public static final String PLUGINS_URL = WEBSITE + "/faq/plugins.html";
public static final String DOWNLOAD_URL = WEBSITE + "/download/";
public static final String LATEST_VERSION_URL = WEBSITE + "ipscan/IPSCAN.VERSION";
private static String version;
private static String buildDate;
/**
* @return version of currently running Angry IP Scanner (retrieved from the jar file)
*/
public static String getVersion() {
if (version == null) {
loadVersionFromJar();
}
return version;
}
/**
* @return build date of currently running Angry IP Scanner (retrieved from the jar file)
*/
public static String getBuildDate() {
if (buildDate == null) {
loadVersionFromJar();
}
return buildDate;
}
private static void loadVersionFromJar() {
- String path = Version.class.getClassLoader().getResource(Version.class.getName().replace('.', '/') + ".class").toString();
+ String path = Version.class.getProtectionDomain().getCodeSource().getLocation().toString();
if (path.startsWith("jar:file:")) {
path = path.substring(4, path.indexOf('!'));
try {
JarFile jarFile = new JarFile(new URI(path).getPath());
Attributes attrs = jarFile.getManifest().getMainAttributes();
version = attrs.getValue("Version");
buildDate = attrs.getValue("Build-Date");
return;
}
catch (Exception e) {
LoggerFactory.getLogger().log(Level.WARNING, "Cannot obtain version", e);
}
}
version = "current";
buildDate = "today";
}
public static String getFullName() {
return NAME + " " + getVersion();
}
}
| true | true | private static void loadVersionFromJar() {
String path = Version.class.getClassLoader().getResource(Version.class.getName().replace('.', '/') + ".class").toString();
if (path.startsWith("jar:file:")) {
path = path.substring(4, path.indexOf('!'));
try {
JarFile jarFile = new JarFile(new URI(path).getPath());
Attributes attrs = jarFile.getManifest().getMainAttributes();
version = attrs.getValue("Version");
buildDate = attrs.getValue("Build-Date");
return;
}
catch (Exception e) {
LoggerFactory.getLogger().log(Level.WARNING, "Cannot obtain version", e);
}
}
version = "current";
buildDate = "today";
}
| private static void loadVersionFromJar() {
String path = Version.class.getProtectionDomain().getCodeSource().getLocation().toString();
if (path.startsWith("jar:file:")) {
path = path.substring(4, path.indexOf('!'));
try {
JarFile jarFile = new JarFile(new URI(path).getPath());
Attributes attrs = jarFile.getManifest().getMainAttributes();
version = attrs.getValue("Version");
buildDate = attrs.getValue("Build-Date");
return;
}
catch (Exception e) {
LoggerFactory.getLogger().log(Level.WARNING, "Cannot obtain version", e);
}
}
version = "current";
buildDate = "today";
}
|
diff --git a/modules/kernel/src/kernel/ui/StandardWorldModelViewerComponent.java b/modules/kernel/src/kernel/ui/StandardWorldModelViewerComponent.java
index 8796b93..ee3f153 100644
--- a/modules/kernel/src/kernel/ui/StandardWorldModelViewerComponent.java
+++ b/modules/kernel/src/kernel/ui/StandardWorldModelViewerComponent.java
@@ -1,37 +1,37 @@
package kernel.ui;
import java.awt.Dimension;
import javax.swing.JComponent;
import rescuecore2.standard.view.StandardWorldModelViewer;
import kernel.Kernel;
import kernel.KernelListenerAdapter;
import kernel.Timestep;
/**
A KernelGUIComponent that will view a standard world model.
*/
public class StandardWorldModelViewerComponent implements KernelGUIComponent {
private static final int SIZE = 500;
@Override
public JComponent getGUIComponent(final Kernel kernel) {
final StandardWorldModelViewer viewer = new StandardWorldModelViewer();
viewer.setPreferredSize(new Dimension(SIZE, SIZE));
viewer.view(kernel.getWorldModel());
kernel.addKernelListener(new KernelListenerAdapter() {
@Override
public void timestepCompleted(Timestep time) {
- viewer.view(kernel.getWorldModel(), time.getCommands(), time.getUpdates());
+ viewer.view(kernel.getWorldModel(), time.getCommands());
viewer.repaint();
}
});
return viewer;
}
@Override
public String getGUIComponentName() {
return "World view";
}
}
| true | true | public JComponent getGUIComponent(final Kernel kernel) {
final StandardWorldModelViewer viewer = new StandardWorldModelViewer();
viewer.setPreferredSize(new Dimension(SIZE, SIZE));
viewer.view(kernel.getWorldModel());
kernel.addKernelListener(new KernelListenerAdapter() {
@Override
public void timestepCompleted(Timestep time) {
viewer.view(kernel.getWorldModel(), time.getCommands(), time.getUpdates());
viewer.repaint();
}
});
return viewer;
}
| public JComponent getGUIComponent(final Kernel kernel) {
final StandardWorldModelViewer viewer = new StandardWorldModelViewer();
viewer.setPreferredSize(new Dimension(SIZE, SIZE));
viewer.view(kernel.getWorldModel());
kernel.addKernelListener(new KernelListenerAdapter() {
@Override
public void timestepCompleted(Timestep time) {
viewer.view(kernel.getWorldModel(), time.getCommands());
viewer.repaint();
}
});
return viewer;
}
|
diff --git a/src/main/java/org/apache/jena/fuseki/server/FusekiErrorHandler.java b/src/main/java/org/apache/jena/fuseki/server/FusekiErrorHandler.java
index 9418c00..7a378ac 100644
--- a/src/main/java/org/apache/jena/fuseki/server/FusekiErrorHandler.java
+++ b/src/main/java/org/apache/jena/fuseki/server/FusekiErrorHandler.java
@@ -1,99 +1,99 @@
/*
* 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.jena.fuseki.server;
import static java.lang.String.format ;
import java.io.ByteArrayOutputStream ;
import java.io.IOException ;
import java.io.OutputStreamWriter ;
import java.io.PrintWriter ;
import java.io.StringWriter ;
import java.io.Writer ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;
import org.apache.jena.fuseki.Fuseki ;
import org.apache.jena.fuseki.http.HttpSC ;
import org.eclipse.jetty.http.HttpHeaders ;
import org.eclipse.jetty.http.HttpMethods ;
import org.eclipse.jetty.http.MimeTypes ;
import org.eclipse.jetty.server.HttpConnection ;
import org.eclipse.jetty.server.Request ;
import org.eclipse.jetty.server.handler.ErrorHandler ;
public class FusekiErrorHandler extends ErrorHandler
{
/* ------------------------------------------------------------ */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpConnection connection = HttpConnection.getCurrentConnection();
connection.getRequest().setHandled(true);
String method = request.getMethod();
if(!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))
return;
response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8) ;
response.setHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate,no-cache,no-store") ;
ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024) ;
//String writer = IO.UTF8(null) ;
Writer writer = new OutputStreamWriter(bytes, "UTF-8") ;
handleErrorPage(request, writer, connection.getResponse().getStatus(), connection.getResponse().getReason());
if ( ! Fuseki.VERSION.equalsIgnoreCase("development") )
{
writer.write("\n") ;
writer.write("\n") ;
- writer.write(format("Fuseki - version %s (Date: %s)", Fuseki.VERSION, Fuseki.BUILD_DATE)) ;
+ writer.write(format("Fuseki - version %s (Date: %s)\n", Fuseki.VERSION, Fuseki.BUILD_DATE)) ;
}
writer.flush();
response.setContentLength(bytes.size()) ;
// Copy :-(
response.getOutputStream().write(bytes.toByteArray()) ;
writer.close() ;
}
/* ------------------------------------------------------------ */
@Override
protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message)
throws IOException
{
if ( message == null )
message = HttpSC.getMessage(code) ;
writer.write(format("Error %d: %s\n", code, message)) ;
Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception");
while(th!=null)
{
writer.write("\n");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.flush();
writer.write(sw.getBuffer().toString());
writer.write("\n");
th = th.getCause();
}
}
}
| true | true | public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpConnection connection = HttpConnection.getCurrentConnection();
connection.getRequest().setHandled(true);
String method = request.getMethod();
if(!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))
return;
response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8) ;
response.setHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate,no-cache,no-store") ;
ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024) ;
//String writer = IO.UTF8(null) ;
Writer writer = new OutputStreamWriter(bytes, "UTF-8") ;
handleErrorPage(request, writer, connection.getResponse().getStatus(), connection.getResponse().getReason());
if ( ! Fuseki.VERSION.equalsIgnoreCase("development") )
{
writer.write("\n") ;
writer.write("\n") ;
writer.write(format("Fuseki - version %s (Date: %s)", Fuseki.VERSION, Fuseki.BUILD_DATE)) ;
}
writer.flush();
response.setContentLength(bytes.size()) ;
// Copy :-(
response.getOutputStream().write(bytes.toByteArray()) ;
writer.close() ;
}
| public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpConnection connection = HttpConnection.getCurrentConnection();
connection.getRequest().setHandled(true);
String method = request.getMethod();
if(!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))
return;
response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8) ;
response.setHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate,no-cache,no-store") ;
ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024) ;
//String writer = IO.UTF8(null) ;
Writer writer = new OutputStreamWriter(bytes, "UTF-8") ;
handleErrorPage(request, writer, connection.getResponse().getStatus(), connection.getResponse().getReason());
if ( ! Fuseki.VERSION.equalsIgnoreCase("development") )
{
writer.write("\n") ;
writer.write("\n") ;
writer.write(format("Fuseki - version %s (Date: %s)\n", Fuseki.VERSION, Fuseki.BUILD_DATE)) ;
}
writer.flush();
response.setContentLength(bytes.size()) ;
// Copy :-(
response.getOutputStream().write(bytes.toByteArray()) ;
writer.close() ;
}
|
diff --git a/src/com/android/ficus/zipper/ClipperzCard.java b/src/com/android/ficus/zipper/ClipperzCard.java
index dc800ac..4ba10b9 100644
--- a/src/com/android/ficus/zipper/ClipperzCard.java
+++ b/src/com/android/ficus/zipper/ClipperzCard.java
@@ -1,100 +1,104 @@
/*
* Copyright (C) 2011 Ficus Kirkpatrick
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ficus.zipper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* One Clipperz card.
*/
public class ClipperzCard {
/** The display name of this card. */
public final String label;
/** An ordered list of key/value fields for this card. */
public final List<ClipperzField> fields;
/**
* Create a new Clipperz card.
* @param label Display name of this card
* @param fields List of fields
*/
public ClipperzCard(String label, List<ClipperzField> fields) {
this.label = label;
this.fields = fields;
}
/**
* One name/value field in a Clipperz card.
*/
public static class ClipperzField {
public ClipperzField(String name, String value, boolean hidden) {
this.name = name;
this.value = value;
this.hidden = hidden;
}
public final String name;
public final String value;
public final boolean hidden;
}
/**
* Parse a list of Clipperz cards from a JSON-formatted string in the format
* exported by Clipperz JSON Export mode.
* @return A list of cards or null if the string cannot be parsed
*/
public static List<ClipperzCard> from(String jsonString) {
JSONTokener tokener = new JSONTokener(jsonString);
try {
List<ClipperzCard> cards = new ArrayList<ClipperzCard>();
// Each card is a subobject in a root-level array.
JSONArray root = (JSONArray) tokener.nextValue();
for (int i = 0; i < root.length(); i++) {
JSONObject obj = root.getJSONObject(i);
String label = obj.getString("label");
JSONObject rawFields = obj.getJSONObject("currentVersion").getJSONObject("fields");
// Walk the fields in the JSON object and convert to ClipperzFields.
List<ClipperzField> fields = new ArrayList<ClipperzField>();
@SuppressWarnings("unchecked") Iterator<String> fieldIterator = rawFields.keys();
while (fieldIterator.hasNext()) {
String fieldKey = fieldIterator.next();
JSONObject fieldObj = rawFields.getJSONObject(fieldKey);
ClipperzField field = new ClipperzField(
fieldObj.getString("label"),
fieldObj.getString("value"),
fieldObj.getBoolean("hidden"));
fields.add(field);
}
// Create a card and add it to the list.
cards.add(new ClipperzCard(label, fields));
}
return cards;
} catch (JSONException e) {
return null;
+ } catch (ClassCastException e) {
+ // For valid JSON of the wrong type, e.g. an object when we are expecting
+ // an array.
+ return null;
}
}
}
| true | true | public static List<ClipperzCard> from(String jsonString) {
JSONTokener tokener = new JSONTokener(jsonString);
try {
List<ClipperzCard> cards = new ArrayList<ClipperzCard>();
// Each card is a subobject in a root-level array.
JSONArray root = (JSONArray) tokener.nextValue();
for (int i = 0; i < root.length(); i++) {
JSONObject obj = root.getJSONObject(i);
String label = obj.getString("label");
JSONObject rawFields = obj.getJSONObject("currentVersion").getJSONObject("fields");
// Walk the fields in the JSON object and convert to ClipperzFields.
List<ClipperzField> fields = new ArrayList<ClipperzField>();
@SuppressWarnings("unchecked") Iterator<String> fieldIterator = rawFields.keys();
while (fieldIterator.hasNext()) {
String fieldKey = fieldIterator.next();
JSONObject fieldObj = rawFields.getJSONObject(fieldKey);
ClipperzField field = new ClipperzField(
fieldObj.getString("label"),
fieldObj.getString("value"),
fieldObj.getBoolean("hidden"));
fields.add(field);
}
// Create a card and add it to the list.
cards.add(new ClipperzCard(label, fields));
}
return cards;
} catch (JSONException e) {
return null;
}
}
| public static List<ClipperzCard> from(String jsonString) {
JSONTokener tokener = new JSONTokener(jsonString);
try {
List<ClipperzCard> cards = new ArrayList<ClipperzCard>();
// Each card is a subobject in a root-level array.
JSONArray root = (JSONArray) tokener.nextValue();
for (int i = 0; i < root.length(); i++) {
JSONObject obj = root.getJSONObject(i);
String label = obj.getString("label");
JSONObject rawFields = obj.getJSONObject("currentVersion").getJSONObject("fields");
// Walk the fields in the JSON object and convert to ClipperzFields.
List<ClipperzField> fields = new ArrayList<ClipperzField>();
@SuppressWarnings("unchecked") Iterator<String> fieldIterator = rawFields.keys();
while (fieldIterator.hasNext()) {
String fieldKey = fieldIterator.next();
JSONObject fieldObj = rawFields.getJSONObject(fieldKey);
ClipperzField field = new ClipperzField(
fieldObj.getString("label"),
fieldObj.getString("value"),
fieldObj.getBoolean("hidden"));
fields.add(field);
}
// Create a card and add it to the list.
cards.add(new ClipperzCard(label, fields));
}
return cards;
} catch (JSONException e) {
return null;
} catch (ClassCastException e) {
// For valid JSON of the wrong type, e.g. an object when we are expecting
// an array.
return null;
}
}
|
diff --git a/backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/SnapshotMapper.java b/backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/SnapshotMapper.java
index bb2a5fd1..1a635afe 100644
--- a/backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/SnapshotMapper.java
+++ b/backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/SnapshotMapper.java
@@ -1,19 +1,19 @@
package org.ovirt.engine.api.restapi.types;
import org.ovirt.engine.api.model.Snapshot;
import org.ovirt.engine.core.common.businessentities.DiskImage;
public class SnapshotMapper {
@Mapping(from = DiskImage.class, to = Snapshot.class)
public static Snapshot map(DiskImage entity, Snapshot template) {
Snapshot model = template != null ? template : new Snapshot();
model.setId(entity.getvm_snapshot_id().toString());
if (entity.getdescription() != null) {
model.setDescription(entity.getdescription());
}
- if (entity.getlast_modified_date() != null) {
- model.setDate(DateMapper.map(entity.getlast_modified_date(), null));
+ if (entity.getcreation_date() != null) {
+ model.setDate(DateMapper.map(entity.getcreation_date(), null));
}
return model;
}
}
| true | true | public static Snapshot map(DiskImage entity, Snapshot template) {
Snapshot model = template != null ? template : new Snapshot();
model.setId(entity.getvm_snapshot_id().toString());
if (entity.getdescription() != null) {
model.setDescription(entity.getdescription());
}
if (entity.getlast_modified_date() != null) {
model.setDate(DateMapper.map(entity.getlast_modified_date(), null));
}
return model;
}
| public static Snapshot map(DiskImage entity, Snapshot template) {
Snapshot model = template != null ? template : new Snapshot();
model.setId(entity.getvm_snapshot_id().toString());
if (entity.getdescription() != null) {
model.setDescription(entity.getdescription());
}
if (entity.getcreation_date() != null) {
model.setDate(DateMapper.map(entity.getcreation_date(), null));
}
return model;
}
|
diff --git a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
index 423999a9..93110a44 100644
--- a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
+++ b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/DefaultListItem.java
@@ -1,201 +1,201 @@
package org.pentaho.gwt.widgets.client.listbox;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import org.pentaho.gwt.widgets.client.utils.ElementUtils;
/**
*
* User: Nick Baker
* Date: Mar 9, 2009
* Time: 11:28:45 AM
*/
public class DefaultListItem implements ListItem<Object> {
private String text = ""; //$NON-NLS-1$
private CustomListBox listBox;
private Widget widget;
private Widget dropWidget;
private Image img;
private Widget extraWidget;
private String baseStyleName = "default-list"; //$NON-NLS-1$
private Object value;
public DefaultListItem(){
}
public DefaultListItem(String str){
this();
this.text = str;
this.value = this.text;
createWidgets();
}
/**
* Convenience constructor for creating a listItem with an Image followed by a string..
* <p>
* NOTE: The Image needs to have been constructed with a specified size (ie new Image("src.png",0,0,100,100);)
*
* @param str
* @param img
*/
public DefaultListItem(String str, Image img){
this();
this.text = str;
this.value = this.text;
this.img = img;
createWidgets();
}
public DefaultListItem(String str, Widget widget){
this();
this.text = str;
this.extraWidget = widget;
createWidgets();
}
public void setStylePrimaryName(String style){
baseStyleName = style;
dropWidget.setStylePrimaryName(style+"-item"); //$NON-NLS-1$
widget.setStylePrimaryName(style+"-item"); //$NON-NLS-1$
}
/**
* There are two widgets that need to be maintaned. One that shows in the drop-down when not opened, and
* another that shows in the drop-down popup itself.
*/
private void createWidgets(){
HorizontalPanel hbox = new WrapperPanel(baseStyleName+"-item"); //$NON-NLS-1$
formatWidget(hbox);
widget = hbox;
hbox = new HorizontalPanel();
hbox.setStylePrimaryName(baseStyleName+"-item"); //$NON-NLS-1$
formatWidget(hbox);
dropWidget = hbox;
}
private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
- sp.getElement().getStyle().setProperty("overflow-x","auto");
+ sp.getElement().getStyle().setProperty("overflowX","auto");
sp.add(label);
panel.add(sp);
panel.setCellWidth(label, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
public Widget getWidgetForDropdown() {
return dropWidget;
}
public Widget getWidget() {
return widget;
}
public Object getValue() {
return this.value;
}
public void setValue(Object o) {
this.value = o;
}
public void onHoverEnter() {
}
public void onHoverExit() {
}
public void onSelect() {
widget.addStyleDependentName("selected"); //$NON-NLS-1$
}
public void onDeselect() {
widget.removeStyleDependentName("selected"); //$NON-NLS-1$
}
private class WrapperPanel extends HorizontalPanel {
public WrapperPanel(String styleName){
this.sinkEvents(Event.MOUSEEVENTS);
if(styleName == null){
styleName = "default-list-item"; //$NON-NLS-1$
}
this.setStylePrimaryName(styleName);
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEOVER:
this.addStyleDependentName("hover"); //$NON-NLS-1$
break;
case Event.ONMOUSEOUT:
this.removeStyleDependentName("hover"); //$NON-NLS-1$
break;
case Event.ONMOUSEUP:
listBox.setSelectedItem(DefaultListItem.this);
this.removeStyleDependentName("hover"); //$NON-NLS-1$
default:
break;
}
super.onBrowserEvent(event);
}
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public CustomListBox getListBox() {
return listBox;
}
public void setListBox(CustomListBox listBox) {
this.listBox = listBox;
}
private static class WrapperWidget extends Widget{
public WrapperWidget(Element ele){
this.setElement(ele);
}
}
}
| true | true | private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
sp.getElement().getStyle().setProperty("overflow-x","auto");
sp.add(label);
panel.add(sp);
panel.setCellWidth(label, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
| private void formatWidget(HorizontalPanel panel){
panel.sinkEvents(Event.MOUSEEVENTS);
if(img != null){
Image i = new Image(img.getUrl());
panel.add(i);
panel.setCellVerticalAlignment(i, HasVerticalAlignment.ALIGN_MIDDLE);
i.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
} else if(extraWidget != null){
Element ele = DOM.clone(extraWidget.getElement(), true);
Widget w = new WrapperWidget(ele);
panel.add(w);
panel.setCellVerticalAlignment(w, HasVerticalAlignment.ALIGN_MIDDLE);
w.getElement().getStyle().setProperty("marginRight","2px"); //$NON-NLS-1$ //$NON-NLS-2$
}
Label label = new Label(text);
label.getElement().getStyle().setProperty("cursor","pointer"); //$NON-NLS-1$ //$NON-NLS-2$
label.setWidth("100%"); //$NON-NLS-1$
SimplePanel sp = new SimplePanel();
sp.getElement().getStyle().setProperty("overflowX","auto");
sp.add(label);
panel.add(sp);
panel.setCellWidth(label, "100%"); //$NON-NLS-1$
panel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
ElementUtils.preventTextSelection(panel.getElement());
label.setStylePrimaryName("custom-list-item"); //$NON-NLS-1$
panel.setWidth("100%"); //$NON-NLS-1$
}
|
diff --git a/src/com/java/phondeux/team/TeamCommand.java b/src/com/java/phondeux/team/TeamCommand.java
index fd07d48..2eee633 100644
--- a/src/com/java/phondeux/team/TeamCommand.java
+++ b/src/com/java/phondeux/team/TeamCommand.java
@@ -1,232 +1,232 @@
package com.java.phondeux.team;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class TeamCommand implements CommandExecutor {
private final Team plugin;
public TeamCommand(Team plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Team commands
// create - create a team
// disband - disband a team
// invite - invite a player to a team (admin or mod only)
// deinvite - de-invite a player
// description - set team description
// join - join a team
// leave - leave a team
// kick - kick a player from a team
// open - toggle team open enrollment
// close - toggle team open enrollment
// promote - team member -> mod -> owner
// demote - mod -> team member
// chat - toggle all chat to be team-only
// /tc will also be used to team chat for convenience
// help - a list of the commands and how to use them
Player player = (Player)sender;
Integer pID = plugin.th.playerGetID(player.getName());
Integer pStatus = 0, pTeamID = 0;
try {
pStatus = plugin.th.playerGetStatus(pID);
pTeamID = plugin.th.playerGetTeam(pID);
} catch (SQLException e) {
e.printStackTrace();
}
if (args.length > 0) {
if (args[0].matches("create")) {
if (pStatus != 0) {
player.sendMessage("You are already on a team.");
return true;
}
if (args[1].length() > 8) {
player.sendMessage("Team names are limited to 8 characters.");
return true;
}
- if (!(args[1].matches("\\w"))) {
+ if (!(args[1].matches("\\b\\w+"))) {
player.sendMessage("Team names may be made up of only a-z, A-Z, or 0-9");
return true;
}
if (plugin.th.teamExists(args[1])) {
player.sendMessage("A team with that name already exists.");
return true;
}
try {
int teamid = plugin.th.teamCreate(args[1]);
plugin.th.playerSetTeam(pID, teamid);
plugin.th.playerSetStatus(pID, 3);
player.sendMessage("Team " + args[1] + " created successfully!");
plugin.eh.CreateEvent().TeamCreate(pID, teamid);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("disband")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
plugin.th.teamDelete(pTeamID);
ArrayList<String> members = plugin.th.playersGetNameOnTeam(pTeamID);
for (String m : members) {
plugin.th.playerSetStatus(plugin.th.playerGetID(m), 0);
plugin.th.playerSetTeam(plugin.th.playerGetID(m), 0);
if (plugin.getServer().getPlayer(m) != null) {
plugin.getServer().getPlayer(m).sendMessage("Your team has been disbanded.");
}
}
plugin.th.playerSetStatus(pID, 0);
plugin.eh.CreateEvent().TeamDisband(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("invite")) {
return true;
}
if (args[0].matches("deinvite")) {
return true;
}
if (args[0].matches("description")) {
return true;
}
if (args[0].matches("join")) {
if (pStatus != 0) {
player.sendMessage("You're already on a team.");
return true;
}
Integer teamid = plugin.th.teamGetID(args[1]);
if (!plugin.th.teamExists(teamid)) {
player.sendMessage("The team " + args[1] + " doesn't exist.");
return true;
}
try {
if (plugin.th.teamGetStatus(teamid) == 1) {
player.sendMessage(args[1] + " is closed.");
return true;
}
plugin.th.playerSetStatus(pID, 1);
plugin.th.playerSetTeam(pID, teamid);
plugin.eh.CreateEvent().PlayerJoin(pID, teamid);
player.sendMessage("You've joined " + args[1] + ".");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("leave")) {
if (pStatus == 0) {
player.sendMessage("You aren't on a team.");
return true;
}
if (pStatus == 3) {
player.sendMessage("You own your team, you must disband it.");
return true;
}
try {
plugin.th.playerSetStatus(pID, 0);
plugin.th.playerSetTeam(pID, 0);
plugin.eh.CreateEvent().PlayerLeave(pID, pTeamID);
player.sendMessage("You've left your team.");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("kick")) {
return true;
}
if (args[0].matches("open")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 0) {
player.sendMessage("Your team is already open.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 0);
plugin.eh.CreateEvent().TeamOpen(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("close")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 1) {
player.sendMessage("Your team is already closed.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 1);
plugin.eh.CreateEvent().TeamClose(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("promote")) {
return true;
}
if (args[0].matches("demote")) {
return true;
}
if (args[0].matches("chat")) {
return true;
}
if (args[0].matches("help")) {
try {
ArrayList<String> tmp = plugin.th.teamGetList();
for (String s : tmp) {
String msg = s + ": ";
int teamid = plugin.th.teamGetID(s);
ArrayList<String> tmp2 = plugin.th.playersGetNameOnTeam(teamid);
for (String s2 : tmp2) {
msg += s2 + ", ";
}
player.sendMessage(msg);
}
if (tmp.size() == 0) {
player.sendMessage("No teams");
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
} else {
// Return a simple two/three column list of commands and how to get a full list
// ie /team help #
player.sendMessage("Using /team");
player.sendMessage(ChatColor.RED + "/team create" + ChatColor.WHITE + " - Creates a team");
return true;
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Team commands
// create - create a team
// disband - disband a team
// invite - invite a player to a team (admin or mod only)
// deinvite - de-invite a player
// description - set team description
// join - join a team
// leave - leave a team
// kick - kick a player from a team
// open - toggle team open enrollment
// close - toggle team open enrollment
// promote - team member -> mod -> owner
// demote - mod -> team member
// chat - toggle all chat to be team-only
// /tc will also be used to team chat for convenience
// help - a list of the commands and how to use them
Player player = (Player)sender;
Integer pID = plugin.th.playerGetID(player.getName());
Integer pStatus = 0, pTeamID = 0;
try {
pStatus = plugin.th.playerGetStatus(pID);
pTeamID = plugin.th.playerGetTeam(pID);
} catch (SQLException e) {
e.printStackTrace();
}
if (args.length > 0) {
if (args[0].matches("create")) {
if (pStatus != 0) {
player.sendMessage("You are already on a team.");
return true;
}
if (args[1].length() > 8) {
player.sendMessage("Team names are limited to 8 characters.");
return true;
}
if (!(args[1].matches("\\w"))) {
player.sendMessage("Team names may be made up of only a-z, A-Z, or 0-9");
return true;
}
if (plugin.th.teamExists(args[1])) {
player.sendMessage("A team with that name already exists.");
return true;
}
try {
int teamid = plugin.th.teamCreate(args[1]);
plugin.th.playerSetTeam(pID, teamid);
plugin.th.playerSetStatus(pID, 3);
player.sendMessage("Team " + args[1] + " created successfully!");
plugin.eh.CreateEvent().TeamCreate(pID, teamid);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("disband")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
plugin.th.teamDelete(pTeamID);
ArrayList<String> members = plugin.th.playersGetNameOnTeam(pTeamID);
for (String m : members) {
plugin.th.playerSetStatus(plugin.th.playerGetID(m), 0);
plugin.th.playerSetTeam(plugin.th.playerGetID(m), 0);
if (plugin.getServer().getPlayer(m) != null) {
plugin.getServer().getPlayer(m).sendMessage("Your team has been disbanded.");
}
}
plugin.th.playerSetStatus(pID, 0);
plugin.eh.CreateEvent().TeamDisband(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("invite")) {
return true;
}
if (args[0].matches("deinvite")) {
return true;
}
if (args[0].matches("description")) {
return true;
}
if (args[0].matches("join")) {
if (pStatus != 0) {
player.sendMessage("You're already on a team.");
return true;
}
Integer teamid = plugin.th.teamGetID(args[1]);
if (!plugin.th.teamExists(teamid)) {
player.sendMessage("The team " + args[1] + " doesn't exist.");
return true;
}
try {
if (plugin.th.teamGetStatus(teamid) == 1) {
player.sendMessage(args[1] + " is closed.");
return true;
}
plugin.th.playerSetStatus(pID, 1);
plugin.th.playerSetTeam(pID, teamid);
plugin.eh.CreateEvent().PlayerJoin(pID, teamid);
player.sendMessage("You've joined " + args[1] + ".");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("leave")) {
if (pStatus == 0) {
player.sendMessage("You aren't on a team.");
return true;
}
if (pStatus == 3) {
player.sendMessage("You own your team, you must disband it.");
return true;
}
try {
plugin.th.playerSetStatus(pID, 0);
plugin.th.playerSetTeam(pID, 0);
plugin.eh.CreateEvent().PlayerLeave(pID, pTeamID);
player.sendMessage("You've left your team.");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("kick")) {
return true;
}
if (args[0].matches("open")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 0) {
player.sendMessage("Your team is already open.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 0);
plugin.eh.CreateEvent().TeamOpen(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("close")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 1) {
player.sendMessage("Your team is already closed.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 1);
plugin.eh.CreateEvent().TeamClose(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("promote")) {
return true;
}
if (args[0].matches("demote")) {
return true;
}
if (args[0].matches("chat")) {
return true;
}
if (args[0].matches("help")) {
try {
ArrayList<String> tmp = plugin.th.teamGetList();
for (String s : tmp) {
String msg = s + ": ";
int teamid = plugin.th.teamGetID(s);
ArrayList<String> tmp2 = plugin.th.playersGetNameOnTeam(teamid);
for (String s2 : tmp2) {
msg += s2 + ", ";
}
player.sendMessage(msg);
}
if (tmp.size() == 0) {
player.sendMessage("No teams");
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
} else {
// Return a simple two/three column list of commands and how to get a full list
// ie /team help #
player.sendMessage("Using /team");
player.sendMessage(ChatColor.RED + "/team create" + ChatColor.WHITE + " - Creates a team");
return true;
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Team commands
// create - create a team
// disband - disband a team
// invite - invite a player to a team (admin or mod only)
// deinvite - de-invite a player
// description - set team description
// join - join a team
// leave - leave a team
// kick - kick a player from a team
// open - toggle team open enrollment
// close - toggle team open enrollment
// promote - team member -> mod -> owner
// demote - mod -> team member
// chat - toggle all chat to be team-only
// /tc will also be used to team chat for convenience
// help - a list of the commands and how to use them
Player player = (Player)sender;
Integer pID = plugin.th.playerGetID(player.getName());
Integer pStatus = 0, pTeamID = 0;
try {
pStatus = plugin.th.playerGetStatus(pID);
pTeamID = plugin.th.playerGetTeam(pID);
} catch (SQLException e) {
e.printStackTrace();
}
if (args.length > 0) {
if (args[0].matches("create")) {
if (pStatus != 0) {
player.sendMessage("You are already on a team.");
return true;
}
if (args[1].length() > 8) {
player.sendMessage("Team names are limited to 8 characters.");
return true;
}
if (!(args[1].matches("\\b\\w+"))) {
player.sendMessage("Team names may be made up of only a-z, A-Z, or 0-9");
return true;
}
if (plugin.th.teamExists(args[1])) {
player.sendMessage("A team with that name already exists.");
return true;
}
try {
int teamid = plugin.th.teamCreate(args[1]);
plugin.th.playerSetTeam(pID, teamid);
plugin.th.playerSetStatus(pID, 3);
player.sendMessage("Team " + args[1] + " created successfully!");
plugin.eh.CreateEvent().TeamCreate(pID, teamid);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("disband")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
plugin.th.teamDelete(pTeamID);
ArrayList<String> members = plugin.th.playersGetNameOnTeam(pTeamID);
for (String m : members) {
plugin.th.playerSetStatus(plugin.th.playerGetID(m), 0);
plugin.th.playerSetTeam(plugin.th.playerGetID(m), 0);
if (plugin.getServer().getPlayer(m) != null) {
plugin.getServer().getPlayer(m).sendMessage("Your team has been disbanded.");
}
}
plugin.th.playerSetStatus(pID, 0);
plugin.eh.CreateEvent().TeamDisband(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("invite")) {
return true;
}
if (args[0].matches("deinvite")) {
return true;
}
if (args[0].matches("description")) {
return true;
}
if (args[0].matches("join")) {
if (pStatus != 0) {
player.sendMessage("You're already on a team.");
return true;
}
Integer teamid = plugin.th.teamGetID(args[1]);
if (!plugin.th.teamExists(teamid)) {
player.sendMessage("The team " + args[1] + " doesn't exist.");
return true;
}
try {
if (plugin.th.teamGetStatus(teamid) == 1) {
player.sendMessage(args[1] + " is closed.");
return true;
}
plugin.th.playerSetStatus(pID, 1);
plugin.th.playerSetTeam(pID, teamid);
plugin.eh.CreateEvent().PlayerJoin(pID, teamid);
player.sendMessage("You've joined " + args[1] + ".");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("leave")) {
if (pStatus == 0) {
player.sendMessage("You aren't on a team.");
return true;
}
if (pStatus == 3) {
player.sendMessage("You own your team, you must disband it.");
return true;
}
try {
plugin.th.playerSetStatus(pID, 0);
plugin.th.playerSetTeam(pID, 0);
plugin.eh.CreateEvent().PlayerLeave(pID, pTeamID);
player.sendMessage("You've left your team.");
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("kick")) {
return true;
}
if (args[0].matches("open")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 0) {
player.sendMessage("Your team is already open.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 0);
plugin.eh.CreateEvent().TeamOpen(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("close")) {
if (pStatus != 3) {
player.sendMessage("Either you aren't on a team, or you are not the owner.");
return true;
}
try {
if (plugin.th.teamGetStatus(pTeamID) == 1) {
player.sendMessage("Your team is already closed.");
return true;
}
plugin.th.teamSetStatus(pTeamID, 1);
plugin.eh.CreateEvent().TeamClose(pID, pTeamID);
} catch (SQLException e) {
player.sendMessage("Database error.");
e.printStackTrace();
}
return true;
}
if (args[0].matches("promote")) {
return true;
}
if (args[0].matches("demote")) {
return true;
}
if (args[0].matches("chat")) {
return true;
}
if (args[0].matches("help")) {
try {
ArrayList<String> tmp = plugin.th.teamGetList();
for (String s : tmp) {
String msg = s + ": ";
int teamid = plugin.th.teamGetID(s);
ArrayList<String> tmp2 = plugin.th.playersGetNameOnTeam(teamid);
for (String s2 : tmp2) {
msg += s2 + ", ";
}
player.sendMessage(msg);
}
if (tmp.size() == 0) {
player.sendMessage("No teams");
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
} else {
// Return a simple two/three column list of commands and how to get a full list
// ie /team help #
player.sendMessage("Using /team");
player.sendMessage(ChatColor.RED + "/team create" + ChatColor.WHITE + " - Creates a team");
return true;
}
return true;
}
|
diff --git a/FastBoard/java/fastboard/checkmove/helper/FastFlipCalcHelper0.java b/FastBoard/java/fastboard/checkmove/helper/FastFlipCalcHelper0.java
index 18d5ab0..12bf4e9 100644
--- a/FastBoard/java/fastboard/checkmove/helper/FastFlipCalcHelper0.java
+++ b/FastBoard/java/fastboard/checkmove/helper/FastFlipCalcHelper0.java
@@ -1,22 +1,22 @@
package fastboard.checkmove.helper;
/**
* Created by IntelliJ IDEA.
* User: knhjp
* Date: Nov 8, 2009
* Time: 11:37:10 AM
* This class is used to determine the color of square 0
*/
public class FastFlipCalcHelper0 implements FastFlipCalcHelper {
@Override public boolean isWhite(int line) {
- return false;
+ return line%3 == 2;
}
@Override public boolean isBlack(int line) {
return false;
}
@Override public boolean isEmpty(int line) {
return false;
}
}
| true | true | @Override public boolean isWhite(int line) {
return false;
}
| @Override public boolean isWhite(int line) {
return line%3 == 2;
}
|
diff --git a/src/main/java/com/zaxxer/hikari/util/FastStatementList.java b/src/main/java/com/zaxxer/hikari/util/FastStatementList.java
index 1de37962..6241c6b5 100644
--- a/src/main/java/com/zaxxer/hikari/util/FastStatementList.java
+++ b/src/main/java/com/zaxxer/hikari/util/FastStatementList.java
@@ -1,133 +1,132 @@
/*
* Copyright (C) 2013 Brett Wooldridge
*
* 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.zaxxer.hikari.util;
import java.sql.Statement;
/**
* Fast list without range checking.
*
* @author Brett Wooldridge
*/
public final class FastStatementList
{
private Statement[] elementData;
private int size;
/**
* Construct a FastList with a default size of 16.
*/
public FastStatementList()
{
this.elementData = new Statement[32];
}
/**
* Construct a FastList with a specfied size.
*
* @param size the initial size of the FastList
*/
public FastStatementList(int size)
{
this.elementData = new Statement[size];
}
/**
* Add an element to the tail of the FastList.
*
* @param element the element to add
*/
public void add(Statement element)
{
try
{
elementData[size++] = element;
}
catch (ArrayIndexOutOfBoundsException oob)
{
// overflow-conscious code
- size--;
int oldCapacity = elementData.length;
int newCapacity = oldCapacity << 1;
Statement[] newElementData = new Statement[newCapacity];
System.arraycopy(elementData, 0, newElementData, 0, oldCapacity);
- newElementData[size++] = element;
+ newElementData[size] = element;
elementData = (Statement[]) newElementData;
}
}
/**
* Get the element at the specified index.
*
* @param index the index of the element to get
* @return the element, or ArrayIndexOutOfBounds is thrown if the index is invalid
*/
public Statement get(int index)
{
return elementData[index];
}
/**
* This remove method is most efficient when the element being removed
* is the last element. Equality is identity based, not equals() based.
* Only the first matching element is removed.
*
* @param element the element to remove
*/
public void remove(Object element)
{
for (int index = size - 1; index >= 0; index--)
{
if (element == elementData[index])
{
int numMoved = size - index - 1;
if (numMoved > 0)
{
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
break;
}
}
}
/**
* Clear the FastList.
*/
public void clear()
{
for (int i = 0; i < size; i++)
{
elementData[i] = null;
}
size = 0;
}
/**
* Get the current number of elements in the FastList.
*
* @return the number of current elements
*/
public int size()
{
return size;
}
}
| false | true | public void add(Statement element)
{
try
{
elementData[size++] = element;
}
catch (ArrayIndexOutOfBoundsException oob)
{
// overflow-conscious code
size--;
int oldCapacity = elementData.length;
int newCapacity = oldCapacity << 1;
Statement[] newElementData = new Statement[newCapacity];
System.arraycopy(elementData, 0, newElementData, 0, oldCapacity);
newElementData[size++] = element;
elementData = (Statement[]) newElementData;
}
}
| public void add(Statement element)
{
try
{
elementData[size++] = element;
}
catch (ArrayIndexOutOfBoundsException oob)
{
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity << 1;
Statement[] newElementData = new Statement[newCapacity];
System.arraycopy(elementData, 0, newElementData, 0, oldCapacity);
newElementData[size] = element;
elementData = (Statement[]) newElementData;
}
}
|
diff --git a/android/src/org/coolreader/crengine/Engine.java b/android/src/org/coolreader/crengine/Engine.java
index 25490f0f..fb3eb70d 100644
--- a/android/src/org/coolreader/crengine/Engine.java
+++ b/android/src/org/coolreader/crengine/Engine.java
@@ -1,1641 +1,1647 @@
package org.coolreader.crengine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.coolreader.CoolReader;
import org.coolreader.R;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.view.View;
/**
* CoolReader Engine class.
*
* Only one instance is allowed.
*/
public class Engine {
public static final Logger log = L.create("en");
private final CoolReader mActivity;
private final BackgroundThread mBackgroundThread;
private File[] mountedRootsList;
private Map<String, String> mountedRootsMap;
static final private String LIBRARY_NAME = "cr3engine-45-15";
// private final View mMainView;
// private final ExecutorService mExecutor =
// Executors.newFixedThreadPool(1);
/**
* Get storage root directories.
*
* @return array of r/w storage roots
*/
public File[] getStorageDirectories(boolean writableOnly) {
Collection<File> res = new HashSet<File>(2);
for (File dir : mountedRootsList) {
if (dir.isDirectory() && (!writableOnly || dir.canWrite()))
res.add(dir);
}
return res.toArray(new File[res.size()]);
}
public Map<String, String> getMountedRootsMap() {
return mountedRootsMap;
}
public boolean isRootsMountPoint(String path) {
if (mountedRootsMap == null)
return false;
return mountedRootsMap.containsKey(path);
}
/**
* Get or create writable subdirectory for specified base directory
*
* @param dir
* is base directory
* @param subdir
* is subdirectory name, null to use base directory
* @param createIfNotExists
* is true to force directory creation
* @return writable directory, null if not exist or not writable
*/
public static File getSubdir(File dir, String subdir,
boolean createIfNotExists, boolean writableOnly) {
if (dir == null)
return null;
File dataDir = dir;
if (subdir != null) {
dataDir = new File(dataDir, subdir);
if (!dataDir.isDirectory() && createIfNotExists)
dataDir.mkdir();
}
if (dataDir.isDirectory() && (!writableOnly || dataDir.canWrite()))
return dataDir;
return null;
}
/**
* Returns array of writable data directories on external storage
*
* @param subdir
* @param createIfNotExists
* @return
*/
public File[] getDataDirectories(String subdir,
boolean createIfNotExists, boolean writableOnly) {
File[] roots = getStorageDirectories(writableOnly);
ArrayList<File> res = new ArrayList<File>(roots.length);
for (File dir : roots) {
File dataDir = getSubdir(dir, ".cr3", createIfNotExists,
writableOnly);
if (subdir != null)
dataDir = getSubdir(dataDir, subdir, createIfNotExists,
writableOnly);
if (dataDir != null)
res.add(dataDir);
}
return res.toArray(new File[] {});
}
public interface EngineTask {
public void work() throws Exception;
public void done();
public void fail(Exception e);
}
// public static class FatalError extends RuntimeException {
// private Engine engine;
// private String msg;
// public FatalError( Engine engine, String msg )
// {
// this.engine = engine;
// this.msg = msg;
// }
// public void handle()
// {
// engine.fatalError(msg);
// }
// }
public final static boolean LOG_ENGINE_TASKS = false;
private class TaskHandler implements Runnable {
final EngineTask task;
public TaskHandler(EngineTask task) {
this.task = task;
}
public String toString() {
return "[handler for " + this.task.toString() + "]";
}
public void run() {
try {
if (LOG_ENGINE_TASKS)
log.i("running task.work() "
+ task.getClass().getName());
if (!initialized)
throw new IllegalStateException("Engine not initialized");
// run task
task.work();
if (LOG_ENGINE_TASKS)
log.i("exited task.work() "
+ task.getClass().getName());
// post success callback
mBackgroundThread.postGUI(new Runnable() {
public void run() {
if (LOG_ENGINE_TASKS)
log.i("running task.done() "
+ task.getClass().getName()
+ " in gui thread");
task.done();
}
});
// } catch ( final FatalError e ) {
// TODO:
// Handler h = view.getHandler();
//
// if ( h==null ) {
// View root = view.getRootView();
// h = root.getHandler();
// }
// if ( h==null ) {
// //
// e.handle();
// } else {
// h.postAtFrontOfQueue(new Runnable() {
// public void run() {
// e.handle();
// }
// });
// }
} catch (final Exception e) {
log.e("exception while running task "
+ task.getClass().getName(), e);
// post error callback
mBackgroundThread.postGUI(new Runnable() {
public void run() {
log.e("running task.fail(" + e.getMessage()
+ ") " + task.getClass().getSimpleName()
+ " in gui thread ");
task.fail(e);
}
});
}
}
}
/**
* Execute task in Engine thread
*
* @param task
* is task to execute
*/
public void execute(final EngineTask task) {
if (LOG_ENGINE_TASKS)
log.d("executing task " + task.getClass().getSimpleName());
TaskHandler taskHandler = new TaskHandler(task);
mBackgroundThread.executeBackground(taskHandler);
}
/**
* Schedule task for execution in Engine thread
*
* @param task
* is task to execute
*/
public void post(final EngineTask task) {
if (LOG_ENGINE_TASKS)
log.d("executing task " + task.getClass().getSimpleName());
TaskHandler taskHandler = new TaskHandler(task);
mBackgroundThread.postBackground(taskHandler);
}
/**
* Schedule Runnable for execution in GUI thread after all current Engine
* queue tasks done.
*
* @param task
*/
public void runInGUI(final Runnable task) {
execute(new EngineTask() {
public void done() {
mBackgroundThread.postGUI(task);
}
public void fail(Exception e) {
// do nothing
}
public void work() throws Exception {
// do nothing
}
});
}
public void fatalError(String msg) {
AlertDialog dlg = new AlertDialog.Builder(mActivity).setMessage(msg)
.setTitle("CoolReader fatal error").show();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// do nothing
}
dlg.dismiss();
mActivity.finish();
}
private ProgressDialog mProgress;
private boolean enable_progress = true;
private boolean progressShown = false;
private static int PROGRESS_STYLE = ProgressDialog.STYLE_HORIZONTAL;
private Drawable progressIcon = null;
// public void setProgressDrawable( final BitmapDrawable drawable )
// {
// if ( enable_progress ) {
// mBackgroundThread.executeGUI( new Runnable() {
// public void run() {
// // show progress
// log.v("showProgress() - in GUI thread");
// if ( mProgress!=null && progressShown ) {
// hideProgress();
// progressIcon = drawable;
// showProgress(mProgressPos, mProgressMessage);
// //mProgress.setIcon(drawable);
// }
// }
// });
// }
// }
public void showProgress(final int mainProgress, final int resourceId) {
showProgress(mainProgress,
mActivity.getResources().getString(resourceId));
}
private String mProgressMessage = null;
private int mProgressPos = 0;
private volatile int nextProgressId = 0;
public class DelayedProgress {
private volatile boolean cancelled;
private volatile boolean shown;
/**
* Cancel scheduled progress.
*/
public void cancel() {
cancelled = true;
}
/**
* Cancel and hide scheduled progress.
*/
public void hide() {
this.cancelled = true;
BackgroundThread.instance().executeGUI(new Runnable() {
@Override
public void run() {
if ( shown )
hideProgress();
shown = false;
}
});
}
DelayedProgress( final int percent, final String msg, final int delayMillis ) {
this.cancelled = false;
BackgroundThread.instance().postGUI(new Runnable() {
@Override
public void run() {
if ( !cancelled ) {
showProgress( percent, msg );
shown = true;
}
}
}, delayMillis);
}
}
/**
* Display progress dialog after delay.
* (thread-safe)
* @param mainProgress is percent*100
* @param msg is progress message text
* @param delayMillis is delay before display of progress
* @return DelayedProgress object which can be use to hide or cancel this schedule
*/
public DelayedProgress showProgressDelayed(final int mainProgress, final String msg, final int delayMillis ) {
return new DelayedProgress(mainProgress, msg, delayMillis);
}
/**
* Show progress dialog.
* (thread-safe)
* @param mainProgress is percent*100
* @param msg is progress message
*/
public void showProgress(final int mainProgress, final String msg) {
final int progressId = ++nextProgressId;
mProgressMessage = msg;
mProgressPos = mainProgress;
if (mainProgress == 10000) {
//log.v("mainProgress==10000 : calling hideProgress");
hideProgress();
return;
}
log.v("showProgress(" + mainProgress + ", \"" + msg
+ "\") is called : " + Thread.currentThread().getName());
if (enable_progress) {
mBackgroundThread.executeGUI(new Runnable() {
public void run() {
// show progress
//log.v("showProgress() - in GUI thread");
if (progressId != nextProgressId) {
//log.v("showProgress() - skipping duplicate progress event");
return;
}
if (mProgress == null) {
//log.v("showProgress() - creating progress window");
try {
if (mActivity != null && mActivity.isStarted()) {
mProgress = new ProgressDialog(mActivity);
mProgress
.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if (progressIcon != null)
mProgress.setIcon(progressIcon);
else
mProgress.setIcon(R.drawable.cr3_logo);
mProgress.setMax(10000);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
mProgress
.setTitle(mActivity
.getResources()
.getString(
R.string.progress_please_wait));
mProgress.setMessage(msg);
mProgress.show();
progressShown = true;
}
} catch (Exception e) {
Log.e("cr3",
"Exception while trying to show progress dialog",
e);
progressShown = false;
mProgress = null;
}
} else {
mProgress.setProgress(mainProgress);
mProgress.setMessage(msg);
if (!mProgress.isShowing()) {
mProgress.show();
progressShown = true;
}
}
}
});
}
}
/**
* Hide progress dialog (if shown).
* (thread-safe)
*/
public void hideProgress() {
final int progressId = ++nextProgressId;
log.v("hideProgress() - is called : "
+ Thread.currentThread().getName());
// log.v("hideProgress() is called");
mBackgroundThread.executeGUI(new Runnable() {
public void run() {
// hide progress
// log.v("hideProgress() - in GUI thread");
if (progressId != nextProgressId) {
// Log.v("cr3",
// "hideProgress() - skipping duplicate progress event");
return;
}
if (mProgress != null) {
// if ( mProgress.isShowing() )
// mProgress.hide();
progressShown = false;
progressIcon = null;
if (mProgress.isShowing())
mProgress.dismiss();
mProgress = null;
// log.v("hideProgress() - in GUI thread, finished");
}
}
});
}
public boolean isProgressShown() {
return progressShown;
}
public String loadFileUtf8(File file) {
try {
InputStream is = new FileInputStream(file);
return loadResourceUtf8(is);
} catch (Exception e) {
log.e("cannot load resource from file " + file);
return null;
}
}
public String loadResourceUtf8(int id) {
try {
InputStream is = this.mActivity.getResources().openRawResource(id);
return loadResourceUtf8(is);
} catch (Exception e) {
log.e("cannot load resource " + id);
return null;
}
}
public String loadResourceUtf8(InputStream is) {
try {
int available = is.available();
if (available <= 0)
return null;
byte buf[] = new byte[available];
if (is.read(buf) != available)
throw new IOException("Resource not read fully");
is.close();
String utf8 = new String(buf, 0, available, "UTF8");
return utf8;
} catch (Exception e) {
log.e("cannot load resource");
return null;
}
}
public byte[] loadResourceBytes(int id) {
try {
InputStream is = this.mActivity.getResources().openRawResource(id);
return loadResourceBytes(is);
} catch (Exception e) {
log.e("cannot load resource");
return null;
}
}
public static byte[] loadResourceBytes(File f) {
if (f == null || !f.isFile() || !f.exists())
return null;
FileInputStream is = null;
try {
is = new FileInputStream(f);
byte[] res = loadResourceBytes(is);
return res;
} catch (IOException e) {
log.e("Cannot open file " + f);
}
return null;
}
public static byte[] loadResourceBytes(InputStream is) {
try {
int available = is.available();
if (available <= 0)
return null;
byte buf[] = new byte[available];
if (is.read(buf) != available)
throw new IOException("Resource not read fully");
is.close();
return buf;
} catch (Exception e) {
log.e("cannot load resource");
return null;
}
}
/**
* Initialize CoolReader Engine
*
* @param fontList
* is array of .ttf font pathnames to load
*/
public Engine(CoolReader activity, BackgroundThread backgroundThread) {
this.mActivity = activity;
this.mBackgroundThread = backgroundThread;
installLibrary();
initMountRoots();
mFonts = findFonts();
// this.mMainView = mainView;
//
// log.i("Engine() : initializing Engine in UI thread");
// if (!initialized) {
// installLibrary();
// }
initializeStarted = true;
log.i("Engine() : scheduling init task");
BackgroundThread.backgroundExecutor.execute(new Runnable() {
public void run() {
try {
log.i("Engine() : running init() in engine thread");
init();
// android.view.ViewRoot.getRunQueue().post(new Runnable() {
// public void run() {
//
// }
// });
} catch (final Exception e) {
log.e("Exception while initializing Engine", e);
// handler.post(new Runnable() {
// public void run() {
// // TODO: fatal error
// }
// });
}
}
});
}
private native boolean initInternal(String[] fontList);
private native void uninitInternal();
private native String[] getFontFaceListInternal();
private native String[] getArchiveItemsInternal(String arcName); // pairs:
// pathname,
// size
private native boolean setKeyBacklightInternal(int value);
private native boolean setCacheDirectoryInternal(String dir, int size);
private native boolean scanBookPropertiesInternal(FileInfo info);
private native byte[] scanBookCoverInternal(String path);
private native void drawBookCoverInternal(Bitmap bmp, byte[] data, String fontFace, String title, String authors, String seriesName, int seriesNumber, int bpp);
private static native void suspendLongOperationInternal(); // cancel current long operation in engine thread (swapping to cache file) -- call it from GUI thread
public static void suspendLongOperation() {
if (isInitialized()) {
suspendLongOperationInternal();
}
}
/**
* Checks whether specified directlry or file is symbolic link.
* (thread-safe)
* @param pathName is path to check
* @return path link points to if specified directory is link (symlink), null for regular file/dir
*/
public native static String isLink(String pathName);
private static final int HYPH_NONE = 0;
private static final int HYPH_ALGO = 1;
private static final int HYPH_DICT = 2;
private static final int HYPH_BOOK = 0;
private native boolean setHyphenationMethod(int type, byte[] dictData);
public ArrayList<ZipEntry> getArchiveItems(String zipFileName) {
final int itemsPerEntry = 2;
String[] in;
synchronized(this) {
in = getArchiveItemsInternal(zipFileName);
}
ArrayList<ZipEntry> list = new ArrayList<ZipEntry>();
for (int i = 0; i <= in.length - itemsPerEntry; i += itemsPerEntry) {
ZipEntry e = new ZipEntry(in[i]);
e.setSize(Integer.valueOf(in[i + 1]));
e.setCompressedSize(Integer.valueOf(in[i + 1]));
list.add(e);
}
return list;
}
public static class HyphDict {
private static HyphDict[] values = new HyphDict[] {};
public final static HyphDict NONE = new HyphDict("NONE", HYPH_NONE, 0, "[None]", "");
public final static HyphDict ALGORITHM = new HyphDict("ALGORITHM", HYPH_ALGO, 0, "[Algorythmic]", "");
public final static HyphDict BOOK_LANGUAGE = new HyphDict("BOOK LANGUAGE", HYPH_BOOK, 0, "[From Book Language]", "");
public final static HyphDict RUSSIAN = new HyphDict("RUSSIAN", HYPH_DICT, R.raw.russian_enus_hyphen, "Russian", "ru");
public final static HyphDict ENGLISH = new HyphDict("ENGLISH", HYPH_DICT, R.raw.english_us_hyphen, "English US", "en");
public final static HyphDict GERMAN = new HyphDict("GERMAN", HYPH_DICT, R.raw.german_hyphen, "German", "de");
public final static HyphDict UKRAINIAN = new HyphDict("UKRAINIAN", HYPH_DICT,R.raw.ukrain_hyphen, "Ukrainian", "uk");
public final static HyphDict SPANISH = new HyphDict("SPANISH", HYPH_DICT,R.raw.spanish_hyphen, "Spanish", "es");
public final static HyphDict FRENCH = new HyphDict("FRENCH", HYPH_DICT,R.raw.french_hyphen, "French", "fr");
public final static HyphDict BULGARIAN = new HyphDict("BULGARIAN", HYPH_DICT, R.raw.bulgarian_hyphen, "Bulgarian", "bg");
public final static HyphDict SWEDISH = new HyphDict("SWEDISH", HYPH_DICT, R.raw.swedish_hyphen, "Swedish", "sv");
public final static HyphDict POLISH = new HyphDict("POLISH", HYPH_DICT, R.raw.polish_hyphen, "Polish", "pl");
public final static HyphDict HUNGARIAN = new HyphDict("HUNGARIAN", HYPH_DICT, R.raw.hungarian_hyphen, "Hungarian", "hu");
public final static HyphDict GREEK = new HyphDict("GREEK", HYPH_DICT, R.raw.greek_hyphen, "Greek", "el");
public final String code;
public final int type;
public final int resource;
public final String name;
public final File file;
public String language;
public static HyphDict[] values() {
return values;
}
private static void add(HyphDict dict) {
// Arrays.copyOf(values, values.length+1); -- absent until API level 9
HyphDict[] list = new HyphDict[values.length+1];
for (int i=0; i<values.length; i++)
list[i] = values[i];
list[list.length-1] = dict;
values = list;
}
private HyphDict(String code, int type, int resource, String name, String language) {
this.type = type;
this.resource = resource;
this.name = name;
this.file = null;
this.code = code;
this.language = language;
// register in list
add(this);
}
private HyphDict(File file) {
this.type = HYPH_DICT;
this.resource = 0;
this.name = file.getName();
this.file = file;
this.code = this.name;
this.language = "";
// register in list
add(this);
}
private static HyphDict byLanguage(String language) {
if (language != null && !language.trim().equals("")) {
for (HyphDict dict : values) {
if (dict != BOOK_LANGUAGE) {
if (dict.language.equals(language))
return dict;
}
}
}
return NONE;
}
public static HyphDict byCode(String code) {
for (HyphDict dict : values)
if (dict.toString().equals(code))
return dict;
return NONE;
}
public static HyphDict byFileName(String fileName) {
for (HyphDict dict : values)
if (dict.file!=null && dict.file.getName().equals(fileName))
return dict;
return NONE;
}
@Override
public String toString() {
return code;
}
public String getName() {
if (this == BOOK_LANGUAGE) {
if (language != null && !language.trim().equals("")) {
return this.name + " (currently: " + this.language + ")";
} else {
return this.name + " (currently: none)";
}
} else {
return name;
}
}
public static boolean fromFile(File file) {
if (file==null || !file.exists() || !file.isFile() || !file.canRead())
return false;
String fn = file.getName();
if (!fn.toLowerCase().endsWith(".pdb") && !fn.toLowerCase().endsWith(".pattern"))
return false; // wrong file name
if (byFileName(file.getName())!=NONE)
return false; // already registered
new HyphDict(file);
return true;
}
};
private HyphDict currentHyphDict = null;
private String currentHyphLanguage = null;
public boolean setHyphenationLanguage(final String wanted_language) {
String language = getLanguage(wanted_language);
log.i("setHyphenationLanguage( " + language + " ) is called");
if (language == currentHyphLanguage || currentHyphDict != HyphDict.BOOK_LANGUAGE)
return false;
currentHyphLanguage = language;
HyphDict dict = HyphDict.byLanguage(language);
setHyphenationDictionaryInternal(dict);
if (dict != null) {
HyphDict.BOOK_LANGUAGE.language = language;
} else {
HyphDict.BOOK_LANGUAGE.language = "";
}
log.i("setHyphenationLanguage( " + language + " ) set to " + dict);
return true;
}
private String getLanguage(final String language) {
if (language == null || "".equals(language.trim())) {
return "";
} else if (language.contains("-")) {
return language.substring(0, language.indexOf("-")).toLowerCase();
} else {
return language.toLowerCase();
}
}
public boolean setHyphenationDictionary(final HyphDict dict) {
log.i("setHyphenationDictionary( " + dict + " ) is called");
if (currentHyphDict == dict)
return false;
currentHyphDict = dict;
setHyphenationDictionaryInternal(dict);
return true;
}
private void setHyphenationDictionaryInternal(final HyphDict dict) {
// byte[] image = loadResourceBytes(R.drawable.tx_old_book);
mBackgroundThread.postBackground(new Runnable() {
public void run() {
if (!initialized)
throw new IllegalStateException("CREngine is not initialized");
byte[] data = null;
if (dict.type == HYPH_DICT) {
if (dict.resource!=0) {
data = loadResourceBytes(dict.resource);
} else if (dict.file!=null) {
data = loadResourceBytes(dict.file);
}
}
log.i("Setting engine's hyphenation dictionary to " + dict);
setHyphenationMethod(dict.type, data);
}
});
}
public boolean scanBookProperties(FileInfo info) {
if (!initialized)
throw new IllegalStateException("CREngine is not initialized");
synchronized(this) {
long start = android.os.SystemClock.uptimeMillis();
boolean res = scanBookPropertiesInternal(info);
long duration = android.os.SystemClock.uptimeMillis() - start;
L.v("scanBookProperties took " + duration + " ms for " + info.getPathName());
return res;
}
}
public byte[] scanBookCover(String path) {
synchronized(this) {
long start = Utils.timeStamp();
byte[] res = scanBookCoverInternal(path);
long duration = Utils.timeInterval(start);
L.v("scanBookCover took " + duration + " ms for " + path);
return res;
}
}
/**
* Draw book coverpage into bitmap buffer.
* If cover image specified, this image will be drawn (resized to buffer size).
* If no cover image, default coverpage will be drawn, with author, title, series.
* @param bmp is buffer to draw in.
* @param data is coverpage image data bytes, or empty array if no cover image
* @param fontFace is font face to use.
* @param title is book title.
* @param authors is book authors list
* @param seriesName is series name
* @param seriesNumber is series number
* @param bpp is bits per pixel (specify <=8 for eink grayscale dithering)
*/
public void drawBookCover(Bitmap bmp, byte[] data, String fontFace, String title, String authors, String seriesName, int seriesNumber, int bpp) {
synchronized(this) {
long start = Utils.timeStamp();
drawBookCoverInternal(bmp, data, fontFace, title, authors, seriesName, seriesNumber, bpp);
long duration = Utils.timeInterval(start);
L.v("drawBookCover took " + duration + " ms");
}
}
public String[] getFontFaceList() {
if (!initialized)
return null; //throw new IllegalStateException("CREngine is not initialized");
synchronized(this) {
return getFontFaceListInternal();
}
}
private int lastSystemUiVisibility = -1;
private boolean setSystemUiVisibility(int value) {
if (DeviceInfo.getSDKLevel() >= DeviceInfo.HONEYCOMB) {
boolean a4 = DeviceInfo.getSDKLevel() >= DeviceInfo.ICE_CREAM_SANDWICH;
if (value == lastSystemUiVisibility)// && a4)
return false;
lastSystemUiVisibility = value;
if (!a4)
value &= SYSTEM_UI_FLAG_LOW_PROFILE;
View view;
//if (a4)
view = mActivity.getWindow().getDecorView(); // getReaderView();
//else
// view = mActivity.getContentView(); // getReaderView();
if (view == null)
return false;
Method m;
try {
m = view.getClass().getMethod("setSystemUiVisibility", int.class);
m.invoke(view, value);
return true;
} catch (SecurityException e) {
// ignore
} catch (NoSuchMethodException e) {
// ignore
} catch (IllegalArgumentException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
} catch (InvocationTargetException e) {
// ignore
}
}
return false;
}
public boolean setSystemUiVisibility() {
if (DeviceInfo.getSDKLevel() >= DeviceInfo.HONEYCOMB) {
int flags = 0;
if (currentKeyBacklightLevel == 0)
flags |= SYSTEM_UI_FLAG_LOW_PROFILE;
if (mActivity.isFullscreen())
flags |= SYSTEM_UI_FLAG_HIDE_NAVIGATION;
setSystemUiVisibility(flags);
return true;
}
return false;
}
private final static int SYSTEM_UI_FLAG_LOW_PROFILE = 1;
private final static int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2;
private final static int SYSTEM_UI_FLAG_VISIBLE = 0;
private int currentKeyBacklightLevel = 1;
public boolean setKeyBacklight(int value) {
if (!initialized)
return false;
currentKeyBacklightLevel = value;
// Try ICS way
if (DeviceInfo.getSDKLevel() >= DeviceInfo.HONEYCOMB) {
setSystemUiVisibility();
}
// thread safe
return setKeyBacklightInternal(value);
}
final static int CACHE_DIR_SIZE = 32000000;
private String createCacheDir(File baseDir, String subDir) {
String cacheDirName = null;
if (baseDir.isDirectory()) {
if (baseDir.canWrite()) {
if (subDir != null) {
baseDir = new File(baseDir, subDir);
baseDir.mkdir();
}
if (baseDir.exists() && baseDir.canWrite()) {
File cacheDir = new File(baseDir, "cache");
if (cacheDir.exists() || cacheDir.mkdirs()) {
if (cacheDir.canWrite()) {
cacheDirName = cacheDir.getAbsolutePath();
CR3_SETTINGS_DIR_NAME = baseDir.getAbsolutePath();
}
}
}
} else {
log.i(baseDir.toString() + " is read only");
}
} else {
log.i(baseDir.toString() + " is not found");
}
return cacheDirName;
}
public static String getExternalSettingsDirName() {
return CR3_SETTINGS_DIR_NAME;
}
public static File getExternalSettingsDir() {
return CR3_SETTINGS_DIR_NAME!=null ? new File(CR3_SETTINGS_DIR_NAME) : null;
}
public static boolean moveFile( File oldPlace, File newPlace ) {
boolean removeNewFile = true;
log.i("Moving file " + oldPlace.getAbsolutePath() + " to " + newPlace.getAbsolutePath());
if ( !oldPlace.exists() ) {
log.e("File " + oldPlace.getAbsolutePath() + " does not exist!");
return false;
}
FileOutputStream os = null;
FileInputStream is = null;
try {
if ( !newPlace.createNewFile() )
return false; // cannot create file
os = new FileOutputStream(newPlace);
is = new FileInputStream(oldPlace);
byte[] buf = new byte[0x10000];
for (;;) {
int bytesRead = is.read(buf);
if ( bytesRead<=0 )
break;
os.write(buf, 0, bytesRead);
}
removeNewFile = false;
oldPlace.delete();
return true;
} catch ( IOException e ) {
return false;
} finally {
try {
if (os != null)
os.close();
} catch (IOException ee) {
// ignore
}
try {
if (is != null)
is.close();
} catch (IOException ee) {
// ignore
}
if ( removeNewFile )
newPlace.delete();
}
}
/**
* Checks whether file under old path exists, and moves it to better place when necessary.
* Can be slow if big file is being moved.
* @param bestPlace is desired directory for file (e.g. new place after migration)
* @param oldPlace is old (obsolete) directory for file (e.g. location from older releases)
* @param filename is name of file
* @return file to use (from old or new place)
*/
public static File checkOrMoveFile( File bestPlace, File oldPlace, String filename ) {
if ( !bestPlace.exists() ) {
bestPlace.mkdirs();
}
File oldFile = new File(oldPlace, filename);
if ( bestPlace.isDirectory() && bestPlace.canWrite() ) {
File bestFile = new File(bestPlace, filename);
if (bestFile.exists())
return bestFile; // already exists
if (oldFile.exists() && oldFile.isFile()) {
// move file
if (moveFile(oldFile, bestFile))
return bestFile;
return oldFile;
}
return bestFile;
}
return oldFile;
}
private static String CR3_SETTINGS_DIR_NAME;
public final static String CACHE_BASE_DIR_NAME = ".cr3"; // "Books"
private void initCacheDirectory() {
String cacheDirName = null;
// SD card
cacheDirName = createCacheDir(
Environment.getExternalStorageDirectory(), CACHE_BASE_DIR_NAME);
// non-standard SD mount points
if (cacheDirName == null) {
for (String dirname : mountedRootsMap.keySet()) {
cacheDirName = createCacheDir(new File(dirname),
CACHE_BASE_DIR_NAME);
if ( cacheDirName!=null )
break;
}
}
// internal flash
if (cacheDirName == null) {
File cacheDir = mActivity.getCacheDir();
if (!cacheDir.isDirectory())
cacheDir.mkdir();
cacheDirName = createCacheDir(cacheDir, null);
// File cacheDir = mActivity.getDir("cache", Context.MODE_PRIVATE);
// if (cacheDir.isDirectory() && cacheDir.canWrite())
// cacheDirName = cacheDir.getAbsolutePath();
}
// set cache directory for engine
if (cacheDirName != null) {
log.i(cacheDirName
+ " will be used for cache, maxCacheSize=" + CACHE_DIR_SIZE);
synchronized(this) {
setCacheDirectoryInternal(cacheDirName, CACHE_DIR_SIZE);
}
}
}
private boolean addMountRoot(Map<String, String> list, String pathname, int resourceId)
{
return addMountRoot(list, pathname, mActivity.getResources().getString(resourceId));
}
private boolean addMountRoot(Map<String, String> list, String path, String name) {
if (list.containsKey(path))
return false;
for (String key : list.keySet()) {
if (path.equals(key)) { // path.startsWith(key + "/")
log.w("Skipping duplicate path " + path + " == " + key);
return false; // duplicate subpath
}
}
try {
File dir = new File(path);
if (dir.isDirectory()) {
// String[] d = dir.list();
// if ((d!=null && d.length>0) || dir.canWrite()) {
log.i("Adding FS root: " + path + " " + name);
list.put(path, name);
// return true;
// } else {
// log.i("Skipping mount point " + path + " : no files or directories found here, and writing is disabled");
// }
}
} catch (Exception e) {
// ignore
}
return false;
}
// private static final String[] SYSTEM_ROOT_PATHS = {"/system", "/data", "/mnt"};
// private void autoAddRoots(Map<String, String> list, String rootPath, String[] pathsToExclude)
// {
// try {
// File root = new File(rootPath);
// File[] files = root.listFiles();
// if ( files!=null ) {
// for ( File f : files ) {
// if ( !f.isDirectory() )
// continue;
// String fullPath = f.getAbsolutePath();
// if (isLink(fullPath) != null) {
// L.d("skipping symlink " + fullPath);
// continue;
// }
// boolean skip = false;
// for ( String path : pathsToExclude ) {
// if ( fullPath.startsWith(path) ) {
// skip = true;
// break;
// }
// }
// if ( skip )
// continue;
// if ( !f.canWrite() ) {
// L.i("Path is readonly: " + f.getAbsolutePath());
// continue;
// }
// L.i("Found possible mount point " + f.getAbsolutePath());
// addMountRoot(list, f.getAbsolutePath(), f.getAbsolutePath());
// }
// }
// } catch ( Exception e ) {
// L.w("Exception while trying to auto add roots");
// }
// }
public static String ntrim(String str) {
if (str == null)
return null;
str = str.trim();
if (str.length() == 0)
return null;
return str;
}
public static boolean empty(String str) {
if (str == null || str.length() == 0)
return true;
if (str.trim().length() == 0)
return true;
return false;
}
private void initMountRoots() {
Map<String, String> map = new LinkedHashMap<String, String>();
// standard external directory
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
// dirty fix
if ("/nand".equals(sdpath) && new File("/sdcard").isDirectory())
sdpath = "/sdcard";
// main storage
addMountRoot(map, sdpath, R.string.dir_sd_card);
// retrieve list of mount points from system
String[] fstabLocations = new String[] {
"/system/etc/vold.conf",
"/system/etc/vold.fstab",
"/etc/vold.conf",
"/etc/vold.fstab",
};
String s = null;
+ String fstabFileName = null;
for (String fstabFile : fstabLocations) {
+ fstabFileName = fstabFile;
s = loadFileUtf8(new File(fstabFile));
if (s != null)
log.i("found fstab file " + fstabFile);
}
if (s == null)
- log.d("fstab file not found");
+ log.w("fstab file not found");
if ( s!= null) {
String[] rows = s.split("\n");
+ int rulesFound = 0;
for (String row : rows) {
if (row != null && row.startsWith("dev_mount")) {
log.d("mount rule: " + row);
+ rulesFound++;
String[] cols = row.split(" ");
if (cols.length >= 5) {
String name = ntrim(cols[1]);
String point = ntrim(cols[2]);
String mode = ntrim(cols[3]);
String dev = ntrim(cols[4]);
if (empty(name) || empty(point) || empty(mode) || empty(dev))
continue;
String label = null;
boolean hasusb = dev.indexOf("usb") >= 0;
boolean hasmmc = dev.indexOf("mmc") >= 0;
log.i("mount point found: '" + name + "' " + point + " device = " + dev);
if ("auto".equals(mode)) {
// assume AUTO is for externally automount devices
if (hasusb)
label = "External USB Storage";
else if (hasmmc)
label = "External SD";
else
label = "External Storage";
} else {
if (hasmmc)
label = "Internal SD";
else
label = "Internal Storage";
}
if (!point.equals(sdpath)) {
// external SD
addMountRoot(map, point, label + " (" + point + ")");
}
}
}
}
+ if (rulesFound == 0)
+ log.w("mount point rules not found in " + fstabFileName);
}
// TODO: probably, hardcoded list is not necessary after /etc/vold parsing
String[] knownMountPoints = new String[] {
"/system/media/sdcard", // internal SD card on Nook
"/media",
"/nand",
"/PocketBook701", // internal SD card on PocketBook 701 IQ
"/mnt/extsd",
"/mnt/external1",
"/mnt/external_sd",
"/mnt/udisk",
"/mnt/sdcard2",
"/mnt/ext.sd",
"/ext.sd",
"/extsd",
"/sdcard",
"/sdcard2",
"/mnt/udisk",
"/sdcard-ext",
"/sd-ext",
"/mnt/external1",
"/mnt/external2",
"/mnt/sdcard1",
"/mnt/sdcard2",
"/mnt/usb_storage",
"/mnt/external_sd",
"/emmc",
"/external",
"/Removable/SD",
"/Removable/MicroSD",
"/Removable/USBDisk1",
};
for (String point : knownMountPoints) {
String link = isLink(point);
if (link != null) {
log.d("standard mount point path is link: " + point + " > " + link);
addMountRoot(map, link, link);
} else {
addMountRoot(map, point, point);
}
}
// auto detection
//autoAddRoots(map, "/", SYSTEM_ROOT_PATHS);
//autoAddRoots(map, "/mnt", new String[] {});
mountedRootsMap = map;
Collection<File> list = new ArrayList<File>();
for (String f : map.keySet()) {
list.add(new File(f));
}
mountedRootsList = list.toArray(new File[] {});
pathCorrector = new MountPathCorrector(mountedRootsList);
Log.i("cr3", "Root list: " + list + ", root links: " + pathCorrector);
// testPathNormalization("/sdcard/books/test.fb2");
// testPathNormalization("/mnt/sdcard/downloads/test.fb2");
// testPathNormalization("/mnt/sd/dir/test.fb2");
}
// private void testPathNormalization(String path) {
// Log.i("cr3", "normalization: " + path + " => " + normalizePathUsingRootLinks(new File(path)));
// }
String[] mFonts;
private void init() throws IOException {
if (initialized)
throw new IllegalStateException("Already initialized");
String[] fonts = findFonts();
findExternalHyphDictionaries();
synchronized(this) {
if (!initInternal(mFonts))
throw new IOException("Cannot initialize CREngine JNI");
}
// Initialization of cache directory
initCacheDirectory();
initialized = true;
}
// public void waitTasksCompletion()
// {
// log.i("waiting for engine tasks completion");
// try {
// mExecutor.awaitTermination(0, TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// // ignore
// }
// }
/**
* Uninitialize engine.
*/
public void uninit() {
log.i("Engine.uninit() is called");
BackgroundThread.backgroundExecutor.execute(new Runnable() {
public void run() {
log.i("Engine.uninit() : in background thread");
if (initialized) {
synchronized(this) {
uninitInternal();
}
initialized = false;
}
}
});
}
protected void finalize() throws Throwable {
log.i("Engine.finalize() is called");
// if ( initialized ) {
// //uninitInternal();
// initialized = false;
// }
}
public static boolean isInitialized() {
return initialized;
}
static private boolean initialized = false;
static private boolean initializeStarted = false;
private String[] findFonts() {
ArrayList<File> dirs = new ArrayList<File>();
File[] dataDirs = getDataDirectories("fonts", false, false);
for (File dir : dataDirs)
dirs.add(dir);
File[] rootDirs = getStorageDirectories(false);
for (File dir : rootDirs)
dirs.add(new File(dir, "fonts"));
dirs.add(new File(Environment.getRootDirectory(), "fonts"));
ArrayList<String> fontPaths = new ArrayList<String>();
for (File fontDir : dirs) {
if (fontDir.isDirectory()) {
log.v("Scanning directory " + fontDir.getAbsolutePath()
+ " for font files");
// get font names
String[] fileList = fontDir.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
String lc = filename.toLowerCase();
return (lc.endsWith(".ttf") || lc.endsWith(".otf")
|| lc.endsWith(".pfb") || lc.endsWith(".pfa"))
// && !filename.endsWith("Fallback.ttf")
;
}
});
// append path
for (int i = 0; i < fileList.length; i++) {
String pathName = new File(fontDir, fileList[i])
.getAbsolutePath();
fontPaths.add(pathName);
log.v("found font: " + pathName);
}
}
}
Collections.sort(fontPaths);
return fontPaths.toArray(new String[] {});
}
private String SO_NAME = "lib" + LIBRARY_NAME + ".so";
private boolean force_install_library = false;
private void installLibrary() {
try {
if (force_install_library)
throw new Exception("forcing install");
// try loading library w/o manual installation
log.i("trying to load library " + LIBRARY_NAME
+ " w/o installation");
System.loadLibrary(LIBRARY_NAME);
// try invoke native method
//log.i("trying execute native method ");
//setHyphenationMethod(HYPH_NONE, new byte[] {});
log.i(LIBRARY_NAME + " loaded successfully");
} catch (Exception ee) {
log.i(SO_NAME + " not found using standard paths, will install manually");
File sopath = mActivity.getDir("libs", Context.MODE_PRIVATE);
File soname = new File(sopath, SO_NAME);
try {
sopath.mkdirs();
File zip = new File(mActivity.getPackageCodePath());
ZipFile zipfile = new ZipFile(zip);
ZipEntry zipentry = zipfile.getEntry("lib/armeabi/" + SO_NAME);
if (!soname.exists() || zipentry.getSize() != soname.length()) {
InputStream is = zipfile.getInputStream(zipentry);
OutputStream os = new FileOutputStream(soname);
Log.i("cr3",
"Installing JNI library "
+ soname.getAbsolutePath());
final int BUF_SIZE = 0x10000;
byte[] buf = new byte[BUF_SIZE];
int n;
while ((n = is.read(buf)) > 0)
os.write(buf, 0, n);
is.close();
os.close();
} else {
log.i("JNI library " + soname.getAbsolutePath()
+ " is up to date");
}
System.load(soname.getAbsolutePath());
//setHyphenationMethod(HYPH_NONE, new byte[] {});
} catch (Exception e) {
log.e("cannot install " + LIBRARY_NAME + " library", e);
}
}
}
public static final BackgroundTextureInfo NO_TEXTURE = new BackgroundTextureInfo(
BackgroundTextureInfo.NO_TEXTURE_ID, "(SOLID COLOR)", 0);
private static final BackgroundTextureInfo[] internalTextures = {
NO_TEXTURE,
new BackgroundTextureInfo("bg_paper1", "Paper 1",
R.drawable.bg_paper1),
new BackgroundTextureInfo("bg_paper1_dark", "Paper 1 (dark)",
R.drawable.bg_paper1_dark),
new BackgroundTextureInfo("tx_wood", "Wood", DeviceInfo.getSDKLevel() == 3 ? R.drawable.tx_wood_v3 : R.drawable.tx_wood),
new BackgroundTextureInfo("tx_wood_dark", "Wood (dark)",
DeviceInfo.getSDKLevel() == 3 ? R.drawable.tx_wood_dark_v3 : R.drawable.tx_wood_dark),
new BackgroundTextureInfo("tx_fabric", "Fabric",
R.drawable.tx_fabric),
new BackgroundTextureInfo("tx_fabric_dark", "Fabric (dark)",
R.drawable.tx_fabric_dark),
new BackgroundTextureInfo("tx_fabric_indigo_fibre", "Fabric fibre",
R.drawable.tx_fabric_indigo_fibre),
new BackgroundTextureInfo("tx_fabric_indigo_fibre_dark",
"Fabric fibre (dark)",
R.drawable.tx_fabric_indigo_fibre_dark),
new BackgroundTextureInfo("tx_gray_sand", "Gray sand",
R.drawable.tx_gray_sand),
new BackgroundTextureInfo("tx_gray_sand_dark", "Gray sand (dark)",
R.drawable.tx_gray_sand_dark),
new BackgroundTextureInfo("tx_green_wall", "Green wall",
R.drawable.tx_green_wall),
new BackgroundTextureInfo("tx_green_wall_dark",
"Green wall (dark)", R.drawable.tx_green_wall_dark),
new BackgroundTextureInfo("tx_metal_red_light", "Metall red",
R.drawable.tx_metal_red_light),
new BackgroundTextureInfo("tx_metal_red_dark", "Metall red (dark)",
R.drawable.tx_metal_red_dark),
new BackgroundTextureInfo("tx_metall_copper", "Metall copper",
R.drawable.tx_metall_copper),
new BackgroundTextureInfo("tx_metall_copper_dark",
"Metall copper (dark)", R.drawable.tx_metall_copper_dark),
new BackgroundTextureInfo("tx_metall_old_blue", "Metall blue",
R.drawable.tx_metall_old_blue),
new BackgroundTextureInfo("tx_metall_old_blue_dark",
"Metall blue (dark)", R.drawable.tx_metall_old_blue_dark),
new BackgroundTextureInfo("tx_old_book", "Old book",
R.drawable.tx_old_book),
new BackgroundTextureInfo("tx_old_book_dark", "Old book (dark)",
R.drawable.tx_old_book_dark),
new BackgroundTextureInfo("tx_old_paper", "Old paper",
R.drawable.tx_old_paper),
new BackgroundTextureInfo("tx_old_paper_dark", "Old paper (dark)",
R.drawable.tx_old_paper_dark),
new BackgroundTextureInfo("tx_paper", "Paper", R.drawable.tx_paper),
new BackgroundTextureInfo("tx_paper_dark", "Paper (dark)",
R.drawable.tx_paper_dark),
new BackgroundTextureInfo("tx_rust", "Rust", R.drawable.tx_rust),
new BackgroundTextureInfo("tx_rust_dark", "Rust (dark)",
R.drawable.tx_rust_dark),
new BackgroundTextureInfo("tx_sand", "Sand", R.drawable.tx_sand),
new BackgroundTextureInfo("tx_sand_dark", "Sand (dark)",
R.drawable.tx_sand_dark),
new BackgroundTextureInfo("tx_stones", "Stones",
R.drawable.tx_stones),
new BackgroundTextureInfo("tx_stones_dark", "Stones (dark)",
R.drawable.tx_stones_dark), };
public static final String DEF_DAY_BACKGROUND_TEXTURE = "bg_paper1";
public static final String DEF_NIGHT_BACKGROUND_TEXTURE = "bg_paper1_dark";
public BackgroundTextureInfo[] getAvailableTextures() {
ArrayList<BackgroundTextureInfo> list = new ArrayList<BackgroundTextureInfo>(
internalTextures.length);
list.add(NO_TEXTURE);
findExternalTextures(list);
for (int i = 1; i < internalTextures.length; i++)
list.add(internalTextures[i]);
return list.toArray(new BackgroundTextureInfo[] {});
}
public void findHyphDictionariesFromDirectory(File dir) {
for (File f : dir.listFiles()) {
if (!f.isDirectory()) {
if (HyphDict.fromFile(f))
log.i("Registered external hyphenation dict " + f.getAbsolutePath());
}
}
}
public void findExternalHyphDictionaries() {
for (File d : getStorageDirectories(false)) {
File base = new File(d, ".cr3");
if (!base.isDirectory())
base = new File(d, "cr3");
if (!base.isDirectory())
continue;
File subdir = new File(base, "hyph");
if (subdir.isDirectory())
findHyphDictionariesFromDirectory(subdir);
}
}
public void findTexturesFromDirectory(File dir,
Collection<BackgroundTextureInfo> listToAppend) {
for (File f : dir.listFiles()) {
if (!f.isDirectory()) {
BackgroundTextureInfo item = BackgroundTextureInfo.fromFile(f
.getAbsolutePath());
if (item != null)
listToAppend.add(item);
}
}
}
public void findExternalTextures(
Collection<BackgroundTextureInfo> listToAppend) {
for (File d : getStorageDirectories(false)) {
File base = new File(d, ".cr3");
if (!base.isDirectory())
base = new File(d, "cr3");
if (!base.isDirectory())
continue;
File subdirTextures = new File(base, "textures");
File subdirBackgrounds = new File(base, "backgrounds");
if (subdirTextures.isDirectory())
findTexturesFromDirectory(subdirTextures, listToAppend);
if (subdirBackgrounds.isDirectory())
findTexturesFromDirectory(subdirBackgrounds, listToAppend);
}
}
public byte[] getImageData(BackgroundTextureInfo texture) {
if (texture.isNone())
return null;
if (texture.resourceId != 0) {
byte[] data = loadResourceBytes(texture.resourceId);
return data;
} else if (texture.id != null && texture.id.startsWith("/")) {
File f = new File(texture.id);
byte[] data = loadResourceBytes(f);
return data;
}
return null;
}
public BackgroundTextureInfo getTextureInfoById(String id) {
if (id == null)
return NO_TEXTURE;
if (id.startsWith("/")) {
BackgroundTextureInfo item = BackgroundTextureInfo.fromFile(id);
if (item != null)
return item;
} else {
for (BackgroundTextureInfo item : internalTextures)
if (item.id.equals(id))
return item;
}
return NO_TEXTURE;
}
/**
* Create progress dialog control.
* @param resourceId is string resource Id of dialog title, 0 to disable progress
* @return created control object.
*/
public ProgressControl createProgress(int resourceId) {
return new ProgressControl(resourceId);
}
private static final int PROGRESS_UPDATE_INTERVAL = DeviceInfo.EINK_SCREEN ? 4000 : 500;
private static final int PROGRESS_SHOW_INTERVAL = DeviceInfo.EINK_SCREEN ? 4000 : 1500;
public class ProgressControl {
private final int resourceId;
private long createTime = Utils.timeStamp();
private long lastUpdateTime;
private boolean shown;
private ProgressControl(int resourceId) {
this.resourceId = resourceId;
}
public void hide() {
if (resourceId == 0)
return; // disabled
if (shown)
hideProgress();
shown = false;
}
public void setProgress(int percent) {
if (resourceId == 0)
return; // disabled
if (Utils.timeInterval(createTime) < PROGRESS_SHOW_INTERVAL)
return;
if (Utils.timeInterval(lastUpdateTime) < PROGRESS_UPDATE_INTERVAL)
return;
shown = true;
lastUpdateTime = Utils.timeStamp();
showProgress(percent, resourceId);
}
}
MountPathCorrector pathCorrector;
public MountPathCorrector getPathCorrector() {
return pathCorrector;
}
}
| false | true | private void initMountRoots() {
Map<String, String> map = new LinkedHashMap<String, String>();
// standard external directory
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
// dirty fix
if ("/nand".equals(sdpath) && new File("/sdcard").isDirectory())
sdpath = "/sdcard";
// main storage
addMountRoot(map, sdpath, R.string.dir_sd_card);
// retrieve list of mount points from system
String[] fstabLocations = new String[] {
"/system/etc/vold.conf",
"/system/etc/vold.fstab",
"/etc/vold.conf",
"/etc/vold.fstab",
};
String s = null;
for (String fstabFile : fstabLocations) {
s = loadFileUtf8(new File(fstabFile));
if (s != null)
log.i("found fstab file " + fstabFile);
}
if (s == null)
log.d("fstab file not found");
if ( s!= null) {
String[] rows = s.split("\n");
for (String row : rows) {
if (row != null && row.startsWith("dev_mount")) {
log.d("mount rule: " + row);
String[] cols = row.split(" ");
if (cols.length >= 5) {
String name = ntrim(cols[1]);
String point = ntrim(cols[2]);
String mode = ntrim(cols[3]);
String dev = ntrim(cols[4]);
if (empty(name) || empty(point) || empty(mode) || empty(dev))
continue;
String label = null;
boolean hasusb = dev.indexOf("usb") >= 0;
boolean hasmmc = dev.indexOf("mmc") >= 0;
log.i("mount point found: '" + name + "' " + point + " device = " + dev);
if ("auto".equals(mode)) {
// assume AUTO is for externally automount devices
if (hasusb)
label = "External USB Storage";
else if (hasmmc)
label = "External SD";
else
label = "External Storage";
} else {
if (hasmmc)
label = "Internal SD";
else
label = "Internal Storage";
}
if (!point.equals(sdpath)) {
// external SD
addMountRoot(map, point, label + " (" + point + ")");
}
}
}
}
}
// TODO: probably, hardcoded list is not necessary after /etc/vold parsing
String[] knownMountPoints = new String[] {
"/system/media/sdcard", // internal SD card on Nook
"/media",
"/nand",
"/PocketBook701", // internal SD card on PocketBook 701 IQ
"/mnt/extsd",
"/mnt/external1",
"/mnt/external_sd",
"/mnt/udisk",
"/mnt/sdcard2",
"/mnt/ext.sd",
"/ext.sd",
"/extsd",
"/sdcard",
"/sdcard2",
"/mnt/udisk",
"/sdcard-ext",
"/sd-ext",
"/mnt/external1",
"/mnt/external2",
"/mnt/sdcard1",
"/mnt/sdcard2",
"/mnt/usb_storage",
"/mnt/external_sd",
"/emmc",
"/external",
"/Removable/SD",
"/Removable/MicroSD",
"/Removable/USBDisk1",
};
for (String point : knownMountPoints) {
String link = isLink(point);
if (link != null) {
log.d("standard mount point path is link: " + point + " > " + link);
addMountRoot(map, link, link);
} else {
addMountRoot(map, point, point);
}
}
// auto detection
//autoAddRoots(map, "/", SYSTEM_ROOT_PATHS);
//autoAddRoots(map, "/mnt", new String[] {});
mountedRootsMap = map;
Collection<File> list = new ArrayList<File>();
for (String f : map.keySet()) {
list.add(new File(f));
}
mountedRootsList = list.toArray(new File[] {});
pathCorrector = new MountPathCorrector(mountedRootsList);
Log.i("cr3", "Root list: " + list + ", root links: " + pathCorrector);
// testPathNormalization("/sdcard/books/test.fb2");
// testPathNormalization("/mnt/sdcard/downloads/test.fb2");
// testPathNormalization("/mnt/sd/dir/test.fb2");
}
| private void initMountRoots() {
Map<String, String> map = new LinkedHashMap<String, String>();
// standard external directory
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
// dirty fix
if ("/nand".equals(sdpath) && new File("/sdcard").isDirectory())
sdpath = "/sdcard";
// main storage
addMountRoot(map, sdpath, R.string.dir_sd_card);
// retrieve list of mount points from system
String[] fstabLocations = new String[] {
"/system/etc/vold.conf",
"/system/etc/vold.fstab",
"/etc/vold.conf",
"/etc/vold.fstab",
};
String s = null;
String fstabFileName = null;
for (String fstabFile : fstabLocations) {
fstabFileName = fstabFile;
s = loadFileUtf8(new File(fstabFile));
if (s != null)
log.i("found fstab file " + fstabFile);
}
if (s == null)
log.w("fstab file not found");
if ( s!= null) {
String[] rows = s.split("\n");
int rulesFound = 0;
for (String row : rows) {
if (row != null && row.startsWith("dev_mount")) {
log.d("mount rule: " + row);
rulesFound++;
String[] cols = row.split(" ");
if (cols.length >= 5) {
String name = ntrim(cols[1]);
String point = ntrim(cols[2]);
String mode = ntrim(cols[3]);
String dev = ntrim(cols[4]);
if (empty(name) || empty(point) || empty(mode) || empty(dev))
continue;
String label = null;
boolean hasusb = dev.indexOf("usb") >= 0;
boolean hasmmc = dev.indexOf("mmc") >= 0;
log.i("mount point found: '" + name + "' " + point + " device = " + dev);
if ("auto".equals(mode)) {
// assume AUTO is for externally automount devices
if (hasusb)
label = "External USB Storage";
else if (hasmmc)
label = "External SD";
else
label = "External Storage";
} else {
if (hasmmc)
label = "Internal SD";
else
label = "Internal Storage";
}
if (!point.equals(sdpath)) {
// external SD
addMountRoot(map, point, label + " (" + point + ")");
}
}
}
}
if (rulesFound == 0)
log.w("mount point rules not found in " + fstabFileName);
}
// TODO: probably, hardcoded list is not necessary after /etc/vold parsing
String[] knownMountPoints = new String[] {
"/system/media/sdcard", // internal SD card on Nook
"/media",
"/nand",
"/PocketBook701", // internal SD card on PocketBook 701 IQ
"/mnt/extsd",
"/mnt/external1",
"/mnt/external_sd",
"/mnt/udisk",
"/mnt/sdcard2",
"/mnt/ext.sd",
"/ext.sd",
"/extsd",
"/sdcard",
"/sdcard2",
"/mnt/udisk",
"/sdcard-ext",
"/sd-ext",
"/mnt/external1",
"/mnt/external2",
"/mnt/sdcard1",
"/mnt/sdcard2",
"/mnt/usb_storage",
"/mnt/external_sd",
"/emmc",
"/external",
"/Removable/SD",
"/Removable/MicroSD",
"/Removable/USBDisk1",
};
for (String point : knownMountPoints) {
String link = isLink(point);
if (link != null) {
log.d("standard mount point path is link: " + point + " > " + link);
addMountRoot(map, link, link);
} else {
addMountRoot(map, point, point);
}
}
// auto detection
//autoAddRoots(map, "/", SYSTEM_ROOT_PATHS);
//autoAddRoots(map, "/mnt", new String[] {});
mountedRootsMap = map;
Collection<File> list = new ArrayList<File>();
for (String f : map.keySet()) {
list.add(new File(f));
}
mountedRootsList = list.toArray(new File[] {});
pathCorrector = new MountPathCorrector(mountedRootsList);
Log.i("cr3", "Root list: " + list + ", root links: " + pathCorrector);
// testPathNormalization("/sdcard/books/test.fb2");
// testPathNormalization("/mnt/sdcard/downloads/test.fb2");
// testPathNormalization("/mnt/sd/dir/test.fb2");
}
|
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSliderBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSliderBean.java
index 9e212c5f..1a0eb623 100644
--- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSliderBean.java
+++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSliderBean.java
@@ -1,77 +1,82 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* 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.richfaces.tests.metamer.bean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.richfaces.component.html.HtmlInputNumberSlider;
import org.richfaces.tests.metamer.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Managed bean for rich:inputNumberSlider.
*
* @author <a href="mailto:[email protected]">Pavol Pitonak</a>
* @version $Revision$
*/
@ManagedBean(name = "richInputNumberSliderBean")
@ViewScoped
public class RichInputNumberSliderBean implements Serializable {
private static final long serialVersionUID = 595154649809L;
private static Logger logger;
private Attributes attributes;
/**
* Initializes the managed bean.
*/
@PostConstruct
public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(HtmlInputNumberSlider.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("inputSize", 3);
attributes.setAttribute("maxValue", 100);
attributes.setAttribute("minValue", 0);
attributes.setAttribute("rendered", true);
attributes.setAttribute("showBoundaryValues", true);
attributes.setAttribute("showInput", true);
attributes.setAttribute("step", 1);
+ attributes.setAttribute("value", 0);
+ attributes.remove("converter");
+ attributes.remove("validator");
+ attributes.remove("valueChangeListener");
+ attributes.remove("valueChangeListeners");
}
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
}
| false | true | public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(HtmlInputNumberSlider.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("inputSize", 3);
attributes.setAttribute("maxValue", 100);
attributes.setAttribute("minValue", 0);
attributes.setAttribute("rendered", true);
attributes.setAttribute("showBoundaryValues", true);
attributes.setAttribute("showInput", true);
attributes.setAttribute("step", 1);
}
| public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getUIComponentAttributes(HtmlInputNumberSlider.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("inputSize", 3);
attributes.setAttribute("maxValue", 100);
attributes.setAttribute("minValue", 0);
attributes.setAttribute("rendered", true);
attributes.setAttribute("showBoundaryValues", true);
attributes.setAttribute("showInput", true);
attributes.setAttribute("step", 1);
attributes.setAttribute("value", 0);
attributes.remove("converter");
attributes.remove("validator");
attributes.remove("valueChangeListener");
attributes.remove("valueChangeListeners");
}
|
diff --git a/src/demos/swt/Snippet209.java b/src/demos/swt/Snippet209.java
index d4238e2..f75d59d 100644
--- a/src/demos/swt/Snippet209.java
+++ b/src/demos/swt/Snippet209.java
@@ -1,141 +1,142 @@
/*******************************************************************************
/**
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
// package org.eclipse.swt.snippets;
package demos.swt;
/*
* SWT OpenGL snippet: use JOGL to draw to an SWT GLCanvas
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*
* @since 3.2
*/
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.opengl.GLData;
import javax.media.opengl.GLProfile;
import javax.media.opengl.GL2;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.glu.GLU;
public class Snippet209 {
static void drawTorus(GL2 gl, float r, float R, int nsides, int rings) {
float ringDelta = 2.0f * (float) Math.PI / rings;
float sideDelta = 2.0f * (float) Math.PI / nsides;
float theta = 0.0f, cosTheta = 1.0f, sinTheta = 0.0f;
for (int i = rings - 1; i >= 0; i--) {
float theta1 = theta + ringDelta;
float cosTheta1 = (float) Math.cos(theta1);
float sinTheta1 = (float) Math.sin(theta1);
gl.glBegin(gl.GL_QUAD_STRIP);
float phi = 0.0f;
for (int j = nsides; j >= 0; j--) {
phi += sideDelta;
float cosPhi = (float) Math.cos(phi);
float sinPhi = (float) Math.sin(phi);
float dist = R + r * cosPhi;
gl.glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi);
gl.glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi);
gl.glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi);
gl.glVertex3f(cosTheta * dist, -sinTheta * dist, r * sinPhi);
}
gl.glEnd();
theta = theta1;
cosTheta = cosTheta1;
sinTheta = sinTheta1;
}
}
public static void main(String [] args) {
final GLProfile gl2Profile = GLProfile.get(GLProfile.GL2);
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
final GLCanvas canvas = new GLCanvas(comp, SWT.NONE, data);
canvas.setCurrent();
final GLContext context = GLDrawableFactory.getFactory(gl2Profile).createExternalGLContext();
canvas.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
Rectangle bounds = canvas.getBounds();
float fAspect = (float) bounds.width / (float) bounds.height;
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glViewport(0, 0, bounds.width, bounds.height);
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glLoadIdentity();
GLU glu = new GLU();
glu.gluPerspective(45.0f, fAspect, 0.5f, 400.0f);
gl.glMatrixMode(gl.GL_MODELVIEW);
gl.glLoadIdentity();
context.release();
}
});
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
+ gl.setSwapInterval(1);
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
gl.glClearDepth(1.0);
gl.glLineWidth(2);
gl.glEnable(gl.GL_DEPTH_TEST);
context.release();
shell.setText("SWT/JOGL Example");
shell.setSize(640, 480);
shell.open();
display.asyncExec(new Runnable() {
int rot = 0;
public void run() {
if (!canvas.isDisposed()) {
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
gl.glClearColor(.3f, .5f, .8f, 1.0f);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -10.0f);
float frot = rot;
gl.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);
gl.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);
rot++;
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE);
gl.glColor3f(0.9f, 0.9f, 0.9f);
drawTorus(gl, 1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15);
canvas.swapBuffers();
context.release();
display.asyncExec(this);
}
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
| true | true | public static void main(String [] args) {
final GLProfile gl2Profile = GLProfile.get(GLProfile.GL2);
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
final GLCanvas canvas = new GLCanvas(comp, SWT.NONE, data);
canvas.setCurrent();
final GLContext context = GLDrawableFactory.getFactory(gl2Profile).createExternalGLContext();
canvas.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
Rectangle bounds = canvas.getBounds();
float fAspect = (float) bounds.width / (float) bounds.height;
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glViewport(0, 0, bounds.width, bounds.height);
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glLoadIdentity();
GLU glu = new GLU();
glu.gluPerspective(45.0f, fAspect, 0.5f, 400.0f);
gl.glMatrixMode(gl.GL_MODELVIEW);
gl.glLoadIdentity();
context.release();
}
});
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
gl.glClearDepth(1.0);
gl.glLineWidth(2);
gl.glEnable(gl.GL_DEPTH_TEST);
context.release();
shell.setText("SWT/JOGL Example");
shell.setSize(640, 480);
shell.open();
display.asyncExec(new Runnable() {
int rot = 0;
public void run() {
if (!canvas.isDisposed()) {
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
gl.glClearColor(.3f, .5f, .8f, 1.0f);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -10.0f);
float frot = rot;
gl.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);
gl.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);
rot++;
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE);
gl.glColor3f(0.9f, 0.9f, 0.9f);
drawTorus(gl, 1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15);
canvas.swapBuffers();
context.release();
display.asyncExec(this);
}
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
| public static void main(String [] args) {
final GLProfile gl2Profile = GLProfile.get(GLProfile.GL2);
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
final GLCanvas canvas = new GLCanvas(comp, SWT.NONE, data);
canvas.setCurrent();
final GLContext context = GLDrawableFactory.getFactory(gl2Profile).createExternalGLContext();
canvas.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
Rectangle bounds = canvas.getBounds();
float fAspect = (float) bounds.width / (float) bounds.height;
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glViewport(0, 0, bounds.width, bounds.height);
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glLoadIdentity();
GLU glu = new GLU();
glu.gluPerspective(45.0f, fAspect, 0.5f, 400.0f);
gl.glMatrixMode(gl.GL_MODELVIEW);
gl.glLoadIdentity();
context.release();
}
});
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.setSwapInterval(1);
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
gl.glClearDepth(1.0);
gl.glLineWidth(2);
gl.glEnable(gl.GL_DEPTH_TEST);
context.release();
shell.setText("SWT/JOGL Example");
shell.setSize(640, 480);
shell.open();
display.asyncExec(new Runnable() {
int rot = 0;
public void run() {
if (!canvas.isDisposed()) {
canvas.setCurrent();
context.makeCurrent();
GL2 gl = context.getGL().getGL2();
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
gl.glClearColor(.3f, .5f, .8f, 1.0f);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -10.0f);
float frot = rot;
gl.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);
gl.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);
rot++;
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE);
gl.glColor3f(0.9f, 0.9f, 0.9f);
drawTorus(gl, 1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15);
canvas.swapBuffers();
context.release();
display.asyncExec(this);
}
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
|
diff --git a/src/org/ita/testrefactoring/astparser/TypeCache.java b/src/org/ita/testrefactoring/astparser/TypeCache.java
index 3a037bc..44266be 100644
--- a/src/org/ita/testrefactoring/astparser/TypeCache.java
+++ b/src/org/ita/testrefactoring/astparser/TypeCache.java
@@ -1,47 +1,47 @@
package org.ita.testrefactoring.astparser;
import java.util.HashMap;
import org.ita.testrefactoring.metacode.Type;
public class TypeCache extends HashMap<String, Type> {
private ASTEnvironment environment;
public TypeCache(ASTEnvironment environment) {
this.environment = environment;
}
/**
*
*/
private static final long serialVersionUID = 7973930399495455846L;
@Override
public Type get(Object key) {
if (key == null) {
key = "java.lang.Object";
}
Type cachedType = super.get(key);
if (cachedType == null) {
String fullQualifiedName = key.toString();
String packageName = ASTEnvironment.extractPackageName(fullQualifiedName);
String typeName = ASTEnvironment.extractTypeName(fullQualifiedName);
ASTPackage pack = environment.getPackageList().get(packageName);
if (pack == null) {
pack = environment.createPackage(packageName);
}
- environment.createDummyType(typeName, pack);
+ Type newType = environment.createDummyType(typeName, pack);
- cachedType = super.get(key);
+ cachedType = super.get(newType.getQualifiedName());
}
return cachedType;
}
}
| false | true | public Type get(Object key) {
if (key == null) {
key = "java.lang.Object";
}
Type cachedType = super.get(key);
if (cachedType == null) {
String fullQualifiedName = key.toString();
String packageName = ASTEnvironment.extractPackageName(fullQualifiedName);
String typeName = ASTEnvironment.extractTypeName(fullQualifiedName);
ASTPackage pack = environment.getPackageList().get(packageName);
if (pack == null) {
pack = environment.createPackage(packageName);
}
environment.createDummyType(typeName, pack);
cachedType = super.get(key);
}
return cachedType;
}
| public Type get(Object key) {
if (key == null) {
key = "java.lang.Object";
}
Type cachedType = super.get(key);
if (cachedType == null) {
String fullQualifiedName = key.toString();
String packageName = ASTEnvironment.extractPackageName(fullQualifiedName);
String typeName = ASTEnvironment.extractTypeName(fullQualifiedName);
ASTPackage pack = environment.getPackageList().get(packageName);
if (pack == null) {
pack = environment.createPackage(packageName);
}
Type newType = environment.createDummyType(typeName, pack);
cachedType = super.get(newType.getQualifiedName());
}
return cachedType;
}
|
diff --git a/freeplane/src/org/freeplane/features/mindmapmode/text/EditNodeBase.java b/freeplane/src/org/freeplane/features/mindmapmode/text/EditNodeBase.java
index 8a66b80de..8b31df6a8 100644
--- a/freeplane/src/org/freeplane/features/mindmapmode/text/EditNodeBase.java
+++ b/freeplane/src/org/freeplane/features/mindmapmode/text/EditNodeBase.java
@@ -1,323 +1,323 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.mindmapmode.text;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.LinkedList;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.common.map.NodeModel;
import org.freeplane.features.mindmapmode.ortho.SpellCheckerController;
/**
* @author foltin
*/
abstract public class EditNodeBase {
abstract static class EditDialog extends JDialog {
class CancelAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(final ActionEvent e) {
confirmedCancel();
}
}
class DialogWindowListener extends WindowAdapter {
/*
* (non-Javadoc)
* @seejava.awt.event.WindowAdapter#windowLostFocus(java.awt.event.
* WindowEvent)
*/
/*
* (non-Javadoc)
* @see
* java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent
* )
*/
@Override
public void windowClosing(final WindowEvent e) {
if (isVisible()) {
confirmedSubmit();
}
}
}
class SplitAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(final ActionEvent e) {
split();
}
}
class SubmitAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(final ActionEvent e) {
submit();
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
private EditNodeBase base;
EditDialog(final EditNodeBase base, final String title, final Frame frame) {
super(frame, title, /*modal=*/true);
getContentPane().setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
final DialogWindowListener dfl = new DialogWindowListener();
addWindowListener(dfl);
this.base = base;
}
protected void cancel() {
setVisible(false);
}
protected void confirmedCancel() {
if (isChanged()) {
final int action = JOptionPane.showConfirmDialog(this, TextUtils.getText("long_node_changed_cancel"), "",
JOptionPane.OK_CANCEL_OPTION);
if (action == JOptionPane.CANCEL_OPTION) {
return;
}
}
cancel();
}
protected void confirmedSubmit() {
if (isChanged()) {
final int action = JOptionPane.showConfirmDialog(this, TextUtils.getText("long_node_changed_submit"), "",
JOptionPane.YES_NO_CANCEL_OPTION);
if (action == JOptionPane.CANCEL_OPTION) {
return;
}
if (action == JOptionPane.YES_OPTION) {
submit();
return;
}
}
cancel();
}
/**
* @return Returns the base.
*/
EditNodeBase getBase() {
return base;
}
abstract protected boolean isChanged();
/**
* @param base
* The base to set.
*/
void setBase(final EditNodeBase base) {
this.base = base;
}
protected void split() {
setVisible(false);
}
protected void submit() {
setVisible(false);
}
}
protected JPopupMenu createPopupMenu(Component component){
JPopupMenu menu = new JPopupMenu();
if(! (component instanceof JTextComponent)){
return menu;
}
final ActionMap actionMap = ((JTextComponent)component).getActionMap();
final Action copyAction = actionMap.get(DefaultEditorKit.copyAction);
if(copyAction != null)
menu.add(TextUtils.getText("CopyAction.text")).addActionListener(copyAction);
final Action cutAction = actionMap.get(DefaultEditorKit.cutAction);
if(cutAction != null)
menu.add(TextUtils.getText("CutAction.text")).addActionListener(cutAction);
final Action pasteAction = actionMap.get(DefaultEditorKit.pasteAction);
if(pasteAction != null)
menu.add(TextUtils.getText("PasteAction.text")).addActionListener(pasteAction);
SpellCheckerController.getController().addSpellCheckerMenu(menu);
return menu;
}
public interface IEditControl {
void cancel();
void ok(String newText);
void split(String newText, int position);
}
protected static final int BUTTON_CANCEL = 1;
protected static final int BUTTON_OK = 0;
protected static final int BUTTON_SPLIT = 2;
final private IEditControl editControl;
// final private ModeController modeController;
protected NodeModel node;
protected String text;
private Color background;
protected Color getBackground() {
return background;
}
protected FocusListener textFieldListener = null;
protected EditNodeBase(final NodeModel node, final String text,
final IEditControl editControl) {
// this.modeController = modeController;
this.editControl = editControl;
this.node = node;
this.text = text;
}
public void closeEdit() {
if (textFieldListener != null) {
textFieldListener.focusLost(null);
}
}
/**
*/
public IEditControl getEditControl() {
return editControl;
}
/**
*/
public NodeModel getNode() {
return node;
}
/**
*/
protected String getText() {
return text;
}
/**
*/
public FocusListener getTextFieldListener() {
return textFieldListener;
}
protected void redispatchKeyEvents(final JTextComponent textComponent, final KeyEvent firstKeyEvent) {
if (textComponent.hasFocus()) {
return;
}
final KeyboardFocusManager currentKeyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
class KeyEventQueue implements KeyEventDispatcher, FocusListener {
LinkedList<KeyEvent> events = new LinkedList<KeyEvent>();
public boolean dispatchKeyEvent(final KeyEvent ke) {
- if(ke.getKeyChar() != 0){
+ if(ke.getKeyChar() != 0 && ke.getKeyChar() != KeyEvent.CHAR_UNDEFINED){
if (ke.getID() == KeyEvent.KEY_PRESSED){
KeyEvent newEvent = new KeyEvent(textComponent, KeyEvent.KEY_TYPED, ke.getWhen(), ke.getModifiers(), KeyEvent.VK_UNDEFINED, ke.getKeyChar(), KeyEvent.KEY_LOCATION_UNKNOWN);
events.add(newEvent);
}
}
return true;
}
public void focusGained(final FocusEvent e) {
e.getComponent().removeFocusListener(this);
currentKeyboardFocusManager.removeKeyEventDispatcher(this);
for (final KeyEvent ke : events) {
SwingUtilities.processKeyBindings(ke);
}
}
public void focusLost(final FocusEvent e) {
}
};
final KeyEventQueue keyEventDispatcher = new KeyEventQueue();
currentKeyboardFocusManager.addKeyEventDispatcher(keyEventDispatcher);
textComponent.addFocusListener(keyEventDispatcher);
if (firstKeyEvent == null) {
return;
}
if (firstKeyEvent.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
switch (firstKeyEvent.getKeyCode()) {
case KeyEvent.VK_HOME:
textComponent.setCaretPosition(textComponent.viewToModel(new Point(0, 0)));
// firstKeyEvent.consume();
break;
case KeyEvent.VK_END:
textComponent.setCaretPosition(textComponent.getDocument().getLength());
// firstKeyEvent.consume();
break;
}
}
else {
textComponent.selectAll();
keyEventDispatcher.dispatchKeyEvent(firstKeyEvent);
}
}
/**
*/
public void setTextFieldListener(final FocusListener listener) {
textFieldListener = listener;
}
abstract public void show(JFrame frame);
public void setBackground(Color background) {
this.background = background;
}
}
| true | true | protected void redispatchKeyEvents(final JTextComponent textComponent, final KeyEvent firstKeyEvent) {
if (textComponent.hasFocus()) {
return;
}
final KeyboardFocusManager currentKeyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
class KeyEventQueue implements KeyEventDispatcher, FocusListener {
LinkedList<KeyEvent> events = new LinkedList<KeyEvent>();
public boolean dispatchKeyEvent(final KeyEvent ke) {
if(ke.getKeyChar() != 0){
if (ke.getID() == KeyEvent.KEY_PRESSED){
KeyEvent newEvent = new KeyEvent(textComponent, KeyEvent.KEY_TYPED, ke.getWhen(), ke.getModifiers(), KeyEvent.VK_UNDEFINED, ke.getKeyChar(), KeyEvent.KEY_LOCATION_UNKNOWN);
events.add(newEvent);
}
}
return true;
}
public void focusGained(final FocusEvent e) {
e.getComponent().removeFocusListener(this);
currentKeyboardFocusManager.removeKeyEventDispatcher(this);
for (final KeyEvent ke : events) {
SwingUtilities.processKeyBindings(ke);
}
}
public void focusLost(final FocusEvent e) {
}
};
final KeyEventQueue keyEventDispatcher = new KeyEventQueue();
currentKeyboardFocusManager.addKeyEventDispatcher(keyEventDispatcher);
textComponent.addFocusListener(keyEventDispatcher);
if (firstKeyEvent == null) {
return;
}
if (firstKeyEvent.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
switch (firstKeyEvent.getKeyCode()) {
case KeyEvent.VK_HOME:
textComponent.setCaretPosition(textComponent.viewToModel(new Point(0, 0)));
// firstKeyEvent.consume();
break;
case KeyEvent.VK_END:
textComponent.setCaretPosition(textComponent.getDocument().getLength());
// firstKeyEvent.consume();
break;
}
}
else {
textComponent.selectAll();
keyEventDispatcher.dispatchKeyEvent(firstKeyEvent);
}
}
| protected void redispatchKeyEvents(final JTextComponent textComponent, final KeyEvent firstKeyEvent) {
if (textComponent.hasFocus()) {
return;
}
final KeyboardFocusManager currentKeyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
class KeyEventQueue implements KeyEventDispatcher, FocusListener {
LinkedList<KeyEvent> events = new LinkedList<KeyEvent>();
public boolean dispatchKeyEvent(final KeyEvent ke) {
if(ke.getKeyChar() != 0 && ke.getKeyChar() != KeyEvent.CHAR_UNDEFINED){
if (ke.getID() == KeyEvent.KEY_PRESSED){
KeyEvent newEvent = new KeyEvent(textComponent, KeyEvent.KEY_TYPED, ke.getWhen(), ke.getModifiers(), KeyEvent.VK_UNDEFINED, ke.getKeyChar(), KeyEvent.KEY_LOCATION_UNKNOWN);
events.add(newEvent);
}
}
return true;
}
public void focusGained(final FocusEvent e) {
e.getComponent().removeFocusListener(this);
currentKeyboardFocusManager.removeKeyEventDispatcher(this);
for (final KeyEvent ke : events) {
SwingUtilities.processKeyBindings(ke);
}
}
public void focusLost(final FocusEvent e) {
}
};
final KeyEventQueue keyEventDispatcher = new KeyEventQueue();
currentKeyboardFocusManager.addKeyEventDispatcher(keyEventDispatcher);
textComponent.addFocusListener(keyEventDispatcher);
if (firstKeyEvent == null) {
return;
}
if (firstKeyEvent.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
switch (firstKeyEvent.getKeyCode()) {
case KeyEvent.VK_HOME:
textComponent.setCaretPosition(textComponent.viewToModel(new Point(0, 0)));
// firstKeyEvent.consume();
break;
case KeyEvent.VK_END:
textComponent.setCaretPosition(textComponent.getDocument().getLength());
// firstKeyEvent.consume();
break;
}
}
else {
textComponent.selectAll();
keyEventDispatcher.dispatchKeyEvent(firstKeyEvent);
}
}
|
diff --git a/game.java b/game.java
index 4b6344f..731fd3e 100755
--- a/game.java
+++ b/game.java
@@ -1,480 +1,480 @@
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
class posCalc
{
int absPosX, absPosY, camSizeX, camSizeY, onCamX, onCamY;
public posCalc(int camX, int camY, int csX, int csY)
{
onCamX=camX;
onCamY=camY;
camSizeX=csX;
camSizeY=csY;
}
int camY(int absY)
{
return onCamY-(absPosY-absY);
}
int camX(int absX)
{
return onCamX-(absPosX-absX);
}
void update(int pX, int pY)
{
absPosX=pX;
absPosY=pY;
}
}
class oBase
{
Image img;
String imageName;
int posx,posy;
int vspeed=0, hspeed=0;
int width, height;
Boolean in_air = false;
Boolean gravity = false;
Boolean tiled = false;
int depth = 0;
public oBase(Image a, int x, int y,int d )//without mask
{
posx=x;
posy=y;
depth = d;
img = a;
width=0;
height=0;
}
public oBase(Image a, int x, int y,int d, int maskX, int maskY)//with mask
{
posx=x;
posy=y;
depth = d;
img = a;
width=maskX;
height=maskY;
}
public Boolean xinside(int x)
{
if(x>posx && x<posx+width)
{
return true;
}
return false;
}
public Boolean yinside(int y)
{
if(y>posy && y< posy+height)
{
return true;
}
return false;
}
/*
void move()
{
posx+=hspeed;
posy+=vspeed;
if(hspeed>0) //moving right
{
for(int i = 0)
if(this.posx+width) //check for collision
}
if(hspeed<0) //moving left
{
if(this.x)
}
if(vspeed>0)//moving up
{
}
if(vspeed<0)//moving down
{
}
}
*/
}
class oList
{
posCalc pC;
Toolkit toolkit = Toolkit.getDefaultToolkit();
ArrayList<Image> images = new ArrayList<Image>();
ArrayList<oBase> objects = new ArrayList<oBase>();
int camera;
public oList(int cam, int screenSizeX, int screenSizeY, int cameraX, int cameraY)
{
pC=new posCalc(cameraX,cameraY,screenSizeX,screenSizeY);
camera = cam;
}
void loadObjects(String filename) throws IOException
{
Scanner oF = new Scanner(new File(filename));
while(oF.hasNextLine())
{
this.add(oF.nextInt(),oF.nextInt(),oF.nextInt(),oF.nextInt(),oF.nextInt(), oF.nextInt());
}
}
void loadImages(String filename) throws IOException
{
Scanner resFile = new Scanner(new File(filename));
while(resFile.hasNextLine())
{
this.addImage(resFile.nextLine());
}
}
void addImage(String img)
{
images.add(toolkit.getImage(img));
}
void add(oBase x)
{
objects.add(x);
}
void add(int ImageIndex, int x, int y, int depth)
{
objects.add(new oBase(images.get(ImageIndex),x,y,depth));
}
void add(int ImageIndex, int x, int y, int depth, int mX, int mY)
{
objects.add(new oBase(images.get(ImageIndex),x,y,depth,mX,mY));
}
private void swap(int x, int y)
{
oBase temp = objects.get(x);
objects.set(x,objects.get(y));
objects.set(y,temp);
}
public void sortDepth()//simple bubble sort
{
boolean sorted;
int p = 1;
do
{
sorted = true;
for (int q = 0; q < objects.size()-p; q++)
if (objects.get(q).depth < objects.get(q+1).depth) //sort objects with least depth to last so they are drawn last
{
swap(q,q+1);
sorted = false;
}
p++;
}
while (!sorted);
}
void setTiled(int i)
{
objects.get(i).tiled=true;
}
void unsetTiled(int i)
{
objects.get(i).tiled=false;
}
void setGravity(int i)
{
objects.get(i).gravity=true;
}
void unsetGravity(int i)
{
objects.get(i).gravity=false;
}
void sethSpeed(int i, int x)
{
objects.get(i).hspeed=x;
}
void setvSpeed(int i, int x)
{
objects.get(i).vspeed=x;
}
void move(Graphics g, game z)
{
for(int x = 0; x<objects.size();x++)
{
//objects.get(x).move();
//objects.get(x).posx+=objects.get(x).hspeed;
//objects.get(x).posy+=objects.get(x).vspeed;
if(objects.get(x).hspeed>0) //moving right
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).width+objects.get(x).hspeed)) //if will collide right
- if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
+ //if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx-objects.get(x).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).hspeed<0) //moving left
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).hspeed)) //if will collide left
- if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
+ //if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx+objects.get(i).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).vspeed<0)//moving up
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).vspeed)) //if will collide top
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy+objects.get(i).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(objects.get(x).vspeed>0)//moving down
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).height+objects.get(x).vspeed)) //if will collide bottom
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy-objects.get(x).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(camera < objects.size()) //if camera references an object that exists
pC.update(objects.get(camera).posx,objects.get(camera).posy);
if(objects.get(x).tiled == true) //if background
{
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
}
else
{
g.drawImage(objects.get(x).img, pC.camX(objects.get(x).posx), pC.camY(objects.get(x).posy),z);
}
}
}
void draw(Graphics g, game z)
{
for(int x = 0; x<objects.size();x++)
{
//objects.get(x).move();
//objects.get(x).posx+=objects.get(x).hspeed;
//objects.get(x).posy+=objects.get(x).vspeed;
if(objects.get(x).hspeed>0) //moving right
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).width+objects.get(x).hspeed)) //if will collide right
if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx-objects.get(x).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).hspeed<0) //moving left
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).hspeed)) //if will collide left
if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx+objects.get(i).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).vspeed<0)//moving up
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).vspeed)) //if will collide top
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy+objects.get(i).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(objects.get(x).vspeed>0)//moving down
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).height+objects.get(x).vspeed)) //if will collide bottom
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy-objects.get(x).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(camera < objects.size()) //if camera references an object that exists
pC.update(objects.get(camera).posx,objects.get(camera).posy);
if(objects.get(x).tiled == true) //if background
{
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
}
else
{
g.drawImage(objects.get(x).img, pC.camX(objects.get(x).posx), pC.camY(objects.get(x).posy),z);
}
}
}
}
class game extends Panel implements KeyListener
{
oList objectlist = new oList(2,700,350,300,180);
public static void main(String[] args) throws IOException
{
Frame f = new Frame();
f.addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent e)
{
System.exit(0);
};
});
game x = new game();
x.setFocusable(true);
x.setSize(700,350); // same size as defined in the HTML APPLET
f.add(x);
f.pack();
x.init();
f.setSize(700,350+20); // add 20, seems enough for the Frame title,
while(true)
{
x.repaint();
f.show();
try{
Thread.sleep(20);
}
catch(InterruptedException ex){}
}
}
AudioClip soundFile1;
public void init() throws IOException
{
addKeyListener(this);
/*soundFile1.play();
addKeyListener(this);*/
//load images
objectlist.loadImages("game/res.dat");
objectlist.loadObjects("game/objects.dat");
//extra initializations
objectlist.sethSpeed(2,4);
//objectlist.add(1,500,500,0,this);
objectlist.setTiled(0);
objectlist.setGravity(2);
}
public void paint(Graphics g)
{
objectlist.sortDepth();
objectlist.draw(g,this);
}
public void update(Graphics g)
{
paint(g);
}
public void keyPressed(KeyEvent ke)
{
switch(ke.getKeyCode())
{
case KeyEvent.VK_DOWN:
objectlist.setvSpeed(objectlist.camera,10);
break;
case KeyEvent.VK_RIGHT:
objectlist.sethSpeed(objectlist.camera,10);
break;
case KeyEvent.VK_LEFT:
objectlist.sethSpeed(objectlist.camera,-10);
break;
case KeyEvent.VK_UP:
objectlist.setvSpeed(objectlist.camera,-10);
break;
}
}
public void keyTyped(KeyEvent ke) {}
public void keyReleased(KeyEvent ke)
{
switch(ke.getKeyCode())
{
case KeyEvent.VK_DOWN:
objectlist.setvSpeed(objectlist.camera,0);
break;
case KeyEvent.VK_RIGHT:
objectlist.sethSpeed(objectlist.camera,0);
//objects.get(camera).hspeed=0;
break;
case KeyEvent.VK_LEFT:
objectlist.sethSpeed(objectlist.camera,0);
//objects.get(camera).hspeed=0;
break;
case KeyEvent.VK_UP:
objectlist.setvSpeed(objectlist.camera,0);
break;
}
}
public boolean mouseDrag(Event e, int x, int y)
{
return true;
}
public boolean mouseDown(Event e, int x, int y)
{
return true;
}
public boolean mouseUp(Event e, int x, int y)
{
return true;
}
}
| false | true | void move(Graphics g, game z)
{
for(int x = 0; x<objects.size();x++)
{
//objects.get(x).move();
//objects.get(x).posx+=objects.get(x).hspeed;
//objects.get(x).posy+=objects.get(x).vspeed;
if(objects.get(x).hspeed>0) //moving right
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).width+objects.get(x).hspeed)) //if will collide right
if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx-objects.get(x).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).hspeed<0) //moving left
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).hspeed)) //if will collide left
if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx+objects.get(i).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).vspeed<0)//moving up
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).vspeed)) //if will collide top
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy+objects.get(i).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(objects.get(x).vspeed>0)//moving down
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).height+objects.get(x).vspeed)) //if will collide bottom
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy-objects.get(x).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(camera < objects.size()) //if camera references an object that exists
pC.update(objects.get(camera).posx,objects.get(camera).posy);
if(objects.get(x).tiled == true) //if background
{
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
}
else
{
g.drawImage(objects.get(x).img, pC.camX(objects.get(x).posx), pC.camY(objects.get(x).posy),z);
}
}
}
| void move(Graphics g, game z)
{
for(int x = 0; x<objects.size();x++)
{
//objects.get(x).move();
//objects.get(x).posx+=objects.get(x).hspeed;
//objects.get(x).posy+=objects.get(x).vspeed;
if(objects.get(x).hspeed>0) //moving right
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).width+objects.get(x).hspeed)) //if will collide right
//if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx-objects.get(x).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).hspeed<0) //moving left
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).xinside(objects.get(x).posx+objects.get(x).hspeed)) //if will collide left
//if(objects.get(i).yinside(objects.get(x).posy)||objects.get(i).yinside(objects.get(x).posy+objects.get(x).height))
{
objects.get(x).posx=objects.get(i).posx+objects.get(i).width;
objects.get(x).hspeed=0;
}
}
objects.get(x).posx+=objects.get(x).hspeed;
}
if(objects.get(x).vspeed<0)//moving up
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).vspeed)) //if will collide top
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy+objects.get(i).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(objects.get(x).vspeed>0)//moving down
{
for(int i = 0; i < objects.size(); i++)
{
if(i!=x&&!objects.get(i).tiled) //if not itself and not tiled
if(objects.get(i).yinside(objects.get(x).posy+objects.get(x).height+objects.get(x).vspeed)) //if will collide bottom
if(objects.get(i).xinside(objects.get(x).posx)||objects.get(i).xinside(objects.get(x).posx+objects.get(x).width))
{
objects.get(x).posy=objects.get(i).posy-objects.get(x).height;
objects.get(x).vspeed=0;
}
}
objects.get(x).posy+=objects.get(x).vspeed;
}
if(camera < objects.size()) //if camera references an object that exists
pC.update(objects.get(camera).posx,objects.get(camera).posy);
if(objects.get(x).tiled == true) //if background
{
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 350-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 700-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
g.drawImage(objects.get(x).img, 0-objects.get(camera).posx%700, 0-objects.get(camera).posy%350, z);
}
else
{
g.drawImage(objects.get(x).img, pC.camX(objects.get(x).posx), pC.camY(objects.get(x).posy),z);
}
}
}
|
diff --git a/app/src/ee/ioc/phon/android/arvutaja/ArvutajaActivity.java b/app/src/ee/ioc/phon/android/arvutaja/ArvutajaActivity.java
index ca4f9ca..72888ab 100644
--- a/app/src/ee/ioc/phon/android/arvutaja/ArvutajaActivity.java
+++ b/app/src/ee/ioc/phon/android/arvutaja/ArvutajaActivity.java
@@ -1,960 +1,962 @@
package ee.ioc.phon.android.arvutaja;
/*
* Copyright 2011-2013, Institute of Cybernetics at Tallinn University of Technology
*
* 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.
*/
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.RecognitionListener;
import android.speech.RecognitionService;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.text.format.Time;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CursorTreeAdapter;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.AbsListView.OnScrollListener;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.preference.PreferenceManager;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import ee.ioc.phon.android.arvutaja.Constants.State;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Qeval;
import ee.ioc.phon.android.arvutaja.provider.Query;
import ee.ioc.phon.android.speechutils.TtsProvider;
public class ArvutajaActivity extends AbstractRecognizerActivity {
public static final String EXTRA_LAUNCH_RECOGNIZER = "ee.ioc.phon.android.extra.LAUNCH_RECOGNIZER";
// Set of non-standard extras that K6nele supports
public static final String EXTRA_GRAMMAR_URL = "ee.ioc.phon.android.extra.GRAMMAR_URL";
public static final String EXTRA_GRAMMAR_TARGET_LANG = "ee.ioc.phon.android.extra.GRAMMAR_TARGET_LANG";
public static final String RESULTS_RECOGNITION_LINEARIZATIONS = "ee.ioc.phon.android.extra.RESULTS_RECOGNITION_LINEARIZATIONS";
public static final String RESULTS_RECOGNITION_LINEARIZATION_COUNTS = "ee.ioc.phon.android.extra.RESULTS_RECOGNITION_LINEARIZATION_COUNTS";
private State mState = State.INIT;
private static final Uri QUERY_CONTENT_URI = Query.Columns.CONTENT_URI;
private static final Uri QEVAL_CONTENT_URI = Qeval.Columns.CONTENT_URI;
private static final String SORT_ORDER_TIMESTAMP = Query.Columns.TIMESTAMP + " DESC";
private static final String SORT_ORDER_TRANSLATION = Query.Columns.TRANSLATION + " ASC";
private static final String SORT_ORDER_EVALUATION = Query.Columns.EVALUATION + " DESC";
private Resources mRes;
private SharedPreferences mPrefs;
private Vibrator mVibrator;
private static String mCurrentSortOrder;
private MicButton mButtonMicrophone;
private ExpandableListView mListView;
private MyExpandableListAdapter mAdapter;
private QueryHandler mQueryHandler;
private SpeechRecognizer mSr;
private TtsProvider mTts;
private static final String[] QUERY_PROJECTION = new String[] {
Query.Columns._ID,
Query.Columns.TIMESTAMP,
Query.Columns.UTTERANCE,
Query.Columns.TRANSLATION,
Query.Columns.EVALUATION
};
private static final String[] QEVAL_PROJECTION = new String[] {
Qeval.Columns._ID,
Qeval.Columns.TIMESTAMP,
Qeval.Columns.UTTERANCE,
Qeval.Columns.TRANSLATION,
Qeval.Columns.EVALUATION
};
private static final int GROUP_TIMESTAMP_COLUMN_INDEX = 1;
// Query identifiers for onQueryComplete
private static final int TOKEN_GROUP = 0;
private static final int TOKEN_CHILD = 1;
private static final class QueryHandler extends AsyncQueryHandler {
private final WeakReference<ArvutajaActivity> mRef;
private CursorTreeAdapter mAdapter;
public QueryHandler(ArvutajaActivity activity, CursorTreeAdapter adapter) {
super(activity.getContentResolver());
mRef = new WeakReference<ArvutajaActivity>(activity);
mAdapter = adapter;
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
case TOKEN_GROUP:
mAdapter.setGroupCursor(cursor);
break;
case TOKEN_CHILD:
int groupPosition = (Integer) cookie;
mAdapter.setChildrenCursor(groupPosition, cursor);
break;
}
updateUi();
}
protected void onDeleteComplete(int token, Object cookie, int result) {
updateUi();
}
protected void onInsertComplete(int token, Object cookie, Uri uri) {
updateUi();
// TODO: This should be done in a better way.
// The idea is that if insert was called with cookie set to "true",
// then we launch the Show-activity to display the inserted entry.
ArvutajaActivity outerClass = mRef.get();
if (outerClass != null && cookie != null && cookie instanceof Boolean) {
Boolean cookieAsBoolean = (Boolean) cookie;
if (cookieAsBoolean.booleanValue()) {
outerClass.showDetails(uri);
}
}
}
public void insert(Uri contentUri, ContentValues values) {
startInsert(1, null, contentUri, values);
}
public void insert(Uri contentUri, ContentValues values, boolean displayEntry) {
startInsert(1, displayEntry, contentUri, values);
}
public void delete(Uri contentUri, long key) {
Uri uri = ContentUris.withAppendedId(contentUri, key);
startDelete(1, null, uri, null, null);
}
private void updateUi() {
ArvutajaActivity outerClass = mRef.get();
if (outerClass != null) {
int count = mAdapter.getGroupCount();
outerClass.getActionBar().setSubtitle(
outerClass.getResources().getQuantityString(R.plurals.numberOfInputs, count, count));
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mRes = getResources();
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Some devices (NOOK) do not have a vibrator
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (mVibrator != null && ! mVibrator.hasVibrator()) {
mVibrator = null;
}
mButtonMicrophone = (MicButton) findViewById(R.id.buttonMicrophone);
mListView = (ExpandableListView) findViewById(R.id.list);
mListView.setGroupIndicator(getResources().getDrawable(R.drawable.list_selector_expandable));
mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View _view, int position, long _id) {
ExpandableListView listView = (ExpandableListView) parent;
// Converts a flat list position (the raw position of an item (child or group) in the list)
// to a group and/or child position (represented in a packed position).
long packedPosition = listView.getExpandableListPosition(position);
Cursor cursor = null;
final Uri contentUri;
final long key;
String translation = null;
if (ExpandableListView.getPackedPositionType(packedPosition) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
cursor = (Cursor) listView.getExpandableListAdapter().getGroup(position);
if (cursor == null) {
return false;
}
key = cursor.getLong(cursor.getColumnIndex(Query.Columns._ID));
contentUri = QUERY_CONTENT_URI;
translation = cursor.getString(cursor.getColumnIndex(Query.Columns.TRANSLATION));
} else if (ExpandableListView.getPackedPositionType(packedPosition) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
cursor = (Cursor) listView.getExpandableListAdapter().getChild(groupPosition, childPosition);
if (cursor == null) {
return false;
}
key = cursor.getLong(cursor.getColumnIndex(Qeval.Columns._ID));
contentUri = QEVAL_CONTENT_URI;
translation = cursor.getString(cursor.getColumnIndex(Qeval.Columns.TRANSLATION));
} else {
return false;
}
String message = null;
if (translation == null) {
message = getString(R.string.confirmDeleteMultiEntry);
} else {
message = getString(R.string.confirmDeleteEntry, translation);
}
Utils.getYesNoDialog(
ArvutajaActivity.this,
message,
new Executable() {
public void execute() {
mQueryHandler.delete(contentUri, key);
}
}
).show();
return true;
}
});
mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
Cursor cursor = (Cursor) parent.getExpandableListAdapter().getGroup(groupPosition);
String translation = cursor.getString(cursor.getColumnIndex(Query.Columns.TRANSLATION));
if (translation != null) {
long key = cursor.getLong(cursor.getColumnIndex(Query.Columns._ID));
showDetails(ContentUris.withAppendedId(QUERY_CONTENT_URI, key));
}
return false;
}
});
mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Cursor cursor = (Cursor) parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
long key = cursor.getLong(cursor.getColumnIndex(Qeval.Columns._ID));
showDetails(ContentUris.withAppendedId(QEVAL_CONTENT_URI, key));
return false;
}
});
mListView.setOnScrollListener(new OnScrollListener() {
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
mButtonMicrophone.fadeIn();
} else {
mButtonMicrophone.fadeOut();
}
}
});
mAdapter = new MyExpandableListAdapter(
this,
R.layout.list_item_group,
R.layout.list_item_child,
new String[] { Query.Columns.UTTERANCE, Query.Columns.TRANSLATION, Query.Columns.EVALUATION },
new int[] { R.id.list_item_utterance, R.id.list_item_translation, R.id.list_item_evaluation },
new String[] { Qeval.Columns.UTTERANCE, Qeval.Columns.TRANSLATION, Qeval.Columns.EVALUATION },
new int[] { R.id.list_item_utterance, R.id.list_item_translation, R.id.list_item_evaluation }
);
mListView.setAdapter(mAdapter);
registerForContextMenu(mListView);
getActionBar().setHomeButtonEnabled(false);
mQueryHandler = new QueryHandler(this, mAdapter);
startQuery(mPrefs.getString(getString(R.string.prefCurrentSortOrder), SORT_ORDER_TIMESTAMP));
}
/**
* We initialize the speech recognizer here, assuming that the configuration
* changed after onStop. That is why onStop destroys the recognizer.
*/
@Override
public void onStart() {
super.onStart();
if (mPrefs.getBoolean(getString(R.string.prefFirstTime), true)) {
if (isRecognizerInstalled(getString(R.string.nameK6nelePkg), getString(R.string.nameK6neleCls))) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(getString(R.string.keyService), getString(R.string.nameK6nelePkg));
editor.putString(getString(R.string.prefRecognizerServiceCls), getString(R.string.nameK6neleService));
editor.putBoolean(getString(R.string.prefFirstTime), false);
editor.commit();
AlertDialog d = Utils.getOkDialog(
this,
getString(R.string.msgFoundK6nele)
);
d.show();
} else {
// This can have 3 outcomes: K6nele gets installed, "Later" is pressed, "Never" is pressed.
// In the latter case we set prefFirstTime = false, so that this dialog is not shown again.
goToStore();
}
}
ComponentName serviceComponent = getServiceComponent();
if (serviceComponent == null) {
toast(getString(R.string.errorNoDefaultRecognizer));
goToStore();
} else {
Log.i("Starting service: " + serviceComponent);
mSr = SpeechRecognizer.createSpeechRecognizer(this, serviceComponent);
if (mSr == null) {
toast(getString(R.string.errorNoDefaultRecognizer));
} else {
final String lang = mPrefs.getString(getString(R.string.keyLanguage), getString(R.string.defaultLanguage));
if (mPrefs.getBoolean(getString(R.string.keyUseTts), mRes.getBoolean(R.bool.defaultUseTts))) {
mTts = new TtsProvider(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
getActionBar().setTitle(getString(R.string.labelApp) + " (" + lang + ")");
if (status == TextToSpeech.SUCCESS) {
Locale locale = mTts.chooseLanguage(lang);
if (locale == null) {
toast(getString(R.string.errorTtsLangNotAvailable, lang));
} else {
mTts.setLanguage(locale);
}
} else {
toast(getString(R.string.errorTtsInitError));
Log.e(getString(R.string.errorTtsInitError));
}
}
});
} else {
mTts = null;
getActionBar().setTitle(getString(R.string.labelApp) + " (" + lang + ")");
}
Intent intentRecognizer = createRecognizerIntent(
lang,
getString(R.string.defaultGrammar),
getString(R.string.nameLangLinearize));
setUpRecognizerGui(mSr, intentRecognizer);
processIntent(mSr, intentRecognizer);
}
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
if (mSr != null) {
mSr.cancel(); // TODO: do we need this, we do destroy anyway?
mSr.destroy();
mSr = null;
}
// Stop TTS
if (mTts != null) {
mTts.shutdown();
}
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(getString(R.string.prefCurrentSortOrder), mCurrentSortOrder);
editor.commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
mAdapter.changeCursor(null);
mAdapter = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
// Indicate the current sort order by checking the corresponding radio button
int id = mPrefs.getInt(getString(R.string.prefCurrentSortOrderMenu), R.id.menuMainSortByTimestamp);
MenuItem menuItem = menu.findItem(id);
menuItem.setChecked(true);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuMainSortByTimestamp:
sort(item, SORT_ORDER_TIMESTAMP);
return true;
case R.id.menuMainSortByTranslation:
sort(item, SORT_ORDER_TRANSLATION);
return true;
case R.id.menuMainSortByEvaluation:
sort(item, SORT_ORDER_EVALUATION);
return true;
case R.id.menuMainExamples:
startActivity(new Intent(this, ExamplesActivity.class));
return true;
case R.id.menuMainSettings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void sort(MenuItem item, String sortOrder) {
startQuery(sortOrder);
item.setChecked(true);
// Save the ID of the selected item.
// TODO: ideally this should be done in onDestory
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(getString(R.string.prefCurrentSortOrderMenu), item.getItemId());
editor.commit();
}
private void onSuccess(String lang, Bundle bundle) {
ArrayList<String> lins = bundle.getStringArrayList(RESULTS_RECOGNITION_LINEARIZATIONS);
ArrayList<Integer> counts = bundle.getIntegerArrayList(RESULTS_RECOGNITION_LINEARIZATION_COUNTS);
ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// TODO: confidence scores support is only in API 14
if (lins == null || lins.isEmpty() || counts == null || counts.isEmpty()) {
if (matches == null || matches.isEmpty()) {
showErrorDialog(R.string.errorResultNoMatch);
return;
}
lins = new ArrayList<String>();
counts = new ArrayList<Integer>();
for (String match : matches) {
lins.add(match); // utterance
lins.add(match); // translation
lins.add("GVS"); // TODO: target language
counts.add(1);
}
}
processResults(lang, lins, counts);
}
private void launchIntent(String commandAsString) {
try {
Command command = CommandParser.getCommand(this, commandAsString);
Intent intent = command.getIntent();
if (getIntentActivities(intent).size() == 0) {
AlertDialog d = Utils.getGoToStoreDialog(
this,
getString(R.string.errorIntentActivityNotPresent),
command.getSuggestion()
);
d.show();
// Make the textview clickable. Must be called after show()
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
} else {
startForeignActivity(intent);
}
} catch (CommandParseException e) {
toast(getString(R.string.errorCommandNotSupported));
}
}
private Intent createRecognizerIntent(String langSource, String grammar, String langTarget) {
Locale locale = new Locale(langSource);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getApplicationContext().getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, langSource);
// TODO: check it later as well, as the recognizer might ignore it,
// e.g. GVS always returns 5 results regardless of this setting.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,
Integer.parseInt(mPrefs.getString(getString(R.string.keyMaxResults), getString(R.string.defaultMaxResults))));
intent.putExtra(EXTRA_GRAMMAR_URL, grammar);
// Request the App-language and (if switched on) the TTS-language (e.g. Engtts).
// We assume (in the following) that only a single variant is returned for both types of languages.
if (mPrefs.getBoolean(getString(R.string.keyUseTts), mRes.getBoolean(R.bool.defaultUseTts))) {
intent.putExtra(EXTRA_GRAMMAR_TARGET_LANG, langTarget + "," + Utils.localeToTtsCode(locale));
} else {
intent.putExtra(EXTRA_GRAMMAR_TARGET_LANG, langTarget);
}
return intent;
}
/**
* This is called after successful speech recognition to inform the user
* about the results and also store the results.
*
* We assume that each hypothesis comes with {@code 2*n} linearizations
* corresponding to {@code n} parse results of the raw recognition result.
* Each result has 2 linearizations (App and ???tts), in any order.
* We ignore that results where App is empty or is repeated.
*
* <ul>
* <li>raw utterance of hypothesis 1
* <li>linearization 1.1
* <li>language code of linearization 1.1 (App)
* <li>linearization 1.2
* <li>language code of linearization 1.2 (Engtts)
* <li>...
* <li>raw utterance of hypothesis 2
* <li>...
* </ul>
*/
private void processResults(String lang, List<String> lins, List<Integer> counts) {
Time now = new Time();
now.setToNow();
long timestamp = now.toMillis(false);
Locale locale = new Locale(lang);
String ttsLang = Utils.localeToTtsCode(locale);
String ttsPhrase = null;
List<ContentValues> valuesList = new ArrayList<ContentValues>();
Set<String> seen = new HashSet<String>();
int begin = 0;
for (Integer c : counts) {
int end = begin + 1 + 2*c;
String utterance = lins.get(begin);
Log.i("UTT: " + utterance);
for (int pos = begin + 1; pos < end; pos = pos + 2) {
String lin = lins.get(pos);
String targetLang = lins.get(pos+1);
Log.i("-> LIN " + pos + ": " + targetLang + ": " + lin);
// TODO: we currently only pick out the first TTS language linearization,
// because in the case of several linearizations they are not currently spoken.
// TODO: we ignore "no lang" (which the server currently prints if an undefined language was queried)
// This should be fixed in the server.
if (ttsLang.equals(targetLang)) {
if (ttsPhrase == null && ! "no lang".equals(lin)) {
ttsPhrase = lin;
}
continue;
}
String key = lin + "|" + targetLang;
if (lin.isEmpty() || seen.contains(key)) {
continue;
} else {
seen.add(key);
}
ContentValues values = new ContentValues();
values.put(Qeval.Columns.TIMESTAMP, timestamp);
values.put(Qeval.Columns.UTTERANCE, utterance);
values.put(Qeval.Columns.TRANSLATION, lin);
values.put(Qeval.Columns.LANG, lang);
values.put(Qeval.Columns.TARGET_LANG, targetLang);
try {
Object evaluation = CommandParser.getCommand(getApplicationContext(), lin).getOut();
if (evaluation instanceof Double) {
Double dblEvaluation = (Double) evaluation;
values.put(Qeval.Columns.EVALUATION, dblEvaluation);
} else {
values.put(Qeval.Columns.EVALUATION, "");
}
} catch (Exception e) {
// We store the exception message in the "message" field,
// but it should not be shown to the user.
values.put(Qeval.Columns.MESSAGE, e.getMessage());
}
valuesList.add(values);
}
begin = end;
}
if (valuesList.isEmpty()) {
showErrorDialog(R.string.errorResultNoMatch);
// We use the speech input locale, not the GUI locale,
// i.e. if the user speaks in English, then respond in English,
// even though the (visual) GUI is in German.
say(LocalizedStrings.getString(locale, R.string.errorResultNoMatch));
} else if (valuesList.size() == 1) {
if (ttsPhrase != null) {
Double dblEvaluation = valuesList.get(0).getAsDouble(Qeval.Columns.EVALUATION);
String ttsOutput = Utils.makeTtsOutput(
locale,
ttsPhrase,
dblEvaluation
);
say(ttsOutput);
// We also toast the string that is meant for TTS, because it can say it wrong,
// e.g. the English TTS engine (on my device, at the time of writing)
// reads 10^9 as some other number (because of overflow?)
toast(ttsOutput);
}
// If the transcription is not ambiguous, and the user prefers to
// evaluate using an external activity, then we launch it via an intent.
boolean launchExternalEvaluator = mPrefs.getBoolean(
getString(R.string.keyUseExternalEvaluator),
mRes.getBoolean(R.bool.defaultUseExternalEvaluator));
mQueryHandler.insert(QUERY_CONTENT_URI, valuesList.get(0), ! launchExternalEvaluator);
if (launchExternalEvaluator) {
launchIntent(lins.get(1));
}
} else {
// We use the speech input locale, not the GUI locale,
// i.e. if the user speaks in English, then respond in English,
// even though the (visual) GUI is in German.
say(LocalizedStrings.getString(locale, R.string.ambiguous, valuesList.size()));
ContentValues values = new ContentValues();
values.put(Query.Columns.TIMESTAMP, timestamp);
// TRANSLATION must remain NULL here
values.put(Query.Columns.EVALUATION, getString(R.string.ambiguous));
mQueryHandler.insert(QUERY_CONTENT_URI, values);
for (ContentValues cv : valuesList) {
mQueryHandler.insert(QEVAL_CONTENT_URI, cv);
}
}
}
private void startQuery(String sortOrder) {
mCurrentSortOrder = sortOrder;
mQueryHandler.startQuery(
TOKEN_GROUP,
null,
QUERY_CONTENT_URI,
QUERY_PROJECTION,
null,
null,
sortOrder
);
}
private void say(String str) {
if (mTts != null) {
mTts.say(str);
//toast(str); // for testing
}
}
private void setUpRecognizerGui(final SpeechRecognizer sr, final Intent intentRecognizer) {
final AudioCue audioCue;
if (mPrefs.getBoolean(getString(R.string.keyAudioCues), mRes.getBoolean(R.bool.defaultAudioCues))) {
audioCue = new AudioCue(this);
} else {
audioCue = null;
}
sr.setRecognitionListener(new RecognitionListener() {
@Override
public void onBeginningOfSpeech() {
mState = State.LISTENING;
}
@Override
public void onBufferReceived(byte[] buffer) {
// TODO maybe show buffer waveform
}
@Override
public void onEndOfSpeech() {
mState = State.TRANSCRIBING;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playStopSound();
}
}
@Override
public void onError(int error) {
mState = State.ERROR;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playErrorSound();
}
switch (error) {
case SpeechRecognizer.ERROR_AUDIO:
showErrorDialog(R.string.errorResultAudioError);
break;
case SpeechRecognizer.ERROR_CLIENT:
showErrorDialog(R.string.errorResultClientError);
break;
case SpeechRecognizer.ERROR_NETWORK:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_SERVER:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_NO_MATCH:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
// This is programmer error.
break;
default:
break;
}
}
@Override
public void onEvent(int eventType, Bundle params) {
// TODO ???
}
@Override
public void onPartialResults(Bundle partialResults) {
// ignore
}
@Override
public void onReadyForSpeech(Bundle params) {
mState = State.RECORDING;
mButtonMicrophone.setState(mState);
}
@Override
public void onResults(Bundle results) {
mState = State.INIT;
mButtonMicrophone.setState(mState);
onSuccess(intentRecognizer.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE), results);
}
@Override
public void onRmsChanged(float rmsdB) {
mButtonMicrophone.setVolumeLevel(rmsdB);
}
});
mButtonMicrophone.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
vibrate();
}
return false;
}
});
mButtonMicrophone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mState == State.INIT || mState == State.ERROR) {
- mTts.stop();
+ if (mTts != null) {
+ mTts.stop();
+ }
if (audioCue != null) {
audioCue.playStartSoundAndSleep();
}
sr.startListening(intentRecognizer);
}
else if (mState == State.RECORDING) {
//sr.cancel();
}
else if (mState == State.TRANSCRIBING) {
//sr.cancel();
}
else if (mState == State.LISTENING) {
sr.stopListening();
} else {
// TODO: bad state to press the button
}
}
});
LinearLayout llMicrophone = (LinearLayout) findViewById(R.id.llMicrophone);
llMicrophone.setVisibility(View.VISIBLE);
llMicrophone.setEnabled(true);
}
/**
* Immediately launch the recognizer if
* - action is ACTION_VOICE_COMMAND, or
* - EXTRA_LAUNCH_RECOGNIZER == true
*/
private void processIntent(SpeechRecognizer sr, Intent intentRecognizer) {
Intent intentArvutaja = getIntent();
Bundle extras = intentArvutaja.getExtras();
if (
Intent.ACTION_VOICE_COMMAND.equals(intentArvutaja.getAction())
||
extras != null && extras.getBoolean(ArvutajaActivity.EXTRA_LAUNCH_RECOGNIZER)) {
// We disable the intent so that it would not fire on orientation change
Intent intentVoid = new Intent(this, ArvutajaActivity.class);
intentVoid.setAction(null);
setIntent(intentVoid);
mButtonMicrophone.performClick();
}
}
private void vibrate() {
if (mVibrator != null) {
mVibrator.vibrate(30);
}
}
private void showDetails(Uri uri) {
Intent intent = new Intent(this, ShowActivity.class);
intent.setData(uri);
startActivity(intent);
}
private void goToStore() {
AlertDialog d = Utils.getGoToStoreDialogWithThreeButtons(
this,
getString(R.string.errorRecognizerNotPresent, getString(R.string.nameRecognizer)),
Uri.parse(getString(R.string.urlK6neleDownload))
);
d.show();
}
/**
* This is one way to find out if a specific recognizer is installed.
* Alternatively we could query the service.
*/
private boolean isRecognizerInstalled(String pkg, String cls) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.setComponent(new ComponentName(pkg, cls));
return (getIntentActivities(intent).size() > 0);
}
/**
* Look up the default recognizer service in the preferences.
* If the default have not been set then set the first available
* recognizer as the default. If no recognizer is installed then
* return null.
*/
private ComponentName getServiceComponent() {
String pkg = mPrefs.getString(getString(R.string.keyService), null);
String cls = mPrefs.getString(getString(R.string.prefRecognizerServiceCls), null);
if (pkg == null || cls == null) {
List<ResolveInfo> services = getPackageManager().queryIntentServices(
new Intent(RecognitionService.SERVICE_INTERFACE), 0);
if (services.isEmpty()) {
return null;
}
ResolveInfo ri = services.iterator().next();
pkg = ri.serviceInfo.packageName;
cls = ri.serviceInfo.name;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(getString(R.string.keyService), pkg);
editor.putString(getString(R.string.prefRecognizerServiceCls), cls);
editor.commit();
}
return new ComponentName(pkg, cls);
}
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
// Note that the constructor does not take a Cursor. This is done to avoid querying the
// database on the main thread.
public MyExpandableListAdapter(Context context, int groupLayout,
int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
int[] childrenTo) {
super(context, null, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
mQueryHandler.startQuery(
TOKEN_CHILD,
groupCursor.getPosition(),
QEVAL_CONTENT_URI,
QEVAL_PROJECTION,
Qeval.Columns.TIMESTAMP + "=?",
new String[] { "" + groupCursor.getLong(GROUP_TIMESTAMP_COLUMN_INDEX) },
null
);
return null;
}
}
}
| true | true | private void setUpRecognizerGui(final SpeechRecognizer sr, final Intent intentRecognizer) {
final AudioCue audioCue;
if (mPrefs.getBoolean(getString(R.string.keyAudioCues), mRes.getBoolean(R.bool.defaultAudioCues))) {
audioCue = new AudioCue(this);
} else {
audioCue = null;
}
sr.setRecognitionListener(new RecognitionListener() {
@Override
public void onBeginningOfSpeech() {
mState = State.LISTENING;
}
@Override
public void onBufferReceived(byte[] buffer) {
// TODO maybe show buffer waveform
}
@Override
public void onEndOfSpeech() {
mState = State.TRANSCRIBING;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playStopSound();
}
}
@Override
public void onError(int error) {
mState = State.ERROR;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playErrorSound();
}
switch (error) {
case SpeechRecognizer.ERROR_AUDIO:
showErrorDialog(R.string.errorResultAudioError);
break;
case SpeechRecognizer.ERROR_CLIENT:
showErrorDialog(R.string.errorResultClientError);
break;
case SpeechRecognizer.ERROR_NETWORK:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_SERVER:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_NO_MATCH:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
// This is programmer error.
break;
default:
break;
}
}
@Override
public void onEvent(int eventType, Bundle params) {
// TODO ???
}
@Override
public void onPartialResults(Bundle partialResults) {
// ignore
}
@Override
public void onReadyForSpeech(Bundle params) {
mState = State.RECORDING;
mButtonMicrophone.setState(mState);
}
@Override
public void onResults(Bundle results) {
mState = State.INIT;
mButtonMicrophone.setState(mState);
onSuccess(intentRecognizer.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE), results);
}
@Override
public void onRmsChanged(float rmsdB) {
mButtonMicrophone.setVolumeLevel(rmsdB);
}
});
mButtonMicrophone.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
vibrate();
}
return false;
}
});
mButtonMicrophone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mState == State.INIT || mState == State.ERROR) {
mTts.stop();
if (audioCue != null) {
audioCue.playStartSoundAndSleep();
}
sr.startListening(intentRecognizer);
}
else if (mState == State.RECORDING) {
//sr.cancel();
}
else if (mState == State.TRANSCRIBING) {
//sr.cancel();
}
else if (mState == State.LISTENING) {
sr.stopListening();
} else {
// TODO: bad state to press the button
}
}
});
LinearLayout llMicrophone = (LinearLayout) findViewById(R.id.llMicrophone);
llMicrophone.setVisibility(View.VISIBLE);
llMicrophone.setEnabled(true);
}
| private void setUpRecognizerGui(final SpeechRecognizer sr, final Intent intentRecognizer) {
final AudioCue audioCue;
if (mPrefs.getBoolean(getString(R.string.keyAudioCues), mRes.getBoolean(R.bool.defaultAudioCues))) {
audioCue = new AudioCue(this);
} else {
audioCue = null;
}
sr.setRecognitionListener(new RecognitionListener() {
@Override
public void onBeginningOfSpeech() {
mState = State.LISTENING;
}
@Override
public void onBufferReceived(byte[] buffer) {
// TODO maybe show buffer waveform
}
@Override
public void onEndOfSpeech() {
mState = State.TRANSCRIBING;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playStopSound();
}
}
@Override
public void onError(int error) {
mState = State.ERROR;
mButtonMicrophone.setState(mState);
if (audioCue != null) {
audioCue.playErrorSound();
}
switch (error) {
case SpeechRecognizer.ERROR_AUDIO:
showErrorDialog(R.string.errorResultAudioError);
break;
case SpeechRecognizer.ERROR_CLIENT:
showErrorDialog(R.string.errorResultClientError);
break;
case SpeechRecognizer.ERROR_NETWORK:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
showErrorDialog(R.string.errorResultNetworkError);
break;
case SpeechRecognizer.ERROR_SERVER:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
showErrorDialog(R.string.errorResultServerError);
break;
case SpeechRecognizer.ERROR_NO_MATCH:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
showErrorDialog(R.string.errorResultNoMatch);
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
// This is programmer error.
break;
default:
break;
}
}
@Override
public void onEvent(int eventType, Bundle params) {
// TODO ???
}
@Override
public void onPartialResults(Bundle partialResults) {
// ignore
}
@Override
public void onReadyForSpeech(Bundle params) {
mState = State.RECORDING;
mButtonMicrophone.setState(mState);
}
@Override
public void onResults(Bundle results) {
mState = State.INIT;
mButtonMicrophone.setState(mState);
onSuccess(intentRecognizer.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE), results);
}
@Override
public void onRmsChanged(float rmsdB) {
mButtonMicrophone.setVolumeLevel(rmsdB);
}
});
mButtonMicrophone.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
vibrate();
}
return false;
}
});
mButtonMicrophone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mState == State.INIT || mState == State.ERROR) {
if (mTts != null) {
mTts.stop();
}
if (audioCue != null) {
audioCue.playStartSoundAndSleep();
}
sr.startListening(intentRecognizer);
}
else if (mState == State.RECORDING) {
//sr.cancel();
}
else if (mState == State.TRANSCRIBING) {
//sr.cancel();
}
else if (mState == State.LISTENING) {
sr.stopListening();
} else {
// TODO: bad state to press the button
}
}
});
LinearLayout llMicrophone = (LinearLayout) findViewById(R.id.llMicrophone);
llMicrophone.setVisibility(View.VISIBLE);
llMicrophone.setEnabled(true);
}
|
diff --git a/plugins/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/MetaDataRetriever.java b/plugins/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/MetaDataRetriever.java
index 2db07fb12..01a25178d 100644
--- a/plugins/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/MetaDataRetriever.java
+++ b/plugins/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/MetaDataRetriever.java
@@ -1,122 +1,129 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.oda.jdbc.ui.editors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.datatools.connectivity.oda.IAdvancedQuery;
import org.eclipse.datatools.connectivity.oda.IConnection;
import org.eclipse.datatools.connectivity.oda.IParameterMetaData;
import org.eclipse.datatools.connectivity.oda.IQuery;
import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
import org.eclipse.datatools.connectivity.oda.OdaException;
import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
import org.eclipse.datatools.connectivity.oda.design.Properties;
import org.eclipse.datatools.connectivity.oda.design.Property;
import org.eclipse.datatools.connectivity.oda.spec.QuerySpecification;
import org.eclipse.datatools.connectivity.oda.spec.util.QuerySpecificationHelper;
/**
*
* This class serves to provide the updated ParameterMetaData and ResultSetMetaData information
* according to the specified updated query text
*
*/
class MetaDataRetriever
{
private IResultSetMetaData resultMeta;
private IParameterMetaData paramMeta;
private IQuery query;
private static Logger logger = Logger.getLogger( MetaDataRetriever.class.getName( ) );
MetaDataRetriever( OdaConnectionProvider odaConnectionProvider, DataSetDesign dataSetDesign )
{
try
{
IConnection connection = odaConnectionProvider.openConnection( );
query = connection.newQuery( dataSetDesign.getOdaExtensionDataSetId( ) );
QuerySpecification querySpec = new QuerySpecificationHelper((String)null).createQuerySpecification();
Properties properties = dataSetDesign.getPublicProperties();
if( properties!= null )
{
for( Property prop : properties.getProperties())
{
querySpec.setProperty( prop.getName(), prop.getValue());
}
}
- query.setSpecification( querySpec );
+ try
+ {
+ query.setSpecification( querySpec );
+ }
+ catch( UnsupportedOperationException ue )
+ {
+ //This method is not supported by CallStatement.
+ }
query.prepare( dataSetDesign.getQueryText( ) );
try
{
paramMeta = query.getParameterMetaData( );
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
if ( !( query instanceof IAdvancedQuery ) )
{
resultMeta = query.getMetaData( );
}
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
/**
* Get the ParameterMetaData object
*
* @return IParameterMetaData
*/
IParameterMetaData getParameterMetaData( )
{
return this.paramMeta;
}
/**
* Get the ResultSetMetaData object
*
* @return IResultSetMetaData
*/
IResultSetMetaData getResultSetMetaData( )
{
return this.resultMeta;
}
/**
* Release
*/
void close( )
{
try
{
if ( query != null )
{
query.close( );
}
}
catch ( OdaException e )
{
//ignore it
}
finally
{
query = null;
}
}
}
| true | true | MetaDataRetriever( OdaConnectionProvider odaConnectionProvider, DataSetDesign dataSetDesign )
{
try
{
IConnection connection = odaConnectionProvider.openConnection( );
query = connection.newQuery( dataSetDesign.getOdaExtensionDataSetId( ) );
QuerySpecification querySpec = new QuerySpecificationHelper((String)null).createQuerySpecification();
Properties properties = dataSetDesign.getPublicProperties();
if( properties!= null )
{
for( Property prop : properties.getProperties())
{
querySpec.setProperty( prop.getName(), prop.getValue());
}
}
query.setSpecification( querySpec );
query.prepare( dataSetDesign.getQueryText( ) );
try
{
paramMeta = query.getParameterMetaData( );
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
if ( !( query instanceof IAdvancedQuery ) )
{
resultMeta = query.getMetaData( );
}
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
| MetaDataRetriever( OdaConnectionProvider odaConnectionProvider, DataSetDesign dataSetDesign )
{
try
{
IConnection connection = odaConnectionProvider.openConnection( );
query = connection.newQuery( dataSetDesign.getOdaExtensionDataSetId( ) );
QuerySpecification querySpec = new QuerySpecificationHelper((String)null).createQuerySpecification();
Properties properties = dataSetDesign.getPublicProperties();
if( properties!= null )
{
for( Property prop : properties.getProperties())
{
querySpec.setProperty( prop.getName(), prop.getValue());
}
}
try
{
query.setSpecification( querySpec );
}
catch( UnsupportedOperationException ue )
{
//This method is not supported by CallStatement.
}
query.prepare( dataSetDesign.getQueryText( ) );
try
{
paramMeta = query.getParameterMetaData( );
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
if ( !( query instanceof IAdvancedQuery ) )
{
resultMeta = query.getMetaData( );
}
}
catch ( OdaException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
|
diff --git a/src/org/eclipse/imp/lpg/builder/JikesPGBuilder.java b/src/org/eclipse/imp/lpg/builder/JikesPGBuilder.java
index 0513dfb..f55bc61 100644
--- a/src/org/eclipse/imp/lpg/builder/JikesPGBuilder.java
+++ b/src/org/eclipse/imp/lpg/builder/JikesPGBuilder.java
@@ -1,271 +1,271 @@
package org.jikespg.uide.builder;
/*
* Licensed Materials - Property of IBM,
* (c) Copyright IBM Corp. 1998, 2004 All Rights Reserved
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.uide.core.SAFARIBuilderBase;
import org.eclipse.uide.runtime.SAFARIPluginBase;
import org.jikespg.uide.JikesPGPlugin;
import org.jikespg.uide.preferences.JikesPGPreferenceCache;
import org.jikespg.uide.views.JikesPGView;
import org.osgi.framework.Bundle;
/**
* @author [email protected]
* @author CLaffra
*/
public class JikesPGBuilder extends SAFARIBuilderBase {
/**
* Extension ID of the JikesPG builder. Must match the ID in the corresponding
* extension definition in plugin.xml.
*/
public static final String BUILDER_ID= JikesPGPlugin.kPluginID + ".jikesPGBuilder";
public static final String PROBLEM_MARKER_ID= JikesPGPlugin.kPluginID + ".problem";
/**
* ID of the LPG plugin, which houses the templates, the LPG executable,
* and the LPG runtime library
*/
public static final String LPG_PLUGIN_ID= "lpg";
private static final String SYNTAX_MSG_REGEXP= "(.*):([0-9]+):([0-9]+):([0-9]+):([0-9]+):([0-9]+):([0-9]+): (.*)";
private static final Pattern SYNTAX_MSG_PATTERN= Pattern.compile(SYNTAX_MSG_REGEXP);
private static final String MISSING_MSG_REGEXP= "Input file \"([^\"]+)\" could not be read";
private static final Pattern MISSING_MSG_PATTERN= Pattern.compile(MISSING_MSG_REGEXP);
protected SAFARIPluginBase getPlugin() {
return JikesPGPlugin.getInstance();
}
protected String getErrorMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getWarningMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getInfoMarkerID() {
return PROBLEM_MARKER_ID;
}
protected boolean isSourceFile(IFile file) {
IPath path= file.getRawLocation();
if (path == null) return false;
String fileName= path.toString();
return (fileName.indexOf("/bin/") == -1 && "g".equals(path.getFileExtension()));
}
protected boolean isOutputFolder(IResource resource) {
return resource.getFullPath().lastSegment().equals("bin");
}
protected void compile(final IFile file) {
String fileName= file.getLocation().toOSString();
String templatePath= getTemplatePath();
JikesPGPlugin.getInstance().maybeWriteInfoMsg("Using template path '" + templatePath + "'.");
try {
File parentDir= new File(fileName).getParentFile();
String cmd[]= new String[] {
getLPGExecutable(),
"-quiet",
(JikesPGPreferenceCache.generateListing ? "-list" : "-nolist"),
- "-include-directory=" + templatePath,
+ "-include-directory='" + templatePath + "'",
// TODO RMF 7/21/05 -- Don't specify -dat-directory; causes performance issues with Eclipse.
// Lexer tables can get quite large, so large that Java as spec'ed can't swallow them
// when translated to a switch statement, or even an array initializer. As a result,
// JikesPG supports the "-dat-directory" option to spill the tables into external data
// files loaded by the lexer at runtime. HOWEVER, loading these external data tables is
// very slow when performed using the standard Eclipse/plugin classloader.
// So: don't enable it by default.
// "-dat-directory=" + getOutputDirectory(resource.getProject()),
fileName};
Process process= Runtime.getRuntime().exec(cmd, new String[0], parentDir);
JikesPGView consoleView= JikesPGView.getDefault();
processJikesPGOutput(file, process, consoleView);
processJikesPGErrors(file, process, consoleView);
doRefresh(file);
} catch (Exception e) {
JikesPGPlugin.getInstance().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
private void processJikesPGErrors(IResource resource, Process process, JikesPGView view) throws IOException {
InputStream is= process.getErrorStream();
BufferedReader in2= new BufferedReader(new InputStreamReader(is));
String line;
while ((line= in2.readLine()) != null) {
if (view != null)
JikesPGView.println(line);
if (parseSyntaxMessageCreateMarker(line))
;
else if (line.indexOf("Input file ") == 0) {
parseMissingFileMessage(line, resource);
} else
handleMiscMessage(line, resource);
// JikesPGPlugin.getInstance().writeErrorMsg(line);
}
is.close();
}
final String lineSep= System.getProperty("line.separator");
final int lineSepBias= lineSep.length() - 1;
private void processJikesPGOutput(final IResource resource, Process process, JikesPGView view) throws IOException {
InputStream is= process.getInputStream();
BufferedReader in= new BufferedReader(new InputStreamReader(is));
String line= null;
while ((line= in.readLine()) != null) {
if (view != null)
JikesPGView.println(line);
else {
System.out.println(line);
}
final String msg= line;
if (parseSyntaxMessageCreateMarker(msg))
;
else if (msg.indexOf("Input file ") == 0) {
parseMissingFileMessage(msg, resource);
} else
handleMiscMessage(msg, resource);
}
}
private void handleMiscMessage(String msg, IResource file) {
if (msg.length() == 0) return;
if (msg.startsWith("Unable to open"))
createMarker(file, 1, -1, -1, msg, IMarker.SEVERITY_ERROR);
if (msg.indexOf("Number of ") < 0 &&
!msg.startsWith("(C) Copyright") &&
!msg.startsWith("IBM LALR Parser"))
createMarker(file, 1, -1, -1, msg, IMarker.SEVERITY_INFO);
}
private void parseMissingFileMessage(String msg, IResource file) {
Matcher matcher= MISSING_MSG_PATTERN.matcher(msg);
if (matcher.matches()) {
String missingFile= matcher.group(1);
int refLine= 1; // Integer.parseInt(matcher.group(2))
createMarker(file, refLine, -1, -1, "Non-existent file referenced: " + missingFile, IMarker.SEVERITY_ERROR);
}
}
private boolean parseSyntaxMessageCreateMarker(final String msg) {
Matcher matcher= SYNTAX_MSG_PATTERN.matcher(msg);
if (matcher.matches()) {
String errorFile= matcher.group(1);
String projectLoc= getProject().getLocation().toOSString();
if (errorFile.startsWith(projectLoc))
errorFile= errorFile.substring(projectLoc.length());
IResource errorResource= getProject().getFile(errorFile);
int startLine= Integer.parseInt(matcher.group(2));
// int startCol= Integer.parseInt(matcher.group(3));
// int endLine= Integer.parseInt(matcher.group(4));
// int endCol= Integer.parseInt(matcher.group(5));
int startChar= Integer.parseInt(matcher.group(6)) - 1;// - (startLine - 1) * lineSepBias + 1;
int endChar= Integer.parseInt(matcher.group(7));// - (endLine - 1) * lineSepBias + 1;
String descrip= matcher.group(8);
if (startLine == 0) startLine= 1;
createMarker(errorResource, startLine, startChar, endChar, descrip, IMarker.SEVERITY_ERROR);
return true;
}
return false;
}
public static String getTemplatePath() {
if (JikesPGPreferenceCache.jikesPGTemplateDir != null &&
JikesPGPreferenceCache.jikesPGTemplateDir.length() > 0)
return JikesPGPreferenceCache.jikesPGTemplateDir;
return getDefaultTemplatePath();
}
public static String getDefaultTemplatePath() {
Bundle bundle= Platform.getBundle(LPG_PLUGIN_ID);
try {
// Use getEntry() rather than getResource(), since the "templates" folder is
// no longer inside the plugin jar (which is now expanded upon installation).
String tmplPath= Platform.asLocalURL(bundle.getEntry("templates")).getFile();
if (Platform.getOS().equals("win32"))
tmplPath= tmplPath.substring(1);
return tmplPath;
} catch(IOException e) {
return null;
}
}
private String getLPGExecutable() throws IOException {
return JikesPGPreferenceCache.jikesPGExecutableFile;
}
public static String getDefaultExecutablePath() {
Bundle bundle= Platform.getBundle(LPG_PLUGIN_ID);
String os= Platform.getOS();
String plat= Platform.getOSArch();
Path path= new Path("bin/lpg-" + os + "_" + plat + (os.equals("win32") ? ".exe" : ""));
URL execURL= Platform.find(bundle, path);
if (execURL == null) {
String errMsg= "Unable to find JikesPG executable at " + path + " in bundle " + bundle.getSymbolicName();
JikesPGPlugin.getInstance().writeErrorMsg(errMsg);
throw new IllegalArgumentException(errMsg);
} else {
// N.B.: The jikespg executable will normally be inside a jar file,
// so use asLocalURL() to extract to a local file if needed.
URL url;
try {
url= Platform.asLocalURL(execURL);
} catch (IOException e) {
JikesPGPlugin.getInstance().writeErrorMsg("Unable to locate default JikesPG executable." + e.getMessage());
return "???";
}
String jikesPGExecPath= url.getFile();
if (os.equals("win32")) // remove leading slash from URL that shows up on Win32(?)
jikesPGExecPath= jikesPGExecPath.substring(1);
JikesPGPlugin.getInstance().maybeWriteInfoMsg("JikesPG executable apparently at '" + jikesPGExecPath + "'.");
return jikesPGExecPath;
}
}
}
| true | true | protected void compile(final IFile file) {
String fileName= file.getLocation().toOSString();
String templatePath= getTemplatePath();
JikesPGPlugin.getInstance().maybeWriteInfoMsg("Using template path '" + templatePath + "'.");
try {
File parentDir= new File(fileName).getParentFile();
String cmd[]= new String[] {
getLPGExecutable(),
"-quiet",
(JikesPGPreferenceCache.generateListing ? "-list" : "-nolist"),
"-include-directory=" + templatePath,
// TODO RMF 7/21/05 -- Don't specify -dat-directory; causes performance issues with Eclipse.
// Lexer tables can get quite large, so large that Java as spec'ed can't swallow them
// when translated to a switch statement, or even an array initializer. As a result,
// JikesPG supports the "-dat-directory" option to spill the tables into external data
// files loaded by the lexer at runtime. HOWEVER, loading these external data tables is
// very slow when performed using the standard Eclipse/plugin classloader.
// So: don't enable it by default.
// "-dat-directory=" + getOutputDirectory(resource.getProject()),
fileName};
Process process= Runtime.getRuntime().exec(cmd, new String[0], parentDir);
JikesPGView consoleView= JikesPGView.getDefault();
processJikesPGOutput(file, process, consoleView);
processJikesPGErrors(file, process, consoleView);
doRefresh(file);
} catch (Exception e) {
JikesPGPlugin.getInstance().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
| protected void compile(final IFile file) {
String fileName= file.getLocation().toOSString();
String templatePath= getTemplatePath();
JikesPGPlugin.getInstance().maybeWriteInfoMsg("Using template path '" + templatePath + "'.");
try {
File parentDir= new File(fileName).getParentFile();
String cmd[]= new String[] {
getLPGExecutable(),
"-quiet",
(JikesPGPreferenceCache.generateListing ? "-list" : "-nolist"),
"-include-directory='" + templatePath + "'",
// TODO RMF 7/21/05 -- Don't specify -dat-directory; causes performance issues with Eclipse.
// Lexer tables can get quite large, so large that Java as spec'ed can't swallow them
// when translated to a switch statement, or even an array initializer. As a result,
// JikesPG supports the "-dat-directory" option to spill the tables into external data
// files loaded by the lexer at runtime. HOWEVER, loading these external data tables is
// very slow when performed using the standard Eclipse/plugin classloader.
// So: don't enable it by default.
// "-dat-directory=" + getOutputDirectory(resource.getProject()),
fileName};
Process process= Runtime.getRuntime().exec(cmd, new String[0], parentDir);
JikesPGView consoleView= JikesPGView.getDefault();
processJikesPGOutput(file, process, consoleView);
processJikesPGErrors(file, process, consoleView);
doRefresh(file);
} catch (Exception e) {
JikesPGPlugin.getInstance().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
|
diff --git a/component/web/security/src/main/java/org/exoplatform/web/login/GateinWCIController.java b/component/web/security/src/main/java/org/exoplatform/web/login/GateinWCIController.java
index 0d6398cfa..e2bcd4c3b 100644
--- a/component/web/security/src/main/java/org/exoplatform/web/login/GateinWCIController.java
+++ b/component/web/security/src/main/java/org/exoplatform/web/login/GateinWCIController.java
@@ -1,98 +1,105 @@
/*
* Copyright (C) 2003-2009 eXo Platform SAS.
*
* 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.exoplatform.web.login;
import org.gatein.wci.security.Credentials;
import org.gatein.wci.security.WCIController;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author <a href="mailto:[email protected]">Alain Defrance</a>
* @version $Revision$
*/
public class GateinWCIController extends WCIController
{
private ServletContext servletContext;
public GateinWCIController(final ServletContext servletContext)
{
if (servletContext == null)
{
throw new IllegalArgumentException("servletContext is null");
}
this.servletContext = servletContext;
}
public void showLoginForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String initialURI = getInitialURI(req);
try
{
String queryString = (String)req.getAttribute("javax.servlet.forward.query_string");
if (req.getAttribute("javax.servlet.forward.query_string") != null)
{
initialURI = initialURI + "?" + queryString;
}
req.setAttribute("org.gatein.portal.login.initial_uri", initialURI);
servletContext.getRequestDispatcher("/login/jsp/login.jsp").include(req, resp);
}
finally
{
req.removeAttribute("org.gatein.portal.login.initial_uri");
}
}
public void showErrorLoginForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
- String initialURI = req.getHeader("referer");
+ //we need to check of the 'initialURI' value is specified or not already for the request. This can occur if an
+ //incorrect login was used on the ErrorLoginForm itself, since we don't want to redirect back to the errorloginform
+ //when the correct login is entered.
+ String initialURI = req.getParameter("initialURI");
if (initialURI == null || initialURI.length() == 0)
{
- initialURI = req.getContextPath();
- }
+ initialURI = req.getHeader("referer");
+ if (initialURI == null || initialURI.length() == 0)
+ {
+ initialURI = req.getContextPath();
+ }
+ }
//
try
{
req.setAttribute("org.gatein.portal.login.initial_uri", initialURI);
servletContext.getRequestDispatcher("/login/jsp/login.jsp").include(req, resp);
}
finally
{
req.removeAttribute("org.gatein.portal.login.initial_uri");
}
}
@Override
public Credentials getCredentials(final HttpServletRequest req, final HttpServletResponse resp)
{
return (Credentials)req.getSession().getAttribute(Credentials.CREDENTIALS);
}
@Override
public String getHomeURI(final HttpServletRequest req)
{
return req.getContextPath();
}
}
| false | true | public void showErrorLoginForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String initialURI = req.getHeader("referer");
if (initialURI == null || initialURI.length() == 0)
{
initialURI = req.getContextPath();
}
//
try
{
req.setAttribute("org.gatein.portal.login.initial_uri", initialURI);
servletContext.getRequestDispatcher("/login/jsp/login.jsp").include(req, resp);
}
finally
{
req.removeAttribute("org.gatein.portal.login.initial_uri");
}
}
| public void showErrorLoginForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
//we need to check of the 'initialURI' value is specified or not already for the request. This can occur if an
//incorrect login was used on the ErrorLoginForm itself, since we don't want to redirect back to the errorloginform
//when the correct login is entered.
String initialURI = req.getParameter("initialURI");
if (initialURI == null || initialURI.length() == 0)
{
initialURI = req.getHeader("referer");
if (initialURI == null || initialURI.length() == 0)
{
initialURI = req.getContextPath();
}
}
//
try
{
req.setAttribute("org.gatein.portal.login.initial_uri", initialURI);
servletContext.getRequestDispatcher("/login/jsp/login.jsp").include(req, resp);
}
finally
{
req.removeAttribute("org.gatein.portal.login.initial_uri");
}
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/dom/parser/c/CFunction.java b/parser/org/eclipse/cdt/internal/core/dom/parser/c/CFunction.java
index 0aef1324d..d7eef03fc 100644
--- a/parser/org/eclipse/cdt/internal/core/dom/parser/c/CFunction.java
+++ b/parser/org/eclipse/cdt/internal/core/dom/parser/c/CFunction.java
@@ -1,427 +1,433 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.c;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IFunctionType;
import org.eclipse.cdt.core.dom.ast.IParameter;
import org.eclipse.cdt.core.dom.ast.IProblemBinding;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.gnu.c.ICASTKnRFunctionDeclarator;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPVisitor;
/**
* Created on Nov 5, 2004
* @author aniefer
*/
public class CFunction implements IFunction, ICInternalFunction {
private IASTStandardFunctionDeclarator [] declarators = null;
private IASTFunctionDeclarator definition;
private static final int FULLY_RESOLVED = 1;
private static final int RESOLUTION_IN_PROGRESS = 1 << 1;
private int bits = 0;
protected IFunctionType type = null;
public CFunction( IASTFunctionDeclarator declarator ){
if( declarator != null ) {
if( declarator.getParent() instanceof IASTFunctionDefinition || declarator instanceof ICASTKnRFunctionDeclarator )
definition = declarator;
else {
declarators = new IASTStandardFunctionDeclarator [] { (IASTStandardFunctionDeclarator) declarator };
}
}
}
public IASTNode getPhysicalNode(){
if( definition != null )
return definition;
else if( declarators != null && declarators.length > 0 )
return declarators[0];
return null;
}
public void addDeclarator( IASTFunctionDeclarator fnDeclarator ){
updateParameterBindings( fnDeclarator );
if( fnDeclarator.getParent() instanceof IASTFunctionDefinition || fnDeclarator instanceof ICASTKnRFunctionDeclarator )
definition = fnDeclarator;
else {
if( declarators == null ){
declarators = new IASTStandardFunctionDeclarator[] { (IASTStandardFunctionDeclarator) fnDeclarator };
return;
}
for( int i = 0; i < declarators.length; i++ ){
if( declarators[i] == null ){
declarators[i] = (IASTStandardFunctionDeclarator) fnDeclarator;
return;
}
}
IASTStandardFunctionDeclarator tmp [] = new IASTStandardFunctionDeclarator [ declarators.length * 2 ];
System.arraycopy( declarators, 0, tmp, 0, declarators.length );
tmp[ declarators.length ] = (IASTStandardFunctionDeclarator) fnDeclarator;
declarators = tmp;
}
}
protected IASTTranslationUnit getTranslationUnit() {
if( definition != null )
return definition.getTranslationUnit();
else if( declarators != null )
return declarators[0].getTranslationUnit();
return null;
}
private void resolveAllDeclarations(){
if( (bits & (FULLY_RESOLVED | RESOLUTION_IN_PROGRESS)) == 0 ){
bits |= RESOLUTION_IN_PROGRESS;
IASTTranslationUnit tu = getTranslationUnit();
if( tu != null ){
CPPVisitor.getDeclarations( tu, this );
}
declarators = (IASTStandardFunctionDeclarator[]) ArrayUtil.trim( IASTStandardFunctionDeclarator.class, declarators );
bits |= FULLY_RESOLVED;
bits &= ~RESOLUTION_IN_PROGRESS;
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#getParameters()
*/
public IParameter[] getParameters() {
IParameter [] result = IParameter.EMPTY_PARAMETER_ARRAY;
IASTFunctionDeclarator dtor = (IASTFunctionDeclarator) getPhysicalNode();
if( dtor == null && (bits & FULLY_RESOLVED) == 0){
resolveAllDeclarations();
dtor = (IASTFunctionDeclarator) getPhysicalNode();
}
if (dtor instanceof IASTStandardFunctionDeclarator) {
IASTParameterDeclaration[] params = ((IASTStandardFunctionDeclarator)dtor).getParameters();
int size = params.length;
result = new IParameter[ size ];
if( size > 0 ){
for( int i = 0; i < size; i++ ){
IASTParameterDeclaration p = params[i];
result[i] = (IParameter) p.getDeclarator().getName().resolveBinding();
}
}
} else if (dtor instanceof ICASTKnRFunctionDeclarator) {
IASTName[] names = ((ICASTKnRFunctionDeclarator)dtor).getParameterNames();
result = new IParameter[ names.length ];
if( names.length > 0 ){
// ensures that the List of parameters is created in the same order as the K&R C parameter names
for( int i=0; i<names.length; i++ ) {
IASTDeclarator decl = CVisitor.getKnRParameterDeclarator( (ICASTKnRFunctionDeclarator) dtor, names[i] );
if( decl != null ) {
result[i] = (IParameter) decl.getName().resolveBinding();
} else {
result[i] = new CParameter.CParameterProblem( names[i], IProblemBinding.SEMANTIC_KNR_PARAMETER_DECLARATION_NOT_FOUND, names[i].toCharArray() );
}
}
}
}
return result;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IBinding#getName()
*/
public String getName() {
IASTFunctionDeclarator dtor = ( definition != null ) ? definition : declarators[0];
return dtor.getName().toString();
}
public char[] getNameCharArray(){
IASTFunctionDeclarator dtor = ( definition != null ) ? definition : declarators[0];
return dtor.getName().toCharArray();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IBinding#getScope()
*/
public IScope getScope() {
IASTFunctionDeclarator dtor = (IASTFunctionDeclarator) getPhysicalNode();
if( dtor != null )
return CVisitor.getContainingScope( dtor.getParent() );
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#getFunctionScope()
*/
public IScope getFunctionScope() {
if( definition != null ){
IASTFunctionDefinition def = (IASTFunctionDefinition) definition.getParent();
return def.getScope();
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#getType()
*/
public IFunctionType getType() {
if( type == null ) {
IASTDeclarator functionDtor = (IASTDeclarator) getPhysicalNode();
if( functionDtor == null && (bits & FULLY_RESOLVED) == 0){
resolveAllDeclarations();
functionDtor = (IASTDeclarator) getPhysicalNode();
}
if( functionDtor != null ) {
while (functionDtor.getNestedDeclarator() != null)
functionDtor = functionDtor.getNestedDeclarator();
IType tempType = CVisitor.createType( functionDtor );
if (tempType instanceof IFunctionType)
type = (IFunctionType)tempType;
}
}
return type;
}
public IBinding resolveParameter( IASTName paramName ){
if( paramName.getBinding() != null )
return paramName.getBinding();
IBinding binding = null;
int idx = 0;
IASTNode parent = paramName.getParent();
while( parent instanceof IASTDeclarator && !(parent instanceof ICASTKnRFunctionDeclarator ) )
parent = parent.getParent();
ICASTKnRFunctionDeclarator fKnRDtor = null;
IASTDeclarator knrParamDtor = null;
if( parent instanceof IASTParameterDeclaration ){
IASTStandardFunctionDeclarator fdtor = (IASTStandardFunctionDeclarator) parent.getParent();
IASTParameterDeclaration [] ps = fdtor.getParameters();
for( ; idx < ps.length; idx++ ){
if( parent == ps[idx] )
break;
}
} else if( parent instanceof IASTSimpleDeclaration ){
//KnR: name in declaration list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent.getParent();
IASTName [] ps = fKnRDtor.getParameterNames();
char [] n = paramName.toCharArray();
for( ; idx < ps.length; idx++ ){
if( CharArrayUtils.equals( ps[idx].toCharArray(), n ) )
break;
}
} else {
//KnR: name in name list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent;
IASTName [] ps = fKnRDtor.getParameterNames();
for( ; idx < ps.length; idx++ ){
if( ps[idx] == paramName)
break;
}
knrParamDtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, paramName );
if( knrParamDtor != null )
paramName = knrParamDtor.getName();
}
//create a new binding and set it for the corresponding parameter in all known defns and decls
binding = new CParameter( paramName );
IASTParameterDeclaration temp = null;
if( definition != null ){
if( definition instanceof IASTStandardFunctionDeclarator ){
- temp = ((IASTStandardFunctionDeclarator)definition).getParameters()[idx];
- temp.getDeclarator().getName().setBinding( binding );
+ IASTParameterDeclaration [] parameters = ((IASTStandardFunctionDeclarator)definition).getParameters();
+ if( parameters.length > idx ) {
+ temp = parameters[idx];
+ temp.getDeclarator().getName().setBinding( binding );
+ }
} else if( definition instanceof ICASTKnRFunctionDeclarator ){
fKnRDtor = (ICASTKnRFunctionDeclarator) definition;
- IASTName n = fKnRDtor.getParameterNames()[idx];
- n.setBinding( binding );
- IASTDeclarator dtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, n );
- if( dtor != null ){
- dtor.getName().setBinding( binding );
- }
+ IASTName [] parameterNames = fKnRDtor.getParameterNames();
+ if( parameterNames.length > idx ) {
+ IASTName n = parameterNames[idx];
+ n.setBinding( binding );
+ IASTDeclarator dtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, n );
+ if( dtor != null ){
+ dtor.getName().setBinding( binding );
+ }
+ }
}
}
if( declarators != null ){
for( int j = 0; j < declarators.length && declarators[j] != null; j++ ){
if( declarators[j].getParameters().length > idx ){
temp = declarators[j].getParameters()[idx];
temp.getDeclarator().getName().setBinding( binding );
}
}
}
return binding;
}
protected void updateParameterBindings( IASTFunctionDeclarator fdtor ){
IParameter [] params = getParameters();
if( fdtor instanceof IASTStandardFunctionDeclarator ){
IASTParameterDeclaration [] nps = ((IASTStandardFunctionDeclarator)fdtor).getParameters();
if(params.length < nps.length )
return;
for( int i = 0; i < nps.length; i++ ){
IASTName name = nps[i].getDeclarator().getName();
name.setBinding( params[i] );
if( params[i] instanceof CParameter )
((CParameter)params[i]).addDeclaration( name );
}
} else {
IASTName [] ns = ((ICASTKnRFunctionDeclarator)fdtor).getParameterNames();
if( params.length > 0 && params.length != ns.length )
return; //problem
for( int i = 0; i < params.length; i++ ){
IASTName name = ns[i];
name.setBinding( params[i] );
IASTDeclarator dtor = CVisitor.getKnRParameterDeclarator( (ICASTKnRFunctionDeclarator) fdtor, name );
if( dtor != null ){
dtor.getName().setBinding( params[i] );
if( params[i] instanceof CParameter )
((CParameter)params[i]).addDeclaration( dtor.getName() );
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#isStatic()
*/
public boolean isStatic() {
return hasStorageClass( IASTDeclSpecifier.sc_static );
}
public boolean hasStorageClass( int storage ){
if( (bits & FULLY_RESOLVED) == 0 ){
resolveAllDeclarations();
}
IASTDeclarator dtor = definition;
IASTDeclarator[] ds = declarators;
int i = -1;
do{
if( dtor != null ){
IASTNode parent = dtor.getParent();
while( !(parent instanceof IASTDeclaration) )
parent = parent.getParent();
IASTDeclSpecifier declSpec = null;
if( parent instanceof IASTSimpleDeclaration ){
declSpec = ((IASTSimpleDeclaration)parent).getDeclSpecifier();
} else if( parent instanceof IASTFunctionDefinition )
declSpec = ((IASTFunctionDefinition)parent).getDeclSpecifier();
if( declSpec.getStorageClass() == storage )
return true;
}
if( ds != null && ++i < ds.length )
dtor = ds[i];
else
break;
} while( dtor != null );
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#isExtern()
*/
public boolean isExtern() {
return hasStorageClass( IASTDeclSpecifier.sc_extern );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#isAuto()
*/
public boolean isAuto() {
return hasStorageClass( IASTDeclSpecifier.sc_auto );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#isRegister()
*/
public boolean isRegister() {
return hasStorageClass( IASTDeclSpecifier.sc_register );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#isInline()
*/
public boolean isInline() {
if( (bits & FULLY_RESOLVED) == 0 ){
resolveAllDeclarations();
}
IASTDeclarator dtor = definition;
IASTDeclarator[] ds = declarators;
int i = -1;
do{
if( dtor != null ){
IASTNode parent = dtor.getParent();
while( !(parent instanceof IASTDeclaration) )
parent = parent.getParent();
IASTDeclSpecifier declSpec = null;
if( parent instanceof IASTSimpleDeclaration ){
declSpec = ((IASTSimpleDeclaration)parent).getDeclSpecifier();
} else if( parent instanceof IASTFunctionDefinition )
declSpec = ((IASTFunctionDefinition)parent).getDeclSpecifier();
if( declSpec.isInline() )
return true;
}
if( ds != null && ++i < ds.length )
dtor = ds[i];
else
break;
} while( dtor != null );
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.dom.ast.IFunction#takesVarArgs()
*/
public boolean takesVarArgs() {
if( (bits & FULLY_RESOLVED) == 0 ){
resolveAllDeclarations();
}
if( definition != null ){
if( definition instanceof IASTStandardFunctionDeclarator )
return ((IASTStandardFunctionDeclarator)definition).takesVarArgs();
return false;
}
if( declarators != null && declarators.length > 0 ){
return declarators[0].takesVarArgs();
}
return false;
}
public void setFullyResolved(boolean resolved) {
if( resolved )
bits |= FULLY_RESOLVED;
else
bits &= ~FULLY_RESOLVED;
}
}
| false | true | public IBinding resolveParameter( IASTName paramName ){
if( paramName.getBinding() != null )
return paramName.getBinding();
IBinding binding = null;
int idx = 0;
IASTNode parent = paramName.getParent();
while( parent instanceof IASTDeclarator && !(parent instanceof ICASTKnRFunctionDeclarator ) )
parent = parent.getParent();
ICASTKnRFunctionDeclarator fKnRDtor = null;
IASTDeclarator knrParamDtor = null;
if( parent instanceof IASTParameterDeclaration ){
IASTStandardFunctionDeclarator fdtor = (IASTStandardFunctionDeclarator) parent.getParent();
IASTParameterDeclaration [] ps = fdtor.getParameters();
for( ; idx < ps.length; idx++ ){
if( parent == ps[idx] )
break;
}
} else if( parent instanceof IASTSimpleDeclaration ){
//KnR: name in declaration list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent.getParent();
IASTName [] ps = fKnRDtor.getParameterNames();
char [] n = paramName.toCharArray();
for( ; idx < ps.length; idx++ ){
if( CharArrayUtils.equals( ps[idx].toCharArray(), n ) )
break;
}
} else {
//KnR: name in name list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent;
IASTName [] ps = fKnRDtor.getParameterNames();
for( ; idx < ps.length; idx++ ){
if( ps[idx] == paramName)
break;
}
knrParamDtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, paramName );
if( knrParamDtor != null )
paramName = knrParamDtor.getName();
}
//create a new binding and set it for the corresponding parameter in all known defns and decls
binding = new CParameter( paramName );
IASTParameterDeclaration temp = null;
if( definition != null ){
if( definition instanceof IASTStandardFunctionDeclarator ){
temp = ((IASTStandardFunctionDeclarator)definition).getParameters()[idx];
temp.getDeclarator().getName().setBinding( binding );
} else if( definition instanceof ICASTKnRFunctionDeclarator ){
fKnRDtor = (ICASTKnRFunctionDeclarator) definition;
IASTName n = fKnRDtor.getParameterNames()[idx];
n.setBinding( binding );
IASTDeclarator dtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, n );
if( dtor != null ){
dtor.getName().setBinding( binding );
}
}
}
if( declarators != null ){
for( int j = 0; j < declarators.length && declarators[j] != null; j++ ){
if( declarators[j].getParameters().length > idx ){
temp = declarators[j].getParameters()[idx];
temp.getDeclarator().getName().setBinding( binding );
}
}
}
return binding;
}
| public IBinding resolveParameter( IASTName paramName ){
if( paramName.getBinding() != null )
return paramName.getBinding();
IBinding binding = null;
int idx = 0;
IASTNode parent = paramName.getParent();
while( parent instanceof IASTDeclarator && !(parent instanceof ICASTKnRFunctionDeclarator ) )
parent = parent.getParent();
ICASTKnRFunctionDeclarator fKnRDtor = null;
IASTDeclarator knrParamDtor = null;
if( parent instanceof IASTParameterDeclaration ){
IASTStandardFunctionDeclarator fdtor = (IASTStandardFunctionDeclarator) parent.getParent();
IASTParameterDeclaration [] ps = fdtor.getParameters();
for( ; idx < ps.length; idx++ ){
if( parent == ps[idx] )
break;
}
} else if( parent instanceof IASTSimpleDeclaration ){
//KnR: name in declaration list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent.getParent();
IASTName [] ps = fKnRDtor.getParameterNames();
char [] n = paramName.toCharArray();
for( ; idx < ps.length; idx++ ){
if( CharArrayUtils.equals( ps[idx].toCharArray(), n ) )
break;
}
} else {
//KnR: name in name list
fKnRDtor = (ICASTKnRFunctionDeclarator) parent;
IASTName [] ps = fKnRDtor.getParameterNames();
for( ; idx < ps.length; idx++ ){
if( ps[idx] == paramName)
break;
}
knrParamDtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, paramName );
if( knrParamDtor != null )
paramName = knrParamDtor.getName();
}
//create a new binding and set it for the corresponding parameter in all known defns and decls
binding = new CParameter( paramName );
IASTParameterDeclaration temp = null;
if( definition != null ){
if( definition instanceof IASTStandardFunctionDeclarator ){
IASTParameterDeclaration [] parameters = ((IASTStandardFunctionDeclarator)definition).getParameters();
if( parameters.length > idx ) {
temp = parameters[idx];
temp.getDeclarator().getName().setBinding( binding );
}
} else if( definition instanceof ICASTKnRFunctionDeclarator ){
fKnRDtor = (ICASTKnRFunctionDeclarator) definition;
IASTName [] parameterNames = fKnRDtor.getParameterNames();
if( parameterNames.length > idx ) {
IASTName n = parameterNames[idx];
n.setBinding( binding );
IASTDeclarator dtor = CVisitor.getKnRParameterDeclarator( fKnRDtor, n );
if( dtor != null ){
dtor.getName().setBinding( binding );
}
}
}
}
if( declarators != null ){
for( int j = 0; j < declarators.length && declarators[j] != null; j++ ){
if( declarators[j].getParameters().length > idx ){
temp = declarators[j].getParameters()[idx];
temp.getDeclarator().getName().setBinding( binding );
}
}
}
return binding;
}
|
diff --git a/wings2/src/java/org/wings/plaf/css/TabbedPaneCG.java b/wings2/src/java/org/wings/plaf/css/TabbedPaneCG.java
index f00527db..ef95264e 100644
--- a/wings2/src/java/org/wings/plaf/css/TabbedPaneCG.java
+++ b/wings2/src/java/org/wings/plaf/css/TabbedPaneCG.java
@@ -1,263 +1,269 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.KeyStroke;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wings.SComponent;
import org.wings.SConstants;
import org.wings.SIcon;
import org.wings.STabbedPane;
import org.wings.io.Device;
import org.wings.session.Browser;
import org.wings.session.BrowserType;
import org.wings.session.SessionManager;
import org.wings.style.CSSSelector;
public class TabbedPaneCG extends AbstractComponentCG implements SConstants {
private final transient static Log log = LogFactory.getLog(TabbedPaneCG.class);
private static final Map placements = new HashMap();
static {
placements.put(new Integer(STabbedPane.TOP), "top");
placements.put(new Integer(STabbedPane.BOTTOM), "bottom");
placements.put(new Integer(STabbedPane.LEFT), "left");
placements.put(new Integer(STabbedPane.RIGHT), "right");
}
public void installCG(SComponent component) {
super.installCG(component);
final STabbedPane tab = (STabbedPane) component;
InputMap inputMap = new InputMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.ALT_DOWN_MASK, false), "previous");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK, false), "next");
tab.setInputMap(inputMap);
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (tab.getSelectedIndex() > 0 && "previous".equals(e.getActionCommand()))
tab.setSelectedIndex(tab.getSelectedIndex() - 1);
else if (tab.getSelectedIndex() < tab.getTabCount() - 1 && "next".equals(e.getActionCommand()))
tab.setSelectedIndex(tab.getSelectedIndex() + 1);
tab.requestFocus();
}
};
ActionMap actionMap = new ActionMap();
actionMap.put("previous", action);
actionMap.put("next", action);
tab.setActionMap(actionMap);
}
public void writeContent(final Device device, final SComponent component)
throws java.io.IOException {
STabbedPane tabbedPane = (STabbedPane) component;
if (tabbedPane.getTabCount() > 0) {
String style = component.getStyle();
boolean childSelectorWorkaround = !component.getSession().getUserAgent().supportsCssChildSelector();
int placement = tabbedPane.getTabPlacement();
device.print("<table cellspacing=\"0\"");
if (childSelectorWorkaround)
Utils.childSelectorWorkaround(device, style);
Utils.printCSSInlineFullSize(device, component.getPreferredSize());
Utils.writeEvents(device, component);
device.print(">");
if (placement == STabbedPane.TOP)
device.print("<tr><th placement=\"top\"");
else if (placement == STabbedPane.LEFT)
device.print("<tr><th placement=\"left\"");
else if (placement == STabbedPane.RIGHT)
device.print("<tr><td");
else if (placement == STabbedPane.BOTTOM)
device.print("<tr><td");
if (childSelectorWorkaround) {
if (placement == STabbedPane.TOP)
Utils.childSelectorWorkaround(device, "STabbedPane_top");
else if (placement == STabbedPane.LEFT)
Utils.childSelectorWorkaround(device, "STabbedPane_left");
else
Utils.childSelectorWorkaround(device, "STabbedPane_pane");
}
device.print(">");
if (placement == STabbedPane.TOP || placement == STabbedPane.LEFT)
writeTabs(device, tabbedPane);
else
writeSelectedPaneContent(device, tabbedPane);
if (placement == STabbedPane.TOP)
device.print("</th></tr><tr><td");
else if (placement == STabbedPane.LEFT)
device.print("</th><td");
else if (placement == STabbedPane.RIGHT)
device.print("</td><th placement=\"right\"");
else if (placement == STabbedPane.BOTTOM)
device.print("</td></tr><tr><th placement=\"bottom\"");
if (childSelectorWorkaround) {
if (placement == STabbedPane.RIGHT)
Utils.childSelectorWorkaround(device, "STabbedPane_right");
else if (placement == STabbedPane.BOTTOM)
Utils.childSelectorWorkaround(device, "STabbedPane_bottom");
else
Utils.childSelectorWorkaround(device, "STabbedPane_pane");
}
device.print(">");
if (placement == STabbedPane.TOP
|| placement == STabbedPane.LEFT) {
writeSelectedPaneContent(device, tabbedPane);
device.print("</td></tr></table>");
} else {
writeTabs(device, tabbedPane);
device.print("</th></tr></table>");
}
} else {
Utils.printDebug(device, "<!-- tabbedPane has no tabs -->");
}
}
/** Renders the currently selected pane of the tabbed Pane. */
private void writeSelectedPaneContent(Device device, STabbedPane tabbedPane) throws IOException {
SComponent selected = tabbedPane.getSelectedComponent();
if (selected != null) {
selected.write(device);
}
}
private void writeTabs(Device device, STabbedPane tabbedPane) throws IOException {
boolean childSelectorWorkaround = !tabbedPane.getSession().getUserAgent().supportsCssChildSelector();
boolean showAsFormComponent = tabbedPane.getShowAsFormComponent();
- boolean konquerorWorkaround = tabbedPane.getSession().getUserAgent().getBrowserType().equals(BrowserType.KONQUEROR);
+ final Browser browser = tabbedPane.getSession().getUserAgent();
+ // substitute whitespaces for konqueror and ie5.0x
+ boolean nbspWorkaround = browser.getBrowserType().equals(
+ BrowserType.KONQUEROR)
+ || (browser.getBrowserType().equals(BrowserType.IE)
+ && browser.getMajorVersion() == 5 && browser
+ .getMinorVersion() <= .1);
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
SIcon icon = tabbedPane.getIconAt(i);
String title = tabbedPane.getTitleAt(i);
String tooltip = tabbedPane.getToolTipText();
- if (konquerorWorkaround)
+ if (nbspWorkaround)
title = nonBreakingSpaces(title);
/*
* needed here so that the tabs can be wrapped. else they are in
* one long line. noticed in firefox and konqueror.
*/
device.print("\n");
if (showAsFormComponent)
device.print("<button name=\"")
.print(Utils.event(tabbedPane))
.print("\" value=\"")
.print(i)
.print("\"");
else
device.print("<a href=\"")
.print(tabbedPane.getRequestURL()
.addParameter(Utils.event(tabbedPane) + "=" + i).toString())
.print("\"");
if (i == tabbedPane.getSelectedIndex()) {
device.print(" selected=\"true\"");
if (tabbedPane.isFocusOwner())
Utils.optAttribute(device, "focus", tabbedPane.getName());
}
if (!tabbedPane.isEnabledAt(i))
device.print(" disabled=\"true\"");
if (childSelectorWorkaround) {
String cssClassName = "STabbedPane_Tab_" + placements.get(new Integer(tabbedPane.getTabPlacement()));
if (i == tabbedPane.getSelectedIndex()) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_selected");
} else if (!tabbedPane.isEnabledAt(i)) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_disabled");
} else {
Utils.childSelectorWorkaround(device, cssClassName);
}
}
device.print(">");
- device.print(" ");
if (icon != null && tabbedPane.getTabPlacement() != STabbedPane.RIGHT) {
device.print("<img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
- device.print("/> ");
+ device.print(" style=\"margin-left:0.2em;\"/>");
}
+ device.print(" ");
Utils.write(device, title);
device.print(" ");
if (icon != null && tabbedPane.getTabPlacement() == STabbedPane.RIGHT) {
device.print(" <img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
device.print("/>");
}
if (showAsFormComponent)
device.print("</button>");
else
device.print("</a>");
}
}
private String nonBreakingSpaces(String title) {
return title.replace(' ', '\u00A0');
}
public CSSSelector mapSelector(CSSSelector selector) {
Browser browser = SessionManager.getSession().getUserAgent();
CSSSelector mappedSelector = null;
if (browser.getBrowserType().equals(BrowserType.IE))
mappedSelector = (CSSSelector) msieMappings.get(selector);
else
mappedSelector = (CSSSelector) geckoMappings.get(selector);
return mappedSelector != null ? mappedSelector : selector;
}
private static final Map msieMappings = new HashMap();
private static final Map geckoMappings = new HashMap();
static {
msieMappings.put(STabbedPane.SELECTOR_SELECTION, new CSSSelector (" *.STabbedPane_selected"));
msieMappings.put(STabbedPane.SELECTOR_CONTENT, new CSSSelector (" td.STabbedPane_pane"));
msieMappings.put(STabbedPane.SELECTOR_TABS, new CSSSelector (" table.STabbedPane th"));
geckoMappings.put(STabbedPane.SELECTOR_SELECTION, new CSSSelector (" > table > tbody > tr > th > *[selected=\"true\"]"));
geckoMappings.put(STabbedPane.SELECTOR_CONTENT, new CSSSelector (" > table > tbody > tr > td"));
geckoMappings.put(STabbedPane.SELECTOR_TABS, new CSSSelector (" > table > tbody > tr > th"));
}
}
| false | true | private void writeTabs(Device device, STabbedPane tabbedPane) throws IOException {
boolean childSelectorWorkaround = !tabbedPane.getSession().getUserAgent().supportsCssChildSelector();
boolean showAsFormComponent = tabbedPane.getShowAsFormComponent();
boolean konquerorWorkaround = tabbedPane.getSession().getUserAgent().getBrowserType().equals(BrowserType.KONQUEROR);
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
SIcon icon = tabbedPane.getIconAt(i);
String title = tabbedPane.getTitleAt(i);
String tooltip = tabbedPane.getToolTipText();
if (konquerorWorkaround)
title = nonBreakingSpaces(title);
/*
* needed here so that the tabs can be wrapped. else they are in
* one long line. noticed in firefox and konqueror.
*/
device.print("\n");
if (showAsFormComponent)
device.print("<button name=\"")
.print(Utils.event(tabbedPane))
.print("\" value=\"")
.print(i)
.print("\"");
else
device.print("<a href=\"")
.print(tabbedPane.getRequestURL()
.addParameter(Utils.event(tabbedPane) + "=" + i).toString())
.print("\"");
if (i == tabbedPane.getSelectedIndex()) {
device.print(" selected=\"true\"");
if (tabbedPane.isFocusOwner())
Utils.optAttribute(device, "focus", tabbedPane.getName());
}
if (!tabbedPane.isEnabledAt(i))
device.print(" disabled=\"true\"");
if (childSelectorWorkaround) {
String cssClassName = "STabbedPane_Tab_" + placements.get(new Integer(tabbedPane.getTabPlacement()));
if (i == tabbedPane.getSelectedIndex()) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_selected");
} else if (!tabbedPane.isEnabledAt(i)) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_disabled");
} else {
Utils.childSelectorWorkaround(device, cssClassName);
}
}
device.print(">");
device.print(" ");
if (icon != null && tabbedPane.getTabPlacement() != STabbedPane.RIGHT) {
device.print("<img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
device.print("/> ");
}
Utils.write(device, title);
device.print(" ");
if (icon != null && tabbedPane.getTabPlacement() == STabbedPane.RIGHT) {
device.print(" <img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
device.print("/>");
}
if (showAsFormComponent)
device.print("</button>");
else
device.print("</a>");
}
}
| private void writeTabs(Device device, STabbedPane tabbedPane) throws IOException {
boolean childSelectorWorkaround = !tabbedPane.getSession().getUserAgent().supportsCssChildSelector();
boolean showAsFormComponent = tabbedPane.getShowAsFormComponent();
final Browser browser = tabbedPane.getSession().getUserAgent();
// substitute whitespaces for konqueror and ie5.0x
boolean nbspWorkaround = browser.getBrowserType().equals(
BrowserType.KONQUEROR)
|| (browser.getBrowserType().equals(BrowserType.IE)
&& browser.getMajorVersion() == 5 && browser
.getMinorVersion() <= .1);
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
SIcon icon = tabbedPane.getIconAt(i);
String title = tabbedPane.getTitleAt(i);
String tooltip = tabbedPane.getToolTipText();
if (nbspWorkaround)
title = nonBreakingSpaces(title);
/*
* needed here so that the tabs can be wrapped. else they are in
* one long line. noticed in firefox and konqueror.
*/
device.print("\n");
if (showAsFormComponent)
device.print("<button name=\"")
.print(Utils.event(tabbedPane))
.print("\" value=\"")
.print(i)
.print("\"");
else
device.print("<a href=\"")
.print(tabbedPane.getRequestURL()
.addParameter(Utils.event(tabbedPane) + "=" + i).toString())
.print("\"");
if (i == tabbedPane.getSelectedIndex()) {
device.print(" selected=\"true\"");
if (tabbedPane.isFocusOwner())
Utils.optAttribute(device, "focus", tabbedPane.getName());
}
if (!tabbedPane.isEnabledAt(i))
device.print(" disabled=\"true\"");
if (childSelectorWorkaround) {
String cssClassName = "STabbedPane_Tab_" + placements.get(new Integer(tabbedPane.getTabPlacement()));
if (i == tabbedPane.getSelectedIndex()) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_selected");
} else if (!tabbedPane.isEnabledAt(i)) {
Utils.childSelectorWorkaround(device, cssClassName + " STabbedPane_Tab_disabled");
} else {
Utils.childSelectorWorkaround(device, cssClassName);
}
}
device.print(">");
if (icon != null && tabbedPane.getTabPlacement() != STabbedPane.RIGHT) {
device.print("<img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
device.print(" style=\"margin-left:0.2em;\"/>");
}
device.print(" ");
Utils.write(device, title);
device.print(" ");
if (icon != null && tabbedPane.getTabPlacement() == STabbedPane.RIGHT) {
device.print(" <img");
Utils.optAttribute(device, "src", icon.getURL());
Utils.optAttribute(device, "alt", tooltip);
Utils.optAttribute(device, "width", icon.getIconWidth());
Utils.optAttribute(device, "height", icon.getIconHeight());
device.print("/>");
}
if (showAsFormComponent)
device.print("</button>");
else
device.print("</a>");
}
}
|
diff --git a/core/src/main/java/hudson/slaves/SlaveComputer.java b/core/src/main/java/hudson/slaves/SlaveComputer.java
index 45832c6d4..54f28a30a 100644
--- a/core/src/main/java/hudson/slaves/SlaveComputer.java
+++ b/core/src/main/java/hudson/slaves/SlaveComputer.java
@@ -1,544 +1,545 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* 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 hudson.slaves;
import hudson.model.*;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Callable;
import hudson.util.StreamTaskListener;
import hudson.util.NullStream;
import hudson.util.RingBufferLogHandler;
import hudson.util.Futures;
import hudson.FilePath;
import hudson.lifecycle.WindowsSlaveInstaller;
import hudson.Util;
import hudson.AbortException;
import hudson.remoting.Launcher;
import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER;
import hudson.slaves.OfflineCause.ChannelTermination;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import java.security.Security;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
/**
* {@link Computer} for {@link Slave}s.
*
* @author Kohsuke Kawaguchi
*/
public class SlaveComputer extends Computer {
private volatile Channel channel;
private volatile transient boolean acceptingTasks = true;
private Charset defaultCharset;
private Boolean isUnix;
/**
* Effective {@link ComputerLauncher} that hides the details of
* how we launch a slave agent on this computer.
*
* <p>
* This is normally the same as {@link Slave#getLauncher()} but
* can be different. See {@link #grabLauncher(Node)}.
*/
private ComputerLauncher launcher;
/**
* Number of failed attempts to reconnect to this node
* (so that if we keep failing to reconnect, we can stop
* trying.)
*/
private transient int numRetryAttempt;
/**
* Tracks the status of the last launch operation, which is always asynchronous.
* This can be used to wait for the completion, or cancel the launch activity.
*/
private volatile Future<?> lastConnectActivity = null;
private Object constructed = new Object();
public SlaveComputer(Slave slave) {
super(slave);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAcceptingTasks() {
return acceptingTasks;
}
/**
* Allows a {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy} to
* suspend tasks being accepted by the slave computer.
*
* @param acceptingTasks {@code true} if the slave can accept tasks.
*/
public void setAcceptingTasks(boolean acceptingTasks) {
this.acceptingTasks = acceptingTasks;
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public Boolean isUnix() {
return isUnix;
}
@Override
public Slave getNode() {
return (Slave)super.getNode();
}
@Override
public String getIcon() {
Future<?> l = lastConnectActivity;
if(l!=null && !l.isDone())
return "computer-flash.gif";
return super.getIcon();
}
/**
* @deprecated since 2008-05-20.
*/
@Deprecated @Override
public boolean isJnlpAgent() {
return launcher instanceof JNLPLauncher;
}
@Override
public boolean isLaunchSupported() {
return launcher.isLaunchSupported();
}
public ComputerLauncher getLauncher() {
return launcher;
}
protected Future<?> _connect(boolean forceReconnect) {
if(channel!=null) return Futures.precomputed(null);
if(!forceReconnect && isConnecting())
return lastConnectActivity;
if(forceReconnect && isConnecting())
logger.fine("Forcing a reconnect on "+getName());
closeChannel();
return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() {
public Object call() throws Exception {
// do this on another thread so that the lengthy launch operation
// (which is typical) won't block UI thread.
TaskListener listener = new StreamTaskListener(openLogFile());
try {
launcher.launch(SlaveComputer.this, listener);
return null;
} catch (AbortException e) {
listener.error(e.getMessage());
throw e;
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
throw e;
} catch (InterruptedException e) {
e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
throw e;
} finally {
if (channel==null)
offlineCause = new OfflineCause.LaunchFailed();
}
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void taskAccepted(Executor executor, Queue.Task task) {
super.taskAccepted(executor, task);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskAccepted(executor, task);
}
if (getNode().getRetentionStrategy() instanceof ExecutorListener) {
((ExecutorListener)getNode().getRetentionStrategy()).taskAccepted(executor, task);
}
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
super.taskCompleted(executor, task, durationMS);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskCompleted(executor, task, durationMS);
}
RetentionStrategy r = getRetentionStrategy();
if (r instanceof ExecutorListener) {
((ExecutorListener) r).taskCompleted(executor, task, durationMS);
}
}
/**
* {@inheritDoc}
*/
@Override
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
super.taskCompletedWithProblems(executor, task, durationMS, problems);
if (launcher instanceof ExecutorListener) {
((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems);
}
RetentionStrategy r = getRetentionStrategy();
if (r instanceof ExecutorListener) {
((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems);
}
}
@Override
public boolean isConnecting() {
Future<?> l = lastConnectActivity;
return isOffline() && l!=null && !l.isDone();
}
public OutputStream openLogFile() {
OutputStream os;
try {
os = new FileOutputStream(getLogFile());
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
os = new NullStream();
}
return os;
}
private final Object channelLock = new Object();
public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException {
setChannel(in,out,taskListener.getLogger(),listener);
}
/**
* Creates a {@link Channel} from the given stream and sets that to this slave.
*
* @param in
* Stream connected to the remote "slave.jar". It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param out
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param launchLog
* If non-null, receive the portion of data in <tt>is</tt> before
* the data goes into the "binary mode". This is useful
* when the established communication channel might include some data that might
* be useful for debugging/trouble-shooting.
* @param listener
* Gets a notification when the channel closes, to perform clean up. Can be null.
*/
public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
if(this.channel!=null)
throw new IllegalStateException("Already connected");
final TaskListener taskListener = new StreamTaskListener(launchLog);
PrintStream log = taskListener.getLogger();
Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE,
in,out, launchLog);
channel.addListener(new Channel.Listener() {
@Override
public void onClosed(Channel c, IOException cause) {
SlaveComputer.this.channel = null;
// Orderly shutdown will have null exception
if (cause!=null) offlineCause = new ChannelTermination(cause);
launcher.afterDisconnect(SlaveComputer.this, taskListener);
}
});
if(listener!=null)
channel.addListener(listener);
String slaveVersion = channel.call(new SlaveVersion());
log.println("Slave.jar version: " + slaveVersion);
boolean _isUnix = channel.call(new DetectOS());
log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave());
String defaultCharsetName = channel.call(new DetectDefaultCharset());
String remoteFs = getNode().getRemoteFS();
if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
FilePath root = new FilePath(channel,getNode().getRemoteFS());
channel.call(new SlaveInitializer());
channel.call(new WindowsSlaveInstaller(remoteFs));
for (ComputerListener cl : ComputerListener.all())
cl.preOnline(this,channel,root,taskListener);
offlineCause = null;
// update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
synchronized(channelLock) {
if(this.channel!=null) {
// check again. we used to have this entire method in a big sycnhronization block,
// but Channel constructor blocks for an external process to do the connection
// if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
// so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
// we'll end up queuing the lot of threads in a pseudo deadlock.
// This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
channel.close();
throw new IllegalStateException("Already connected");
}
isUnix = _isUnix;
numRetryAttempt = 0;
this.channel = channel;
defaultCharset = Charset.forName(defaultCharsetName);
}
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(this,taskListener);
+ log.println("Slave successfully connected and online");
Hudson.getInstance().getQueue().scheduleMaintenance();
}
@Override
public VirtualChannel getChannel() {
return channel;
}
public Charset getDefaultCharset() {
return defaultCharset;
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
if(channel==null)
return Collections.emptyList();
else
return channel.call(new Callable<List<LogRecord>,RuntimeException>() {
public List<LogRecord> call() {
return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView());
}
});
}
public HttpResponse doDoDisconnect(@QueryParameter String offlineMessage) throws IOException, ServletException {
if (channel!=null) {
//does nothing in case computer is already disconnected
checkPermission(Hudson.ADMINISTER);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
disconnect(OfflineCause.create(Messages._SlaveComputer_DisconnectedBy(
Hudson.getAuthentication().getName(),
offlineMessage!=null ? " : " + offlineMessage : "")
));
}
return new HttpRedirect(".");
}
@Override
public Future<?> disconnect(OfflineCause cause) {
super.disconnect(cause);
return Computer.threadPoolForRemoting.submit(new Runnable() {
public void run() {
// do this on another thread so that any lengthy disconnect operation
// (which could be typical) won't block UI thread.
TaskListener listener = new StreamTaskListener(openLogFile());
launcher.beforeDisconnect(SlaveComputer.this, listener);
closeChannel();
launcher.afterDisconnect(SlaveComputer.this, listener);
}
});
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(channel!=null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
connect(true);
// TODO: would be nice to redirect the user to "launching..." wait page,
// then spend a few seconds there and poll for the completion periodically.
rsp.sendRedirect("log");
}
public void tryReconnect() {
numRetryAttempt++;
if(numRetryAttempt<6 || (numRetryAttempt%12)==0) {
// initially retry several times quickly, and after that, do it infrequently.
logger.info("Attempting to reconnect "+nodeName);
connect(true);
}
}
/**
* Serves jar files for JNLP slave agents.
*
* @deprecated since 2008-08-18.
* This URL binding is no longer used and moved up directly under to {@link Hudson},
* but it's left here for now just in case some old JNLP slave agents request it.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
@Override
protected void kill() {
super.kill();
closeChannel();
}
public RetentionStrategy getRetentionStrategy() {
Slave n = getNode();
return n==null ? null : n.getRetentionStrategy();
}
/**
* If still connected, disconnect.
*/
private void closeChannel() {
// TODO: race condition between this and the setChannel method.
Channel c = channel;
channel = null;
isUnix = null;
if (c != null) {
try {
c.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e);
}
}
for (ComputerListener cl : ComputerListener.all())
cl.onOffline(this);
}
@Override
protected void setNode(Node node) {
super.setNode(node);
launcher = grabLauncher(node);
// maybe the configuration was changed to relaunch the slave, so try to re-launch now.
// "constructed==null" test is an ugly hack to avoid launching before the object is fully
// constructed.
if(constructed!=null) {
if (node instanceof Slave)
((Slave)node).getRetentionStrategy().check(this);
else
connect(false);
}
}
/**
* Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}.
* The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation.
*
* <p>
* Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method.
* This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs
* additional pre-launch step (such as waiting for the provisioned node to become available)
* before the user specified launch step (like SSH connection) kicks in.
*
* @see ComputerLauncherFilter
*/
protected ComputerLauncher grabLauncher(Node node) {
return ((Slave)node).getLauncher();
}
private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName());
private static final class SlaveVersion implements Callable<String,IOException> {
public String call() throws IOException {
try { return Launcher.VERSION; }
catch (Throwable ex) { return "< 1.335"; } // Older slave.jar won't have VERSION
}
}
private static final class DetectOS implements Callable<Boolean,IOException> {
public Boolean call() throws IOException {
return File.pathSeparatorChar==':';
}
}
private static final class DetectDefaultCharset implements Callable<String,IOException> {
public String call() throws IOException {
return Charset.defaultCharset().name();
}
}
/**
* Puts the {@link #SLAVE_LOG_HANDLER} into a separate class so that loading this class
* in JVM doesn't end up loading tons of additional classes.
*/
static final class LogHolder {
/**
* This field is used on each slave node to record log records on the slave.
*/
static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler();
}
private static class SlaveInitializer implements Callable<Void,RuntimeException> {
public Void call() {
// avoid double installation of the handler. JNLP slaves can reconnect to the master multiple times
// and each connection gets a different RemoteClassLoader, so we need to evict them by class name,
// not by their identity.
Logger logger = Logger.getLogger("hudson");
for (Handler h : logger.getHandlers()) {
if (h.getClass().getName().equals(SLAVE_LOG_HANDLER.getClass().getName()))
logger.removeHandler(h);
}
logger.addHandler(SLAVE_LOG_HANDLER);
// remove Sun PKCS11 provider if present. See http://hudson.gotdns.com/wiki/display/HUDSON/Solaris+Issue+6276483
try {
Security.removeProvider("SunPKCS11-Solaris");
} catch (SecurityException e) {
// ignore this error.
}
return null;
}
private static final long serialVersionUID = 1L;
}
}
| true | true | public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
if(this.channel!=null)
throw new IllegalStateException("Already connected");
final TaskListener taskListener = new StreamTaskListener(launchLog);
PrintStream log = taskListener.getLogger();
Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE,
in,out, launchLog);
channel.addListener(new Channel.Listener() {
@Override
public void onClosed(Channel c, IOException cause) {
SlaveComputer.this.channel = null;
// Orderly shutdown will have null exception
if (cause!=null) offlineCause = new ChannelTermination(cause);
launcher.afterDisconnect(SlaveComputer.this, taskListener);
}
});
if(listener!=null)
channel.addListener(listener);
String slaveVersion = channel.call(new SlaveVersion());
log.println("Slave.jar version: " + slaveVersion);
boolean _isUnix = channel.call(new DetectOS());
log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave());
String defaultCharsetName = channel.call(new DetectDefaultCharset());
String remoteFs = getNode().getRemoteFS();
if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
FilePath root = new FilePath(channel,getNode().getRemoteFS());
channel.call(new SlaveInitializer());
channel.call(new WindowsSlaveInstaller(remoteFs));
for (ComputerListener cl : ComputerListener.all())
cl.preOnline(this,channel,root,taskListener);
offlineCause = null;
// update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
synchronized(channelLock) {
if(this.channel!=null) {
// check again. we used to have this entire method in a big sycnhronization block,
// but Channel constructor blocks for an external process to do the connection
// if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
// so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
// we'll end up queuing the lot of threads in a pseudo deadlock.
// This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
channel.close();
throw new IllegalStateException("Already connected");
}
isUnix = _isUnix;
numRetryAttempt = 0;
this.channel = channel;
defaultCharset = Charset.forName(defaultCharsetName);
}
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(this,taskListener);
Hudson.getInstance().getQueue().scheduleMaintenance();
}
| public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
if(this.channel!=null)
throw new IllegalStateException("Already connected");
final TaskListener taskListener = new StreamTaskListener(launchLog);
PrintStream log = taskListener.getLogger();
Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE,
in,out, launchLog);
channel.addListener(new Channel.Listener() {
@Override
public void onClosed(Channel c, IOException cause) {
SlaveComputer.this.channel = null;
// Orderly shutdown will have null exception
if (cause!=null) offlineCause = new ChannelTermination(cause);
launcher.afterDisconnect(SlaveComputer.this, taskListener);
}
});
if(listener!=null)
channel.addListener(listener);
String slaveVersion = channel.call(new SlaveVersion());
log.println("Slave.jar version: " + slaveVersion);
boolean _isUnix = channel.call(new DetectOS());
log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave());
String defaultCharsetName = channel.call(new DetectDefaultCharset());
String remoteFs = getNode().getRemoteFS();
if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
FilePath root = new FilePath(channel,getNode().getRemoteFS());
channel.call(new SlaveInitializer());
channel.call(new WindowsSlaveInstaller(remoteFs));
for (ComputerListener cl : ComputerListener.all())
cl.preOnline(this,channel,root,taskListener);
offlineCause = null;
// update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
synchronized(channelLock) {
if(this.channel!=null) {
// check again. we used to have this entire method in a big sycnhronization block,
// but Channel constructor blocks for an external process to do the connection
// if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
// so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
// we'll end up queuing the lot of threads in a pseudo deadlock.
// This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
channel.close();
throw new IllegalStateException("Already connected");
}
isUnix = _isUnix;
numRetryAttempt = 0;
this.channel = channel;
defaultCharset = Charset.forName(defaultCharsetName);
}
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(this,taskListener);
log.println("Slave successfully connected and online");
Hudson.getInstance().getQueue().scheduleMaintenance();
}
|
diff --git a/src/de/binaervarianz/holopod/EpisodeDetailsActivity.java b/src/de/binaervarianz/holopod/EpisodeDetailsActivity.java
index 52bb3bc..49dfc6c 100644
--- a/src/de/binaervarianz/holopod/EpisodeDetailsActivity.java
+++ b/src/de/binaervarianz/holopod/EpisodeDetailsActivity.java
@@ -1,123 +1,125 @@
package de.binaervarianz.holopod;
import de.binaervarianz.holopod.db.DatabaseHandler;
import de.binaervarianz.holopod.db.Episode;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class EpisodeDetailsActivity extends Activity {
Episode episode;
DatabaseHandler db;
private DownloadManager dm;
private long enqueue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.podcast_details);
episode = (Episode) getIntent().getSerializableExtra("Episode");
db = new DatabaseHandler(this);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP
| ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setTitle(episode.toString());
}
TextView title = (TextView) findViewById(R.id.podcast_detail_title);
- title.setText(episode.getSubtitle());
+ title.setText(episode.getTitle());
TextView subtitle = (TextView) findViewById(R.id.podcast_detail_subtitle);
subtitle.setText(episode.getSubtitle());
+ TextView description = (TextView) findViewById(R.id.podcast_detail_description);
+ description.setText(episode.getDescription());
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.i("Ep.DL", uriString);
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.episode_details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.PlayPodcast:
return true;
case R.id.menu_dl_rm:
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
final String url = episode.getEncUrl();
Request request = new Request(Uri.parse(url));
request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
request.setTitle("HoloPod");
request.setDescription(episode.toString());
request.setMimeType(episode.getEncType());
request.setDestinationInExternalFilesDir(
this,
Environment.DIRECTORY_PODCASTS,
url.substring(url.lastIndexOf('/') + 1,
url.lastIndexOf('.')));
enqueue = dm.enqueue(request);
return true;
case R.id.menu_settings:
startActivity(new Intent(getApplicationContext(),
SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.podcast_details);
episode = (Episode) getIntent().getSerializableExtra("Episode");
db = new DatabaseHandler(this);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP
| ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setTitle(episode.toString());
}
TextView title = (TextView) findViewById(R.id.podcast_detail_title);
title.setText(episode.getSubtitle());
TextView subtitle = (TextView) findViewById(R.id.podcast_detail_subtitle);
subtitle.setText(episode.getSubtitle());
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.i("Ep.DL", uriString);
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.podcast_details);
episode = (Episode) getIntent().getSerializableExtra("Episode");
db = new DatabaseHandler(this);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP
| ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setTitle(episode.toString());
}
TextView title = (TextView) findViewById(R.id.podcast_detail_title);
title.setText(episode.getTitle());
TextView subtitle = (TextView) findViewById(R.id.podcast_detail_subtitle);
subtitle.setText(episode.getSubtitle());
TextView description = (TextView) findViewById(R.id.podcast_detail_description);
description.setText(episode.getDescription());
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.i("Ep.DL", uriString);
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
|
diff --git a/src/java/fedora/server/security/servletfilters/ExtendedHttpServletRequestWrapper.java b/src/java/fedora/server/security/servletfilters/ExtendedHttpServletRequestWrapper.java
index 5179e4df7..3870250b0 100644
--- a/src/java/fedora/server/security/servletfilters/ExtendedHttpServletRequestWrapper.java
+++ b/src/java/fedora/server/security/servletfilters/ExtendedHttpServletRequestWrapper.java
@@ -1,498 +1,510 @@
package fedora.server.security.servletfilters;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import fedora.server.errors.authorization.AuthzOperationalException;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Hashtable;
import java.security.Principal;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author Bill Niebel ([email protected])
*/
public class ExtendedHttpServletRequestWrapper
extends HttpServletRequestWrapper implements ExtendedHttpServletRequest {
private static Log log = LogFactory.getLog(ExtendedHttpServletRequestWrapper.class);
private String username = null;
private String password = null;
private String authority;
private Principal userPrincipal;
private boolean wrapperWriteLocked = false;
public final void lockWrapper() throws Exception {
lockSponsoredUser();
wrapperWriteLocked = true;
}
private String sponsoredUser = null; // null == not yet set; "" == no sponsored user; other values valid
private void setSponsoredUser(String sponsoredUser) throws Exception {
if (this.sponsoredUser == null) {
this.sponsoredUser = sponsoredUser;
}
}
public void setSponsoredUser() throws Exception {
String method = "setSponsoredUser";
String sponsoredUser = "";
log.debug(method + " , isSponsoredUserRequested()==" + isSponsoredUserRequested());
if (isSponsoredUserRequested()) {
sponsoredUser = getFromHeader();
log.debug(method + " , sponsoredUser==" + sponsoredUser);
}
setSponsoredUser(sponsoredUser);
}
public void lockSponsoredUser() throws Exception {
setSponsoredUser("");
}
public void setAuthenticated(Principal userPrincipal, String authority) throws Exception {
if (wrapperWriteLocked) {
throw new Exception();
}
if (isAuthenticated()) {
throw new Exception();
}
this.userPrincipal = userPrincipal;
this.authority = authority;
}
public Principal getUserPrincipal() {
//this order reinforces that container-supplied userPrincipal should not be overridden in setUserPrincipal()
Principal userPrincipal = super.getUserPrincipal();
if (userPrincipal == null) {
userPrincipal = this.userPrincipal;
}
return userPrincipal;
}
public final boolean isUserSponsored() {
return ! ((sponsoredUser == null) || "".equals(sponsoredUser));
}
protected boolean isSponsoredUserRequested() {
String sponsoredUser = getFromHeader();
boolean isSponsoredUserRequested = ! ((sponsoredUser == null) || "".equals(sponsoredUser));
return isSponsoredUserRequested;
}
public final boolean isAuthenticated() {
return (getUserPrincipal() != null);
}
public String getRemoteUser() {
String remoteUser = null;
if (isUserSponsored()) {
remoteUser = sponsoredUser;
} else {
remoteUser = super.getRemoteUser();
if ((remoteUser == null) && (userPrincipal != null)) {
remoteUser = userPrincipal.getName();
}
}
return remoteUser;
}
private final Map authenticatedAttributes = new Hashtable();
private final Map sponsoredAttributes = new Hashtable();
public final void auditInnerMap(Map map) {
if (log.isDebugEnabled()) {
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
Object value = map.get(key);
StringBuffer sb = new StringBuffer(key + "==");
String comma = "";
if (value instanceof String) {
sb.append(value);
} else if (value instanceof String[]) {
sb.append("[");
for (int i = 0; i < ((String[])value).length; i++) {
Object o = ((String[])value)[i];
if (o instanceof String) {
sb.append(comma + o);
comma = ",";
} else {
sb.append(comma + "UNKNOWN");
comma = ",";
}
}
sb.append("]");
} else if (value instanceof Set) {
sb.append("{");
for (Iterator it2 = ((Set)value).iterator(); it2.hasNext();) {
Object o = it2.next();
if (o instanceof String) {
sb.append(comma + o);
comma = ",";
} else {
sb.append(comma + "UNKNOWN");
comma = ",";
}
}
sb.append("}");
} else {
sb.append("UNKNOWN");
}
log.debug(sb.toString());
}
}
}
public final void auditInnerSet(Set set) {
if (log.isDebugEnabled()) {
for (Iterator it = set.iterator(); it.hasNext();) {
Object value = it.next();
if (value instanceof String) {
log.debug(value);
} else {
log.debug("UNKNOWN");
}
}
}
}
public final void auditOuterMap(Map map, String desc) {
if (log.isDebugEnabled()) {
log.debug("");
log.debug("auditing " + desc);
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
Object key = it.next();
Object inner = map.get(key);
String authority = "";
if (key instanceof String) {
authority = (String) key;
} else {
authority = "<authority not a string>";
}
if (inner instanceof Map) {
log.debug(authority + " maps to . . .");
auditInnerMap((Map)inner);
} else if (inner instanceof Set) {
log.debug(authority + " maps to . . .");
auditInnerSet((Set)inner);
} else {
log.debug(authority + " maps to an unknown object==" + map.getClass().getName());
}
}
}
}
public void audit() {
if (log.isDebugEnabled()) {
log.debug("\n===AUDIT===");
log.debug("auditing wrapped request");
auditOuterMap(authenticatedAttributes, "authenticatedAttributes");
auditOuterMap(sponsoredAttributes, "sponsoredAttributes");
log.debug("===AUDIT===\n");
}
}
public boolean getAttributeDefined(String key) throws AuthzOperationalException {
boolean defined = false;
Map map = null;
if (isUserSponsored()) {
map = sponsoredAttributes;
} else {
map = authenticatedAttributes;
}
for (Iterator iterator = map.values().iterator(); iterator.hasNext(); ) {
Map attributesFromOneAuthority = (Map) iterator.next();
if (attributesFromOneAuthority.containsKey(key)) {
defined = true;
break;
}
}
return defined;
}
public Set getAttributeValues(String key) throws AuthzOperationalException {
Set accumulatedValues4Key = null;
Map map = null;
if (isUserSponsored()) {
map = sponsoredAttributes;
} else {
map = authenticatedAttributes;
}
for (Iterator iterator = map.values().iterator(); iterator.hasNext(); ) {
Map attributesFromOneAuthority = (Map) iterator.next();
if (attributesFromOneAuthority.containsKey(key)) {
Set someValues4Key = (Set) attributesFromOneAuthority.get(key);
if ((someValues4Key != null) && ! someValues4Key.isEmpty()) {
if (accumulatedValues4Key == null) {
accumulatedValues4Key = new HashSet();
}
accumulatedValues4Key.addAll(someValues4Key);
}
}
}
if (accumulatedValues4Key == null) {
accumulatedValues4Key = IMMUTABLE_NULL_SET;
}
return accumulatedValues4Key;
}
public boolean hasAttributeValues(String key) throws AuthzOperationalException {
Set temp = getAttributeValues(key);
return ! temp.isEmpty();
}
public boolean isAttributeDefined(String key) throws AuthzOperationalException {
boolean isAttributeDefined;
isAttributeDefined = getAttributeDefined(key);
return isAttributeDefined;
}
private void putIntoMap(Map map, String key, Object value) throws Exception {
if (wrapperWriteLocked) {
throw new Exception();
}
if (! isAuthenticated()) {
throw new Exception("can't collect user roles/attributes/groups until after authentication");
}
if ((map == null) || (key == null) || (value == null)) {
throw new Exception("null parm, map==" + map + ", key==" + key + ", value==" + value);
}
if (map.containsKey(key)) {
throw new Exception("map already contains key==" + key);
}
log.debug("mapping " + key + " => " + value + " in " + map);
map.put(key,value);
}
private void putMapIntoMap(Map map, String key, Object value) throws Exception {
if (!(value instanceof Map)) {
throw new Exception("input parm must be a map");
}
putIntoMap(map, key, value);
}
public void addAttributes(String authority, Map attributes) throws Exception {
if (isUserSponsored()) {
// after user is sponsored, only sponsored-user roles/attributes/groups are collected
putMapIntoMap(sponsoredAttributes, authority, attributes);
} else {
// before user is sponsored, only authenticated-user roles/attributes/groups are collected
putMapIntoMap(authenticatedAttributes, authority, attributes);
}
}
private Map getAllAttributes (Map attributeGroup) {
Map all = new Hashtable();
for (Iterator it = attributeGroup.values().iterator(); it.hasNext(); ) {
Map m = (Map) it.next();
all.putAll(m);
}
return all;
}
public Map getAllAttributes() throws AuthzOperationalException {
Map all = null;
if (isUserSponsored()) {
all = getAllAttributes(sponsoredAttributes);
} else {
all = getAllAttributes(authenticatedAttributes);
}
return all;
}
public static final String BASIC = "Basic";
private final String[] parseUsernamePassword(String header) throws Exception {
String here = "parseUsernamePassword():";
String[] usernamePassword = null;
String msg = here + "header intact";
if ((header == null) || "".equals(header)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String authschemeUsernamepassword[] = header.split("\\s+");
msg = here + "header split";
if (authschemeUsernamepassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "auth scheme";
String authscheme = authschemeUsernamepassword[0];
if ((authscheme == null) && ! BASIC.equalsIgnoreCase(authscheme)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", authscheme==" + authscheme);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "digest non-null";
String usernamepassword = authschemeUsernamepassword[1];
if ((usernamepassword == null) || "".equals(usernamepassword)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", usernamepassword==" + usernamepassword);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED + ", usernamepassword==" + usernamepassword);
byte[] encoded = usernamepassword.getBytes();
msg = here + "digest base64-encoded";
if (! Base64.isArrayByteBase64(encoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", encoded==" + encoded);
throw new Exception(exceptionMsg);
}
if (log.isDebugEnabled()) log.debug(msg + SUCCEEDED + ", encoded==" + encoded);
byte[] decodedAsByteArray = Base64.decodeBase64(encoded);
log.debug(here + "got decoded bytes" + SUCCEEDED + ", decodedAsByteArray==" + decodedAsByteArray);
String decoded = new String(decodedAsByteArray); //decodedAsByteArray.toString();
log.debug(here + "got decoded string" + SUCCEEDED + ", decoded==" + decoded);
msg = here + "digest decoded";
if ((decoded == null) || "".equals(decoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String DELIMITER = ":";
- if ((decoded == null) || (decoded.indexOf(DELIMITER) < 0) || (decoded.startsWith(DELIMITER)) ) {
- usernamePassword = new String[0];
+ if (decoded == null) {
+ log.error("decoded user/password is null . . . returning 0-length strings");
+ usernamePassword = new String[2];
+ usernamePassword[0] = "";
+ usernamePassword[1] = "";
+ } else if (decoded.indexOf(DELIMITER) < 0) {
+ String exceptionMsg = "decoded user/password lacks delimiter";
+ log.fatal(exceptionMsg + " . . . throwing exception");
+ throw new Exception(exceptionMsg);
+ } else if (decoded.startsWith(DELIMITER)) {
+ log.error("decoded user/password is lacks user . . . returning 0-length strings");
+ usernamePassword = new String[2];
+ usernamePassword[0] = "";
+ usernamePassword[1] = "";
} else if (decoded.endsWith(DELIMITER)) { // no password, e.g., user == "guest"
usernamePassword = new String[2];
usernamePassword[0] = decoded.substring(0,decoded.length()-1);
usernamePassword[1] = "";
- } else {
+ } else { // usual, expected case
usernamePassword = decoded.split(DELIMITER);
}
msg = here + "user/password split";
if (usernamePassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
return usernamePassword;
}
public static final String AUTHORIZATION = "Authorization";
public final String getAuthorizationHeader() {
log.debug("getAuthorizationHeader()");
log.debug("getting this headers");
for (Enumeration enu = this.getHeaderNames(); enu.hasMoreElements(); ) {
String name = (String) enu.nextElement();
log.debug("another headername==" + name);
String value = this.getHeader(name);
log.debug("another headervalue==" + value);
}
log.debug("getting super headers");
for (Enumeration enu = super.getHeaderNames(); enu.hasMoreElements(); ) {
String name = (String) enu.nextElement();
log.debug("another headername==" + name);
String value = super.getHeader(name);
log.debug("another headervalue==" + value);
}
return getHeader(AUTHORIZATION);
}
public static final String FROM = "From";
public final String getFromHeader() {
return getHeader(FROM);
}
public final String getUser() throws Exception {
if (username == null) {
log.debug("username==null, so will grok now");
String authorizationHeader = getAuthorizationHeader();
log.debug("authorizationHeader==" + authorizationHeader);
if ((authorizationHeader != null) && ! "".equals(authorizationHeader)) {
log.debug("authorizationHeader is intact");
String[] usernamePassword = parseUsernamePassword(authorizationHeader);
log.debug("usernamePassword[] length==" + usernamePassword.length);
username = usernamePassword[0];
log.debug("username (usernamePassword[0])==" + username);
if (super.getRemoteUser() == null) {
log.debug("had none before");
} else if ((super.getRemoteUser() == username) || super.getRemoteUser().equals(username)) {
log.debug("got same now");
} else {
throw new Exception("somebody got it wrong");
}
}
}
log.debug("return user==" + username);
return username;
}
public final String getPassword() throws Exception {
if (password == null) {
String authorizationHeader = getAuthorizationHeader();
if ((authorizationHeader != null) && ! "".equals(authorizationHeader)) {
String[] usernamePassword = parseUsernamePassword(authorizationHeader);
password = usernamePassword[1];
}
}
log.debug("return password==" + password);
return password;
}
public final String getAuthority() {
return authority;
}
public ExtendedHttpServletRequestWrapper(HttpServletRequest wrappedRequest) throws Exception {
super(wrappedRequest);
}
/**
* @deprecated As of Version 2.1 of the Java Servlet API, use
* {@link ServletContext#getRealPath(java.lang.String)}.
*/
@Deprecated
public String getRealPath(String path) {
return super.getRealPath(path);
}
/**
* @deprecated As of Version 2.1 of the Java Servlet API, use
* {@link #isRequestedSessionIdFromURL()}.
*/
@Deprecated
public boolean isRequestedSessionIdFromUrl() {
return isRequestedSessionIdFromURL();
}
public boolean isSecure() {
log.debug("super.isSecure()==" + super.isSecure());
log.debug("this.getLocalPort()==" + this.getLocalPort());
log.debug("this.getProtocol()==" + this.getProtocol());
log.debug("this.getServerPort()==" + this.getServerPort());
log.debug("this.getRequestURI()==" + this.getRequestURI());
return super.isSecure();
}
}
| false | true | private final String[] parseUsernamePassword(String header) throws Exception {
String here = "parseUsernamePassword():";
String[] usernamePassword = null;
String msg = here + "header intact";
if ((header == null) || "".equals(header)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String authschemeUsernamepassword[] = header.split("\\s+");
msg = here + "header split";
if (authschemeUsernamepassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "auth scheme";
String authscheme = authschemeUsernamepassword[0];
if ((authscheme == null) && ! BASIC.equalsIgnoreCase(authscheme)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", authscheme==" + authscheme);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "digest non-null";
String usernamepassword = authschemeUsernamepassword[1];
if ((usernamepassword == null) || "".equals(usernamepassword)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", usernamepassword==" + usernamepassword);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED + ", usernamepassword==" + usernamepassword);
byte[] encoded = usernamepassword.getBytes();
msg = here + "digest base64-encoded";
if (! Base64.isArrayByteBase64(encoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", encoded==" + encoded);
throw new Exception(exceptionMsg);
}
if (log.isDebugEnabled()) log.debug(msg + SUCCEEDED + ", encoded==" + encoded);
byte[] decodedAsByteArray = Base64.decodeBase64(encoded);
log.debug(here + "got decoded bytes" + SUCCEEDED + ", decodedAsByteArray==" + decodedAsByteArray);
String decoded = new String(decodedAsByteArray); //decodedAsByteArray.toString();
log.debug(here + "got decoded string" + SUCCEEDED + ", decoded==" + decoded);
msg = here + "digest decoded";
if ((decoded == null) || "".equals(decoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String DELIMITER = ":";
if ((decoded == null) || (decoded.indexOf(DELIMITER) < 0) || (decoded.startsWith(DELIMITER)) ) {
usernamePassword = new String[0];
} else if (decoded.endsWith(DELIMITER)) { // no password, e.g., user == "guest"
usernamePassword = new String[2];
usernamePassword[0] = decoded.substring(0,decoded.length()-1);
usernamePassword[1] = "";
} else {
usernamePassword = decoded.split(DELIMITER);
}
msg = here + "user/password split";
if (usernamePassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
return usernamePassword;
}
| private final String[] parseUsernamePassword(String header) throws Exception {
String here = "parseUsernamePassword():";
String[] usernamePassword = null;
String msg = here + "header intact";
if ((header == null) || "".equals(header)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String authschemeUsernamepassword[] = header.split("\\s+");
msg = here + "header split";
if (authschemeUsernamepassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", header==" + header);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "auth scheme";
String authscheme = authschemeUsernamepassword[0];
if ((authscheme == null) && ! BASIC.equalsIgnoreCase(authscheme)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", authscheme==" + authscheme);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
msg = here + "digest non-null";
String usernamepassword = authschemeUsernamepassword[1];
if ((usernamepassword == null) || "".equals(usernamepassword)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", usernamepassword==" + usernamepassword);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED + ", usernamepassword==" + usernamepassword);
byte[] encoded = usernamepassword.getBytes();
msg = here + "digest base64-encoded";
if (! Base64.isArrayByteBase64(encoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", encoded==" + encoded);
throw new Exception(exceptionMsg);
}
if (log.isDebugEnabled()) log.debug(msg + SUCCEEDED + ", encoded==" + encoded);
byte[] decodedAsByteArray = Base64.decodeBase64(encoded);
log.debug(here + "got decoded bytes" + SUCCEEDED + ", decodedAsByteArray==" + decodedAsByteArray);
String decoded = new String(decodedAsByteArray); //decodedAsByteArray.toString();
log.debug(here + "got decoded string" + SUCCEEDED + ", decoded==" + decoded);
msg = here + "digest decoded";
if ((decoded == null) || "".equals(decoded)) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
String DELIMITER = ":";
if (decoded == null) {
log.error("decoded user/password is null . . . returning 0-length strings");
usernamePassword = new String[2];
usernamePassword[0] = "";
usernamePassword[1] = "";
} else if (decoded.indexOf(DELIMITER) < 0) {
String exceptionMsg = "decoded user/password lacks delimiter";
log.fatal(exceptionMsg + " . . . throwing exception");
throw new Exception(exceptionMsg);
} else if (decoded.startsWith(DELIMITER)) {
log.error("decoded user/password is lacks user . . . returning 0-length strings");
usernamePassword = new String[2];
usernamePassword[0] = "";
usernamePassword[1] = "";
} else if (decoded.endsWith(DELIMITER)) { // no password, e.g., user == "guest"
usernamePassword = new String[2];
usernamePassword[0] = decoded.substring(0,decoded.length()-1);
usernamePassword[1] = "";
} else { // usual, expected case
usernamePassword = decoded.split(DELIMITER);
}
msg = here + "user/password split";
if (usernamePassword.length != 2) {
String exceptionMsg = msg + FAILED;
log.fatal(exceptionMsg + ", digest decoded==" + decoded);
throw new Exception(exceptionMsg);
}
log.debug(msg + SUCCEEDED);
return usernamePassword;
}
|
diff --git a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMImport.java b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMImport.java
index 24169b98..856032f5 100644
--- a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMImport.java
+++ b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMImport.java
@@ -1,79 +1,79 @@
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.osm.cli.commands;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import java.util.List;
import org.geogit.cli.AbstractCommand;
import org.geogit.cli.CLICommand;
import org.geogit.cli.GeogitCLI;
import org.geogit.osm.internal.EmptyOSMDownloadException;
import org.geogit.osm.internal.Mapping;
import org.geogit.osm.internal.OSMDownloadReport;
import org.geogit.osm.internal.OSMImportOp;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
/**
* Imports data from an OSM file
*/
@Parameters(commandNames = "import", commandDescription = "Import OpenStreetMap data from a file")
public class OSMImport extends AbstractCommand implements CLICommand {
@Parameter(arity = 1, description = "OSM file path", required = true)
public List<String> apiUrl = Lists.newArrayList();
@Parameter(names = { "--add" }, description = "Do not remove previous data before importing")
public boolean add = false;
@Parameter(names = { "--no-raw" }, description = "Do not import raw data when using a mapping")
public boolean noRaw = false;
@Parameter(names = { "--mapping" }, description = "The file that contains the data mapping to use")
public String mappingFile;
@Override
protected void runInternal(GeogitCLI cli) throws Exception {
checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
checkArgument(apiUrl != null && apiUrl.size() == 1, "One file must be specified");
File importFile = new File(apiUrl.get(0));
checkArgument(importFile.exists(), "The specified OSM data file does not exist");
Mapping mapping = null;
if (mappingFile != null) {
mapping = Mapping.fromFile(mappingFile);
}
try {
Optional<OSMDownloadReport> report = cli.getGeogit().command(OSMImportOp.class)
.setDataSource(importFile.getAbsolutePath()).setMapping(mapping)
.setNoRaw(noRaw).setAdd(add).setProgressListener(cli.getProgressListener())
.call();
if (report.isPresent() && report.get().getUnpprocessedCount() > 0) {
cli.getConsole().println(
"Some elements in the by specified file could not be processed.\nProcessed entities: "
+ report.get().getCount() + "\nWrong or uncomplete elements: "
+ report.get().getUnpprocessedCount());
}
} catch (EmptyOSMDownloadException e) {
throw new IllegalArgumentException(
"The specified filter did not contain any valid element.\n"
+ "No changes were made to the repository.\n");
} catch (RuntimeException e) {
- new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
+ throw new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
}
}
}
| true | true | protected void runInternal(GeogitCLI cli) throws Exception {
checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
checkArgument(apiUrl != null && apiUrl.size() == 1, "One file must be specified");
File importFile = new File(apiUrl.get(0));
checkArgument(importFile.exists(), "The specified OSM data file does not exist");
Mapping mapping = null;
if (mappingFile != null) {
mapping = Mapping.fromFile(mappingFile);
}
try {
Optional<OSMDownloadReport> report = cli.getGeogit().command(OSMImportOp.class)
.setDataSource(importFile.getAbsolutePath()).setMapping(mapping)
.setNoRaw(noRaw).setAdd(add).setProgressListener(cli.getProgressListener())
.call();
if (report.isPresent() && report.get().getUnpprocessedCount() > 0) {
cli.getConsole().println(
"Some elements in the by specified file could not be processed.\nProcessed entities: "
+ report.get().getCount() + "\nWrong or uncomplete elements: "
+ report.get().getUnpprocessedCount());
}
} catch (EmptyOSMDownloadException e) {
throw new IllegalArgumentException(
"The specified filter did not contain any valid element.\n"
+ "No changes were made to the repository.\n");
} catch (RuntimeException e) {
new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
}
}
| protected void runInternal(GeogitCLI cli) throws Exception {
checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
checkArgument(apiUrl != null && apiUrl.size() == 1, "One file must be specified");
File importFile = new File(apiUrl.get(0));
checkArgument(importFile.exists(), "The specified OSM data file does not exist");
Mapping mapping = null;
if (mappingFile != null) {
mapping = Mapping.fromFile(mappingFile);
}
try {
Optional<OSMDownloadReport> report = cli.getGeogit().command(OSMImportOp.class)
.setDataSource(importFile.getAbsolutePath()).setMapping(mapping)
.setNoRaw(noRaw).setAdd(add).setProgressListener(cli.getProgressListener())
.call();
if (report.isPresent() && report.get().getUnpprocessedCount() > 0) {
cli.getConsole().println(
"Some elements in the by specified file could not be processed.\nProcessed entities: "
+ report.get().getCount() + "\nWrong or uncomplete elements: "
+ report.get().getUnpprocessedCount());
}
} catch (EmptyOSMDownloadException e) {
throw new IllegalArgumentException(
"The specified filter did not contain any valid element.\n"
+ "No changes were made to the repository.\n");
} catch (RuntimeException e) {
throw new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
}
}
|
diff --git a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RuntimeWorkspaceSetup.java b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RuntimeWorkspaceSetup.java
index cc6c67603..239ea9aed 100644
--- a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RuntimeWorkspaceSetup.java
+++ b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RuntimeWorkspaceSetup.java
@@ -1,340 +1,339 @@
/*
* Copyright (c) 2005 Borland Software Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Artem Tikhomirov (Borland) - initial API and implementation
*/
package org.eclipse.gmf.tests.setup;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.codegen.ecore.Generator;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.osgi.framework.Bundle;
/**
* ALMOST TRUE: With PDE, we need source code in the running workspace to allow compilation of our code
* (because PDE doesn't reexport set of plugins from it's running configuration, and it's no longer possible
* to set Target Platform to "same as running" as it was back in Eclipse 2.x).
*
* !!! NEW !!!
*
* Now, we managed to compile against linked binary folders, although using linked content instead of plugins
* requires us to explicitly add some plugins earlier available through plugin re-export (namely, oe.jface.text)
*
*
* Classloading works because there's -dev argument in the command line. With PDE launch, it's done by PDE.
* Without PDE, running tests as part of the build relies on Eclipse Testing Framework's org.eclipse.test_3.1.0/library.xml
* which specifies "-dev bin". Once it's not specified, or new format (properties file with plugin-id=binfolder)
* is in use, classloading of the generated code will fail and another mechanism should be invented then.
*
* If you get ClassNotFoundException while running tests in PDE environment, try to set read-only attribute for the next file:
* 'development-workspace'\.metadata\.plugins\org.eclipse.pde.core\'JUnitLaunchConfigName'\dev.properties
* @author artem
*/
public class RuntimeWorkspaceSetup {
/**
* Copy of <code>PDECore.CLASSPATH_CONTAINER_ID</code>
*/
private static final String PLUGIN_CONTAINER_ID = "org.eclipse.pde.core.requiredPlugins"; //$NON-NLS-1$
private boolean isDevLaunchMode;
public RuntimeWorkspaceSetup() {
isDevLaunchMode = isDevLaunchMode();
}
/**
* Copy (almost, except for strange unused assignment) of <code>PDECore.isDevLaunchMode()</code>
*/
private static boolean isDevLaunchMode() {
String[] args = Platform.getApplicationArgs();
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-pdelaunch")) { //$NON-NLS-1$
return true;
}
}
return false;
}
/**
* @return <code>this</code> for convenience
*/
// TODO Refactor to clear away similar code (CodeCompilationTest, RuntimeWorkspaceSetup, GenProjectSetup)
public RuntimeWorkspaceSetup init() throws Exception {
ensureJava14();
if (isDevLaunchMode) {
// Need to get some gmf source code into target workspace
importDevPluginsIntoRunTimeWorkspace(new String[] {
// "org.apache.batik",
"org.eclipse.gmf.runtime.notation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.edit", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.gef.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.type.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.clipboard.core", //$NON-NLS-1$
"org.eclipse.emf.validation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.commands.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.actions", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.providers", //$NON-NLS-1$
"antlr", //$NON-NLS-1$
"org.eclipse.emf.ocl", //$NON-NLS-1$
"org.eclipse.emf.query", //$NON-NLS-1$
"org.eclipse.emf.query.ocl", //$NON-NLS-1$
- "org.eclipse.gmf.tests", //$NON-NLS-1$
//
"org.eclipse.emf.edit", //$NON-NLS-1$
"org.eclipse.emf.transaction", //$NON-NLS-1$
"org.eclipse.emf.workspace", //$NON-NLS-1$
});
}
return this;
}
public static IProject getSOSProject() {
return ResourcesPlugin.getWorkspace().getRoot().getProject(".SOSProject"); //$NON-NLS-1$
}
/**
* Another approach - output binary folders of required plugins are linked as subfolders
* of our own sosProject (created in the target workspace). Then, we could use library classpathEntries
* (details why we should use _workspace_ paths for libraries could be found at
* <code>org.eclipse.jdt.internal.core.builder.NameEnvironment#computeClasspathLocations</code>)
*
* TODO don't assume workspace is clear, check sosProject existence first
* TODO utilize GenDiagram.requiredPluginIDs once it's a field (i.e. add oe.jface.text and don't create plugin project then, just plain project with links
*/
private void importDevPluginsIntoRunTimeWorkspace(String[] pluginIDs) throws CoreException {
IProject p = getSOSProject();
final Path srcPath = new Path('/' + p.getName() + "/src"); //$NON-NLS-1$
Generator.createEMFProject(srcPath, null, Collections.EMPTY_LIST, new NullProgressMonitor(), Generator.EMF_PLUGIN_PROJECT_STYLE, null);
StringBuffer pluginXmlContent = new StringBuffer();
pluginXmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?eclipse version=\"3.0\"?>\n<plugin "); //$NON-NLS-1$
pluginXmlContent.append(" version=\"1.0.0\" name='%providerName' id='"); //$NON-NLS-1$
pluginXmlContent.append(p.getName());
pluginXmlContent.append("'>\n<requires>\n"); //$NON-NLS-1$
pluginXmlContent.append("<import plugin='org.eclipse.jface.text' export='true'/>\n"); //$NON-NLS-1$
pluginXmlContent.append("<import plugin='org.eclipse.ui.views.properties.tabbed' export='true'/>\n"); //$NON-NLS-1$
ClasspathEntry[] classpathEntries = getClasspathEntries(pluginIDs);
for (int i = 0; i < classpathEntries.length; i++) {
classpathEntries[i].importTo(p, pluginXmlContent);
}
pluginXmlContent.append("</requires>\n</plugin>"); //$NON-NLS-1$
p.getFile("plugin.xml").create(new ByteArrayInputStream(pluginXmlContent.toString().getBytes()), true, new NullProgressMonitor()); //$NON-NLS-1$
}
private ClasspathEntry[] getClasspathEntries(String[] pluginIDs) {
ArrayList/*<ClasspathEntry>*/ entries = new ArrayList/*<ClasspathEntry>*/(pluginIDs.length);
for (int i = 0; i < pluginIDs.length; i++) {
ClasspathEntry nextEntry = new ClasspathEntry(pluginIDs[i]);
if (nextEntry.isValid()) {
entries.add(nextEntry);
} else {
System.out.println("Bundle " + pluginIDs[i] + " is missing, skipped."); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return (ClasspathEntry[]) entries.toArray(new ClasspathEntry[entries.size()]);
}
private IJavaProject asJavaProject(IProject p) {
return JavaCore.create(p);
}
/**
* TODO uniqueClassPathEntries is not needed if diagramProj gets here only once. It's not the case
* now - refactor LinkCreationConstraintsTest to utilize genProject created in AuditRulesTest (?)
* TODO refactor with ClasspathContainerInitializer - just for the sake of fixing the knowledge
*/
public void updateClassPath(IProject diagramProj) throws CoreException {
if (!isDevLaunchMode) {
return;
}
IResource[] members;
try {
members = getSOSProject().members();
} catch (CoreException ex) {
ex.printStackTrace();
members = new IResource[0];
}
final IJavaProject sosJavaPrj = asJavaProject(getSOSProject());
IClasspathEntry[] cpOrig = asJavaProject(diagramProj).getRawClasspath();
ArrayList rv = new ArrayList(10 + cpOrig.length + members.length);
IClasspathContainer c = JavaCore.getClasspathContainer(new Path(PLUGIN_CONTAINER_ID), sosJavaPrj);
if (c != null) {
IClasspathEntry[] cpAdd = c.getClasspathEntries();
rv.addAll(Arrays.asList(cpAdd));
}
for (int i = 0; i < members.length; i++) {
if (!members[i].isLinked()) {
continue;
}
rv.add(JavaCore.newLibraryEntry(members[i].getFullPath(), null, null));
}
final Set uniqueClassPathEntries = new HashSet();
IClasspathEntry[] cpOrigResolved = asJavaProject(diagramProj).getResolvedClasspath(true);
for (int i = 0; i < cpOrigResolved.length; i++) {
uniqueClassPathEntries.add(cpOrigResolved[i].getPath());
}
for (Iterator it = rv.iterator(); it.hasNext();) {
IClasspathEntry next = (IClasspathEntry) it.next();
if (uniqueClassPathEntries.contains(next.getPath())) {
it.remove();
} else {
uniqueClassPathEntries.add(next.getPath());
}
}
rv.addAll(Arrays.asList(cpOrig));
IClasspathEntry[] cpNew = (IClasspathEntry[]) rv.toArray(new IClasspathEntry[rv.size()]);
asJavaProject(diagramProj).setRawClasspath(cpNew, new NullProgressMonitor());
}
/**
* at least
*/
public void ensureJava14() {
if (!JavaCore.VERSION_1_4.equals(JavaCore.getOption(JavaCore.COMPILER_SOURCE))) {
Hashtable options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_4);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_4);
JavaCore.setOptions(options);
}
}
private class ClasspathEntry {
private String myPluginID;
private URL myBundleURL;
private String myRelativePath;
private File myBundleFile;
private File myClassesContainerFile;
private ClasspathEntry(String pluginID) {
myPluginID = pluginID;
}
public void importTo(IProject p, StringBuffer pluginXmlContent) {
if (!getClassesContainerFile().exists()) {
pluginXmlContent.append("<import plugin='"); //$NON-NLS-1$
pluginXmlContent.append(myPluginID);
pluginXmlContent.append("' export='true'/>\n"); //$NON-NLS-1$
} else {
if (getClassesContainerFile().isDirectory()) {
String entryName = getBundleFile().getName().replace('.', '_');
IFolder folder = p.getFolder(entryName);
try {
folder.createLink(new Path(getClassesContainerFile().getAbsolutePath()), IResource.REPLACE, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
} else if (getClassesContainerFile().isFile()) {
String entryName = getClassesContainerFile().getName();
IFile file = p.getFile(entryName);
try {
file.createLink(new Path(getClassesContainerFile().getAbsolutePath()), IResource.REPLACE, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
}
}
}
private File getClassesContainerFile() {
if (myClassesContainerFile == null) {
myClassesContainerFile = new File(getBundleFile(), getRelativePath());
}
return myClassesContainerFile;
}
private File getBundleFile() {
if (myBundleFile == null) {
myBundleFile = new File(getBundleURL().getFile());
}
return myBundleFile;
}
private String getRelativePath() {
if (myRelativePath == null) {
if ("antlr".equals(myPluginID)) { //$NON-NLS-1$
myRelativePath = "/lib/antlr.jar"; //$NON-NLS-1$
}
else {
myRelativePath = "/bin/"; //$NON-NLS-1$
}
}
return myRelativePath;
}
private URL getBundleURL() {
if (myBundleURL == null) {
Bundle bundle = Platform.getBundle(myPluginID);
if (bundle == null) {
throw new NullPointerException("No plugin '" + myPluginID + "' found in the platform");
}
try {
myBundleURL = Platform.resolve(bundle.getEntry("/")); //$NON-NLS-1$
} catch (IOException e) {
e.printStackTrace();
}
}
return myBundleURL;
}
public boolean isValid() {
return getBundleURL() != null;
}
}
}
| true | true | public RuntimeWorkspaceSetup init() throws Exception {
ensureJava14();
if (isDevLaunchMode) {
// Need to get some gmf source code into target workspace
importDevPluginsIntoRunTimeWorkspace(new String[] {
// "org.apache.batik",
"org.eclipse.gmf.runtime.notation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.edit", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.gef.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.type.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.clipboard.core", //$NON-NLS-1$
"org.eclipse.emf.validation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.commands.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.actions", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.providers", //$NON-NLS-1$
"antlr", //$NON-NLS-1$
"org.eclipse.emf.ocl", //$NON-NLS-1$
"org.eclipse.emf.query", //$NON-NLS-1$
"org.eclipse.emf.query.ocl", //$NON-NLS-1$
"org.eclipse.gmf.tests", //$NON-NLS-1$
//
"org.eclipse.emf.edit", //$NON-NLS-1$
"org.eclipse.emf.transaction", //$NON-NLS-1$
"org.eclipse.emf.workspace", //$NON-NLS-1$
});
}
return this;
}
| public RuntimeWorkspaceSetup init() throws Exception {
ensureJava14();
if (isDevLaunchMode) {
// Need to get some gmf source code into target workspace
importDevPluginsIntoRunTimeWorkspace(new String[] {
// "org.apache.batik",
"org.eclipse.gmf.runtime.notation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.edit", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.draw2d.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.gef.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.type.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.clipboard.core", //$NON-NLS-1$
"org.eclipse.emf.validation", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.action.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.commands.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.core", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui", //$NON-NLS-1$
"org.eclipse.gmf.runtime.common.ui.services.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.emf.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.actions", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.properties", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.providers.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.render", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor", //$NON-NLS-1$
"org.eclipse.gmf.runtime.diagram.ui.resources.editor.ide", //$NON-NLS-1$
"org.eclipse.gmf.runtime.notation.providers", //$NON-NLS-1$
"antlr", //$NON-NLS-1$
"org.eclipse.emf.ocl", //$NON-NLS-1$
"org.eclipse.emf.query", //$NON-NLS-1$
"org.eclipse.emf.query.ocl", //$NON-NLS-1$
//
"org.eclipse.emf.edit", //$NON-NLS-1$
"org.eclipse.emf.transaction", //$NON-NLS-1$
"org.eclipse.emf.workspace", //$NON-NLS-1$
});
}
return this;
}
|
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillAssassinsBlade.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillAssassinsBlade.java
index 428d041a..3076d7e7 100644
--- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillAssassinsBlade.java
+++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillAssassinsBlade.java
@@ -1,205 +1,205 @@
package com.herocraftonline.dev.heroes.skill.skills;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.ItemStack;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.api.SkillResult;
import com.herocraftonline.dev.heroes.effects.EffectType;
import com.herocraftonline.dev.heroes.effects.ExpirableEffect;
import com.herocraftonline.dev.heroes.effects.PeriodicDamageEffect;
import com.herocraftonline.dev.heroes.hero.Hero;
import com.herocraftonline.dev.heroes.skill.ActiveSkill;
import com.herocraftonline.dev.heroes.skill.Skill;
import com.herocraftonline.dev.heroes.skill.SkillConfigManager;
import com.herocraftonline.dev.heroes.skill.SkillType;
import com.herocraftonline.dev.heroes.util.Messaging;
import com.herocraftonline.dev.heroes.util.Setting;
import com.herocraftonline.dev.heroes.util.Util;
public class SkillAssassinsBlade extends ActiveSkill {
private String applyText;
private String expireText;
public SkillAssassinsBlade(Heroes plugin) {
super(plugin, "AssassinsBlade");
setDescription("You poison your blade which will deal an extra $1 damage every $2 seconds.");
setUsage("/skill ablade");
setArgumentRange(0, 0);
setIdentifiers("skill ablade", "skill assassinsblade");
setTypes(SkillType.BUFF);
Bukkit.getServer().getPluginManager().registerEvents(new SkillDamageListener(this), plugin);
}
@Override
public ConfigurationSection getDefaultConfig() {
ConfigurationSection node = super.getDefaultConfig();
node.set("weapons", Util.swords);
node.set("buff-duration", 600000); // 10 minutes in milliseconds
node.set("poison-duration", 10000); // 10 seconds in milliseconds
node.set(Setting.PERIOD.node(), 2000); // 2 seconds in milliseconds
node.set("tick-damage", 2);
node.set("attacks", 1); // How many attacks the buff lasts for.
node.set(Setting.APPLY_TEXT.node(), "%target% is poisoned!");
node.set(Setting.EXPIRE_TEXT.node(), "%target% has recovered from the poison!");
return node;
}
@Override
public void init() {
super.init();
applyText = SkillConfigManager.getRaw(this, Setting.APPLY_TEXT, "%target% is poisoned!").replace("%target%", "$1");
expireText = SkillConfigManager.getRaw(this, Setting.EXPIRE_TEXT, "%target% has recovered from the poison!").replace("%target%", "$1");
}
@Override
public SkillResult use(Hero hero, String[] args) {
long duration = SkillConfigManager.getUseSetting(hero, this, "buff-duration", 600000, false);
int numAttacks = SkillConfigManager.getUseSetting(hero, this, "attacks", 1, false);
hero.addEffect(new AssassinBladeBuff(this, duration, numAttacks));
broadcastExecuteText(hero);
return SkillResult.NORMAL;
}
public class AssassinBladeBuff extends ExpirableEffect {
private int applicationsLeft = 1;
public AssassinBladeBuff(Skill skill, long duration, int numAttacks) {
super(skill, "PoisonBlade", duration);
this.applicationsLeft = numAttacks;
this.types.add(EffectType.BENEFICIAL);
this.types.add(EffectType.POISON);
}
/**
* @return the applicationsLeft
*/
public int getApplicationsLeft() {
return applicationsLeft;
}
@Override
public void remove(Hero hero) {
super.remove(hero);
Messaging.send(hero.getPlayer(), "Your blade is no longer poisoned!");
}
/**
* @param applicationsLeft
* the applicationsLeft to set
*/
public void setApplicationsLeft(int applicationsLeft) {
this.applicationsLeft = applicationsLeft;
}
}
public class AssassinsPoison extends PeriodicDamageEffect {
public AssassinsPoison(Skill skill, long period, long duration, int tickDamage, Player applier) {
super(skill, "AssassinsPoison", period, duration, tickDamage, applier);
this.types.add(EffectType.POISON);
}
@Override
public void apply(LivingEntity lEntity) {
super.apply(lEntity);
broadcast(lEntity.getLocation(), applyText, Messaging.getLivingEntityName(lEntity).toLowerCase());
}
@Override
public void apply(Hero hero) {
super.apply(hero);
Player player = hero.getPlayer();
broadcast(player.getLocation(), applyText, player.getDisplayName());
}
@Override
public void remove(LivingEntity lEntity) {
super.remove(lEntity);
broadcast(lEntity.getLocation(), expireText, Messaging.getLivingEntityName(lEntity).toLowerCase());
}
@Override
public void remove(Hero hero) {
super.remove(hero);
Player player = hero.getPlayer();
broadcast(player.getLocation(), expireText, player.getDisplayName());
}
}
public class SkillDamageListener implements Listener {
private final Skill skill;
public SkillDamageListener(Skill skill) {
this.skill = skill;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamage(EntityDamageEvent event) {
- if (event.isCancelled() || !(event instanceof EntityDamageByEntityEvent)) {
+ if (event.isCancelled() || !(event instanceof EntityDamageByEntityEvent) || event.getDamage() == 0) {
return;
}
// If our target isn't a creature or player lets exit
if (!(event.getEntity() instanceof LivingEntity) && !(event.getEntity() instanceof Player)) {
return;
}
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (!(subEvent.getDamager() instanceof Player)) {
return;
}
Player player = (Player) subEvent.getDamager();
ItemStack item = player.getItemInHand();
Hero hero = plugin.getHeroManager().getHero(player);
if (!SkillConfigManager.getUseSetting(hero, skill, "weapons", Util.swords).contains(item.getType().name())) {
return;
}
if (hero.hasEffect("PoisonBlade")) {
long duration = SkillConfigManager.getUseSetting(hero, skill, "poison-duration", 10000, false);
long period = SkillConfigManager.getUseSetting(hero, skill, Setting.PERIOD, 2000, false);
int tickDamage = SkillConfigManager.getUseSetting(hero, skill, "tick-damage", 2, false);
AssassinsPoison apEffect = new AssassinsPoison(skill, period, duration, tickDamage, player);
Entity target = event.getEntity();
if (event.getEntity() instanceof Player) {
Hero targetHero = plugin.getHeroManager().getHero((Player) target);
targetHero.addEffect(apEffect);
checkBuff(hero);
} else if (target instanceof LivingEntity) {
plugin.getEffectManager().addEntityEffect((LivingEntity) target, apEffect);
checkBuff(hero);
}
}
}
private void checkBuff(Hero hero) {
AssassinBladeBuff abBuff = (AssassinBladeBuff) hero.getEffect("PoisonBlade");
abBuff.applicationsLeft -= 1;
if (abBuff.applicationsLeft < 1) {
hero.removeEffect(abBuff);
}
}
}
@Override
public String getDescription(Hero hero) {
int damage = SkillConfigManager.getUseSetting(hero, this, Setting.DAMAGE, 2, false);
double seconds = SkillConfigManager.getUseSetting(hero, this, "poison-duration", 10000, false) / 1000.0;
String s = getDescription().replace("$1", damage + "").replace("$2", seconds + "");
return s;
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled() || !(event instanceof EntityDamageByEntityEvent)) {
return;
}
// If our target isn't a creature or player lets exit
if (!(event.getEntity() instanceof LivingEntity) && !(event.getEntity() instanceof Player)) {
return;
}
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (!(subEvent.getDamager() instanceof Player)) {
return;
}
Player player = (Player) subEvent.getDamager();
ItemStack item = player.getItemInHand();
Hero hero = plugin.getHeroManager().getHero(player);
if (!SkillConfigManager.getUseSetting(hero, skill, "weapons", Util.swords).contains(item.getType().name())) {
return;
}
if (hero.hasEffect("PoisonBlade")) {
long duration = SkillConfigManager.getUseSetting(hero, skill, "poison-duration", 10000, false);
long period = SkillConfigManager.getUseSetting(hero, skill, Setting.PERIOD, 2000, false);
int tickDamage = SkillConfigManager.getUseSetting(hero, skill, "tick-damage", 2, false);
AssassinsPoison apEffect = new AssassinsPoison(skill, period, duration, tickDamage, player);
Entity target = event.getEntity();
if (event.getEntity() instanceof Player) {
Hero targetHero = plugin.getHeroManager().getHero((Player) target);
targetHero.addEffect(apEffect);
checkBuff(hero);
} else if (target instanceof LivingEntity) {
plugin.getEffectManager().addEntityEffect((LivingEntity) target, apEffect);
checkBuff(hero);
}
}
}
| public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled() || !(event instanceof EntityDamageByEntityEvent) || event.getDamage() == 0) {
return;
}
// If our target isn't a creature or player lets exit
if (!(event.getEntity() instanceof LivingEntity) && !(event.getEntity() instanceof Player)) {
return;
}
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (!(subEvent.getDamager() instanceof Player)) {
return;
}
Player player = (Player) subEvent.getDamager();
ItemStack item = player.getItemInHand();
Hero hero = plugin.getHeroManager().getHero(player);
if (!SkillConfigManager.getUseSetting(hero, skill, "weapons", Util.swords).contains(item.getType().name())) {
return;
}
if (hero.hasEffect("PoisonBlade")) {
long duration = SkillConfigManager.getUseSetting(hero, skill, "poison-duration", 10000, false);
long period = SkillConfigManager.getUseSetting(hero, skill, Setting.PERIOD, 2000, false);
int tickDamage = SkillConfigManager.getUseSetting(hero, skill, "tick-damage", 2, false);
AssassinsPoison apEffect = new AssassinsPoison(skill, period, duration, tickDamage, player);
Entity target = event.getEntity();
if (event.getEntity() instanceof Player) {
Hero targetHero = plugin.getHeroManager().getHero((Player) target);
targetHero.addEffect(apEffect);
checkBuff(hero);
} else if (target instanceof LivingEntity) {
plugin.getEffectManager().addEntityEffect((LivingEntity) target, apEffect);
checkBuff(hero);
}
}
}
|
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ReflectionUtils.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ReflectionUtils.java
index 4fee5f4f95..be63c81620 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ReflectionUtils.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ReflectionUtils.java
@@ -1,340 +1,340 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.serializer.Deserializer;
import org.apache.hadoop.io.serializer.SerializationFactory;
import org.apache.hadoop.io.serializer.Serializer;
/**
* General reflection utils
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class ReflectionUtils {
private static final Class<?>[] EMPTY_ARRAY = new Class[]{};
volatile private static SerializationFactory serialFactory = null;
/**
* Cache of constructors for each class. Pins the classes so they
* can't be garbage collected until ReflectionUtils can be collected.
*/
private static final Map<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE =
new ConcurrentHashMap<Class<?>, Constructor<?>>();
/**
* Check and set 'configuration' if necessary.
*
* @param theObject object for which to set configuration
* @param conf Configuration
*/
public static void setConf(Object theObject, Configuration conf) {
if (conf != null) {
if (theObject instanceof Configurable) {
((Configurable) theObject).setConf(conf);
}
setJobConf(theObject, conf);
}
}
/**
* This code is to support backward compatibility and break the compile
* time dependency of core on mapred.
* This should be made deprecated along with the mapred package HADOOP-1230.
* Should be removed when mapred package is removed.
*/
private static void setJobConf(Object theObject, Configuration conf) {
//If JobConf and JobConfigurable are in classpath, AND
//theObject is of type JobConfigurable AND
//conf is of type JobConf then
//invoke configure on theObject
try {
Class<?> jobConfClass =
conf.getClassByNameOrNull("org.apache.hadoop.mapred.JobConf");
if (jobConfClass == null) {
return;
}
Class<?> jobConfigurableClass =
conf.getClassByNameOrNull("org.apache.hadoop.mapred.JobConfigurable");
if (jobConfigurableClass == null) {
return;
}
if (jobConfClass.isAssignableFrom(conf.getClass()) &&
jobConfigurableClass.isAssignableFrom(theObject.getClass())) {
Method configureMethod =
jobConfigurableClass.getMethod("configure", jobConfClass);
configureMethod.invoke(theObject, conf);
}
} catch (Exception e) {
throw new RuntimeException("Error in configuring object", e);
}
}
/** Create an object for the given class and initialize it from conf
*
* @param theClass class of which an object is created
* @param conf Configuration
* @return a new object
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass, Configuration conf) {
T result;
try {
Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
if (meth == null) {
meth = theClass.getDeclaredConstructor(EMPTY_ARRAY);
meth.setAccessible(true);
CONSTRUCTOR_CACHE.put(theClass, meth);
}
result = meth.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
setConf(result, conf);
return result;
}
static private ThreadMXBean threadBean =
ManagementFactory.getThreadMXBean();
public static void setContentionTracing(boolean val) {
threadBean.setThreadContentionMonitoringEnabled(val);
}
private static String getTaskName(long id, String name) {
if (name == null) {
return Long.toString(id);
}
return id + " (" + name + ")";
}
/**
* Print all of the thread's information and stack traces.
*
* @param stream the stream to
* @param title a string title for the stack trace
*/
- public static void printThreadInfo(PrintWriter stream,
+ public synchronized static void printThreadInfo(PrintWriter stream,
String title) {
final int STACK_DEPTH = 20;
boolean contention = threadBean.isThreadContentionMonitoringEnabled();
long[] threadIds = threadBean.getAllThreadIds();
stream.println("Process Thread Dump: " + title);
stream.println(threadIds.length + " active threads");
for (long tid: threadIds) {
ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
if (info == null) {
stream.println(" Inactive");
continue;
}
stream.println("Thread " +
getTaskName(info.getThreadId(),
info.getThreadName()) + ":");
Thread.State state = info.getThreadState();
stream.println(" State: " + state);
stream.println(" Blocked count: " + info.getBlockedCount());
stream.println(" Waited count: " + info.getWaitedCount());
if (contention) {
stream.println(" Blocked time: " + info.getBlockedTime());
stream.println(" Waited time: " + info.getWaitedTime());
}
if (state == Thread.State.WAITING) {
stream.println(" Waiting on " + info.getLockName());
} else if (state == Thread.State.BLOCKED) {
stream.println(" Blocked on " + info.getLockName());
stream.println(" Blocked by " +
getTaskName(info.getLockOwnerId(),
info.getLockOwnerName()));
}
stream.println(" Stack:");
for (StackTraceElement frame: info.getStackTrace()) {
stream.println(" " + frame.toString());
}
}
stream.flush();
}
private static long previousLogTime = 0;
/**
* Log the current thread stacks at INFO level.
* @param log the logger that logs the stack trace
* @param title a descriptive title for the call stacks
* @param minInterval the minimum time from the last
*/
public static void logThreadInfo(Log log,
String title,
long minInterval) {
boolean dumpStack = false;
if (log.isInfoEnabled()) {
synchronized (ReflectionUtils.class) {
long now = Time.now();
if (now - previousLogTime >= minInterval * 1000) {
previousLogTime = now;
dumpStack = true;
}
}
if (dumpStack) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
printThreadInfo(new PrintWriter(buffer), title);
log.info(buffer.toString());
}
}
}
/**
* Return the correctly-typed {@link Class} of the given object.
*
* @param o object whose correctly-typed <code>Class</code> is to be obtained
* @return the correctly typed <code>Class</code> of the given object.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClass(T o) {
return (Class<T>)o.getClass();
}
// methods to support testing
static void clearCache() {
CONSTRUCTOR_CACHE.clear();
}
static int getCacheSize() {
return CONSTRUCTOR_CACHE.size();
}
/**
* A pair of input/output buffers that we use to clone writables.
*/
private static class CopyInCopyOutBuffer {
DataOutputBuffer outBuffer = new DataOutputBuffer();
DataInputBuffer inBuffer = new DataInputBuffer();
/**
* Move the data from the output buffer to the input buffer.
*/
void moveData() {
inBuffer.reset(outBuffer.getData(), outBuffer.getLength());
}
}
/**
* Allocate a buffer for each thread that tries to clone objects.
*/
private static ThreadLocal<CopyInCopyOutBuffer> cloneBuffers
= new ThreadLocal<CopyInCopyOutBuffer>() {
@Override
protected synchronized CopyInCopyOutBuffer initialValue() {
return new CopyInCopyOutBuffer();
}
};
private static SerializationFactory getFactory(Configuration conf) {
if (serialFactory == null) {
serialFactory = new SerializationFactory(conf);
}
return serialFactory;
}
/**
* Make a copy of the writable object using serialization to a buffer
* @param dst the object to copy from
* @param src the object to copy into, which is destroyed
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static <T> T copy(Configuration conf,
T src, T dst) throws IOException {
CopyInCopyOutBuffer buffer = cloneBuffers.get();
buffer.outBuffer.reset();
SerializationFactory factory = getFactory(conf);
Class<T> cls = (Class<T>) src.getClass();
Serializer<T> serializer = factory.getSerializer(cls);
serializer.open(buffer.outBuffer);
serializer.serialize(src);
buffer.moveData();
Deserializer<T> deserializer = factory.getDeserializer(cls);
deserializer.open(buffer.inBuffer);
dst = deserializer.deserialize(dst);
return dst;
}
@Deprecated
public static void cloneWritableInto(Writable dst,
Writable src) throws IOException {
CopyInCopyOutBuffer buffer = cloneBuffers.get();
buffer.outBuffer.reset();
src.write(buffer.outBuffer);
buffer.moveData();
dst.readFields(buffer.inBuffer);
}
/**
* Gets all the declared fields of a class including fields declared in
* superclasses.
*/
public static List<Field> getDeclaredFieldsIncludingInherited(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
while (clazz != null) {
for (Field field : clazz.getDeclaredFields()) {
fields.add(field);
}
clazz = clazz.getSuperclass();
}
return fields;
}
/**
* Gets all the declared methods of a class including methods declared in
* superclasses.
*/
public static List<Method> getDeclaredMethodsIncludingInherited(Class<?> clazz) {
List<Method> methods = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
methods.add(method);
}
clazz = clazz.getSuperclass();
}
return methods;
}
}
| true | true | public static void printThreadInfo(PrintWriter stream,
String title) {
final int STACK_DEPTH = 20;
boolean contention = threadBean.isThreadContentionMonitoringEnabled();
long[] threadIds = threadBean.getAllThreadIds();
stream.println("Process Thread Dump: " + title);
stream.println(threadIds.length + " active threads");
for (long tid: threadIds) {
ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
if (info == null) {
stream.println(" Inactive");
continue;
}
stream.println("Thread " +
getTaskName(info.getThreadId(),
info.getThreadName()) + ":");
Thread.State state = info.getThreadState();
stream.println(" State: " + state);
stream.println(" Blocked count: " + info.getBlockedCount());
stream.println(" Waited count: " + info.getWaitedCount());
if (contention) {
stream.println(" Blocked time: " + info.getBlockedTime());
stream.println(" Waited time: " + info.getWaitedTime());
}
if (state == Thread.State.WAITING) {
stream.println(" Waiting on " + info.getLockName());
} else if (state == Thread.State.BLOCKED) {
stream.println(" Blocked on " + info.getLockName());
stream.println(" Blocked by " +
getTaskName(info.getLockOwnerId(),
info.getLockOwnerName()));
}
stream.println(" Stack:");
for (StackTraceElement frame: info.getStackTrace()) {
stream.println(" " + frame.toString());
}
}
stream.flush();
}
| public synchronized static void printThreadInfo(PrintWriter stream,
String title) {
final int STACK_DEPTH = 20;
boolean contention = threadBean.isThreadContentionMonitoringEnabled();
long[] threadIds = threadBean.getAllThreadIds();
stream.println("Process Thread Dump: " + title);
stream.println(threadIds.length + " active threads");
for (long tid: threadIds) {
ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
if (info == null) {
stream.println(" Inactive");
continue;
}
stream.println("Thread " +
getTaskName(info.getThreadId(),
info.getThreadName()) + ":");
Thread.State state = info.getThreadState();
stream.println(" State: " + state);
stream.println(" Blocked count: " + info.getBlockedCount());
stream.println(" Waited count: " + info.getWaitedCount());
if (contention) {
stream.println(" Blocked time: " + info.getBlockedTime());
stream.println(" Waited time: " + info.getWaitedTime());
}
if (state == Thread.State.WAITING) {
stream.println(" Waiting on " + info.getLockName());
} else if (state == Thread.State.BLOCKED) {
stream.println(" Blocked on " + info.getLockName());
stream.println(" Blocked by " +
getTaskName(info.getLockOwnerId(),
info.getLockOwnerName()));
}
stream.println(" Stack:");
for (StackTraceElement frame: info.getStackTrace()) {
stream.println(" " + frame.toString());
}
}
stream.flush();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.